From 7e55bb1fa94e80b66f986c9ee3bdd97bac477161 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 22 Nov 2026 22:10:50 -0600 Subject: [PATCH] feat(atlas-search): recommendation snapshot paging state machine (#10158) Implements slice C9139-01: pinned parent snapshot with materialized total order (score DESC, immutable recommendation ID ASC), per-page signed envelopes with their own EnvelopeId, cursors binding only the parent SnapshotId plus position, wrong-parent and expired-cursor rejection, and terminal done semantics. Identities are byte-identical to the fixture oracle in doc/2026-11-13T03-40-00Z_design_id-atlas-summit/part-c/. Supersedes the earlier unimplemented test sketch on this branch: that draft used placeholder envelope ids and a pluggable sign stub, so it could not verify the fixture vectors; the new test asserts the exact fixture parent snapshot id and page envelope ids. Refs #10158 --- .../worker/src/recommendation_state.ts | 311 ++++++++++++++++++ .../worker/test/recommendation_state.test.ts | 234 +++++++++++++ 2 files changed, 545 insertions(+) create mode 100644 pkgs/atlas-search/worker/src/recommendation_state.ts create mode 100644 pkgs/atlas-search/worker/test/recommendation_state.test.ts diff --git a/pkgs/atlas-search/worker/src/recommendation_state.ts b/pkgs/atlas-search/worker/src/recommendation_state.ts new file mode 100644 index 000000000..c74eb244b --- /dev/null +++ b/pkgs/atlas-search/worker/src/recommendation_state.ts @@ -0,0 +1,311 @@ +/** + * Recommendation snapshot paging state machine (developing-today/code#10158, + * slice C9139-01, V3 design §#9139 fanout and DO accumulator S6.4–S6.7, S6.15). + * + * At job start the parent snapshot inputs, ranking configuration and + * candidate cutoff are pinned; the total order is materialized once: + * score DESC, then immutable recommendation ID ASC. Later arrivals belong + * to the next snapshot and cannot reorder current pages. + * + * Identity rules (must stay byte-identical to the fixture oracle in + * `doc/2026-11-13T03-40-00Z_design_id-atlas-summit/part-c/`): + * - `ParentSnapshotId` is SHA-256 over the deterministic-CBOR encoding of + * the complete signed parent envelope. The parent preimage describes + * inputs/ranking/cutoff and excludes page EnvelopeIds (no hash cycle). + * - Each independently retained/transported page has its own signed + * envelope; its body binds `ParentSnapshotId`, page position and entries, + * and its `EnvelopeId` is SHA-256 over the complete signed page envelope + * including the signature bytes. + * - A cursor binds only the pinned parent ID plus position (and optional + * expiry), never a page ID. Restart/replay at the same parent and + * position returns the same page envelope bytes. + * - Wrong-parent and expired cursors reject. `done` is the terminal + * signal, computed independently of page emptiness: an empty page is + * terminal only when its position has consumed the whole order. + * + * Signature fields are deterministic fixture markers: this module performs + * no cryptographic signature verification and claims no production state, + * exactly as the oracle states. + */ + +export interface RecommendationCandidate { + id: string; + score_micros: number; + arrival_sequence: number; +} + +export interface ParentBody { + type: string; + tenant: string; + algorithm: string; + cutoff_sequence: number; + page_size: number; + input_digest: string; + candidate_set: RecommendationCandidate[]; +} + +export interface ParentEnvelope { + body: ParentBody; + /** Raw signature bytes (fixture markers; not verified). */ + signature: Uint8Array; +} + +export interface PageEntry { + id: string; + score_micros: number; + arrival_sequence: number; +} + +export interface PageBody { + parent_snapshot_id: string; + position: number; + entries: PageEntry[]; + done: boolean; +} + +export interface PageEnvelope { + body: PageBody; + /** Raw signature bytes (fixture markers; not verified). */ + signature: Uint8Array; +} + +export interface PageCursor { + parent_snapshot_id: string; + position: number; + /** Unix epoch milliseconds; absent cursors never expire. */ + expires_at?: number; +} + +/** A pinned snapshot: parent identity plus its materialized total order. */ +export interface RecommendationSnapshot { + parent: ParentEnvelope; + parent_snapshot_id: string; + ordered: PageEntry[]; + page_size: number; +} + +export class WrongParentSnapshotIdError extends Error { + readonly code = "WrongParentSnapshotId"; + constructor() { + super("WrongParentSnapshotId"); + this.name = "WrongParentSnapshotIdError"; + } +} + +export class CursorExpiredError extends Error { + readonly code = "CursorExpired"; + constructor() { + super("CursorExpired"); + this.name = "CursorExpiredError"; + } +} + +export class InvalidPagePositionError extends Error { + readonly code = "InvalidPagePosition"; + constructor(position: number) { + super(`InvalidPagePosition: ${position}`); + this.name = "InvalidPagePositionError"; + } +} + +/** Decode a lowercase hex string to bytes. */ +export function hexToBytes(hex: string): Uint8Array { + if (hex.length % 2 !== 0) throw new Error("hex string must have even length"); + const out = new Uint8Array(hex.length / 2); + for (let i = 0; i < out.length; i++) { + out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16); + } + return out; +} + +// --- Deterministic CBOR subset (mirrors recommendation-page-oracle.py) --- + +type CborValue = + | boolean + | number + | Uint8Array + | string + | CborValue[] + | { [key: string]: CborValue }; + +function cborHead(major: number, value: number): Uint8Array { + if (value < 24) return new Uint8Array([(major << 5) | value]); + if (value < 256) return new Uint8Array([(major << 5) | 24, value]); + if (value < 65536) { + return new Uint8Array([(major << 5) | 25, value >> 8, value & 0xff]); + } + if (value < 2 ** 32) { + return new Uint8Array([ + (major << 5) | 26, + (value >>> 24) & 0xff, + (value >>> 16) & 0xff, + (value >>> 8) & 0xff, + value & 0xff, + ]); + } + const hi = Math.floor(value / 2 ** 32); + const lo = value >>> 0; + return new Uint8Array([ + (major << 5) | 27, + (hi >>> 24) & 0xff, + (hi >>> 16) & 0xff, + (hi >>> 8) & 0xff, + hi & 0xff, + (lo >>> 24) & 0xff, + (lo >>> 16) & 0xff, + (lo >>> 8) & 0xff, + lo & 0xff, + ]); +} + +function concat(parts: Uint8Array[]): Uint8Array { + const total = parts.reduce((n, p) => n + p.length, 0); + const out = new Uint8Array(total); + let at = 0; + for (const p of parts) { + out.set(p, at); + at += p.length; + } + return out; +} + +function compareBytes(a: Uint8Array, b: Uint8Array): number { + const n = Math.min(a.length, b.length); + for (let i = 0; i < n; i++) { + if (a[i] !== b[i]) return a[i] - b[i]; + } + return a.length - b.length; +} + +/** + * Deterministic CBOR encoding for the fixture subset. Map keys sort by + * (encoded-key length, encoded-key bytes), exactly as the oracle does. + */ +export function deterministicCbor(value: CborValue): Uint8Array { + if (typeof value === "boolean") return new Uint8Array([value ? 0xf5 : 0xf4]); + if (typeof value === "number") { + if (!Number.isInteger(value)) throw new Error("CBOR subset supports integers only"); + return value >= 0 ? cborHead(0, value) : cborHead(1, -1 - value); + } + if (value instanceof Uint8Array) { + return concat([cborHead(2, value.length), value]); + } + if (typeof value === "string") { + const data = new TextEncoder().encode(value); + return concat([cborHead(3, data.length), data]); + } + if (Array.isArray(value)) { + return concat([cborHead(4, value.length), ...value.map(deterministicCbor)]); + } + const entries = Object.entries(value).map(([k, v]) => { + const ek = deterministicCbor(k); + return { ek, ev: deterministicCbor(v) }; + }); + entries.sort((a, b) => a.ek.length - b.ek.length || compareBytes(a.ek, b.ek)); + return concat([ + cborHead(5, entries.length), + ...entries.flatMap(({ ek, ev }) => [ek, ev]), + ]); +} + +/** `sha256:` + hex(SHA-256(deterministic-CBOR(value))). */ +export async function digestId(value: CborValue): Promise { + const digest = await crypto.subtle.digest("SHA-256", deterministicCbor(value)); + return ( + "sha256:" + + [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("") + ); +} + +// --- Snapshot / paging state machine --- + +function envelopeValue(envelope: { body: unknown; signature: Uint8Array }): CborValue { + return { body: envelope.body as CborValue, signature: envelope.signature }; +} + +/** SHA-256 identity of the complete signed parent envelope. */ +export async function parentSnapshotId(parent: ParentEnvelope): Promise { + return digestId(envelopeValue(parent)); +} + +/** SHA-256 identity of the complete signed page envelope. */ +export async function pageEnvelopeId(page: PageEnvelope): Promise { + return digestId(envelopeValue(page)); +} + +/** + * Pin the parent snapshot: materialize the total order once (score DESC, + * then immutable recommendation ID ASC) over candidates at or before the + * cutoff. Later arrivals are excluded; they belong to the next snapshot. + */ +export async function createSnapshot(parent: ParentEnvelope): Promise { + const body = parent.body; + const ordered = body.candidate_set + .filter((c) => c.arrival_sequence <= body.cutoff_sequence) + .map((c) => ({ id: c.id, score_micros: c.score_micros, arrival_sequence: c.arrival_sequence })) + .sort((a, b) => b.score_micros - a.score_micros || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); + return { + parent, + parent_snapshot_id: await parentSnapshotId(parent), + ordered, + page_size: body.page_size, + }; +} + +/** + * Materialize the page at `position` in the pinned order. Positions must + * be a multiple of the page size within [0, total]; anything else is an + * `InvalidPagePositionError`. `done` is true exactly when this page + * consumes the whole order (empty pages at the boundary are terminal). + */ +export async function makePage( + snapshot: RecommendationSnapshot, + position: number, + signatureHex: string, +): Promise<{ envelope: PageEnvelope; envelope_id: string }> { + const total = snapshot.ordered.length; + if (position < 0 || position > total || position % snapshot.page_size !== 0) { + throw new InvalidPagePositionError(position); + } + const entries = snapshot.ordered.slice(position, position + snapshot.page_size); + const envelope: PageEnvelope = { + body: { + parent_snapshot_id: snapshot.parent_snapshot_id, + position, + entries, + done: position + entries.length >= total, + }, + signature: hexToBytes(signatureHex), + }; + return { envelope, envelope_id: await pageEnvelopeId(envelope) }; +} + +/** + * Replay a page from a cursor. The cursor binds only the pinned parent + * ID plus position. A wrong parent rejects with + * `WrongParentSnapshotIdError`; an expired cursor rejects with + * `CursorExpiredError` and is never applied. Replay at the same parent + * and position returns the same page envelope. + */ +export async function pageFromCursor( + snapshot: RecommendationSnapshot, + cursor: PageCursor, + signatureHex: string, + nowMs: number = Date.now(), +): Promise<{ envelope: PageEnvelope; envelope_id: string }> { + if (cursor.parent_snapshot_id !== snapshot.parent_snapshot_id) { + throw new WrongParentSnapshotIdError(); + } + if (cursor.expires_at !== undefined && nowMs >= cursor.expires_at) { + throw new CursorExpiredError(); + } + return makePage(snapshot, cursor.position, signatureHex); +} + +/** The cursor following a page: same parent, position advanced by entries. */ +export function nextCursor(page: PageEnvelope): PageCursor { + return { + parent_snapshot_id: page.body.parent_snapshot_id, + position: page.body.position + page.body.entries.length, + }; +} diff --git a/pkgs/atlas-search/worker/test/recommendation_state.test.ts b/pkgs/atlas-search/worker/test/recommendation_state.test.ts new file mode 100644 index 000000000..b0a99f3b6 --- /dev/null +++ b/pkgs/atlas-search/worker/test/recommendation_state.test.ts @@ -0,0 +1,234 @@ +/** + * Tests for the recommendation snapshot paging state machine (#10158, + * slice C9139-01). + * + * Oracle: `doc/2026-11-13T03-40-00Z_design_id-atlas-summit/part-c/ + * recommendation-page-fixture.json`, as recomputed by + * `recommendation-page-oracle.py` (expected output in + * `recommendation-page-oracle-output.txt`). The fixture values below are + * copied verbatim from that fixture; a drift in ordering, identity, + * cursor binding or envelope bytes fails here. + */ +import { describe, expect, it } from "vitest"; +import { + createSnapshot, + CursorExpiredError, + hexToBytes, + InvalidPagePositionError, + makePage, + nextCursor, + pageFromCursor, + WrongParentSnapshotIdError, + type PageEnvelope, + type ParentEnvelope, +} from "../src/recommendation_state"; + +// Fixture: synthetic-recommendation-page/v1 (verbatim from the fixture file). +const PARENT: ParentEnvelope = { + body: { + type: "recommendation-parent-v1", + tenant: "tenant-a", + algorithm: "score-desc-id-asc-v1", + cutoff_sequence: 7, + page_size: 2, + input_digest: "sha256:synthetic-input-set-7", + candidate_set: [ + { id: "rec-b", score_micros: 900, arrival_sequence: 5 }, + { id: "rec-c", score_micros: 700, arrival_sequence: 7 }, + { id: "rec-a", score_micros: 900, arrival_sequence: 4 }, + ], + }, + signature: hexToBytes("746573742d706172656e742d7369676e6174757265"), +}; +const PAGE_0_SIGNATURE_HEX = "746573742d706167652d30"; +const PAGE_2_SIGNATURE_HEX = "746573742d706167652d32"; +const EXPECTED_PARENT_SNAPSHOT_ID = + "sha256:8797b6bd7f4821dfb8273ee23cad9dacd50e9361b06d8a4e686f2515b8cf5c91"; +const EXPECTED_PAGE_0_ENVELOPE_ID = + "sha256:e67e1aa7ad2343411ec8019ec1bef037ee0c8e8d27d01f305df641a2d957fc7d"; +const EXPECTED_PAGE_2_ENVELOPE_ID = + "sha256:50edb5f8e6dfb49b16580b44dffd8932998f4f21bee6836a951698f01c2de0a2"; + +async function fixtureSnapshot() { + return createSnapshot(PARENT); +} + +describe("recommendation snapshot paging (oracle: recommendation-page-fixture)", () => { + it("derives the fixture parent snapshot id", async () => { + const snapshot = await fixtureSnapshot(); + expect(snapshot.parent_snapshot_id).toBe(EXPECTED_PARENT_SNAPSHOT_ID); + }); + + it("materializes score DESC then immutable id ASC, excluding post-cutoff arrivals", async () => { + const snapshot = await fixtureSnapshot(); + // Equal score 900: rec-a before rec-b (id ASC). rec-aa (arrival 8, + // score 999) is past the cutoff of 7 and belongs to the next snapshot. + expect(snapshot.ordered.map((c) => c.id)).toEqual(["rec-a", "rec-b", "rec-c"]); + expect(snapshot.ordered.map((c) => c.id)).not.toContain("rec-aa"); + }); + + it("page 0 reproduces the exact fixture envelope id, order and done=false", async () => { + const snapshot = await fixtureSnapshot(); + const { envelope, envelope_id } = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + expect(envelope_id).toBe(EXPECTED_PAGE_0_ENVELOPE_ID); + expect(envelope.body.entries.map((e) => e.id)).toEqual(["rec-a", "rec-b"]); + expect(envelope.body.done).toBe(false); + expect(envelope.body.parent_snapshot_id).toBe(EXPECTED_PARENT_SNAPSHOT_ID); + expect(envelope.body.position).toBe(0); + }); + + it("page 2 reproduces the exact fixture envelope id, order and terminal done=true", async () => { + const snapshot = await fixtureSnapshot(); + const { envelope, envelope_id } = await makePage(snapshot, 2, PAGE_2_SIGNATURE_HEX); + expect(envelope_id).toBe(EXPECTED_PAGE_2_ENVELOPE_ID); + expect(envelope.body.entries.map((e) => e.id)).toEqual(["rec-c"]); + expect(envelope.body.done).toBe(true); + }); + + it("advances the cursor to the fixture expected next cursor", async () => { + const snapshot = await fixtureSnapshot(); + const { envelope } = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + expect(nextCursor(envelope)).toEqual({ + parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, + position: 2, + }); + }); + + it("restart/replay at the same parent and position returns the same page envelope", async () => { + const snapshot = await fixtureSnapshot(); + const first = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + const replayed = await pageFromCursor( + snapshot, + { parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, position: 0 }, + PAGE_0_SIGNATURE_HEX, + ); + expect(replayed.envelope_id).toBe(first.envelope_id); + expect(replayed.envelope_id).toBe(EXPECTED_PAGE_0_ENVELOPE_ID); + expect(replayed.envelope).toEqual(first.envelope); + // Duplicate replay is idempotent: same cursor again, same bytes. + const again = await pageFromCursor( + snapshot, + { parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, position: 0 }, + PAGE_0_SIGNATURE_HEX, + ); + expect(again.envelope).toEqual(first.envelope); + }); + + it("rejects a wrong-parent cursor", async () => { + const snapshot = await fixtureSnapshot(); + await expect( + pageFromCursor( + snapshot, + { + parent_snapshot_id: + "sha256:0000000000000000000000000000000000000000000000000000000000000000", + position: 0, + }, + PAGE_0_SIGNATURE_HEX, + ), + ).rejects.toBeInstanceOf(WrongParentSnapshotIdError); + }); + + it("rejects an expired cursor and accepts an unexpired one", async () => { + const snapshot = await fixtureSnapshot(); + const now = 1_800_000_000_000; + await expect( + pageFromCursor( + snapshot, + { parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, position: 0, expires_at: now }, + PAGE_0_SIGNATURE_HEX, + now, + ), + ).rejects.toBeInstanceOf(CursorExpiredError); + const ok = await pageFromCursor( + snapshot, + { + parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, + position: 0, + expires_at: now + 60_000, + }, + PAGE_0_SIGNATURE_HEX, + now, + ); + expect(ok.envelope_id).toBe(EXPECTED_PAGE_0_ENVELOPE_ID); + }); + + it("rejects invalid page positions", async () => { + const snapshot = await fixtureSnapshot(); + for (const position of [-1, 1, 3, 4]) { + await expect(makePage(snapshot, position, PAGE_0_SIGNATURE_HEX)).rejects.toBeInstanceOf( + InvalidPagePositionError, + ); + } + }); + + it("an empty snapshot yields an empty terminal page (done is the terminal signal, not emptiness)", async () => { + const empty: ParentEnvelope = { + body: { ...PARENT.body, candidate_set: [] }, + signature: PARENT.signature, + }; + const snapshot = await createSnapshot(empty); + const { envelope } = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + expect(envelope.body.entries).toEqual([]); + expect(envelope.body.done).toBe(true); + }); + + it("a page at the exact end boundary is empty and terminal", async () => { + const two: ParentEnvelope = { + body: { + ...PARENT.body, + candidate_set: [ + { id: "rec-a", score_micros: 900, arrival_sequence: 4 }, + { id: "rec-b", score_micros: 900, arrival_sequence: 5 }, + ], + }, + signature: PARENT.signature, + }; + const snapshot = await createSnapshot(two); + const first = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + expect(first.envelope.body.done).toBe(true); + const boundary = await makePage(snapshot, 2, PAGE_2_SIGNATURE_HEX); + expect(boundary.envelope.body.entries).toEqual([]); + expect(boundary.envelope.body.done).toBe(true); + expect(nextCursor(boundary.envelope)).toEqual({ + parent_snapshot_id: snapshot.parent_snapshot_id, + position: 2, + }); + }); + + it("page envelope ids differ across pages and across parents", async () => { + const snapshot = await fixtureSnapshot(); + const p0 = await makePage(snapshot, 0, PAGE_0_SIGNATURE_HEX); + const p2 = await makePage(snapshot, 2, PAGE_2_SIGNATURE_HEX); + expect(p0.envelope_id).not.toBe(p2.envelope_id); + const other: ParentEnvelope = { + body: { ...PARENT.body, tenant: "tenant-b" }, + signature: PARENT.signature, + }; + const otherSnapshot = await createSnapshot(other); + expect(otherSnapshot.parent_snapshot_id).not.toBe(EXPECTED_PARENT_SNAPSHOT_ID); + const otherPage = await makePage(otherSnapshot, 0, PAGE_0_SIGNATURE_HEX); + expect(otherPage.envelope_id).not.toBe(p0.envelope_id); + }); + + it("keeps the parent preimage free of page ids (no hash cycle)", async () => { + const snapshot = await fixtureSnapshot(); + const body = snapshot.parent.body as unknown as Record; + expect(body).not.toHaveProperty("pages"); + expect(body).not.toHaveProperty("page_envelope_ids"); + expect(body).not.toHaveProperty("page_ids"); + }); + + it("exposes the page body type for consumers", () => { + const envelope: PageEnvelope = { + body: { + parent_snapshot_id: EXPECTED_PARENT_SNAPSHOT_ID, + position: 0, + entries: [], + done: true, + }, + signature: new Uint8Array(), + }; + expect(envelope.body.done).toBe(true); + }); +});