Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions conformance/knowledge/filters.jsonl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{"session":"knowledge-filters","description":"draft-1 knowledge, puzzle filters: an opening and the puzzle of the day filter puzzles, facets list openings, and a malformed opening is refused (spec/knowledge.md, Opening and daily)","requires":["knowledge.puzzleFilters"]}
{"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","read":true,"puzzleSelection":true,"puzzleFilters":true}}}}}
{"comment":"An opening nobody has and a daily request answer with puzzles of that kind, none or some, and the sources."}
{"send":{"jsonrpc":"2.0","id":2,"method":"knowledge/puzzles","params":{"opening":"No_Such_Opening_Anywhere","order":"random","limit":5}}}
{"expect":{"id":2,"result":{"puzzles":[],"sources":[],"seed":"$integer"}}}
{"send":{"jsonrpc":"2.0","id":3,"method":"knowledge/puzzles","params":{"daily":true,"order":"random","seed":20406,"limit":1}}}
{"expect":{"id":3,"result":{"puzzles":"$array","sources":"$array","seed":20406}}}
{"send":{"jsonrpc":"2.0","id":4,"method":"knowledge/puzzles","params":{"daily":false,"limit":1}}}
{"expect":{"id":4,"result":{"puzzles":"$array","sources":"$array"}}}
{"comment":"Facets list the openings in the same shape as the themes."}
{"send":{"jsonrpc":"2.0","id":5,"method":"knowledge/puzzleFacets"}}
{"expect":{"id":5,"result":{"bands":"$array","total":"$array","themes":"$array","openings":"$array","sources":"$array"}}}
{"comment":"Refused: an opening that isn't one."}
{"send":{"jsonrpc":"2.0","id":6,"method":"knowledge/puzzles","params":{"opening":"Sicilian Defense"}}}
{"expect":{"id":6,"error":{"code":-32602}}}
{"send":{"jsonrpc":"2.0","id":7,"method":"knowledge/puzzles","params":{"opening":""}}}
{"expect":{"id":7,"error":{"code":-32602}}}
{"send":{"jsonrpc":"2.0","id":8,"method":"shutdown"}}
{"expect":{"id":8,"result":null}}
{"send":{"jsonrpc":"2.0","method":"exit"}}
{"expectExit":0}
49 changes: 49 additions & 0 deletions crates/cnp/src/knowledge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,11 @@ pub struct Capabilities {
/// is available. A client sends none of them to a node that doesn't offer it.
#[serde(default)]
pub puzzle_selection: bool,
/// `knowledge/puzzles` takes `daily` and `opening`, and `knowledge/puzzleFacets` answers
/// with `openings`. Needs [`Capabilities::puzzle_selection`]. A client sends none of them
/// to a node that doesn't offer it.
#[serde(default)]
pub puzzle_filters: bool,
/// The kinds of file the node can import ([`KIND_LICHESS_PUZZLES`] and the like).
#[serde(default)]
pub kinds: Vec<String>,
Expand Down Expand Up @@ -367,6 +372,18 @@ pub fn valid_theme(text: &str) -> bool {
(1..=MAX_THEME_BYTES).contains(&text.len()) && text.bytes().all(|b| b.is_ascii_alphanumeric())
}

/// The longest an opening is, in bytes.
pub const MAX_OPENING_BYTES: usize = 128;

/// Whether `text` is an opening as the source writes it: 1 to [`MAX_OPENING_BYTES`] letters,
/// digits, underscores and hyphens, as Lichess's `Sicilian_Defense`.
pub fn valid_opening(text: &str) -> bool {
(1..=MAX_OPENING_BYTES).contains(&text.len())
&& text
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}

/// Checks a read's `limit`, `after` and `theme`, or says what is wrong.
fn valid_page(
limit: Option<u32>,
Expand Down Expand Up @@ -454,6 +471,14 @@ pub struct PuzzlesParams {
/// Only puzzles that pass this filter. Needs [`Capabilities::puzzle_selection`].
#[serde(skip_serializing_if = "Option::is_none")]
pub quality: Option<Quality>,
/// Only puzzles of this opening family, as the source writes it (`Sicilian_Defense`).
/// Needs [`Capabilities::puzzle_filters`].
#[serde(skip_serializing_if = "Option::is_none")]
pub opening: Option<String>,
/// Only puzzles that were the source's puzzle of the day. Needs
/// [`Capabilities::puzzle_filters`].
#[serde(skip_serializing_if = "Option::is_none")]
pub daily: Option<bool>,
}

/// [`PuzzlesParams`] as they are read, from an object or from nothing.
Expand All @@ -476,6 +501,10 @@ struct PuzzlesFields {
seed: Option<u32>,
#[serde(default)]
quality: Option<Quality>,
#[serde(default)]
opening: Option<String>,
#[serde(default)]
daily: Option<bool>,
}

impl From<Option<PuzzlesFields>> for PuzzlesParams {
Expand All @@ -490,6 +519,8 @@ impl From<Option<PuzzlesFields>> for PuzzlesParams {
order: f.order,
seed: f.seed,
quality: f.quality,
opening: f.opening,
daily: f.daily,
}
}
}
Expand All @@ -506,6 +537,11 @@ impl PuzzlesParams {
{
return Err("minRating is no more than maxRating".into());
}
if self.opening.as_ref().is_some_and(|o| !valid_opening(o)) {
return Err(format!(
"an opening is 1 to {MAX_OPENING_BYTES} letters, digits, underscores and hyphens"
));
}
Ok(())
}
}
Expand Down Expand Up @@ -615,6 +651,15 @@ pub struct ThemeCounts {
pub counts: Vec<u64>,
}

/// How many puzzles an opening family has in each [`Band`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OpeningCounts {
/// The opening family, as the source writes it.
pub opening: String,
/// One count for each band of [`FacetsResult::bands`], in its order.
pub counts: Vec<u64>,
}

/// `knowledge/puzzleFacets`' result.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct FacetsResult {
Expand All @@ -629,6 +674,10 @@ pub struct FacetsResult {
/// When a [`Quality`] filter was asked for: the thresholds it used.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub quality: Option<QualityThresholds>,
/// Each opening family that has at least one puzzle, with its counts. Only from a node
/// that offers [`Capabilities::puzzle_filters`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub openings: Vec<OpeningCounts>,
}

/// How many puzzles each theme has in each rating band, from complete imports.
Expand Down
64 changes: 63 additions & 1 deletion crates/cnp/tests/knowledge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ fn the_specs_json_examples_are_valid() {
} else if value.get("exercises").is_some() {
let r: knowledge::ExercisesResult = serde_json::from_value(value).unwrap();
assert_eq!(r.exercises[0].candidates[0].uci, "f4f5");
} else if value.get("minRating").is_some() {
} else if value.get("minRating").is_some() || value.get("daily").is_some() {
serde_json::from_value::<knowledge::PuzzlesParams>(value)
.unwrap()
.validate()
Expand Down Expand Up @@ -461,3 +461,65 @@ fn facets_params_may_be_left_out_and_the_answer_is_counts_by_band() {
json!({"minRating":1000})
);
}

#[test]
fn the_filters_capability_is_its_own_switch_and_older_nodes_lack_it() {
let c: knowledge::Capabilities =
serde_json::from_value(json!({"read":true,"puzzleSelection":true,"contract":"draft-1"}))
.unwrap();
assert!(c.puzzle_selection && !c.puzzle_filters);
let c: knowledge::Capabilities = serde_json::from_value(
json!({"read":true,"puzzleSelection":true,"puzzleFilters":true,"contract":"draft-1"}),
)
.unwrap();
assert!(c.puzzle_filters);
assert_eq!(
serde_json::to_value(&c).unwrap()["puzzleFilters"],
json!(true)
);
}

#[test]
fn an_opening_and_a_daily_filter_are_written_only_when_asked_for() {
let p: knowledge::PuzzlesParams = serde_json::from_value(
json!({"opening":"Sicilian_Defense","daily":true,"order":"random","limit":1}),
)
.unwrap();
assert_eq!(p.opening.as_deref(), Some("Sicilian_Defense"));
assert_eq!(p.daily, Some(true));
assert!(p.validate().is_ok());
let plain = knowledge::PuzzlesParams {
theme: Some("fork".into()),
..Default::default()
};
assert_eq!(
serde_json::to_value(&plain).unwrap(),
json!({"theme":"fork"})
);
for bad in ["", "Sicilian Defense", "Sicilian/Defense", &"a".repeat(129)] {
let p = knowledge::PuzzlesParams {
opening: Some(bad.to_string()),
..Default::default()
};
assert!(p.validate().is_err(), "{bad:?}");
}
assert!(knowledge::valid_opening("Queens_Gambit-Declined"));
}

#[test]
fn facets_list_openings_only_when_the_node_has_them() {
let none: knowledge::FacetsResult =
serde_json::from_value(json!({"bands":[],"total":[],"themes":[],"sources":[]})).unwrap();
assert!(none.openings.is_empty());
assert_eq!(
serde_json::to_value(&none).unwrap(),
json!({"bands":[],"total":[],"themes":[],"sources":[]})
);
let some: knowledge::FacetsResult = serde_json::from_value(json!({
"bands":[{"minRating":0}],"total":[9],"themes":[],"sources":[],
"openings":[{"opening":"Italian_Game","counts":[4]}]
}))
.unwrap();
assert_eq!(some.openings[0].opening, "Italian_Game");
assert_eq!(some.openings[0].counts, [4]);
}
46 changes: 40 additions & 6 deletions spec/knowledge.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,14 @@ the checksum the client says it has, so a damaged or swapped download is refused

```json
{"capabilities": {"knowledge": {"import": true, "read": true, "puzzleSelection": true,
"kinds": ["lichess-puzzles", "lichess-evals", "sts-epd"], "contract": "draft-1"}}}
"puzzleFilters": 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`. A missing
switch is false. `kinds` are the kinds of file the node can import; a request for another kind is
`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
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).

Expand Down Expand Up @@ -241,6 +242,30 @@ other node.
*reliable* meant. The answer has `quality` only when it was asked for. A client doesn't
assume one node's thresholds are another's.

#### Opening and daily

A node that offers `puzzleFilters` also takes two more optional fields, and a client sends them
to no other node.

```json
{"opening": "Sicilian_Defense", "minRating": 1200, "maxRating": 1599, "order": "random", "limit": 1}
```

```json
{"daily": true, "order": "random", "seed": 20406, "limit": 1}
```

- `opening` is an opening **family** as the source writes it (1–128 letters, digits, underscores
and hyphens, as Lichess's `Sicilian_Defense`). The family is the first of a puzzle's opening
tags, so a puzzle of `Sicilian_Defense Sicilian_Defense_Najdorf_Variation` is of
`Sicilian_Defense`, and one with no opening tag is of none. Anything else is -32602.
- `daily` is `true` for only the puzzles that were the source's puzzle of the day (Lichess's:
under two thousand of them), and absent or `false` for every puzzle. Lichess gives a date
to few puzzles, and the date of *today* is probably not among them, so a client that wants
one a day asks for `daily` with a `random` order and the date as the `seed` (the number of
days since 1970, say): everyone with the same imports gets the same puzzle that day.
- They combine with `theme`, the ratings, `quality` and `order` as the other filters do.

### `knowledge/puzzleFacets`

How many puzzles each theme has in each rating band: what a client needs to offer a choice of
Expand Down Expand Up @@ -271,6 +296,10 @@ illustrative counts):
`total` is every puzzle in the band, and a puzzle with several themes is counted under each
of them, so the themes' counts add up to more than `total`.
- A theme with no puzzle in any band is not listed. A band with none has a 0.
- A node that offers `puzzleFilters` also answers with `openings`, in the same shape as
`themes`: `[{"opening": "Italian_Game", "counts": [...]}]`, one count for each band, for
each opening family that has a puzzle (a puzzle with no opening tag is in none, so the counts
don't add up to `total`). Without `puzzleFilters` the field is absent.
- Counts are of the puzzles of **complete imports** and are the same as asking
`knowledge/puzzles` for that theme, band and quality would reach, which a node can keep as it
imports, not work out at each request. A client doesn't treat a count as current after a new
Expand Down Expand Up @@ -353,12 +382,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), choosing the puzzles of the day,
progress notifications in place of polling, reading the records an import rejected, removing
an import's knowledge, searching puzzles by opening or by a position, and Lumbra's OTB games.
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.

## Changes

- **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
optional: a node that doesn't offer it, or a request that doesn't send it, is unchanged.

- **draft 1, 2026-11-14**, added to the draft: **puzzle selection** (capability
`puzzleSelection`, `knowledge/puzzles`' `order`, `seed` and `quality`, and
`knowledge/puzzleFacets`), so a client can offer varied puzzles of a theme and rating band
Expand Down
Loading