From 9194f020eec08c3987ee26e4c64fd773bcde1984 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 26 Nov 2026 18:39:13 -0600 Subject: [PATCH 1/3] feat(core): settle on producer-declared act completion --- CHANGELOG.md | 4 + conformance/fixtures/scenarios.json | 3448 ++++++++++++++++++++- docs/reference.md | 36 +- docs/storage.md | 2 + python/README.md | 1 + python/src/aqi_attend/attend.py | 6 +- python/src/aqi_attend/core/reducer.py | 5 +- python/src/aqi_attend/core/types.py | 8 +- python/src/aqi_attend/core/window.py | 14 +- python/src/aqi_attend/shell/copy.py | 2 + python/tests/scenario.py | 2 + python/tests/test_closing_settlement.py | 70 + python/tests/test_continuation.py | 2 +- python/tests/test_continuous_quiet.py | 4 +- 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 | 3 +- src/core/reducer.ts | 6 +- src/core/types.ts | 13 +- src/core/window.ts | 23 +- src/internal/shared.ts | 7 + test/closing-settlement.test.ts | 76 + test/conformance/scenario.ts | 3 +- test/conformance/scenarios.ts | 62 + test/continuation.test.ts | 2 +- test/continuous-quiet.test.ts | 4 +- test/core-inputs.test.ts | 2 +- test/event-limits.test.ts | 2 +- test/observation-time.test.ts | 2 +- test/recovery.test.ts | 2 +- test/window.test.ts | 2 +- 33 files changed, 3771 insertions(+), 50 deletions(-) create mode 100644 python/tests/test_closing_settlement.py create mode 100644 test/closing-settlement.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 6ea32ca..ef3f707 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ What changed in each release, for people who use attend. The npm package `@acquiredintelligence/attend` and the Python package `aqi-attend` are released together under one version number. +## Unreleased + +- Closing events can set a per-event `quietForMs` for their output. A consequence can carry `settles: true` when that output is complete, including through serial intake. Both runtimes persist the fields at reducer revision 7. See [closing duration and completion](docs/reference.md#closing-duration-and-completion). + ## 0.3.0 (2026-11-14) This is the first release of the Python package. The npm package gains folded notices and five opt-in features, and `attend serve` delivers decisions sooner on Redis and Postgres. diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index c644da9..bf60fbc 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,3451 @@ { "scenarios": [ + { + "scenario": { + "name": "closing combines default grace with explicit deadlines", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "close", + "text": "close a", + "observedAt": 10, + "quietForMs": 800 + }, + { + "id": "b", + "name": "close", + "text": "close b" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 200 + }, + { + "push": "s", + "events": [ + { + "id": "c", + "name": "close", + "text": "close c" + }, + { + "id": "d", + "name": "close", + "text": "close d", + "observedAt": 280, + "quietForMs": 0 + } + ] + }, + { + "advance": 11 + }, + { + "push": "s", + "events": [ + { + "id": "e", + "name": "close", + "text": "close e" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 500 + }, + { + "push": "s", + "events": [ + { + "id": "f", + "name": "close", + "text": "close f", + "observedAt": 700, + "quietForMs": 0 + } + ] + }, + { + "advance": 0 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "45546e68c47d033f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "observedAt": 10, + "quietForMs": 800, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "close", + "data": {}, + "text": "close c", + "kind": "closing", + "seenAt": 300 + }, + { + "id": "d", + "at": 0, + "name": "close", + "data": {}, + "text": "close d", + "observedAt": 280, + "quietForMs": 0, + "kind": "closing", + "seenAt": 300 + }, + { + "id": "e", + "at": 0, + "name": "close", + "data": {}, + "text": "close e", + "kind": "closing", + "seenAt": 311 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 811 + }, + { + "scope": "s", + "window": { + "id": "3ecbd1f2ef91c276", + "events": [ + { + "id": "f", + "at": 0, + "name": "close", + "data": {}, + "text": "close f", + "observedAt": 700, + "quietForMs": 0, + "kind": "closing", + "seenAt": 811 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [ + { + "id": "45546e68c47d033f", + "route": "note", + "at": 811 + } + ], + "now": 811 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "45546e68c47d033f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "45546e68c47d033f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "observedAt": 10, + "quietForMs": 800, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "close", + "data": {}, + "text": "close c", + "kind": "closing", + "seenAt": 300 + }, + { + "id": "d", + "at": 0, + "name": "close", + "data": {}, + "text": "close d", + "observedAt": 280, + "quietForMs": 0, + "kind": "closing", + "seenAt": 300 + }, + { + "id": "e", + "at": 0, + "name": "close", + "data": {}, + "text": "close e", + "kind": "closing", + "seenAt": 311 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "at": 811 + }, + "outcome": "ok" + }, + { + "decision": { + "id": "3ecbd1f2ef91c276", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd1f2ef91c276", + "events": [ + { + "id": "f", + "at": 0, + "name": "close", + "data": {}, + "text": "close f", + "observedAt": 700, + "quietForMs": 0, + "kind": "closing", + "seenAt": 811 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "at": 811 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "45546e68c47d033f", + "reason": "closing", + "count": 5, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "45546e68c47d033f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "45546e68c47d033f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "45546e68c47d033f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "45546e68c47d033f" + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd1f2ef91c276", + "reason": "closing", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd1f2ef91c276", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd1f2ef91c276", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd1f2ef91c276", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd1f2ef91c276" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 3, + "error": null + }, + { + "step": 5, + "error": null + }, + { + "step": 8, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "observedAt": 10, + "quietForMs": 800, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 810 + } + }, + { + "step": 6, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c", + "d", + "e" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "observedAt": 10, + "quietForMs": 800, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "close", + "data": {}, + "text": "close c", + "kind": "closing", + "seenAt": 300 + }, + { + "id": "d", + "at": 0, + "name": "close", + "data": {}, + "text": "close d", + "observedAt": 280, + "quietForMs": 0, + "kind": "closing", + "seenAt": 300 + }, + { + "id": "e", + "at": 0, + "name": "close", + "data": {}, + "text": "close e", + "kind": "closing", + "seenAt": 311 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 811 + } + } + ], + "records": { + "s": { + "version": 10, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c", + "d", + "e", + "f" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "45546e68c47d033f", + "route": "note", + "at": 811 + }, + { + "id": "3ecbd1f2ef91c276", + "route": "note", + "at": 811 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "45546e68c47d033f", + "scope": "s", + "at": 811, + "route": "note", + "body": { + "id": "45546e68c47d033f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "45546e68c47d033f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "observedAt": 10, + "quietForMs": 800, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "kind": "closing", + "seenAt": 100 + }, + { + "id": "c", + "at": 0, + "name": "close", + "data": {}, + "text": "close c", + "kind": "closing", + "seenAt": 300 + }, + { + "id": "d", + "at": 0, + "name": "close", + "data": {}, + "text": "close d", + "observedAt": 280, + "quietForMs": 0, + "kind": "closing", + "seenAt": 300 + }, + { + "id": "e", + "at": 0, + "name": "close", + "data": {}, + "text": "close e", + "kind": "closing", + "seenAt": 311 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "at": 811 + }, + "position": "1" + }, + { + "kind": "decision", + "id": "3ecbd1f2ef91c276", + "scope": "s", + "at": 811, + "route": "note", + "body": { + "id": "3ecbd1f2ef91c276", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd1f2ef91c276", + "events": [ + { + "id": "f", + "at": 0, + "name": "close", + "data": {}, + "text": "close f", + "observedAt": 700, + "quietForMs": 0, + "kind": "closing", + "seenAt": 811 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 811 + }, + "at": 811 + }, + "position": "2" + } + ] + } + }, + { + "scenario": { + "name": "a completion applies only to acts admitted before it", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "early", + "name": "out", + "text": "out early", + "settles": true + }, + { + "id": "act", + "name": "drag", + "text": "drag act" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 10 + }, + { + "push": "s", + "events": [ + { + "id": "early", + "name": "out", + "text": "out early", + "settles": true + } + ] + }, + { + "inspect": "s" + }, + { + "push": "s", + "events": [ + { + "id": "done", + "name": "out", + "text": "out done", + "observedAt": 105, + "settles": true + }, + { + "id": "trailing", + "name": "out", + "text": "out trailing" + } + ] + }, + { + "inspect": "s" + }, + { + "push": "s", + "events": [ + { + "id": "alone", + "name": "out", + "text": "out alone", + "settles": true + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "b1cdf195ebcee12a", + "events": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "observedAt": 105, + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "trailing", + "at": 0, + "name": "out", + "data": {}, + "text": "out trailing", + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 110 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "b1cdf195ebcee12a", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "b1cdf195ebcee12a", + "events": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "observedAt": 105, + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "trailing", + "at": 0, + "name": "out", + "data": {}, + "text": "out trailing", + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "at": 110 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 0, + "duplicates": 1 + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "b1cdf195ebcee12a", + "reason": "closing", + "count": 4, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "b1cdf195ebcee12a", + "attempt": 1, + "offerWait": true + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "judged", + "scope": "s", + "batchId": "b1cdf195ebcee12a", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "b1cdf195ebcee12a", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "b1cdf195ebcee12a" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 3, + "error": null + }, + { + "step": 5, + "error": null + }, + { + "step": 7, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "early", + "act" + ], + "buffer": { + "entries": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1100 + } + }, + { + "step": 4, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "early", + "act" + ], + "buffer": { + "entries": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1100 + } + }, + { + "step": 6, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "early", + "act", + "done", + "trailing" + ], + "buffer": { + "entries": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "observedAt": 105, + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "trailing", + "at": 0, + "name": "out", + "data": {}, + "text": "out trailing", + "kind": "consequence", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null, + "endedAt": 105 + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 105 + } + }, + { + "step": 8, + "scope": "s", + "record": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "early", + "act", + "done", + "trailing", + "alone" + ], + "buffer": { + "entries": [ + { + "id": "alone", + "at": 0, + "name": "out", + "data": {}, + "text": "out alone", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "b1cdf195ebcee12a", + "route": "note", + "at": 110 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "early", + "act", + "done", + "trailing", + "alone" + ], + "buffer": { + "entries": [ + { + "id": "alone", + "at": 0, + "name": "out", + "data": {}, + "text": "out alone", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "b1cdf195ebcee12a", + "route": "note", + "at": 110 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "b1cdf195ebcee12a", + "scope": "s", + "at": 110, + "route": "note", + "body": { + "id": "b1cdf195ebcee12a", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "b1cdf195ebcee12a", + "events": [ + { + "id": "early", + "at": 0, + "name": "out", + "data": {}, + "text": "out early", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "act", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag act", + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "observedAt": 105, + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "trailing", + "at": 0, + "name": "out", + "data": {}, + "text": "out trailing", + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "at": 110 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "ordered completion overrides stream quiet through serial intake", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "intakes": [ + "s" + ], + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "close", + "text": "close a", + "quietForMs": 2000 + }, + { + "id": "b", + "name": "drag", + "text": "drag b", + "quietForMs": 1900 + } + ] + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "wrong", + "name": "close", + "text": "close wrong", + "settles": true + } + ], + "source": "feed", + "cursor": "1" + }, + { + "inspect": "s" + }, + { + "submit": "s", + "events": [ + { + "id": "done", + "name": "out", + "text": "out done", + "settles": true + } + ], + "source": "feed", + "cursor": "2" + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 1900, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 110 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "de2e9a837d937444", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 1900, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "at": 110 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "de2e9a837d937444", + "reason": "closing", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "de2e9a837d937444", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "de2e9a837d937444", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "de2e9a837d937444", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "de2e9a837d937444" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": { + "name": "TypeError", + "message": "attend: settles requires a consequence event" + } + }, + { + "step": 4, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 1900, + "kind": "continuous", + "seenAt": 100 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 2000 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 5, + "scope": "s", + "cursors": { + "feed": "2" + }, + "seen": [ + "a", + "b", + "done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "de2e9a837d937444", + "route": "note", + "at": 110 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 5, + "scope": "s", + "cursors": { + "feed": "2" + }, + "seen": [ + "a", + "b", + "done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "de2e9a837d937444", + "route": "note", + "at": 110 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "de2e9a837d937444", + "scope": "s", + "at": 110, + "route": "note", + "body": { + "id": "de2e9a837d937444", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 1900, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 110 + }, + "at": 110 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "after wait only a fresh act can give a completion effect", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "intakes": [ + "s" + ], + "settle": { + "continuation": "accumulate", + "waitHorizonMs": 100 + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "close", + "text": "close a", + "quietForMs": 2000 + }, + { + "id": "done", + "name": "out", + "text": "out done", + "settles": true + } + ] + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "held-only", + "name": "out", + "text": "out held-only", + "settles": true + } + ] + }, + { + "inspect": "s" + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "close", + "text": "close b", + "quietForMs": 2000 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "fresh-done", + "name": "out", + "text": "out fresh-done", + "settles": true + } + ] + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "95912af0dc2a4b0d", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + }, + { + "scope": "s", + "window": { + "id": "e470113cd11322bd", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "held-only", + "at": 0, + "name": "out", + "data": {}, + "text": "out held-only", + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 110 + }, + { + "id": "fresh-done", + "at": 0, + "name": "out", + "data": {}, + "text": "out fresh-done", + "settles": true, + "kind": "consequence", + "seenAt": 120 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 120 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 120 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "e470113cd11322bd", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "e470113cd11322bd", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "held-only", + "at": 0, + "name": "out", + "data": {}, + "text": "out held-only", + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 110 + }, + { + "id": "fresh-done", + "at": 0, + "name": "out", + "data": {}, + "text": "out fresh-done", + "settles": true, + "kind": "consequence", + "seenAt": 120 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 120 + }, + "at": 120 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "95912af0dc2a4b0d", + "reason": "closing", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "95912af0dc2a4b0d", + "attempt": 1, + "offerWait": true + }, + { + "kind": "waiting", + "scope": "s", + "batchId": "95912af0dc2a4b0d", + "waits": 1, + "until": 200 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "e470113cd11322bd", + "reason": "closing", + "count": 5, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "e470113cd11322bd", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "e470113cd11322bd", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "e470113cd11322bd", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "e470113cd11322bd" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + }, + { + "step": 4, + "error": null + }, + { + "step": 7, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "done", + "held-only" + ], + "buffer": { + "entries": [ + { + "id": "held-only", + "at": 0, + "name": "out", + "data": {}, + "text": "out held-only", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "95912af0dc2a4b0d", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 200, + "failures": 0 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 200 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 5, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "done", + "held-only", + "b" + ], + "buffer": { + "entries": [ + { + "id": "held-only", + "at": 0, + "name": "out", + "data": {}, + "text": "out held-only", + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "95912af0dc2a4b0d", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 200, + "failures": 0 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 200 + } + } + ], + "records": { + "s": { + "version": 9, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "done", + "held-only", + "b", + "fresh-done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "e470113cd11322bd", + "route": "note", + "at": 120 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "e470113cd11322bd", + "scope": "s", + "at": 120, + "route": "note", + "body": { + "id": "e470113cd11322bd", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "e470113cd11322bd", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 100 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + }, + { + "id": "held-only", + "at": 0, + "name": "out", + "data": {}, + "text": "out held-only", + "settles": true, + "kind": "consequence", + "seenAt": 110 + }, + { + "id": "b", + "at": 0, + "name": "close", + "data": {}, + "text": "close b", + "quietForMs": 2000, + "kind": "closing", + "seenAt": 110 + }, + { + "id": "fresh-done", + "at": 0, + "name": "out", + "data": {}, + "text": "out fresh-done", + "settles": true, + "kind": "consequence", + "seenAt": 120 + } + ], + "reason": "closing", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 120 + }, + "at": 120 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "completion preserves the accumulating retry deadline", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "intakes": [ + "s" + ], + "settle": { + "continuation": "accumulate", + "retryBackoffMs": [ + 40 + ] + }, + "judge": { + "*": { + "answers": [ + { + "fail": "outage" + }, + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 0 + } + ] + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b" + }, + { + "id": "done", + "name": "out", + "text": "out done", + "settles": true + } + ] + }, + { + "advance": 29 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + }, + { + "scope": "s", + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 110 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 140 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "de2e9a837d937444", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 110 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "at": 140 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "retrying", + "scope": "s", + "stage": "judge", + "id": "3ecbd4f2ef91c78f", + "attempt": 1, + "at": 140, + "message": "outage" + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "de2e9a837d937444", + "reason": "closing", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "de2e9a837d937444", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "de2e9a837d937444", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "de2e9a837d937444", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "de2e9a837d937444" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 4, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "done" + ], + "buffer": { + "entries": [ + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 110 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null, + "endedAt": 110 + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 140, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 140 + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "de2e9a837d937444", + "route": "note", + "at": 140 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "de2e9a837d937444", + "scope": "s", + "at": 140, + "route": "note", + "body": { + "id": "de2e9a837d937444", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "de2e9a837d937444", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 100 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 110 + }, + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 110 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 140 + }, + "at": 140 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "completion takes effect before background retention", + "start": 100, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "intakes": [ + "s" + ], + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 0 + } + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "close", + "text": "close a" + }, + { + "id": "done", + "name": "out", + "text": "out done", + "settles": true + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "close", + "data": {}, + "text": "close a", + "kind": "closing", + "seenAt": 100 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 1, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + } + ] + }, + "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": 100 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 1, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "done", + "at": 0, + "name": "out", + "data": {}, + "text": "out done", + "settles": true, + "kind": "consequence", + "seenAt": 100 + } + ], + "why": "overflow" + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "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": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 100 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "done" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 100, + "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": 100 + } + ], + "reason": "closing", + "waits": 0, + "dropped": 1, + "gap": false, + "settledAt": 100 + }, + "at": 100 + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "decision data survives wait, delivery retry and recent context", @@ -15936,7 +19382,7 @@ "step": 0, "error": { "name": "TypeError", - "message": "attend: quietForMs requires a continuous event" + "message": "attend: quietForMs requires a continuous or closing event" } }, { diff --git a/docs/reference.md b/docs/reference.md index 597cd47..9aa76b0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -4,14 +4,14 @@ | Kind | Use it for | Settles the window | |---|---|---| -| `closing` | The end of an act: a submit, a save, a merged pull request, a finished build | `closingGraceMs` after the last closing event, so the output it causes can join the window | +| `closing` | The end of an act: a submit, a save, a merged pull request, a finished build | After the latest [closing deadline](#closing-duration-and-completion), so the output it causes can join the window | | `flush` | Someone addresses the agent directly: a message to it, an @mention | At once. `wait` is not offered. | | `continuous` | One step of an ongoing act: typing, scrolling, dragging, a partial transcript | Once no continuous event has arrived for `streamGapMs` | | `passive` | A dwell or a look: a hover, a focus, a page view | `passiveQuietMs` after the last passive event | -| `consequence` | System output: a log line, a status change, a tool result | Never. It joins the open window. | +| `consequence` | System output: a log line, a status change, a tool result | Joins the open window. With [`settles: true`](#closing-duration-and-completion), it can end the acts already there. | | `context` | The agent's own output | Never. It joins the open window as context for the judge, and [`defaultNotice`](sinks.md#the-notice) leaves it out. | -`closing`, `flush`, `continuous` and `passive` events are acts: things that happen in the scope and can call for the agent, whether the user did them or an outside party did. A window also settles when its first act is `maxWindowMs` old (reason `age`), when it fills its share of the judge's context window (reason `size`, see [the window budget](judges.md#the-window-budget)), when you call `attend.end(scope)` because the producer knows the unit is over (reason `closing`, `wait` still offered), or when you call `attend.flush(scope)` (reason `forced`, with `wait` not offered). When a window passes `maxEvents`, attend drops its oldest consequence and context events and counts them in `window.dropped`. If the window is still too big, it settles with reason `overflow`. attend never drops an act. Consequence and context events that wait longer than `maxWindowMs` for an act are dropped and counted the same way. +`closing`, `continuous` and `passive` events are acts: things that happen in the scope and can call for the agent, whether the user did them or an outside party did. A window also settles when its first act is `maxWindowMs` old (reason `age`), when it fills its share of the judge's context window (reason `size`, see [the window budget](judges.md#the-window-budget)), when you call `attend.end(scope)` because the producer knows the unit is over (reason `closing`, `wait` still offered), or when you call `attend.flush(scope)` (reason `forced`, with `wait` not offered). When a window passes `maxEvents`, attend drops its oldest consequence and context events and counts them in `window.dropped`. If the window is still too big, it settles with reason `overflow`. attend never drops an act. Consequence and context events that wait longer than `maxWindowMs` for an act are dropped and counted the same way. A system event that should wake the agent on its own, such as a failed deploy or a fired alert, needs an act kind. `closing` is the usual choice. @@ -48,7 +48,7 @@ Both runtimes retain `observedAt` through snapshots, logged inputs, windows and ## Continuous quiet duration -A continuous event can supply a finite, nonnegative `quietForMs`. Zero makes its quiet deadline immediate. `push` and `attach` refuse invalid values or a duration on any other kind before admitting the batch or committing its cursor. +A continuous event can supply a finite, nonnegative `quietForMs`. Zero makes its quiet deadline immediate. `push` and `attach` refuse invalid values or a duration on a kind other than `continuous` or `closing` before admitting the batch or committing its cursor. Once a continuous entry supplies a duration, that group's deadline is the maximum of each entry's observation time plus its duration. An omitted duration uses `streamGapMs`; an omitted observation uses ingestion time. A late observation can therefore be due on arrival, but settlement still happens at processing time. Entry order does not change. @@ -73,6 +73,28 @@ Closing and passive deadlines can still settle the window earlier. Flush, age an When every continuous entry omits `quietForMs`, existing timing remains unchanged, including backwards engine clocks. Explicit durations persist through snapshots, tails and decisions. Replay uses the snapshot policy for omitted durations. Changing a live engine's policy recalculates those default durations; it never changes an explicit duration. [Storage](storage.md) describes version coordination. +## Closing duration and completion + +A `closing` event can supply a finite, nonnegative `quietForMs` in milliseconds. The closing deadline is the latest of the default grace deadline and each explicit entry's effective observation time plus its duration. The default grace applies only to closing entries that omit the field. That group keeps the existing observation-time rule. With no explicit observation in the group, it uses the last entry's ingestion time. Zero gives an explicit entry no grace. Other deadlines can still settle the window earlier. + +Use `settles: true` on a `consequence` event when the producer knows the output is complete. If the open window already contains a `closing`, `continuous` or `passive` act, this makes the window due at the consequence's effective observation time under the same settlement rules as `end(scope)`. It can end an ongoing continuous stream immediately, with reason `closing` and `wait` offered within the usual limits. An already-due observation still settles at processing time. + +A completion with only background or held entries has no settlement effect. Entries later in the same batch still join that batch. The completion remains a consequence for retention even when it sets an end deadline. Both fields are validated before event admission or cursor commit. Supply `settles` only on a consequence and give it the literal value `true`. + +```ts +import { createAttend } from '@acquiredintelligence/attend'; + +const attend = createAttend({ + kind: { saved: 'closing', indexed: 'consequence' }, + judge: async () => ({ route: 'note' }), + sink: 'log', +}); +await attend.push('document', { name: 'saved', quietForMs: 2000 }); +await attend.push('document', { name: 'indexed', settles: true }); +``` + +Both fields work through `push`, `attach` and serial intake. Stored entries retain them in snapshots, logged inputs and decision records. Replay uses the snapshot policy for closing entries that use the default grace. See [storage](storage.md) for version coordination. + ## Routes | Route | The agent | Reaches the sink | @@ -124,7 +146,7 @@ A timer claims the scope before its write starts. During preparation or immediat The promise covers the input write and the immediate chain of judgments, deliveries and their completion, release or deferral writes. A failed immediate write rejects it. A persisted wait or retry with a future deadline releases the turn; the promise does not wait for that future attempt or an open window's quiet deadline. A cursor can therefore already be committed when a later effect write fails. A caller that retries must supply stable event ids and make external delivery idempotent. -An opted-in scope refuses ordinary `push`, `attach`, `flush` and `end`, including after close. Same-engine, same-scope `submit` or `close` from preparation, context, judge or delivery rejects with `IntakeError`; awaiting it would wait on itself. Other scopes progress independently. Do not create cycles by awaiting each other's intakes from callbacks. +An opted-in scope refuses ordinary `push`, `attach`, `flush` and `end`, including after close. Submit a consequence with `settles: true` to end an act in event order. Same-engine, same-scope `submit` or `close` from preparation, context, judge or delivery rejects with `IntakeError`; awaiting it would wait on itself. Other scopes progress independently. Do not create cycles by awaiting each other's intakes from callbacks. An engine's `stop()` also rejects from its own intake callback context, because shutdown joins that callback. To request shutdown from a callback, abort the signal supplied to `run()` and return; await stop from outside the callback. @@ -149,9 +171,9 @@ const attend = createAttend({ }); ``` -After a `wait`, fresh entries alone drive quiet. At the horizon, attend reoffers the whole unresolved window, including fresh entries that are not quiet yet. It can offer `wait` again until `maxWaits` or a whole-window bound requires resolution. A provider failure retains the wait count; a successful `wait` retains the provider failure count. The latter selects the next retry backoff. +After a `wait`, fresh entries alone drive quiet. A consequence with `settles: true` also needs a fresh act earlier in the open window. At the horizon, attend reoffers the whole unresolved window, including fresh entries that are not quiet yet. It can offer `wait` again until `maxWaits` or a whole-window bound requires resolution. A provider failure retains the wait count; a successful `wait` retains the provider failure count. The latter selects the next retry backoff. -During retry, its deadline is a strict not-before time. Fresh quiet, direct address, `flush()`, `end()`, age, count and bytes do not start a judgment earlier. At retry time, every entry still retained after pruning joins the held window. Gap and dropped-entry metadata join its next offer even when no fresh entry survives, and are then cleared from the fresh buffer. A timer that owns serial intake before a later raw registration can retry without that later entry. `flush()` still removes wait and supplies reason `forced`. `end()` applies to fresh open input, keeps reason `closing` and permits wait within the limits; with only an already-settled held window it remains a no-op. +During retry, its deadline is a strict not-before time. Fresh quiet, direct address, `flush()`, `end()`, `settles: true`, age, count and bytes do not start a judgment earlier. At retry time, every entry still retained after pruning joins the held window. Gap and dropped-entry metadata join its next offer even when no fresh entry survives, and are then cleared from the fresh buffer. A timer that owns serial intake before a later raw registration can retry without that later entry. `flush()` still removes wait and supplies reason `forced`. `end()` applies to fresh open input, keeps reason `closing` and permits wait within the limits; with only an already-settled held window it remains a no-op. Eligibility uses the complete offered payload after the usual background shedding. Acts are never dropped. Count above `maxEvents`, rendered bytes at or above `maxWindowBytes`, and age at or above `maxWindowMs` withhold wait. Age starts at the earliest unresolved act's effective observation time. These checks also apply at initial offers, exact quiet/age ties and after absorbing an older observation. A bound makes a waiting window due; during backoff it takes effect at retry time. It does not interrupt an already running judge. A bound can withhold wait even when another deadline supplied the window's reason. Count and rendered bytes are not hard memory-allocation limits. diff --git a/docs/storage.md b/docs/storage.md index 69c26cd..6e181ef 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -45,3 +45,5 @@ Keep processes sharing a store on the same reducer version before using [observa 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. + +[Closing durations and completion](reference.md#closing-duration-and-completion) use reducer revision 7. Upgrade every reader and writer sharing a store before using either field. Replay uses the saved policy for default grace and the logged event times for explicit deadlines. diff --git a/python/README.md b/python/README.md index aeb22d0..f42bab4 100644 --- a/python/README.md +++ b/python/README.md @@ -83,6 +83,7 @@ redis-py runs each concurrent command on a pooled connection of its own, and its - `settle={"continuation": "accumulate"}` retains one unresolved window through waits and retries. [Accumulating continuation](https://github.com/acquiredintelligence/attend/blob/main/docs/reference.md#accumulating-continuation) defines its bounds, failure allowance and stored-mode boundary. - Add `"event_limits": {"counted": 3, "background": 2}` to that setting for an independent counted trigger and background capacity. Both numbers are required; do not also supply `max_events`. [Independent event limits](https://github.com/acquiredintelligence/attend/blob/main/docs/reference.md#independent-event-limits) defines retention, atomic input and saved-policy rules. - A continuous event can carry `quietForMs` in its wire dictionary. [Continuous quiet duration](https://github.com/acquiredintelligence/attend/blob/main/docs/reference.md#continuous-quiet-duration) defines its validation, defaults and recovery. +- A closing event can also carry `quietForMs`. A consequence can carry `settles: True` to end the acts already in the open window, including through serial intake. [Closing duration and completion](https://github.com/acquiredintelligence/attend/blob/main/docs/reference.md#closing-duration-and-completion) defines both fields. - An event's optional `observedAt` keeps its camelCase wire name. It supplies source observation time for deadlines; `seenAt` remains engine ingestion time. The shared [observation-time reference](https://github.com/acquiredintelligence/attend/blob/main/docs/reference.md#observation-time) defines validation, ordering and replay. - Cancelling the task that runs `run()` stops it the way `stop()` does. - `default_notice(decision, max_lines=20, fold=True)` takes its options as keyword arguments. [The notice](https://github.com/acquiredintelligence/attend/blob/main/docs/sinks.md#the-notice) says what it folds. diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index 6a44737..fbeb477 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -375,8 +375,10 @@ def _classify(self, given: Mapping[str, Any] | Sequence[Mapping[str, Any]]) -> l kind = self._kind(copied) if kind not in KINDS: raise TypeError("attend: invalid event kind") - if "quietForMs" in copied and kind != "continuous": - raise TypeError("attend: quietForMs requires a continuous event") + if "quietForMs" in copied and kind not in ("continuous", "closing"): + raise TypeError("attend: quietForMs requires a continuous or closing event") + if "settles" in copied and kind != "consequence": + raise TypeError("attend: settles requires a consequence event") classified.append(cast(KindedEvent, {**copied, "kind": kind})) return classified diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index 9f73344..c0c26dd 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -49,7 +49,7 @@ window_shed, ) -REDUCER_VERSION = 6 +REDUCER_VERSION = 7 """Bumped whenever a release changes a transition. Stored with every snapshot.""" _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") @@ -223,6 +223,9 @@ def _ingest(ctx: _Ctx, state: ScopeState, input: EventsInput) -> None: duplicates += 1 continue entry = cast(Entry, {**event, "seenAt": ctx.now}) + # Act presence is checked in admission order, before background retention. + if entry["kind"] == "consequence" and entry.get("settles") is True and state.open.summary.first_act_index != -1: + state.open.ended_at = observation_time(entry) window_append(state.open, entry, estimate_rendered_bytes(entry)) ctx.out.changed = True if state.seen.size > max(0, policy["seenCount"]): diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 0ae4c1f..21d673d 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -32,6 +32,7 @@ class Event(TypedDict): at: float observedAt: NotRequired[float] quietForMs: NotRequired[float] + settles: NotRequired[Literal[True]] name: str data: JsonObject text: NotRequired[str] @@ -522,17 +523,18 @@ class TriggerSummary: """Everything ``deadline`` reads, kept O(1). Absent times use NaN; minima start at inf and maxima at -inf.""" min_flush_at: float = math.inf - last_closing_at: float = math.nan + last_default_closing_at: float = math.nan last_stream_at: float = math.nan last_passive_at: float = math.nan first_act_at: float = math.nan - max_closing_at: float = -math.inf + max_default_closing_at: float = -math.inf + max_explicit_closing_end_at: float = -math.inf max_stream_at: float = -math.inf max_default_stream_at: float = -math.inf max_explicit_stream_end_at: float = -math.inf max_passive_at: float = -math.inf min_act_at: float = math.inf - closing_observed: bool = False + default_closing_observed: bool = False stream_observed: bool = False passive_observed: bool = False act_observed: bool = False diff --git a/python/src/aqi_attend/core/window.py b/python/src/aqi_attend/core/window.py index 4f40498..30a351e 100644 --- a/python/src/aqi_attend/core/window.py +++ b/python/src/aqi_attend/core/window.py @@ -32,9 +32,12 @@ def _summarize_entry(summary: TriggerSummary, entry: Entry, index: int) -> None: if kind == "flush": summary.min_flush_at = _min(summary.min_flush_at, seen_at) elif kind == "closing": - summary.max_closing_at = _max(summary.max_closing_at, observed_at) - summary.closing_observed |= explicit - summary.last_closing_at = summary.max_closing_at if summary.closing_observed else seen_at + if "quietForMs" in entry: + summary.max_explicit_closing_end_at = _max(summary.max_explicit_closing_end_at, observed_at + entry["quietForMs"]) + else: + summary.max_default_closing_at = _max(summary.max_default_closing_at, observed_at) + summary.default_closing_observed |= explicit + summary.last_default_closing_at = summary.max_default_closing_at if summary.default_closing_observed else seen_at elif kind == "continuous": summary.max_stream_at = _max(summary.max_stream_at, observed_at) summary.stream_observed |= explicit @@ -269,8 +272,9 @@ def window_deadline(policy: SettlePolicy, open: OpenWindow) -> tuple[float, Sett if s.min_flush_at != math.inf and (reason is None or s.min_flush_at < at): at = s.min_flush_at reason = "flush" - closing = s.last_closing_at + policy["closingGraceMs"] - if not math.isnan(s.last_closing_at) and (reason is None or closing < at): + has_default_closing = not math.isnan(s.last_default_closing_at) + closing = _max(s.last_default_closing_at + policy["closingGraceMs"], s.max_explicit_closing_end_at) if has_default_closing else s.max_explicit_closing_end_at + if (has_default_closing or closing != -math.inf) and (reason is None or closing < at): at = closing reason = "closing" if s.max_explicit_stream_end_at == -math.inf: diff --git a/python/src/aqi_attend/shell/copy.py b/python/src/aqi_attend/shell/copy.py index e3dfbab..442b139 100644 --- a/python/src/aqi_attend/shell/copy.py +++ b/python/src/aqi_attend/shell/copy.py @@ -57,6 +57,8 @@ def copy_event(event: Mapping[str, object], fill: tuple[Callable[[], str], Calla raise TypeError("attend: event keys must be strings") if key == "data": continue + if key == "settles" and value is not True: + raise TypeError("attend: settles must be true") fields[key] = _to_json(value, 1) data = event.get("data", {} if fill is not None else None) if not isinstance(data, Mapping): diff --git a/python/tests/scenario.py b/python/tests/scenario.py index 90a2920..b2b2e41 100644 --- a/python/tests/scenario.py +++ b/python/tests/scenario.py @@ -27,6 +27,8 @@ def event_spec(spec: Mapping[str, Any]) -> Event: event["observedAt"] = spec["observedAt"] if "quietForMs" in spec: event["quietForMs"] = spec["quietForMs"] + if "settles" in spec: + event["settles"] = spec["settles"] return event diff --git a/python/tests/test_closing_settlement.py b/python/tests/test_closing_settlement.py new file mode 100644 index 0000000..a73ffae --- /dev/null +++ b/python/tests/test_closing_settlement.py @@ -0,0 +1,70 @@ +"""Closing durations and consequence completion at the event boundary.""" + +import asyncio +from collections.abc import Awaitable, Callable + +import pytest + +from aqi_attend import AbortController, AbortSignal, create_attend, memory_store +from aqi_attend.core.types import Kind, SourceBatch +from aqi_attend.testing import fake_clock, scripted_judge + + +async def test_attached_completion_replays_with_its_cursor() -> None: + clock = fake_clock(100) + store = memory_store() + judge = scripted_judge([{"route": "note"}]) + kinds: dict[str, Kind] = {"save": "closing", "move": "continuous", "out": "consequence"} + writer = create_attend(clock=clock, store=store, judge=judge, sink="log", kind=kinds) + controller = AbortController() + + class Feed: + key = "feed" + + async def subscribe(self, _cursor: str | None, emit: Callable[[SourceBatch], Awaitable[None]], _signal: AbortSignal) -> None: + try: + await emit({"events": [{"id": "done", "at": 0, "name": "out", "data": {}, "observedAt": 80, "settles": True}], "cursor": "2"}) + finally: + controller.abort() + + try: + await writer.push("s", [{"id": "act", "name": "save", "quietForMs": 2000}, {"id": "stream", "name": "move", "quietForMs": 2000}]) + await writer.attach("s", Feed(), signal=controller.signal) + stored = await store.load("s") + assert stored is not None and stored["snapshot"] is not None + assert stored["snapshot"]["record"]["buffer"]["entries"][0].get("quietForMs") == 2000 + tail_input = stored["tail"][0]["input"] + assert tail_input["kind"] == "events" and tail_input["events"][0].get("settles") is True + finally: + await writer.stop() + + reader = create_attend(clock=clock, store=store, judge=judge, sink="log", kind=kinds) + running = asyncio.create_task(reader.run()) + try: + record = await reader.inspect("s") + assert record is not None and record["dueAt"] == record["buffer"].get("endedAt") == 80 + assert record["cursors"] == {"feed": "2"} + await clock.advance(0) + (call,) = judge.calls + assert any(route["route"] == "wait" for route in call["routes"]) + window = call["window"] + assert (window["reason"], window["settledAt"]) == ("closing", 100) + assert [event["id"] for event in window["events"]] == ["act", "stream", "done"] + assert window["events"][0].get("quietForMs") == 2000 + assert window["events"][2].get("settles") is True + finally: + await reader.stop() + await running + await store.close() + + +@pytest.mark.parametrize("settles", [False, None, 1, "true"]) +async def test_invalid_completion_refuses_whole_batch(settles: object) -> None: + attend = create_attend(clock=fake_clock(100), kind={"save": "closing", "out": "consequence"}, judge=scripted_judge([]), sink="log") + try: + with pytest.raises(TypeError, match="settles"): + await attend.push("s", [{"name": "save"}, {"name": "out", "settles": settles}]) + assert await attend.inspect("s") is None + finally: + await attend.stop() + await attend.store.close() diff --git a/python/tests/test_continuation.py b/python/tests/test_continuation.py index c449fc6..80f8e03 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"] == 6 + assert stored["snapshot"]["reducer"] == 7 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 19b6628..590c518 100644 --- a/python/tests/test_continuous_quiet.py +++ b/python/tests/test_continuous_quiet.py @@ -97,7 +97,7 @@ async def test_invalid_duration_refuses_whole_batch(quiet: object) -> None: await attend.store.close() -@pytest.mark.parametrize("kind", ["closing", "passive", "flush", "consequence", "context"]) +@pytest.mark.parametrize("kind", ["passive", "flush", "consequence", "context"]) async def test_duration_on_other_kind_refuses_whole_batch(kind: Kind) -> None: attend = create_attend(clock=fake_clock(100), kind=lambda event: "continuous" if event["name"] == "move" else kind, judge=scripted_judge([{"route": "queue"}]), sink="log") try: @@ -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"] == 6 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 7 finally: await attend.stop() await store.close() diff --git a/python/tests/test_event_limits.py b/python/tests/test_event_limits.py index 0211be3..35c6ba9 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"] == 6 + assert stored["snapshot"]["reducer"] == 7 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 56f13ea..f7acebc 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"] == 6 and stored["tail"] + assert stored["snapshot"]["reducer"] == 7 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 43da12e..db2daf9 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"] == 6 and stored["tail"] + assert stored["snapshot"]["reducer"] == 7 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 11902a0..0c9686b 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"] == 6 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 7 finally: await attend.stop() await store.close() diff --git a/src/attend.ts b/src/attend.ts index 2c51591..4689f5c 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -101,7 +101,8 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' if (event.observedAt !== undefined && event.observedAt > clock.now()) throw new TypeError('attend: observedAt must not be in the future'); const kind = kindOf(event); if (!KINDS.includes(kind)) throw new TypeError('attend: invalid event kind'); - if (event.quietForMs !== undefined && kind !== 'continuous') throw new TypeError('attend: quietForMs requires a continuous event'); + if (event.quietForMs !== undefined && kind !== 'continuous' && kind !== 'closing') throw new TypeError('attend: quietForMs requires a continuous or closing event'); + if (event.settles !== undefined && kind !== 'consequence') throw new TypeError('attend: settles requires a consequence event'); const entry = { ...event, kind }; sizedEvents.set(entry, bytes); classified[i] = entry; diff --git a/src/core/reducer.ts b/src/core/reducer.ts index 7b1c58e..26c93e5 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 = 6; +export const REDUCER_VERSION = 7; /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { @@ -127,6 +127,10 @@ function ingest(ctx: Ctx, state: ScopeState, input: EventsInput): void { for (const event of input.events) { if (!seenAdmit(state, event.id)) { duplicates += 1; continue; } const entry = { ...event, seenAt: ctx.now }; + // Act presence is checked in admission order, before background retention. + if (entry.kind === 'consequence' && entry.settles === true && state.open.summary.firstActIndex !== -1) { + state.open.endedAt = observationTime(entry); + } windowAppend(state.open, entry, estimateRenderedBytes(entry)); ctx.out.changed = true; } diff --git a/src/core/types.ts b/src/core/types.ts index aca84c3..ed9c3a8 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -14,8 +14,10 @@ export interface Event { at: number; /** Source observation time in the engine clock's coordinates. Omit to settle from ingestion. */ observedAt?: number; - /** Quiet duration for a continuous event, in ms. Omit to use streamGapMs. */ + /** Quiet duration in ms for a continuous or closing event. Omit to use the kind's policy default. */ quietForMs?: number; + /** A consequence that ends the acts already in the open window. */ + settles?: true; name: string; data: JsonObject; /** One plain line describing the event, used by the default notice. */ @@ -33,7 +35,7 @@ export const KINDS = ['closing', 'flush', 'continuous', 'passive', 'consequence' * - flush: direct address; settles at once, with wait not offered, and is never shed. * - continuous: one step of an ongoing act; settles once no further step has arrived for a gap. * - passive: a dwell or look; settles after a quiet period. - * - consequence: output that follows from an act; attaches to the act that caused it. + * - consequence: output that follows from an act; can end the open window with settles. * - context: the agent's own earlier output; rides along. */ export type Kind = (typeof KINDS)[number]; @@ -522,19 +524,20 @@ export type KnownIds = Map; */ export interface TriggerSummary { minFlushAt: number; - lastClosingAt: number; + lastDefaultClosingAt: number; lastStreamAt: number; lastPassiveAt: number; firstActAt: number; /** Candidate extrema retain earlier entries before a kind first uses observation time. */ - maxClosingAt: number; + maxDefaultClosingAt: number; + maxExplicitClosingEndAt: number; maxStreamAt: number; /** Default durations retain observation time so policy changes can recompute their ends. */ maxDefaultStreamAt: number; maxExplicitStreamEndAt: number; maxPassiveAt: number; minActAt: number; - closingObserved: boolean; + defaultClosingObserved: boolean; streamObserved: boolean; passiveObserved: boolean; actObserved: boolean; diff --git a/src/core/window.ts b/src/core/window.ts index 218c511..95ae507 100644 --- a/src/core/window.ts +++ b/src/core/window.ts @@ -17,11 +17,11 @@ export function estimateRenderedBytes(event: Event): number { function emptySummary(): TriggerSummary { return { - minFlushAt: Infinity, lastClosingAt: NaN, lastStreamAt: NaN, lastPassiveAt: NaN, + minFlushAt: Infinity, lastDefaultClosingAt: NaN, lastStreamAt: NaN, lastPassiveAt: NaN, firstActAt: NaN, firstActIndex: -1, prefixMinSheddableAt: Infinity, sheddable: 0, lastSeenAt: NaN, - maxClosingAt: -Infinity, maxStreamAt: -Infinity, maxPassiveAt: -Infinity, minActAt: Infinity, + maxDefaultClosingAt: -Infinity, maxExplicitClosingEndAt: -Infinity, maxStreamAt: -Infinity, maxPassiveAt: -Infinity, minActAt: Infinity, maxDefaultStreamAt: -Infinity, maxExplicitStreamEndAt: -Infinity, - closingObserved: false, streamObserved: false, passiveObserved: false, actObserved: false, lastObservationAt: NaN, + defaultClosingObserved: false, streamObserved: false, passiveObserved: false, actObserved: false, lastObservationAt: NaN, }; } @@ -31,9 +31,13 @@ function summarizeEntry(summary: TriggerSummary, entry: Entry, index: number): v if (entry.kind === 'flush') summary.minFlushAt = Math.min(summary.minFlushAt, entry.seenAt); // Without explicit observations, keep the handling of a backwards engine clock. if (entry.kind === 'closing') { - summary.maxClosingAt = Math.max(summary.maxClosingAt, observedAt); - summary.closingObserved ||= explicit; - summary.lastClosingAt = summary.closingObserved ? summary.maxClosingAt : entry.seenAt; + if (entry.quietForMs === undefined) { + summary.maxDefaultClosingAt = Math.max(summary.maxDefaultClosingAt, observedAt); + summary.defaultClosingObserved ||= explicit; + summary.lastDefaultClosingAt = summary.defaultClosingObserved ? summary.maxDefaultClosingAt : entry.seenAt; + } else { + summary.maxExplicitClosingEndAt = Math.max(summary.maxExplicitClosingEndAt, observedAt + entry.quietForMs); + } } if (entry.kind === 'continuous') { summary.maxStreamAt = Math.max(summary.maxStreamAt, observedAt); @@ -275,8 +279,11 @@ export function windowDeadline(policy: SettlePolicy, open: OpenWindow): { at: nu at = s.minFlushAt; reason = 'flush'; } - const closing = s.lastClosingAt + policy.closingGraceMs; - if (!Number.isNaN(s.lastClosingAt) && (reason === null || closing < at)) { + const hasDefaultClosing = !Number.isNaN(s.lastDefaultClosingAt); + const closing = hasDefaultClosing + ? Math.max(s.lastDefaultClosingAt + policy.closingGraceMs, s.maxExplicitClosingEndAt) + : s.maxExplicitClosingEndAt; + if ((hasDefaultClosing || closing !== -Infinity) && (reason === null || closing < at)) { at = closing; reason = 'closing'; } diff --git a/src/internal/shared.ts b/src/internal/shared.ts index 1eddad3..f760812 100644 --- a/src/internal/shared.ts +++ b/src/internal/shared.ts @@ -72,6 +72,7 @@ function copyObject(value: object, key: string | number, depth: number): JsonVal const field = source[name]; if (depth === 0 && name === 'observedAt') checkObservation(field); if (depth === 0 && name === 'quietForMs') checkQuietDuration(field); + if (depth === 0 && name === 'settles') checkSettles(field); const copied = toJson(field, name, depth + 1); if (copied === undefined) continue; if (name === '__proto__') defineProperty(object, name, { value: copied, enumerable: true, writable: true, configurable: true }); @@ -125,6 +126,7 @@ export function copyEvent(event: Event, defaultData = false): Event { fields.data = data; checkObservation(fields.observedAt); checkQuietDuration(fields.quietForMs); + checkSettles(fields.settles); return fields as unknown as Event; } return checkedEvent(toJson(fields, '', 0), defaultData); @@ -137,6 +139,7 @@ function checkedEvent(copied: JsonValue | undefined, defaultData: boolean): Even if (!isRecord(copied) || !isRecord(copied.data)) throw new TypeError('attend: event data must be a JSON object'); checkObservation(copied.observedAt); checkQuietDuration(copied.quietForMs); + checkSettles(copied.settles); return copied as unknown as Event; } @@ -144,6 +147,10 @@ function checkObservation(value: unknown): void { if (value !== undefined && (typeof value !== 'number' || !isFinite(value))) throw new TypeError('attend: observedAt must be a finite number'); } +function checkSettles(value: unknown): void { + if (value !== undefined && value !== true) throw new TypeError('attend: settles must be true'); +} + function checkQuietDuration(value: unknown): void { if (value !== undefined && (typeof value !== 'number' || !isFinite(value) || value < 0)) throw new TypeError('attend: quietForMs must be a finite nonnegative number'); } diff --git a/test/closing-settlement.test.ts b/test/closing-settlement.test.ts new file mode 100644 index 0000000..92baea7 --- /dev/null +++ b/test/closing-settlement.test.ts @@ -0,0 +1,76 @@ +import { expect, test } from 'vitest'; +import { createAttend, memoryStore, type SourceBatch } from '../src/index.js'; +import { fakeClock, scriptedJudge } from '../src/testing.js'; + +test('closing waits for the latest explicit or default deadline', async () => { + const attend = createAttend({ clock: fakeClock(100), kind: { save: 'closing' }, judge: scriptedJudge([]), sink: 'log' }); + try { + await attend.push('s', [ + { id: 'long', name: 'save', observedAt: 10, quietForMs: 2000 }, + { id: 'default', name: 'save' }, + { id: 'short', name: 'save', observedAt: 80, quietForMs: 20 }, + ]); + expect((await attend.inspect('s'))?.dueAt).toBe(2010); + } finally { + await attend.stop(); + } +}); + +test('an attached completion settles a live stream and replays with its cursor', async () => { + const clock = fakeClock(100); + const store = memoryStore(); + const judge = scriptedJudge([{ route: 'note' }]); + const config = { clock, store, judge, sink: 'log', kind: { save: 'closing', move: 'continuous', out: 'consequence' } } as const; + const writer = createAttend(config); + const completion: SourceBatch = { + events: [{ id: 'done', at: 0, name: 'out', data: {}, observedAt: 80, settles: true }], + cursor: '2', + }; + try { + await writer.push('s', [ + { id: 'act', name: 'save', quietForMs: 2000 }, + { id: 'stream', name: 'move', quietForMs: 2000 }, + ]); + const controller = new AbortController(); + await writer.attach('s', { + key: 'feed', + async subscribe(_cursor, emit) { + try { await emit(completion); } + finally { controller.abort(); } + }, + }, { signal: controller.signal }); + const stored = await store.load('s'); + expect(stored?.snapshot?.record.buffer.entries).toMatchObject([{ id: 'act', quietForMs: 2000 }, { id: 'stream' }]); + expect(stored?.tail).toMatchObject([{ input: { kind: 'events', events: [{ id: 'done', settles: true }], cursor: '2' } }]); + } finally { + await writer.stop(); + } + + const reader = createAttend(config); + expect(await reader.inspect('s')).toMatchObject({ + dueAt: 80, cursors: { feed: '2' }, buffer: { endedAt: 80 }, + }); + const running = reader.run(); + try { + await clock.advance(0); + expect(judge.calls).toHaveLength(1); + expect(judge.calls[0]).toMatchObject({ + routes: expect.arrayContaining([{ route: 'wait' }]), + window: { reason: 'closing', settledAt: 100, events: [{ quietForMs: 2000 }, { id: 'stream' }, { settles: true }] }, + }); + } finally { + await reader.stop(); + await running; + } +}); + +test.each([false, null, 1, 'true', Symbol('settles'), { toJSON: () => undefined }])('invalid settles value %s refuses the whole batch', async (settles) => { + const attend = createAttend({ clock: fakeClock(100), kind: { save: 'closing', out: 'consequence' }, judge: scriptedJudge([]), sink: 'log' }); + try { + // @ts-expect-error decoded input can violate the declared type + await expect(attend.push('s', [{ name: 'save' }, { name: 'out', settles }])).rejects.toThrow('settles'); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); diff --git a/test/conformance/scenario.ts b/test/conformance/scenario.ts index e506461..484d205 100644 --- a/test/conformance/scenario.ts +++ b/test/conformance/scenario.ts @@ -56,6 +56,7 @@ export interface EventSpec { at?: number; observedAt?: number; quietForMs?: number; + settles?: true; data?: JsonObject; text?: string; } @@ -277,7 +278,7 @@ export async function runScenario(scenario: Scenario): Promise { if ('push' in step || 'submit' in step) { const scope = 'push' in step ? step.push : step.submit; scopes.add(scope); - const events = step.events.map((e) => ({ id: e.id, at: e.at ?? 0, name: e.name, data: e.data ?? {}, ...(e.text === undefined ? {} : { text: e.text }), ...(e.observedAt === undefined ? {} : { observedAt: e.observedAt }), ...(e.quietForMs === undefined ? {} : { quietForMs: e.quietForMs }) })); + const events = step.events.map((e) => ({ id: e.id, at: e.at ?? 0, name: e.name, data: e.data ?? {}, ...(e.text === undefined ? {} : { text: e.text }), ...(e.observedAt === undefined ? {} : { observedAt: e.observedAt }), ...(e.quietForMs === undefined ? {} : { quietForMs: e.quietForMs }), ...(e.settles === undefined ? {} : { settles: e.settles }) })); if ('push' in step) await result(index, () => attend.push(scope, events)); else { const intake = intakes.get(scope); diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index cb0e7e1..38c039a 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,68 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'closing combines default grace with explicit deadlines', + start: 100, kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [ + push('s', ev('a', 'close', { observedAt: 10, quietForMs: 800 }), ev('b')), { inspect: 's' }, + advance(200), push('s', ev('c'), ev('d', 'close', { observedAt: 280, quietForMs: 0 })), + advance(11), push('s', ev('e')), { inspect: 's' }, + advance(500), push('s', ev('f', 'close', { observedAt: 700, quietForMs: 0 })), advance(0), + ], + }, + { + name: 'a completion applies only to acts admitted before it', + start: 100, kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [ + push('s', ev('early', 'out', { settles: true }), ev('act', 'drag')), { inspect: 's' }, + advance(10), push('s', ev('early', 'out', { settles: true })), { inspect: 's' }, + push('s', ev('done', 'out', { observedAt: 105, settles: true }), ev('trailing', 'out')), { inspect: 's' }, + push('s', ev('alone', 'out', { settles: true })), { inspect: 's' }, + ], + }, + { + name: 'ordered completion overrides stream quiet through serial intake', + start: 100, kinds: KINDS, intakes: ['s'], + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [ + { submit: 's', events: [ev('a', 'close', { quietForMs: 2000 }), ev('b', 'drag', { quietForMs: 1900 })] }, + advance(10), { submit: 's', events: [ev('wrong', 'close', { settles: true })], source: 'feed', cursor: '1' }, { inspect: 's' }, + { submit: 's', events: [ev('done', 'out', { settles: true })], source: 'feed', cursor: '2' }, { inspect: 's' }, + ], + }, + { + name: 'after wait only a fresh act can give a completion effect', + start: 100, kinds: KINDS, intakes: ['s'], + settle: { continuation: 'accumulate', waitHorizonMs: 100 }, + judge: { '*': { answers: [{ route: 'wait' }, { route: 'note' }] } }, + steps: [ + { submit: 's', events: [ev('a', 'close', { quietForMs: 2000 }), ev('done', 'out', { settles: true })] }, + advance(10), { submit: 's', events: [ev('held-only', 'out', { settles: true })] }, { inspect: 's' }, + { submit: 's', events: [ev('b', 'close', { quietForMs: 2000 })] }, { inspect: 's' }, + advance(10), { submit: 's', events: [ev('fresh-done', 'out', { settles: true })] }, + ], + }, + { + name: 'completion preserves the accumulating retry deadline', + start: 100, kinds: KINDS, intakes: ['s'], + settle: { continuation: 'accumulate', retryBackoffMs: [40] }, + judge: { '*': { answers: [{ fail: 'outage' }, { route: 'note' }] } }, + steps: [ + { submit: 's', events: [ev('a', 'drag', { quietForMs: 0 })] }, + advance(10), { submit: 's', events: [ev('b', 'drag'), ev('done', 'out', { settles: true })] }, + advance(29), { inspect: 's' }, advance(1), + ], + }, + { + name: 'completion takes effect before background retention', + start: 100, kinds: KINDS, intakes: ['s'], + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 0 } }, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [{ submit: 's', events: [ev('a', 'close'), ev('done', 'out', { settles: true })] }, { inspect: 's' }], + }, { name: 'decision data survives wait, delivery retry and recent context', start: 0, kinds: KINDS, diff --git a/test/continuation.test.ts b/test/continuation.test.ts index 28e17d8..2d141d3 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(6); + expect(stored?.snapshot?.reducer).toBe(7); 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 2fd2439..a741cc8 100644 --- a/test/continuous-quiet.test.ts +++ b/test/continuous-quiet.test.ts @@ -90,7 +90,7 @@ test('an explicit duration ignores an unused infinite default gap', async () => } }); -test.each(KINDS.filter((kind) => kind !== 'continuous'))('duration on %s refuses the whole batch', async (kind) => { +test.each(KINDS.filter((kind) => kind !== 'continuous' && kind !== 'closing'))('duration on %s refuses the whole batch', async (kind) => { const attend = createAttend({ clock: fakeClock(100), kind: (event) => event.name === 'move' ? 'continuous' : kind, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); try { await expect(attend.push('s', [{ id: 'a', name: 'move' }, { id: 'b', name: 'other', quietForMs: 0 }])).rejects.toThrow('quietForMs'); @@ -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(6); + expect((await store.load('s'))?.snapshot?.reducer).toBe(7); } finally { await attend.stop(); } diff --git a/test/core-inputs.test.ts b/test/core-inputs.test.ts index e96c627..58d6ad1 100644 --- a/test/core-inputs.test.ts +++ b/test/core-inputs.test.ts @@ -356,7 +356,7 @@ test('assertInvariants identifies corrupt counts, rings, summaries, sizes, hashe ['I1:', (s) => { s.open.entries.push(s.open.entries[0]!); }], ['I2:', (s) => { s.seen.size = 31; }], ['I2:', (s) => { s.seen.head = -1; }], - ['I3:', (s) => { s.open.summary.lastClosingAt = 99; }], + ['I3:', (s) => { s.open.summary.lastDefaultClosingAt = 99; }], ['I4:', (s) => { s.open.sizes[0] = 99; }], ['I5:', (s) => { s.open.hash.lo = 0; }], ['I6:', (s) => { s.dueAt = 99; }], diff --git a/test/event-limits.test.ts b/test/event-limits.test.ts index fb8def7..0856c6f 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(6); + expect(stored?.snapshot?.reducer).toBe(7); 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 1a073cf..f72c130 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(6); + expect((await store.load('s'))?.snapshot?.reducer).toBe(7); } finally { await attend.stop(); } diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 166ee37..8f3826a 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, 6); + assert.equal(snapshot.reducerVersion, 7); 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 }); diff --git a/test/window.test.ts b/test/window.test.ts index 9053d8c..cff0686 100644 --- a/test/window.test.ts +++ b/test/window.test.ts @@ -348,7 +348,7 @@ describe('open window', () => { test('reports I3 when a trigger summary is corrupted', () => { const open = openWindow('scope'); - open.summary.lastClosingAt = 123; + open.summary.lastDefaultClosingAt = 123; expect(() => assertWindow('scope', open)).toThrow('I3'); }); From cdfbe2d237202eb8260de26074b5256bed8f2a7d Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 26 Nov 2026 18:39:28 -0600 Subject: [PATCH 2/3] test(core): expect the act completion reducer revision --- 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 58d6ad1..6dcb62f 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, 6); + assert.equal(REDUCER_VERSION, 7); }); test('fromRecord accepts frozen oracle snapshots without changing them', () => { From 74b837a5a096a0c9fc63788c3cb53154651ef588 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 26 Nov 2026 18:49:54 -0600 Subject: [PATCH 3/3] fix(core): read settles only from input logged at revision 7 A tail replayed under an older snapshot was written by a reducer that gave settles no meaning, so it stays plain metadata there instead of ending the window early. Both runtimes, with a regression test in each. --- docs/storage.md | 2 +- python/src/aqi_attend/core/reducer.py | 5 ++- python/src/aqi_attend/core/types.py | 3 ++ python/src/aqi_attend/shell/read.py | 6 ++-- python/tests/test_closing_settlement.py | 47 +++++++++++++++++++++++++ src/core/reducer.ts | 5 ++- src/core/types.ts | 5 +++ src/shell/read.ts | 6 ++-- test/closing-settlement.test.ts | 24 +++++++++++++ 9 files changed, 96 insertions(+), 7 deletions(-) diff --git a/docs/storage.md b/docs/storage.md index 6e181ef..ae56ba9 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -46,4 +46,4 @@ Each adapter also has an `EventLog`: `memoryLog`, `sqliteLog`, `postgresLog` and [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. -[Closing durations and completion](reference.md#closing-duration-and-completion) use reducer revision 7. Upgrade every reader and writer sharing a store before using either field. Replay uses the saved policy for default grace and the logged event times for explicit deadlines. +[Closing durations and completion](reference.md#closing-duration-and-completion) use reducer revision 7. Upgrade every reader and writer sharing a store before using either field. Replay uses the saved policy for default grace and the logged event times for explicit deadlines. A tail logged under a snapshot from an older revision keeps `settles` as plain metadata, since older revisions gave it no meaning; only input logged at revision 7 or later ends a window with it. diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index c0c26dd..a440209 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -52,6 +52,9 @@ REDUCER_VERSION = 7 """Bumped whenever a release changes a transition. Stored with every snapshot.""" +COMPLETION_REVISION = 7 +"""The first revision whose logged inputs give ``settles`` its meaning.""" + _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") @@ -224,7 +227,7 @@ def _ingest(ctx: _Ctx, state: ScopeState, input: EventsInput) -> None: continue entry = cast(Entry, {**event, "seenAt": ctx.now}) # Act presence is checked in admission order, before background retention. - if entry["kind"] == "consequence" and entry.get("settles") is True and state.open.summary.first_act_index != -1: + if ctx.config.completion and entry["kind"] == "consequence" and entry.get("settles") is True and state.open.summary.first_act_index != -1: state.open.ended_at = observation_time(entry) window_append(state.open, entry, estimate_rendered_bytes(entry)) ctx.out.changed = True diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 21d673d..caa7ec0 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -490,6 +490,9 @@ class ApplyConfig: decisions: DeliveryMode = "lane" dead_letters: DeliveryMode = "lane" traces: bool = True + completion: bool = True + """Read ``settles`` on consequences. False while replaying a tail logged under a reducer older + than revision 7, where the field was application metadata with no meaning.""" @dataclass(slots=True) diff --git a/python/src/aqi_attend/shell/read.py b/python/src/aqi_attend/shell/read.py index 03ae21f..fa6c7d4 100644 --- a/python/src/aqi_attend/shell/read.py +++ b/python/src/aqi_attend/shell/read.py @@ -5,7 +5,7 @@ from typing import cast from .._json import clone -from ..core.reducer import apply +from ..core.reducer import COMPLETION_REVISION, apply from ..core.state import from_record, initial_state, to_record from ..core.types import DEFAULT_POLICY, ApplyConfig, ApplyOutput, DeliveryMode, ScopeRecord, ScopeState from ..store.types import ScopeStore, StoredScope @@ -16,7 +16,9 @@ def replay(scope: str, stored: StoredScope, decisions: DeliveryMode, dead_letter snapshot = stored["snapshot"] policy = snapshot["policy"] if snapshot is not None else DEFAULT_POLICY state = from_record(snapshot["record"], policy) if snapshot is not None else initial_state(scope) - config = ApplyConfig(policy, decisions, dead_letters, False) + # A tail under an older snapshot was logged by an older reducer, where ``settles`` meant nothing. + completion = snapshot is None or snapshot["reducer"] >= COMPLETION_REVISION + config = ApplyConfig(policy, decisions, dead_letters, False, completion) for logged in stored["tail"]: apply(config, state, logged, ApplyOutput()) state.version += 1 diff --git a/python/tests/test_closing_settlement.py b/python/tests/test_closing_settlement.py index a73ffae..c056f99 100644 --- a/python/tests/test_closing_settlement.py +++ b/python/tests/test_closing_settlement.py @@ -68,3 +68,50 @@ async def test_invalid_completion_refuses_whole_batch(settles: object) -> None: finally: await attend.stop() await attend.store.close() + + +async def test_a_tail_under_an_older_snapshot_keeps_settles_as_metadata() -> None: + from aqi_attend.core.step import initial_record + from aqi_attend.core.types import default_policy + from aqi_attend.store.types import ScopeWrite + + store = memory_store() + policy = default_policy() + record = initial_record("s") + record.update( + version=1, + seen=["save"], + buffer={"entries": [{"id": "save", "at": 0, "name": "save", "data": {}, "kind": "closing", "seenAt": 100}], "dropped": 0, "gap": False, "forcedAt": None}, + dueAt=100 + policy["closingGraceMs"], + ) + checkpoint: ScopeWrite = { + "scope": "s", + "expectedVersion": 0, + "inputs": [{"now": 100, "input": {"kind": "tick"}}], + "snapshot": {"version": 1, "record": record, "policy": policy, "reducer": 6}, + "appends": [], + } + tail: ScopeWrite = { + "scope": "s", + "expectedVersion": 1, + "snapshot": None, + "appends": [], + "inputs": [ + { + "now": 110, + "input": {"kind": "events", "events": [{"id": "out", "at": 0, "name": "out", "data": {}, "kind": "consequence", "settles": True}]}, + } + ], + } + assert await store.commit([checkpoint]) == ["ok"] + assert await store.commit([tail]) == ["ok"] + attend = create_attend(store=store, clock=fake_clock(110), kind={"save": "closing", "out": "consequence"}, judge=scripted_judge([]), sink="log") + try: + loaded = await attend.inspect("s") + assert loaded is not None + assert loaded["dueAt"] == 100 + policy["closingGraceMs"] + assert loaded["buffer"].get("endedAt") is None + assert [event.get("settles") for event in loaded["buffer"]["entries"]] == [None, True] + finally: + await attend.stop() + await store.close() diff --git a/src/core/reducer.ts b/src/core/reducer.ts index 26c93e5..7fab744 100644 --- a/src/core/reducer.ts +++ b/src/core/reducer.ts @@ -11,6 +11,9 @@ import { estimateRenderedBytes, isBackground, observationTime, openWindow, shedE /** Bumped whenever a release changes a transition. Stored with every snapshot. */ export const REDUCER_VERSION = 7; +/** The first revision whose logged inputs give `settles` its meaning. */ +export const COMPLETION_REVISION = 7; + /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { return { effects: [], appends: [], changed: false }; @@ -128,7 +131,7 @@ function ingest(ctx: Ctx, state: ScopeState, input: EventsInput): void { if (!seenAdmit(state, event.id)) { duplicates += 1; continue; } const entry = { ...event, seenAt: ctx.now }; // Act presence is checked in admission order, before background retention. - if (entry.kind === 'consequence' && entry.settles === true && state.open.summary.firstActIndex !== -1) { + if (ctx.config.completion !== false && entry.kind === 'consequence' && entry.settles === true && state.open.summary.firstActIndex !== -1) { state.open.endedAt = observationTime(entry); } windowAppend(state.open, entry, estimateRenderedBytes(entry)); diff --git a/src/core/types.ts b/src/core/types.ts index ed9c3a8..b0626ce 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -609,6 +609,11 @@ export interface ApplyConfig { deadLetters: 'lane' | 'log'; /** Build trace effects. False when nothing observes. Traces never change state. */ traces: boolean; + /** + * Read `settles` on consequences. False while replaying a tail logged under a reducer older + * than revision 7, where the field was application metadata with no meaning. + */ + completion?: boolean; } /** A row `apply` asks the store to append in the same write as the input that produced it. */ diff --git a/src/shell/read.ts b/src/shell/read.ts index ea37f26..2d22079 100644 --- a/src/shell/read.ts +++ b/src/shell/read.ts @@ -1,4 +1,4 @@ -import { apply, newOutput } from '../core/reducer.js'; +import { apply, COMPLETION_REVISION, newOutput } from '../core/reducer.js'; import { fromRecord, initialState, toRecord } from '../core/state.js'; import { DEFAULT_POLICY, type ApplyConfig, type ScopeRecord, type ScopeState } from '../core/types.js'; import type { ScopeStore, StoredScope } from '../store/types.js'; @@ -7,8 +7,10 @@ import type { ScopeStore, StoredScope } from '../store/types.js'; export function replay(scope: string, stored: StoredScope, modes: Pick): ScopeState { const policy = stored.snapshot?.policy ?? DEFAULT_POLICY; const state = stored.snapshot ? fromRecord(stored.snapshot.record, policy) : initialState(scope, policy); + // A tail under an older snapshot was logged by an older reducer, where `settles` meant nothing. + const completion = !stored.snapshot || stored.snapshot.reducer >= COMPLETION_REVISION; for (const logged of stored.tail) { - apply({ policy, decisions: modes.decisions, deadLetters: modes.deadLetters, traces: false }, state, logged, newOutput()); + apply({ policy, decisions: modes.decisions, deadLetters: modes.deadLetters, traces: false, completion }, state, logged, newOutput()); state.version += 1; } if (state.version !== stored.version) throw new Error(`attend: invalid stored version for scope "${scope}"`); diff --git a/test/closing-settlement.test.ts b/test/closing-settlement.test.ts index 92baea7..d792ca0 100644 --- a/test/closing-settlement.test.ts +++ b/test/closing-settlement.test.ts @@ -1,6 +1,8 @@ import { expect, test } from 'vitest'; import { createAttend, memoryStore, type SourceBatch } from '../src/index.js'; import { fakeClock, scriptedJudge } from '../src/testing.js'; +import { replay } from '../src/shell/read.js'; +import { toRecord } from '../src/core/state.js'; test('closing waits for the latest explicit or default deadline', async () => { const attend = createAttend({ clock: fakeClock(100), kind: { save: 'closing' }, judge: scriptedJudge([]), sink: 'log' }); @@ -74,3 +76,25 @@ test.each([false, null, 1, 'true', Symbol('settles'), { toJSON: () => undefined await attend.stop(); } }); + +test('a tail under an older snapshot keeps settles as metadata', async () => { + const clock = fakeClock(100); + const store = memoryStore(); + const writer = createAttend({ clock, store, judge: scriptedJudge([]), sink: 'log', kind: { save: 'closing', out: 'consequence' } }); + try { + await writer.push('s', [{ id: 'save', name: 'save' }]); + await clock.advance(10); + await writer.push('s', [{ id: 'out', name: 'out', settles: true }]); + } finally { + await writer.stop(); + } + const stored = await store.load('s'); + expect(stored?.snapshot).toBeTruthy(); + expect(stored?.tail).toMatchObject([{ input: { kind: 'events', events: [{ id: 'out', settles: true }] } }]); + const modes = { decisions: 'lane', deadLetters: 'lane' } as const; + expect(toRecord(replay('s', stored!, modes)).buffer.endedAt).toBe(110); + const legacy = { ...stored!, snapshot: { ...stored!.snapshot!, reducer: 6 } }; + const record = toRecord(replay('s', legacy, modes)); + expect(record.buffer.endedAt).toBeUndefined(); + expect(record.buffer.entries).toMatchObject([{ id: 'save' }, { id: 'out', settles: true }]); +});