diff --git a/conformance/README.md b/conformance/README.md index e785f23..59940be 100644 --- a/conformance/README.md +++ b/conformance/README.md @@ -20,7 +20,7 @@ conforms to CNP 1.0 if it passes every session that applies to it. | `preferences/` | The draft preferences extension's read (`spec/preferences.md`) | Nodes that keep preferences | | `games/` | The draft games extension: a save, its retry, a reused version, get, list, searching, deleting, importing and a game's source (`spec/games.md`) | Nodes that keep games (searching, deleting, importing and sources: those that offer them) | | `backups/` | The draft backups extension: the day's automatic backup once, a backup made, restored and the restore undone (`spec/backups.md`) | Nodes that back up what they keep | -| `knowledge/` | The draft knowledge extension: an import's refusals, with none started, and reads on an empty library: arrays, the position an analysis is of, and refusals (`spec/knowledge.md`) | Nodes that import puzzles and positions | +| `knowledge/` | The draft knowledge extension: an import's refusals, with none started, and reads on an empty library: arrays, the position an analysis is of, and refusals; its space: usage, and refusing a removal (`spec/knowledge.md`) | Nodes that import puzzles and positions (space: those that offer it) | The voice sessions check only what doesn't need a model to be ready. A voice node's own tests check its speech and transcription. diff --git a/conformance/knowledge/space.jsonl b/conformance/knowledge/space.jsonl new file mode 100644 index 0000000..dcff8ef --- /dev/null +++ b/conformance/knowledge/space.jsonl @@ -0,0 +1,15 @@ +{"session":"knowledge-space","description":"draft-1 knowledge space: usage answers the knowledge's bytes, and a removal of an import there is no record of, or with a malformed identity, is refused (spec/knowledge.md, Space)","requires":["knowledge.space"]} +{"send":{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocol":"1.0","client":{"name":"cnp-conformance","version":"1.0"}}}} +{"expect":{"id":1,"result":{"capabilities":{"knowledge":{"contract":"draft-1","space":true}}}}} +{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/usage"}} +{"expect":{"id":2,"result":{"bytes":"$integer"}}} +{"comment":"An import there is no record of can't be removed."} +{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/remove","params":{"kind":"lichess-puzzles","checksum":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}} +{"expect":{"id":3,"error":{"code":-32025}}} +{"comment":"A removal without its checksum is invalid params."} +{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/remove","params":{"kind":"lichess-puzzles"}}} +{"expect":{"id":4,"error":{"code":-32602}}} +{"send":{"jsonrpc":"2.0","id":5,"method":"shutdown"}} +{"expect":{"id":5,"result":null}} +{"send":{"jsonrpc":"2.0","method":"exit"}} +{"expectExit":0} diff --git a/crates/cnp/src/knowledge.rs b/crates/cnp/src/knowledge.rs index 1a7df1d..f7e0aa9 100644 --- a/crates/cnp/src/knowledge.rs +++ b/crates/cnp/src/knowledge.rs @@ -4,7 +4,9 @@ //! //! The import half: [`StartImport`] gives the node a file and a [`Manifest`] saying where it is //! from, answers at once, and the import runs on; [`ListImports`] reports where each has got -//! to, and [`CancelImport`] stops one. The read half: [`FindPuzzles`] by theme and rating (easiest +//! to, and [`CancelImport`] stops one. [`KnowledgeUsage`] and [`RemoveImport`] keep the +//! knowledge within a disk limit the client sets: how much the node's knowledge takes, and an +//! import's knowledge taken out again. The read half: [`FindPuzzles`] by theme and rating (easiest //! first, or from a random point, and only the reliable ones if asked), [`FindPuzzleFacets`] //! for how many there are of each theme and rating band, [`FindAnalyses`] of a position, and //! [`FindExercises`] by theme, each from complete imports only and naming its [`Source`]s. @@ -24,7 +26,7 @@ //! **Pitfall: variants aren't versions.** A kind's variants (a puzzle database's releases, the //! Strategic Test Suite's differently scored files) are different sources, told apart by //! [`Import::checksum`]; a node never converts one's scores to another's scale. -use crate::RequestMethod; +use crate::{NoParams, RequestMethod}; use serde::{Deserialize, Serialize}; /// Review identifier, in [`Capabilities::contract`]. Clients must check it before sending @@ -80,6 +82,10 @@ pub struct Capabilities { /// to a node that doesn't offer it. #[serde(default)] pub puzzle_filters: bool, + /// `knowledge/usage` and `knowledge/remove` are available. A client sends neither to a + /// node that doesn't offer it. + #[serde(default)] + pub space: bool, /// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like). #[serde(default)] pub kinds: Vec, @@ -349,6 +355,53 @@ impl RequestMethod for CancelImport { type Result = ImportResult; } +/// `knowledge/usage`'s result. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct UsageResult { + /// The bytes the node's knowledge takes on its disk, everything it keeps for it included. + pub bytes: u64, +} + +/// How much disk the node's knowledge takes, so a client can keep it within a limit. +pub enum KnowledgeUsage {} +impl RequestMethod for KnowledgeUsage { + const NAME: &'static str = "knowledge/usage"; + type Params = NoParams; + type Result = UsageResult; +} + +/// `knowledge/remove`'s params: the import's identity. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoveParams { + /// The kind of file. + pub kind: String, + /// The file's checksum. + pub checksum: String, +} + +/// `knowledge/remove`'s result. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoveResult { + /// The import as it was when the request came, now gone. + pub removed: Import, + /// [`UsageResult::bytes`] once its space is given back. + pub bytes: u64, +} + +/// Takes an import's knowledge out, and the import with it, and answers when it is gone and +/// its space given back to the disk. From the request on, reads and `knowledge/status` leave +/// the import out; a removal the node's stopping interrupts is finished when it starts again. +/// Only that import's knowledge goes: a position another import also has stays, and nothing of +/// the player's is touched. A running import is Busy (-32013), as is a second removal or an +/// import while one runs; an identity the node has no record of is [`NOT_FOUND`]. Importing the +/// same file later imports it afresh. +pub enum RemoveImport {} +impl RequestMethod for RemoveImport { + const NAME: &'static str = "knowledge/remove"; + type Params = RemoveParams; + type Result = RemoveResult; +} + /// One imported file, as a read names where its items came from. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] diff --git a/crates/cnp/tests/knowledge.rs b/crates/cnp/tests/knowledge.rs index aff67f6..2492de0 100644 --- a/crates/cnp/tests/knowledge.rs +++ b/crates/cnp/tests/knowledge.rs @@ -175,6 +175,10 @@ fn the_specs_json_examples_are_valid() { .unwrap() .validate() .unwrap(); + } else if value.get("removed").is_some() { + serde_json::from_value::(value).unwrap(); + } else if value.get("bytes").is_some() { + serde_json::from_value::(value).unwrap(); } else if value.get("import").is_some() { serde_json::from_value::(value).unwrap(); } else if value.get("imports").is_some() { @@ -523,3 +527,53 @@ fn facets_list_openings_only_when_the_node_has_them() { assert_eq!(some.openings[0].opening, "Italian_Game"); assert_eq!(some.openings[0].counts, [4]); } + +#[test] +fn the_space_capability_is_its_own_switch_and_older_nodes_lack_it() { + let offered: knowledge::Capabilities = + serde_json::from_value(json!({"import":true,"space":true,"contract":"draft-1"})).unwrap(); + assert!(offered.space); + let older: knowledge::Capabilities = + serde_json::from_value(json!({"import":true,"contract":"draft-1"})).unwrap(); + assert!(!older.space); + let written = serde_json::to_value(knowledge::Capabilities::default()).unwrap(); + assert_eq!(written["space"], json!(false)); +} + +#[test] +fn usage_takes_no_params_and_answers_bytes() { + let usage = Request::new::(4, &cnp::NoParams); + assert_eq!(usage.method, "knowledge/usage"); + let answer: knowledge::UsageResult = + serde_json::from_value(json!({"bytes": 3_279_056_896_u64})).unwrap(); + assert_eq!(answer.bytes, 3_279_056_896, "more than 32 bits"); + assert!(serde_json::from_value::(json!({"bytes": -1})).is_err()); +} + +#[test] +fn a_removal_names_an_identity_and_answers_the_import_it_removed() { + let remove = Request::new::( + 5, + &knowledge::RemoveParams { + kind: "lichess-puzzles".into(), + checksum: "a".repeat(64), + }, + ); + assert_eq!(remove.method, "knowledge/remove"); + assert_eq!( + serde_json::to_value(&remove.params).unwrap(), + json!({"kind":"lichess-puzzles","checksum":"a".repeat(64)}) + ); + let missing: Result = + serde_json::from_value(json!({"kind":"lichess-puzzles"})); + assert!(missing.is_err()); + let answer: knowledge::RemoveResult = serde_json::from_value(json!({ + "removed": {"kind":"lichess-puzzles","checksum":"a".repeat(64),"name":"Lichess puzzles", + "release":"2026-11-01","state":"complete","read":6193530,"accepted":6193530, + "rejected":0,"duplicate":0,"startedAt":"2026-11-14T10:05:00.000Z", + "finishedAt":"2026-11-14T10:55:00.000Z"}, + "bytes": 49_098_752})) + .unwrap(); + assert_eq!(answer.removed.accepted, 6_193_530); + assert_eq!(answer.bytes, 49_098_752); +} diff --git a/spec/knowledge.md b/spec/knowledge.md index 49bcc04..2827b73 100644 --- a/spec/knowledge.md +++ b/spec/knowledge.md @@ -22,14 +22,16 @@ the checksum the client says it has, so a damaged or swapped download is refused ```json {"capabilities": {"knowledge": {"import": true, "read": true, "puzzleSelection": true, - "puzzleFilters": true, "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], "contract": "draft-1"}}} + "puzzleFilters": true, "space": true, "kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], + "contract": "draft-1"}}} ``` `import` offers `knowledge/import`, `knowledge/status` and `knowledge/cancel`; `read` offers `knowledge/puzzles`, `knowledge/analyses` and `knowledge/exercises`; `puzzleSelection` offers `knowledge/puzzles`' `order`, `seed` and `quality`, and `knowledge/puzzleFacets`; `puzzleFilters` (which needs `puzzleSelection`) offers `knowledge/puzzles`' `opening` and -`daily`, and the `openings` of `knowledge/puzzleFacets`. A missing switch is false. `kinds` are the kinds of file the node can import; a request for another kind is +`daily`, and the `openings` of `knowledge/puzzleFacets`; `space` offers `knowledge/usage` and +`knowledge/remove`. A missing switch is false. `kinds` are the kinds of file the node can import; a request for another kind is refused. A client sends knowledge requests only to a node whose `contract` is `draft-1`. A node without the domain answers them with Method not found (-32601). @@ -162,6 +164,47 @@ with the import, `cancelled`. What it committed stays, and importing the file ag Cancelling an import that isn't running answers with its state unchanged; one the node has no record of is -32025. +## Space + +A client that downloads knowledge as the player needs it, a part at a time, keeps it within a +disk limit the player sets: it asks how much the knowledge takes, and removes what it no longer +wants, such as a whole database a smaller set replaces. The limit is the client's; the node +only reports and removes. + +### `knowledge/usage` + +No params. Answers with the bytes the node's knowledge takes on its disk, everything it keeps +for it included (indexes, journals, space it hasn't given back yet): + +```json +{"bytes": 49098752} +``` + +### `knowledge/remove` + +```json +{"kind": "lichess-puzzles", "checksum": "3f1c0d…9a"} +``` + +Takes an import's knowledge out, and the import with it. It answers when the knowledge is +gone and its space given back to the disk, with the import as it was and the bytes the +knowledge takes now: + +```json +{"removed": { ... an import ... }, "bytes": 49098752} +``` + +- **From the request on, the import is gone** to `knowledge/status` and to every read, even + before the answer. Removing a large import takes a while (minutes for millions of records + on a slow disk); the node answers other requests meanwhile, and a removal its stopping + interrupts is finished when it starts again. +- **Only that import's knowledge goes.** A position another import also has stays, with that + import's items. Nothing of the player's is touched: knowledge is never the player's data. +- An import that is `verifying` or `importing` is Busy (-32013): cancel it first. So is a + second removal, or an import, while one runs. An identity the node has no record of is + -32025, so removing twice answers -32025 the second time. +- Importing the same file later imports it afresh. + ## Reading Reads answer from **complete imports only**: a file that is half imported, cancelled or failed @@ -374,7 +417,7 @@ exercise names its `source`, and a client never mixes the points of two sources. | Error | Meaning | Client action | | --- | --- | --- | | -32602 | Invalid params: an unknown kind, or a malformed path, manifest, checksum, theme, rating, limit, cursor, FEN, order or quality, or a seed with any order but random | Correct the request | -| -32013 | Busy: another import is running | Wait for it, or cancel it | +| -32013 | Busy: an import or a removal is running, or the import to remove is | Wait for it, or cancel the import | | -32022 | Storage or I/O failed | Ask `knowledge/status` for the import's state | | -32025 | No import with that identity | List the imports | | -32027 | The file doesn't exist, isn't a file, or can't be read | Ask the player for the file again | @@ -383,11 +426,17 @@ exercise names its `source`, and a client never mixes the points of two sources. ## Not in draft 1 Several themes in one request (and excluding a theme), progress notifications in place of -polling, reading the records an import rejected, removing an import's knowledge, searching -puzzles by a position, and Lumbra's OTB games. +polling, reading the records an import rejected, removing part of an import's knowledge, +searching puzzles by a position, and Lumbra's OTB games. ## Changes +- **draft 1, 2026-11-17**, added to the draft: **space** (capability `space`, + `knowledge/usage` and `knowledge/remove`), so a client that downloads puzzles a part at a + time can keep the knowledge within a disk limit the player sets, and remove a whole database + a smaller set replaces (cjus/chessdb#48). All optional: a node that doesn't offer it, or a + client that doesn't send them, is unchanged. + - **draft 1, 2026-11-14**, added to the draft: **puzzle filters** (capability `puzzleFilters`, `knowledge/puzzles`' `opening` and `daily`, and `knowledge/puzzleFacets`' `openings`), so a client can offer puzzles of an opening and a puzzle of the day (cjus/chessgui#575). All