From 707b92a46ebd428acaf484f6f8cbecedcf00d128 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 12:14:33 -0600 Subject: [PATCH] feat(atlas): evaluate scoped session co-occurrence candidates offline (#13590) --- .../atlas-search/book/reference/atlas-eval.md | 14 +++ .../eval/fixtures/session-cooccurrence.json | 13 ++ .../atlas-search/eval/session_cooccurrence.py | 119 ++++++++++++++++++ .../eval/test_session_cooccurrence.py | 69 ++++++++++ 4 files changed, 215 insertions(+) create mode 100644 pkgs/atlas-search/eval/fixtures/session-cooccurrence.json create mode 100644 pkgs/atlas-search/eval/session_cooccurrence.py create mode 100644 pkgs/atlas-search/eval/test_session_cooccurrence.py diff --git a/pkgs/atlas-search/book/reference/atlas-eval.md b/pkgs/atlas-search/book/reference/atlas-eval.md index 79ae8f00c7..b11c745cd7 100644 --- a/pkgs/atlas-search/book/reference/atlas-eval.md +++ b/pkgs/atlas-search/book/reference/atlas-eval.md @@ -95,3 +95,17 @@ The report's per-signal means carry the four metrics above — `ndcg10`, `recall | 0 | Success: the report for the requested split was printed to stdout. | | 1 | Runtime failure: unreadable input file, invalid evaluation data, or an evaluation failure. | | 2 | Usage failure: wrong arity (including `--help`/`-h`/`help`) or an unknown split value. | + +## Offline single-user recommendation candidates + +The Python experiment in `eval/session_cooccurrence.py` evaluates the session co-occurrence signal from [#9140](https://github.com/developing-today/code/issues/9140). From the repository root, run the synthetic fixture with: + +```sh +python3 pkgs/atlas-search/eval/session_cooccurrence.py pkgs/atlas-search/eval/fixtures/session-cooccurrence.json -k 2 +``` + +The fixture uses `atlas-recommendation-eval/v1`. One subject has an explicit list of eligible session and item references, a chronological cutoff, and sessions with inclusive integer start/end positions and ordered item opens. References must have a common stable namespace and opens must follow event order. Eligibility comes from the evaluation fixture or a trusted upstream projection that resolves current access and tombstones. The evaluator admits matching subjects and sessions and removes ineligible items before any split or pair count. It discards sessions spanning the cutoff. The CLI reports aggregate counts and metrics. + +Training uses sessions ending at or before the cutoff. Each distinct seed/candidate pair contributes once per training session. Candidates accumulate votes across distinct seeds, omit seeds, and break ties by item reference ascending. Each later session with at least two eligible, distinct opens provides a test case. The first half (rounded down) supplies seeds and the remainder supplies binary relevance. Repeated opens use their first position. Precision and recall use pooled counts, while reciprocal rank and normalized discounted gain use session means. An unseen seed counts as a miss. With no scorable sessions the metrics are null. The fixture hand-counts one hit across two scorable sessions at depth two. + +A live experiment needs a trusted session-to-query join, stable item resolution and an eligibility projection current at evaluation time. The current trace writer in `crates/atlas-core/src/trace.rs` emits a requester and query ID and leaves file/content identity fields null. Feedback in `crates/atlas-core/src/feedback.rs` attaches the opened signal to a query and chunk. The synthetic fixture tests the algorithm only. The package has no production recommendation route from this experiment. diff --git a/pkgs/atlas-search/eval/fixtures/session-cooccurrence.json b/pkgs/atlas-search/eval/fixtures/session-cooccurrence.json new file mode 100644 index 0000000000..db8557b2ff --- /dev/null +++ b/pkgs/atlas-search/eval/fixtures/session-cooccurrence.json @@ -0,0 +1,13 @@ +{ + "schema": "atlas-recommendation-eval/v1", + "subject": "reader", + "cutoff": 10, + "eligible_sessions": ["early-a", "early-b", "test", "no-overlap"], + "eligible_items": ["anchor", "bridge", "companion", "novel"], + "sessions": [ + {"subject": "reader", "id": "early-a", "start": 1, "end": 4, "opens": ["anchor", "bridge", "bridge"]}, + {"subject": "reader", "id": "early-b", "start": 5, "end": 10, "opens": ["anchor", "companion"]}, + {"subject": "reader", "id": "test", "start": 11, "end": 12, "opens": ["anchor", "bridge"]}, + {"subject": "reader", "id": "no-overlap", "start": 13, "end": 14, "opens": ["novel", "companion"]} + ] +} diff --git a/pkgs/atlas-search/eval/session_cooccurrence.py b/pkgs/atlas-search/eval/session_cooccurrence.py new file mode 100644 index 0000000000..4ae5a938d2 --- /dev/null +++ b/pkgs/atlas-search/eval/session_cooccurrence.py @@ -0,0 +1,119 @@ +"""Offline single-subject item candidates and temporal held-out evaluation.""" + +import argparse +from collections import Counter, defaultdict +import json +from math import log2 + + +def reference(value): + if not isinstance(value, str) or not value.strip(): + raise ValueError("expected a nonempty opaque reference") + return value + + +def reference_set(values): + if not isinstance(values, list): + raise ValueError("expected a reference list") + return {reference(value) for value in values} + + +def partitions(data): + if data["schema"] != "atlas-recommendation-eval/v1": + raise ValueError("unsupported evaluation schema") + subject = reference(data["subject"]) + allowed_sessions = reference_set(data["eligible_sessions"]) + allowed_items = reference_set(data["eligible_items"]) + cutoff = data["cutoff"] + if type(cutoff) is not int or not isinstance(data["sessions"], list): + raise ValueError("expected integer cutoff and sessions array") + + train, held_out = [], [] + seen = set() + for session in data["sessions"]: + if session["subject"] != subject or session["id"] not in allowed_sessions: + continue + if session["id"] in seen: + raise ValueError("duplicate scoped session") + seen.add(session["id"]) + start, end = session["start"], session["end"] + if type(start) is not int or type(end) is not int or start > end: + raise ValueError("invalid session interval") + if start <= cutoff < end: + continue + if not isinstance(session["opens"], list): + raise ValueError("expected ordered opens") + opens = dict.fromkeys(item for item in session["opens"] if reference(item) in allowed_items) + if end <= cutoff: + train.append(tuple(opens)) + else: + held_out.append(tuple(opens)) + return train, held_out + + +def index_sessions(sessions): + index = defaultdict(list) + for session in sessions: + items = frozenset(session) + for item in items: + index[item].append(items) + return index + + +def candidates(index, seeds, k): + """One vote per training session and distinct seed/candidate pair.""" + scores = Counter() + seen = set(seeds) + for seed in seen: + for session in index.get(seed, ()): + scores.update(session - seen) + return sorted(scores, key=lambda item: (-scores[item], item))[:k] + + +def evaluate(data, k): + if type(k) is not int or k <= 0: + raise ValueError("k must be a positive integer") + train, held_out = partitions(data) + index = index_sessions(train) + scored = hits = relevant = 0 + reciprocal_ranks = ndcg = 0.0 + for session in held_out: + if len(session) < 2: + continue + half = len(session) // 2 + targets = set(session[half:]) + ranking = candidates(index, session[:half], k) + ranks = [i for i, item in enumerate(ranking, 1) if item in targets] + scored += 1 + hits += len(ranks) + relevant += len(targets) + if ranks: + reciprocal_ranks += 1 / ranks[0] + dcg = sum(1 / log2(rank + 1) for rank in ranks) + ideal = sum(1 / log2(rank + 1) for rank in range(1, min(k, len(targets)) + 1)) + ndcg += dcg / ideal + return { + "k": k, "training_sessions": len(train), "held_out_sessions": len(held_out), + "scored_sessions": scored, "hits": hits, "held_out_items": relevant, + "precision_at_k": hits / (scored * k) if scored else None, + "recall_at_k": hits / relevant if relevant else None, + "mrr_at_k": reciprocal_ranks / scored if scored else None, + "ndcg_at_k": ndcg / scored if scored else None, + } + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("fixture", type=argparse.FileType("r", encoding="utf-8")) + parser.add_argument("-k", type=int, default=10) + args = parser.parse_args() + try: + with args.fixture as stream: + result = evaluate(json.load(stream), args.k) + except (KeyError, ValueError, TypeError) as error: + parser.exit(2, f"invalid evaluation input ({type(error).__name__})\n") + print(json.dumps(result, sort_keys=True)) + + +if __name__ == "__main__": + main() diff --git a/pkgs/atlas-search/eval/test_session_cooccurrence.py b/pkgs/atlas-search/eval/test_session_cooccurrence.py new file mode 100644 index 0000000000..54a0aa9b41 --- /dev/null +++ b/pkgs/atlas-search/eval/test_session_cooccurrence.py @@ -0,0 +1,69 @@ +"""Oracles use explicit session sets, chronological halves and hand-counted pairs.""" + +import json +from pathlib import Path +import unittest + +from session_cooccurrence import candidates, evaluate, index_sessions, partitions + + +def fixture(): + path = Path(__file__).with_name("fixtures") / "session-cooccurrence.json" + return json.loads(path.read_text(encoding="utf-8")) + + +class SessionCooccurrenceTests(unittest.TestCase): + def test_hand_counted_tie_and_cold_start(self): + report = evaluate(fixture(), 2) + self.assertEqual(report["scored_sessions"], 2) + self.assertEqual(report["hits"], 1) + self.assertEqual(report["held_out_items"], 2) + self.assertEqual(report["precision_at_k"], 0.25) + self.assertEqual(report["recall_at_k"], 0.5) + self.assertEqual(report["mrr_at_k"], 0.5) + self.assertEqual(report["ndcg_at_k"], 0.5) + + def test_retired_foreign_and_cross_cutoff_cannot_change_candidates_or_metrics(self): + data = fixture() + original = evaluate(data, 2) + data["eligible_sessions"] += ["crossing", "another"] + for sid, owner, start, end in [ + ("retired", "reader", 1, 2), + ("crossing", "reader", 2, 14), + ("another", "different-reader", 1, 2), + ]: + data["sessions"].append(dict(id=sid, subject=owner, start=start, end=end, + opens=["anchor", "companion", "novel"])) + for session in data["sessions"]: + session["opens"].insert(0, "retired-item") + self.assertEqual(original, evaluate(data, 2)) + train, _ = partitions(data) + self.assertEqual(candidates(index_sessions(train), ["anchor"], 3), ["bridge", "companion"]) + + def test_deduplicates_before_scoring_and_splitting(self): + data = fixture() + data["sessions"][2]["opens"] = ["anchor", "anchor", "bridge", "anchor"] + self.assertEqual(evaluate(data, 2), evaluate(fixture(), 2)) + index = index_sessions([["a", "x", "x", "y"], ["a", "y"], ["b", "x"]]) + self.assertEqual(candidates(index, ["a", "a"], 2), ["y", "x"]) + self.assertEqual(candidates(index, ["a", "b"], 2), ["x", "y"]) + + def test_held_out_sessions_never_train_the_graph(self): + data = fixture() + data["sessions"] = data["sessions"][2:] + report = evaluate(data, 2) + self.assertEqual((report["training_sessions"], report["hits"], report["mrr_at_k"]), (0, 0, 0)) + + def test_empty_scope_and_ambiguous_input(self): + data = fixture() + data["eligible_items"] = [] + self.assertIsNone(evaluate(data, 2)["ndcg_at_k"]) + data["sessions"].append(data["sessions"][0]) + with self.assertRaises(ValueError): + evaluate(data, 2) + with self.assertRaises(ValueError): + evaluate(fixture(), 0) + + +if __name__ == "__main__": + unittest.main()