From 01d0fafbda5e5920bff332a6c2b50bac905540ae Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Fri, 13 Nov 2026 23:01:27 -0600 Subject: [PATCH 1/4] test(core): retain decision data through delivery recovery A host-produced result must reach the sink unchanged after a failed attempt or runner restart, and remain available as recent context. --- python/tests/test_decision_data.py | 91 ++++++++++++++++++++++++++ test/decision-data.test.ts | 100 +++++++++++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 python/tests/test_decision_data.py create mode 100644 test/decision-data.test.ts diff --git a/python/tests/test_decision_data.py b/python/tests/test_decision_data.py new file mode 100644 index 0000000..8e92561 --- /dev/null +++ b/python/tests/test_decision_data.py @@ -0,0 +1,91 @@ +import asyncio +from copy import deepcopy + +import pytest + +from aqi_attend import AbortSignal, Decision, JudgeInput, Judgment, create_attend +from aqi_attend.core.types import JsonValue +from aqi_attend.store.memory import memory_store +from aqi_attend.testing import fake_clock, recording_sink + + +async def test_data_survives_failed_delivery_and_retained_store_restart() -> None: + clock = fake_clock() + store = memory_store() + data: dict[str, JsonValue] = {"revision": 7, "tags": ["alpha"]} + attempts: list[Decision] = [] + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + return {"route": "note", "data": data} + + async def fail(decision: Decision, signal: AbortSignal) -> None: + attempts.append(deepcopy(decision)) + delivered = decision.get("data") + if isinstance(delivered, dict): + delivered["revision"] = 99 + raise RuntimeError("retry") + + first = create_attend(clock=clock, store=store, kind={"change": "closing"}, settle={"closing_grace_ms": 1, "retry_backoff_ms": [10]}, judge=judge, sink=fail) + first_run = asyncio.create_task(first.run()) + try: + await first.push("scope", {"id": "a", "name": "change", "at": 0, "data": {}}) + await clock.advance(1) + assert len(attempts) == 1 + assert attempts[0].get("data") == {"revision": 7, "tags": ["alpha"]} + data["tags"] = ["changed after judgment"] + record = await first.inspect("scope") + assert record is not None + assert record["recent"][0].get("data") == {"revision": 7, "tags": ["alpha"]} + finally: + await first.stop() + await first_run + + sink = recording_sink() + recent: list[JsonValue] = [] + + async def later(input: JudgeInput, signal: AbortSignal) -> Judgment: + prior = input["recent"][0].get("data") + recent.append(deepcopy(prior)) + if isinstance(prior, dict): + prior["revision"] = 100 + return {"route": "note"} + + second = create_attend(clock=clock, store=store, kind={"change": "closing"}, settle={"closing_grace_ms": 1, "retry_backoff_ms": [10]}, judge=later, sink=sink) + second_run = asyncio.create_task(second.run()) + try: + await clock.advance(10) + assert len(sink.delivered) == 1 + assert sink.delivered[0]["id"] == attempts[0]["id"] + assert sink.delivered[0].get("data") == {"revision": 7, "tags": ["alpha"]} + await second.push("scope", {"id": "b", "name": "change", "at": 10, "data": {}}) + await clock.advance(1) + assert recent == [{"revision": 7, "tags": ["alpha"]}] + record = await second.inspect("scope") + assert record is not None + assert record["recent"][0].get("data") == {"revision": 7, "tags": ["alpha"]} + finally: + await second.stop() + await second_run + assert clock.next_at() is None + + +@pytest.mark.parametrize("data", [None, False, 0, "", [], {}]) +async def test_explicit_json_data(data: JsonValue) -> None: + clock = fake_clock() + sink = recording_sink() + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + return {"route": "note", "data": data} + + attend = create_attend(clock=clock, kind={"change": "closing"}, settle={"closing_grace_ms": 1}, sink=sink, judge=judge) + running = asyncio.create_task(attend.run()) + try: + await attend.push("scope", {"id": "a", "name": "change", "at": 0, "data": {}}) + await clock.advance(1) + assert "data" in sink.delivered[0] and sink.delivered[0]["data"] == data + record = await attend.inspect("scope") + assert record is not None + assert "data" in record["recent"][0] and record["recent"][0]["data"] == data + finally: + await attend.stop() + await running diff --git a/test/decision-data.test.ts b/test/decision-data.test.ts new file mode 100644 index 0000000..24d6780 --- /dev/null +++ b/test/decision-data.test.ts @@ -0,0 +1,100 @@ +import { expect, test } from 'vitest'; +import { createAttend } from '../src/attend.js'; +import { memoryStore } from '../src/memory.js'; +import { fakeClock, recordingSink } from '../src/testing.js'; +import type { Decision, JsonObject, JsonValue } from '../src/types.js'; + +test('decision data survives a failed delivery and a retained-store restart', async () => { + const clock = fakeClock(); + const store = memoryStore(); + const data = { revision: 7, tags: ['alpha'] }; + const attempts: Decision[] = []; + const first = createAttend({ + clock, store, kind: { change: 'closing' }, settle: { closingGraceMs: 1, retryBackoffMs: [10] }, + judge: async () => ({ route: 'note', data }), + sink: async (decision) => { + attempts.push(structuredClone(decision)); + if (decision.data && typeof decision.data === 'object' && !Array.isArray(decision.data)) decision.data.revision = 99; + throw new Error('retry'); + }, + }); + const firstRun = first.run(); + try { + await first.push('scope', { id: 'a', name: 'change', at: 0, data: {} }); + await clock.advance(1); + expect(attempts).toHaveLength(1); + expect(attempts[0]?.data).toEqual({ revision: 7, tags: ['alpha'] }); + data.tags.push('changed after judgment'); + expect((await first.inspect('scope'))?.recent[0]?.data).toEqual({ revision: 7, tags: ['alpha'] }); + } finally { + await first.stop(); + await firstRun; + } + + const sink = recordingSink(); + const recent: JsonValue[] = []; + const second = createAttend({ + clock, store, kind: { change: 'closing' }, settle: { closingGraceMs: 1, retryBackoffMs: [10] }, sink, + judge: async (input) => { + const prior = input.recent[0]?.data; + if (prior !== undefined) recent.push(structuredClone(prior)); + if (prior && typeof prior === 'object' && !Array.isArray(prior)) prior.revision = 100; + return { route: 'note' }; + }, + }); + const secondRun = second.run(); + try { + await clock.advance(10); + expect(sink.delivered).toHaveLength(1); + expect(sink.delivered[0]?.id).toBe(attempts[0]?.id); + expect(sink.delivered[0]?.data).toEqual({ revision: 7, tags: ['alpha'] }); + await second.push('scope', { id: 'b', name: 'change', at: 10, data: {} }); + await clock.advance(1); + expect(recent).toEqual([{ revision: 7, tags: ['alpha'] }]); + expect((await second.inspect('scope'))?.recent[0]?.data).toEqual({ revision: 7, tags: ['alpha'] }); + } finally { + await second.stop(); + await secondRun; + } +}); + +const values: JsonValue[] = [null, false, 0, '', [], {}]; +test.each(values.map((data) => ({ data })))('keeps explicit JSON data $data', async ({ data }) => { + const clock = fakeClock(); + const sink = recordingSink(); + const attend = createAttend({ clock, kind: { change: 'closing' }, settle: { closingGraceMs: 1 }, sink, judge: async () => ({ route: 'note', data }) }); + const running = attend.run(); + try { + await attend.push('scope', { id: 'a', name: 'change', at: 0, data: {} }); + await clock.advance(1); + expect(sink.delivered[0]).toHaveProperty('data', data); + expect((await attend.inspect('scope'))?.recent[0]).toHaveProperty('data', data); + } finally { + await attend.stop(); + await running; + } +}); + +test('invalid JSON data retries the judgment before a decision is committed', async () => { + const clock = fakeClock(); + const sink = recordingSink(); + let calls = 0; + const invalid: JsonObject = {}; + Reflect.set(invalid, 'value', 1n); + const attend = createAttend({ + clock, kind: { change: 'closing' }, sink, settle: { closingGraceMs: 1, retryBackoffMs: [10] }, + judge: async () => ({ route: 'note', data: ++calls === 1 ? invalid : { valid: true } }), + }); + const running = attend.run(); + try { + await attend.push('scope', { id: 'a', name: 'change', at: 0, data: {} }); + await clock.advance(1); + expect(sink.delivered).toHaveLength(0); + await clock.advance(10); + expect(calls).toBe(2); + expect(sink.delivered[0]?.data).toEqual({ valid: true }); + } finally { + await attend.stop(); + await running; + } +}); From 380e70918370f2b14e194d007c0e639bbc337ea4 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Fri, 13 Nov 2026 23:08:10 -0600 Subject: [PATCH 2/4] feat(core): retain optional JSON decision data Keep a custom judge result with its decision and recent verdict so delivery retries and recovery do not need a host-side cache. Normalize incoming data, detach outgoing copies, and preserve absent fields for existing callers in both runtimes. --- DEVIATIONS.md | 4 + conformance/fixtures/scenarios.json | 742 ++++++++++++++++++++++ docs/judges.md | 23 +- docs/sinks.md | 2 + docs/storage.md | 2 + python/README.md | 2 + python/src/aqi_attend/attend.py | 4 +- python/src/aqi_attend/core/reducer.py | 13 +- python/src/aqi_attend/core/types.py | 3 + python/src/aqi_attend/shell/copy.py | 24 +- python/tests/test_continuation.py | 2 +- python/tests/test_continuous_quiet.py | 2 +- python/tests/test_decision_data.py | 28 + python/tests/test_event_limits.py | 2 +- python/tests/test_event_limits_interop.py | 2 +- python/tests/test_interop.py | 2 +- python/tests/test_observation_time.py | 2 +- src/attend.ts | 4 +- src/core/reducer.ts | 12 +- src/core/types.ts | 7 +- src/shell/copy.ts | 10 +- test/conformance/scenarios.ts | 11 + test/continuation.test.ts | 2 +- test/continuous-quiet.test.ts | 2 +- test/decision-data.test.ts | 2 + test/event-limits.test.ts | 2 +- test/observation-time.test.ts | 2 +- test/recovery.test.ts | 2 +- 28 files changed, 883 insertions(+), 32 deletions(-) diff --git a/DEVIATIONS.md b/DEVIATIONS.md index ea41931..75cf4d1 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -1,5 +1,9 @@ # Shell changes from the frozen shell +## Decision data + +Custom judges may return optional JSON `data`. Reducer revision 6 keeps it with final decisions and recent verdicts, including skipped verdicts; waits keep no data. Both runtimes detach outgoing copies and normalize data before committing a judgment. Omission preserves the existing record and decision shapes. The shared decision-data scenario and native retry/restart tests cover delivery and recent context without adding a host-owned pending-result store. + ## Independent event limits The optional `settle.eventLimits` pair separates an inclusive counted trigger from FIFO background retention. It requires accumulating continuation and replaces the scalar total limit. Omission preserves the existing scalar path. Retention applies across unresolved held and fresh entries, including transitions from a live offer; it never mutates that offer or drops counted entries. Reducer revision 5 stores the opt-in policy. [Independent event limits](docs/reference.md#independent-event-limits) defines the contract and writer-change boundary. diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index 2625d95..c644da9 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,747 @@ { "scenarios": [ + { + "scenario": { + "name": "decision data survives wait, delivery retry and recent context", + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "closingGraceMs": 1, + "waitHorizonMs": 5, + "retryBackoffMs": [ + 3 + ] + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait", + "data": { + "transient": true + } + }, + { + "route": "note", + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + { + "route": "skip", + "data": false + } + ] + } + }, + "sink": { + "*": { + "attempts": [ + { + "fail": "retry" + }, + "ok" + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "close", + "text": "close a" + } + ] + }, + { + "advance": 1 + }, + { + "inspect": "s" + }, + { + "advance": 5 + }, + { + "inspect": "s" + }, + { + "advance": 3 + }, + { + "push": "s", + "events": [ + { + "id": "b", + "name": "close", + "text": "close b" + } + ] + }, + { + "advance": 1 + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 1 + }, + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 6 + }, + { + "scope": "s", + "window": { + "id": "3ecbd5f2ef91c942", + "events": [ + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 9 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + } + ], + "now": 10 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + "outcome": "Error: retry" + }, + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "closing", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "waiting", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "waits": 1, + "until": 6 + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 2, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "retrying", + "scope": "s", + "stage": "sink", + "id": "3ecbd4f2ef91c78f", + "attempt": 1, + "at": 9, + "message": "retry" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 2 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "reason": "closing", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "route": "skip" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 6, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 6 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 6 + } + }, + { + "step": 4, + "scope": "s", + "record": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [ + { + "item": { + "id": "3ecbd4f2ef91c78f", + "kind": "decision", + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + } + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 9 + } + } + ], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + } + ], + "dueAt": 9 + } + }, + { + "step": 8, + "scope": "s", + "record": { + "version": 11, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + { + "id": "3ecbd5f2ef91c942", + "route": "skip", + "at": 10, + "data": false + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 11, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + { + "id": "3ecbd5f2ef91c942", + "route": "skip", + "at": 10, + "data": false + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 6, + "route": "note", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 0 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1 + }, + "at": 6, + "data": { + "revision": 7, + "tags": [ + "alpha" + ], + "optional": null + } + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "independent limits settle counted equality while retaining background", diff --git a/docs/judges.md b/docs/judges.md index 15203ee..b33270f 100644 --- a/docs/judges.md +++ b/docs/judges.md @@ -2,12 +2,33 @@ **The speed default is a system-one classifier.** `jevJudge` (TypeSafe's Jev, with your own TypeSafe key) and `decisionsJudge` (the OpenAI Decisions API) answer a fixed multiple-choice question with probabilities in roughly 140 ms or more, which is what a real-time agent can afford on every settled window. `llmJudge` calls a general model you already use; it is slower, and its self-reported probabilities are close to one-hot. Use it when you want reasoning over speed. -A judge is a function, `(input: JudgeInput, signal: AbortSignal) => Promise`. It gets the settled `window`, the `routes` on offer with your criteria, your `guidance`, the `predicates` to answer, live `facts` from `context()` and the scope's `recent` verdicts. It returns `{ route, probabilities?, predicates? }`. +A judge is a function, `(input: JudgeInput, signal: AbortSignal) => Promise`. It gets the settled `window`, the `routes` on offer with your criteria, your `guidance`, the `predicates` to answer, live `facts` from `context()` and the scope's `recent` verdicts. It returns `{ route, probabilities?, predicates?, confidence?, data? }`. - Throw to retry with backoff. Throw a `PermanentError` to dead-letter the window at once. - A route that was not offered counts as a retryable failure. Check `input.routes` before you answer `wait`. - Stop when `signal` aborts. attend aborts the call after `judgeTimeoutMs`. +## Carry a result to the sink + +A custom judge can return optional JSON `data`. attend commits it with the final verdict and gives the sink the same value on `decision.data`, including after delivery retries or recovery. Each subsequent custom judge also receives it on `input.recent[].data`. The built-in hosted judge prompts still summarize recent routes and times; they do not embed this data. + +```ts +import { createAttend } from '@acquiredintelligence/attend'; + +const attend = createAttend({ + kind: { 'job.completed': 'closing' }, + judge: async ({ window }) => ({ + route: 'queue', + data: { eventIds: window.events.map((event) => event.id) }, + }), + sink: (decision) => console.log(decision.id, decision.data), +}); +``` + +Omission leaves the field absent. Explicit `null`, `false`, zero and empty values are retained. A `skip` retains data in recent context without calling the sink; a `wait` retains neither a verdict nor its data. JSON normalization follows event data in each runtime. Invalid data fails the judgment and follows its retry schedule. Changes to a sink's copy or a later judge's recent context cannot change stored data. + +Keep data bounded: it is stored in the outbox and up to `recentCount` verdicts. Use compatible reducer versions in every process sharing the store before returning it. The same `data` field is available in Python. + ## llmJudge `llmJudge` from `@acquiredintelligence/attend/llm` works with any model that answers in JSON matching a schema. You pass that one call as `complete`. attend writes the prompt and the schema and validates the reply. With Claude: diff --git a/docs/sinks.md b/docs/sinks.md index 89afbf8..737b6a9 100644 --- a/docs/sinks.md +++ b/docs/sinks.md @@ -2,6 +2,8 @@ A sink delivers decisions to the agent. attend calls `sink.deliver(decision, signal)` at least once per decision, one decision at a time per scope, oldest first. After a crash it can deliver the same decision again with the same id, so make the sink idempotent on `decision.id`, which is unique across scopes. Throw to retry, or throw a `PermanentError` to dead-letter at once. +For a host-prepared result, return [`Judgment.data`](judges.md#carry-a-result-to-the-sink) from the custom judge and read `decision.data` here. The outbox owns that JSON value through retries and recovery, so the sink does not need a separate pending-result cache. The sink receives a detached copy. The default notice remains based on event lines and ignores this field. + A sink can be one function, `(decision, signal) => …`, that gets every delivered decision. `routes()` builds a sink from one handler per delivered route instead, so a route you forgot fails to typecheck. A sink never sees `skip` or `wait`. This excerpt from [`examples/postgres-worker.ts`](../examples/postgres-worker.ts) writes every decision to an inbox table that the agent's runtime reads: ```ts diff --git a/docs/storage.md b/docs/storage.md index d7fc229..69c26cd 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -43,3 +43,5 @@ Keep processes sharing a store on the same reducer version before using [observa [Independent event limits](reference.md#independent-event-limits) uses revision 5. The optional pair persists with the policy, and tails replay under that saved policy before a writer can adopt its configuration. A writer refuses adding, removing or changing the pair while open entries or an unresolved held batch remain, including background-only and released state. Empty scopes may adopt it without changing completed recent/outbox entries. Records without the pair keep scalar limits. Writers must use compatible revisions; this check cannot fence an older writer that lacks it. Each adapter also has an `EventLog`: `memoryLog`, `sqliteLog`, `postgresLog` and `redisLog`. When producers live in other processes and you want a durable shared log in front of attend, append to the log and attach `logSource(log, scope)` instead of calling `push`. + +[Judgment data](judges.md#carry-a-result-to-the-sink) uses reducer revision 6. Optional data stays in logged judgments, decisions and recent verdicts. Old records without it remain readable. Use compatible readers and writers before returning data; replay on a version mismatch does not fence older processes or make them retain the field. diff --git a/python/README.md b/python/README.md index bdb17de..35c6bf1 100644 --- a/python/README.md +++ b/python/README.md @@ -156,3 +156,5 @@ uv run python bench/latency.py --store redis ## License MIT, Zettel Labs, Inc. + +Custom judges can return optional JSON `data`. It reaches `decision["data"]` and subsequent `input["recent"]` verdicts through delivery retries and recovery. Omission keeps the field absent. See [the result contract](../docs/judges.md#carry-a-result-to-the-sink) and [storage compatibility](../docs/storage.md). diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index caa6cfe..6a44737 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -52,7 +52,7 @@ ) from .errors import ConflictError, IntakeError, is_permanent, message_of from .shell.budget import window_bytes_for -from .shell.copy import copy_decision, copy_event, copy_letter, copy_window +from .shell.copy import copy_decision, copy_event, copy_judgment, copy_letter, copy_window from .shell.decisions import DecisionCursorPage, read_decisions from .shell.intake import Intake, owns_callback from .shell.read import read_record @@ -514,7 +514,7 @@ async def _run_judge(self, scope: str, effect: JudgeEffect, controller: AbortCon if threshold is not None: self._observe({"kind": "routeThresholded", "scope": scope, "batchId": batch_id, "from": judgment["route"], "to": threshold["route"], "act": threshold["act"]}) chosen = cast(Judgment, {**judgment, "route": threshold["route"]}) if threshold is not None else judgment - result = {"kind": "judged", "batchId": batch_id, "attempt": attempt, "judgment": cast(Judgment, clone(chosen))} + result = {"kind": "judged", "batchId": batch_id, "attempt": attempt, "judgment": copy_judgment(chosen)} else: result = {"kind": "judgeFailed", "batchId": batch_id, "attempt": attempt, "message": "malformed judgment", "permanent": False} except asyncio.CancelledError: diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index 74cadf7..9f73344 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -3,8 +3,9 @@ from __future__ import annotations import math -from typing import TypedDict, cast +from typing import NotRequired, TypedDict, cast +from .._json import clone from .ids import fnv_hex, fnv_start, fold_id from .seen import seen_admit, seen_release, seen_trim from .types import ( @@ -22,6 +23,7 @@ HeldBatch, InFlightDelivery, InputKind, + JsonValue, JudgedInput, JudgingPhase, Judgment, @@ -47,7 +49,7 @@ window_shed, ) -REDUCER_VERSION = 5 +REDUCER_VERSION = 6 """Bumped whenever a release changes a transition. Stored with every snapshot.""" _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") @@ -60,6 +62,7 @@ class Validated(TypedDict): probabilities: dict[str, float] predicates: dict[str, float] confidence: float | None + data: NotRequired[JsonValue] def same(a: object, b: object) -> bool: @@ -517,6 +520,8 @@ def _on_judged(ctx: _Ctx, state: ScopeState, input: JudgedInput) -> None: return decided: DecidedRoute = route verdict_row: Verdict = {"id": window["id"], "route": decided, "at": ctx.now} + if "data" in verdict: + verdict_row["data"] = verdict["data"] recent = [*state.recent, verdict_row] count = ctx.config.policy["recentCount"] state.recent = [] if count <= 0 else recent[-count:] @@ -533,6 +538,8 @@ def _on_judged(ctx: _Ctx, state: ScopeState, input: JudgedInput) -> None: "window": window, "at": ctx.now, } + if "data" in verdict: + decision["data"] = verdict["data"] ctx.out.appends.append({"kind": "decision", "id": decision["id"], "scope": state.scope, "at": decision["at"], "route": delivered, "body": decision}) if ctx.config.decisions == "lane": state.decisions.append( @@ -592,6 +599,8 @@ def validate(judgment: Judgment, offered: list[Route]) -> Validated | None: if p is not None: predicates[name] = p result: Validated = {"route": route, "probabilities": probabilities, "predicates": predicates, "confidence": _unit(judgment.get("confidence"))} + if "data" in judgment: + result["data"] = cast(JsonValue, clone(judgment["data"])) return result diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 8fc0ba6..0ae4c1f 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -158,6 +158,7 @@ class Verdict(TypedDict): id: str route: DecidedRoute at: float + data: NotRequired[JsonValue] class Decision(TypedDict): @@ -169,6 +170,7 @@ class Decision(TypedDict): probabilities: dict[str, float] predicates: dict[str, float] confidence: float | None + data: NotRequired[JsonValue] window: Window at: float @@ -250,6 +252,7 @@ class Judgment(TypedDict): """What a judge returns. Validated against the offered routes inside ``step``.""" route: Route + data: NotRequired[JsonValue] probabilities: NotRequired[dict[str, float]] predicates: NotRequired[dict[str, float]] confidence: NotRequired[float] diff --git a/python/src/aqi_attend/shell/copy.py b/python/src/aqi_attend/shell/copy.py index 6522f87..e3dfbab 100644 --- a/python/src/aqi_attend/shell/copy.py +++ b/python/src/aqi_attend/shell/copy.py @@ -9,13 +9,13 @@ from typing import Any, cast from .._json import clone, utf8_length -from ..core.types import DeadLetter, Decision, Entry, Event, JsonValue, Window +from ..core.types import DeadLetter, Decision, Entry, Event, JsonValue, Judgment, Window _MAX_DEPTH = 1000 SLICE = 64 -def _to_json(value: object, depth: int) -> JsonValue: +def _to_json(value: object, depth: int, subject: str = "event") -> JsonValue: if value is None or isinstance(value, (str, bool)): return value if isinstance(value, int): @@ -24,19 +24,27 @@ def _to_json(value: object, depth: int) -> JsonValue: # JSON writes NaN and the infinities as null, and -0 as 0. return value + 0.0 if math.isfinite(value) else None if depth >= _MAX_DEPTH: - raise TypeError(f"attend: event data holds a cycle or nests deeper than {_MAX_DEPTH}") + raise TypeError(f"attend: {subject} data holds a cycle or nests deeper than {_MAX_DEPTH}") if isinstance(value, Mapping): mapping = cast(Mapping[object, object], value) out: dict[str, JsonValue] = {} for key, item in mapping.items(): if not isinstance(key, str): - raise TypeError("attend: event data keys must be strings") - out[key] = _to_json(item, depth + 1) + raise TypeError(f"attend: {subject} data keys must be strings") + out[key] = _to_json(item, depth + 1, subject) return out if isinstance(value, (list, tuple)): items = cast(Sequence[object], value) - return [_to_json(item, depth + 1) for item in items] - raise TypeError(f"attend: event data must be JSON, got {type(value).__name__}") + return [_to_json(item, depth + 1, subject) for item in items] + raise TypeError(f"attend: {subject} data must be JSON, got {type(value).__name__}") + + +def copy_judgment(judgment: Judgment) -> Judgment: + """Capture the result and normalize its optional data at the JSON boundary.""" + copy = dict(judgment) + if "data" in judgment: + copy["data"] = _to_json(judgment["data"], 0, "judgment") + return cast(Judgment, clone(copy)) def copy_event(event: Mapping[str, object], fill: tuple[Callable[[], str], Callable[[], float]] | None = None) -> Event: @@ -85,6 +93,8 @@ async def copy_window(window: Window) -> Window: async def copy_decision(decision: Decision) -> Decision: copy = cast(Decision, {**decision, "probabilities": dict(decision["probabilities"]), "predicates": dict(decision["predicates"])}) + if "data" in decision: + copy["data"] = cast(JsonValue, clone(decision["data"])) copy["window"] = await copy_window(decision["window"]) return copy diff --git a/python/tests/test_continuation.py b/python/tests/test_continuation.py index 8d0e28d..c449fc6 100644 --- a/python/tests/test_continuation.py +++ b/python/tests/test_continuation.py @@ -226,7 +226,7 @@ async def test_revision_three_read_and_mode_boundary(item: dict[str, Any]) -> No stored = await store.load("scope") assert stored is not None and stored["snapshot"] is not None assert stored["snapshot"]["policy"].get("continuation") == "accumulate" - assert stored["snapshot"]["reducer"] == 5 + assert stored["snapshot"]["reducer"] == 6 record = await engine.inspect("scope") assert record is not None and record["recent"] == item["expected"]["recent"] else: diff --git a/python/tests/test_continuous_quiet.py b/python/tests/test_continuous_quiet.py index 3454b3b..19b6628 100644 --- a/python/tests/test_continuous_quiet.py +++ b/python/tests/test_continuous_quiet.py @@ -254,7 +254,7 @@ async def test_revision_two_snapshot_and_mixed_tail_rebuild_end_times() -> None: assert loaded is not None and loaded["dueAt"] == 200 assert [(event["id"], event.get("quietForMs"), event["seenAt"]) for event in loaded["buffer"]["entries"]] == [("a", None, 100), ("b", 90, 120), ("c", None, 120)] stored = await store.load("s") - assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 5 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 6 finally: await attend.stop() await store.close() diff --git a/python/tests/test_decision_data.py b/python/tests/test_decision_data.py index 8e92561..22f5a62 100644 --- a/python/tests/test_decision_data.py +++ b/python/tests/test_decision_data.py @@ -1,5 +1,6 @@ import asyncio from copy import deepcopy +from typing import cast import pytest @@ -60,6 +61,7 @@ async def later(input: JudgeInput, signal: AbortSignal) -> Judgment: await second.push("scope", {"id": "b", "name": "change", "at": 10, "data": {}}) await clock.advance(1) assert recent == [{"revision": 7, "tags": ["alpha"]}] + assert "data" not in sink.delivered[1] record = await second.inspect("scope") assert record is not None assert record["recent"][0].get("data") == {"revision": 7, "tags": ["alpha"]} @@ -89,3 +91,29 @@ async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: finally: await attend.stop() await running + + +async def test_invalid_json_data_retries_before_committing_a_decision() -> None: + clock = fake_clock() + sink = recording_sink() + calls = 0 + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + nonlocal calls + calls += 1 + if calls == 1: + return cast(Judgment, {"route": "note", "data": object()}) + return {"route": "note", "data": {"valid": True}} + + attend = create_attend(clock=clock, kind={"change": "closing"}, sink=sink, settle={"closing_grace_ms": 1, "retry_backoff_ms": [10]}, judge=judge) + running = asyncio.create_task(attend.run()) + try: + await attend.push("scope", {"id": "a", "name": "change", "at": 0, "data": {}}) + await clock.advance(1) + assert sink.delivered == [] + await clock.advance(10) + assert calls == 2 + assert sink.delivered[0].get("data") == {"valid": True} + finally: + await attend.stop() + await running diff --git a/python/tests/test_event_limits.py b/python/tests/test_event_limits.py index b9169d3..0211be3 100644 --- a/python/tests/test_event_limits.py +++ b/python/tests/test_event_limits.py @@ -257,7 +257,7 @@ async def test_revision_four_snapshots_and_tails_keep_saved_policy(item: dict[st await write stored = await store.load("s") assert stored is not None and stored["snapshot"] is not None - assert stored["snapshot"]["reducer"] == 5 + assert stored["snapshot"]["reducer"] == 6 assert stored["snapshot"]["policy"].get("eventLimits") == {"counted": 3, "background": 2} record = await engine.inspect("s") assert record is not None and record["recent"] == item["expected"]["recent"] diff --git a/python/tests/test_event_limits_interop.py b/python/tests/test_event_limits_interop.py index 7257d5b..56f13ea 100644 --- a/python/tests/test_event_limits_interop.py +++ b/python/tests/test_event_limits_interop.py @@ -127,7 +127,7 @@ async def test_independent_limits_continue_across_runtimes(kind: str, phase: str written = await (python(owned, "write", scope, phase) if writer == "python" else typescript(kind, prefix, "write", scope, phase)) stored = await owned.load(scope) assert stored is not None and stored["snapshot"] is not None - assert stored["snapshot"]["reducer"] == 5 and stored["tail"] + assert stored["snapshot"]["reducer"] == 6 and stored["tail"] assert stored["snapshot"]["policy"].get("eventLimits") == {"counted": 3, "background": 2} read = await (typescript(kind, prefix, "read", scope, phase) if writer == "python" else python(owned, "read", scope, phase)) assert read["record"] == written["record"] diff --git a/python/tests/test_interop.py b/python/tests/test_interop.py index f117bbc..43da12e 100644 --- a/python/tests/test_interop.py +++ b/python/tests/test_interop.py @@ -156,7 +156,7 @@ async def test_intake_snapshot_and_tail_continue_without_intake_in_other_runtime assert written["record"]["cursors"] == {"feed": "3"} stored = await owned.load(scope) assert stored is not None and stored["snapshot"] is not None - assert stored["snapshot"]["reducer"] == 5 and stored["tail"] + assert stored["snapshot"]["reducer"] == 6 and stored["tail"] encoded = json.dumps(stored) assert all(field not in encoded for field in ('"catchUp"', '"catch_up"', '"prepare"', '"owner"')) read = await (typescript(kind, prefix, "read", scope) if writer == "python" else python(owned, "read", scope)) diff --git a/python/tests/test_observation_time.py b/python/tests/test_observation_time.py index 26c57f5..11902a0 100644 --- a/python/tests/test_observation_time.py +++ b/python/tests/test_observation_time.py @@ -259,7 +259,7 @@ async def test_prior_reducer_snapshot_and_tail_keep_ingestion_deadlines() -> Non assert loaded is not None and loaded["dueAt"] == 2100 assert [(event["id"], event["seenAt"], event.get("observedAt")) for event in loaded["buffer"]["entries"]] == [("a", 1000, None), ("b", 1100, None)] stored = await store.load("s") - assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 5 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 6 finally: await attend.stop() await store.close() diff --git a/src/attend.ts b/src/attend.ts index d2d012f..2c51591 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -8,7 +8,7 @@ import type { Attend, AttendConfig, EventInput } from './shell/types.js'; import { memoryStore } from './store/memory.js'; import { createScopes } from './shell/scope.js'; import { createScheduler } from './shell/scheduler.js'; -import { copyDecision, copyEventSized, copyLetter, copyWindowSliced } from './shell/copy.js'; +import { copyDecision, copyEventSized, copyJudgment, copyLetter, copyWindowSliced } from './shell/copy.js'; import { windowBytesFor } from './shell/budget.js'; import { readRecord } from './shell/read.js'; import { readDecisions } from './shell/decisions.js'; @@ -222,7 +222,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' if (isJudgment(judgment)) { const threshold = config.actThreshold === undefined ? null : thresholdRoute(judgment, effect.offered, config.actThreshold); if (threshold) observe({ kind: 'routeThresholded', scope, batchId, from: judgment.route, to: threshold.route, act: threshold.act }); - result = { kind: 'judged', batchId, attempt, judgment: structuredClone(threshold ? { ...judgment, route: threshold.route } : judgment) }; + result = { kind: 'judged', batchId, attempt, judgment: copyJudgment(threshold ? { ...judgment, route: threshold.route } : judgment) }; } else result = { kind: 'judgeFailed', batchId, attempt, message: 'malformed judgment', permanent: false }; } catch (error) { result = { kind: 'judgeFailed', batchId, attempt, message: messageOf(error), permanent: isPermanent(error) }; diff --git a/src/core/reducer.ts b/src/core/reducer.ts index c09f403..7b1c58e 100644 --- a/src/core/reducer.ts +++ b/src/core/reducer.ts @@ -9,7 +9,7 @@ import { seenAdmit, seenRelease, seenTrim } from './seen.js'; import { estimateRenderedBytes, isBackground, observationTime, openWindow, shedEntries, windowAppend, windowCompact, windowDeadline, windowEntries, windowPrune, windowShed, windowSize } from './window.js'; /** Bumped whenever a release changes a transition. Stored with every snapshot. */ -export const REDUCER_VERSION = 5; +export const REDUCER_VERSION = 6; /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { @@ -367,12 +367,13 @@ function onJudged(ctx: Ctx, state: ScopeState, input: Extract & { route: Route }) | null { +export function validate(judgment: Judgment, offered: Route[]): (Pick & { route: Route }) | null { const route = offered.find((candidate) => candidate === judgment.route); if (route === undefined) return null; const raw: Record = { interrupt: 0, queue: 0, note: 0, ask: 0, skip: 0, wait: 0 }; @@ -407,7 +408,8 @@ export function validate(judgment: Judgment, offered: Route[]): (Pick; /** How sure the judge was of the route, from 0 to 1, when it says; null when it does not. */ confidence: number | null; + /** The judge's JSON result, retained across delivery attempts. */ + data?: JsonValue; window: Window; at: number; } @@ -261,6 +264,8 @@ export interface ScopeRecord { /** What a judge returns. Validated against the offered routes inside `step`. */ export interface Judgment { route: Route; + /** Optional JSON result for the sink and subsequent judge context. */ + data?: JsonValue; /** Per offered route. Missing routes count as 0; the reducer renormalises. */ probabilities?: Partial>; predicates?: Record; diff --git a/src/shell/copy.ts b/src/shell/copy.ts index 62b311e..67f2d04 100644 --- a/src/shell/copy.ts +++ b/src/shell/copy.ts @@ -1,4 +1,4 @@ -import type { DeadLetter, Decision, Event, Window } from '../core/types.js'; +import type { DeadLetter, Decision, Event, Judgment, Window } from '../core/types.js'; import { copyEvent } from '../internal/shared.js'; import { estimateRenderedBytes } from '../core/window.js'; @@ -17,6 +17,13 @@ export function copyEventSized(event: Event, fill?: { id(): string; at(): number const copying = new Set>(); +/** Captures the result and normalizes its optional data at the JSON boundary. */ +export function copyJudgment(judgment: Judgment): Judgment { + const copy = { ...judgment }; + if (copy.data !== undefined) copy.data = JSON.parse(JSON.stringify(copy.data)); + return structuredClone(copy); +} + /** Waits for active window copies when advancing a deterministic test clock. */ export async function drainCopies(): Promise { while (copying.size > 0) await Promise.all(copying); @@ -44,6 +51,7 @@ export function copyWindowSliced(window: Window, slice = 64): Window | Promise { const copy = { ...decision, probabilities: { ...decision.probabilities }, predicates: { ...decision.predicates } }; + if (decision.data !== undefined) copy.data = structuredClone(decision.data); const window = copyWindowSliced(decision.window); return window instanceof Promise ? window.then((window) => ({ ...copy, window })) : { ...copy, window }; } diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index 294f67c..cb0e7e1 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,17 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'decision data survives wait, delivery retry and recent context', + start: 0, kinds: KINDS, + settle: { closingGraceMs: 1, waitHorizonMs: 5, retryBackoffMs: [3] }, + judge: { '*': { answers: [{ route: 'wait', data: { transient: true } }, + { route: 'note', data: { revision: 7, tags: ['alpha'], optional: null } }, + { route: 'skip', data: false }] } }, + sink: { '*': { attempts: [{ fail: 'retry' }, 'ok'] } }, + steps: [push('s', ev('a')), advance(1), { inspect: 's' }, advance(5), { inspect: 's' }, + advance(3), push('s', ev('b')), advance(1), { inspect: 's' }], + }, { name: 'independent limits settle counted equality while retaining background', start: 0, intakes: ['s'], kinds: KINDS, diff --git a/test/continuation.test.ts b/test/continuation.test.ts index b16e774..28e17d8 100644 --- a/test/continuation.test.ts +++ b/test/continuation.test.ts @@ -170,7 +170,7 @@ test.each(legacy.cases)('reads revision-3 $name and refuses an unresolved mode s await pending; const stored = await store.load('scope'); expect(stored?.snapshot?.policy.continuation).toBe('accumulate'); - expect(stored?.snapshot?.reducer).toBe(5); + expect(stored?.snapshot?.reducer).toBe(6); expect((await engine.inspect('scope'))?.recent).toEqual(item.expected.recent); } else { await expect(pending).rejects.toThrow('continuation'); diff --git a/test/continuous-quiet.test.ts b/test/continuous-quiet.test.ts index 39e2a3c..2fd2439 100644 --- a/test/continuous-quiet.test.ts +++ b/test/continuous-quiet.test.ts @@ -204,7 +204,7 @@ test('a revision-two snapshot and mixed tail rebuild continuous end times', asyn const loaded = await attend.inspect('s'); expect(loaded?.dueAt).toBe(200); expect(loaded?.buffer.entries.map((event) => [event.id, event.quietForMs, event.seenAt])).toEqual([['a', undefined, 100], ['b', 90, 120], ['c', undefined, 120]]); - expect((await store.load('s'))?.snapshot?.reducer).toBe(5); + expect((await store.load('s'))?.snapshot?.reducer).toBe(6); } finally { await attend.stop(); } diff --git a/test/decision-data.test.ts b/test/decision-data.test.ts index 24d6780..ef18fc3 100644 --- a/test/decision-data.test.ts +++ b/test/decision-data.test.ts @@ -52,10 +52,12 @@ test('decision data survives a failed delivery and a retained-store restart', as await clock.advance(1); expect(recent).toEqual([{ revision: 7, tags: ['alpha'] }]); expect((await second.inspect('scope'))?.recent[0]?.data).toEqual({ revision: 7, tags: ['alpha'] }); + expect(sink.delivered[1]).not.toHaveProperty('data'); } finally { await second.stop(); await secondRun; } + expect(clock.nextAt()).toBeNull(); }); const values: JsonValue[] = [null, false, 0, '', [], {}]; diff --git a/test/event-limits.test.ts b/test/event-limits.test.ts index 5a425f2..fb8def7 100644 --- a/test/event-limits.test.ts +++ b/test/event-limits.test.ts @@ -177,7 +177,7 @@ test.each(legacy.cases)('revision-four $name snapshot and tail retain their save if (item.name === 'complete') { await write; const stored = await store.load('s'); - expect(stored?.snapshot?.reducer).toBe(5); + expect(stored?.snapshot?.reducer).toBe(6); expect(stored?.snapshot?.policy.eventLimits).toEqual({ counted: 3, background: 2 }); expect((await engine.inspect('s'))?.recent).toEqual(item.expected.recent); } else { diff --git a/test/observation-time.test.ts b/test/observation-time.test.ts index 802805f..1a073cf 100644 --- a/test/observation-time.test.ts +++ b/test/observation-time.test.ts @@ -207,7 +207,7 @@ test('a prior reducer snapshot and tail retain ingestion-time deadlines on upgra const loaded = await attend.inspect('s'); expect(loaded?.dueAt).toBe(2100); expect(loaded?.buffer.entries.map((event) => [event.id, event.seenAt, event.observedAt])).toEqual([['a', 1000, undefined], ['b', 1100, undefined]]); - expect((await store.load('s'))?.snapshot?.reducer).toBe(5); + expect((await store.load('s'))?.snapshot?.reducer).toBe(6); } finally { await attend.stop(); } diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 4c08fcd..166ee37 100644 --- a/test/recovery.test.ts +++ b/test/recovery.test.ts @@ -69,7 +69,7 @@ test('recovers every committed write under all snapshot cadences and policy chan let tailInputs = 0; let snapshotBytes = JSON.stringify(latest.record).length; const replay = (snapshot: Snapshot, through: number, expected: ScopeRecord): void => { - assert.equal(snapshot.reducerVersion, 5); + assert.equal(snapshot.reducerVersion, 6); const restored = fromRecord(deepFreeze(json(snapshot.record)), snapshot.policy); let bound = Math.max(snapshot.policy.seenCount, restored.seen.size); assertInvariants(restored, { ...snapshot.policy, seenCount: bound }); From ce5fe4a89027b54aec6bc60203ad17ffaecdd3b0 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Fri, 13 Nov 2026 23:11:31 -0600 Subject: [PATCH 3/4] test(core): expect the data-aware reducer revision Keep the invariant suite pinned to the revision that retains decision data. --- test/core-inputs.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/core-inputs.test.ts b/test/core-inputs.test.ts index 1038637..e96c627 100644 --- a/test/core-inputs.test.ts +++ b/test/core-inputs.test.ts @@ -379,7 +379,7 @@ test('assertInvariants identifies corrupt counts, rings, summaries, sizes, hashe lane.outbox.decisions.push(lane.outbox.decisions[0]!); lane.dueAt = nextDue(policy, lane); assert.throws(() => assertInvariants(lane, policy), /^Error: outbox: more than one in flight/); - assert.equal(REDUCER_VERSION, 5); + assert.equal(REDUCER_VERSION, 6); }); test('fromRecord accepts frozen oracle snapshots without changing them', () => { From dd6c987ede4b2990e0bd01872a5be19a18da5852 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Fri, 13 Nov 2026 23:17:49 -0600 Subject: [PATCH 4/4] docs(judges): describe data with the Python judge interface Keep the result contract alongside the custom judge API. --- python/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/python/README.md b/python/README.md index 6344670..aeb22d0 100644 --- a/python/README.md +++ b/python/README.md @@ -125,6 +125,8 @@ Repeated cancellation of the runner does not skip its cleanup join. `stop()` rej `aqi_attend.judges` has `jev_judge` (TypeSafe's Jev, with your own key), `decisions_judge` (the OpenAI Decisions API) and `llm_judge`, which wraps any structured-output call you pass as `complete`. They send the same requests as the TypeScript judges, byte for byte. [Choose a judge](https://github.com/acquiredintelligence/attend/blob/main/docs/judges.md) explains each one, the window budget and the act threshold. +Custom judges can return optional JSON `data`. It reaches `decision["data"]` and subsequent `input["recent"]` verdicts through delivery retries and recovery. Omission keeps the field absent. See [the result contract](../docs/judges.md#carry-a-result-to-the-sink) and [storage compatibility](../docs/storage.md). + ## Test with a fake clock ```python @@ -156,5 +158,3 @@ uv run python bench/latency.py --store redis ## License MIT, Zettel Labs, Inc. - -Custom judges can return optional JSON `data`. It reaches `decision["data"]` and subsequent `input["recent"]` verdicts through delivery retries and recovery. Omission keeps the field absent. See [the result contract](../docs/judges.md#carry-a-result-to-the-sink) and [storage compatibility](../docs/storage.md).