diff --git a/DEVIATIONS.md b/DEVIATIONS.md index ef1aadb..651df9b 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -1,5 +1,11 @@ # Shell changes from the frozen shell +## Observation time + +An explicit `Event.observedAt` supplies quiet and age timing independently of ingestion. The frozen reducer has no observation-time input. Its differential cases omit that field and continue to pin the existing behavior, including backwards engine clocks. Shared runtime fixtures and dedicated tests cover explicit observation times, mixed timestamps, pruning, admission and recovery in both runtimes. + +The reducer revision is 2. Snapshots and logged tails without the field retain ingestion timing. The existing upgrade path replays and resnapshots; it is not a downgrade fence. Processes sharing a store must use the same reducer version before opting in. [The reference](docs/reference.md#observation-time) defines the clocks. + ## Commit boundaries Inputs applied before a write starts share a commit. Writes across scopes share a sorted group. Inputs that change nothing are not logged. `owned shell` tests pin grouped writes, version counts, and failure isolation. diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index a657f41..466b7d0 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,2419 @@ { "scenarios": [ + { + "scenario": { + "name": "observation time sets a quiet deadline while at and seenAt remain distinct", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "at": -1, + "observedAt": 100 + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 99 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": -1, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 1100 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": -1, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 1100 + }, + "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": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "queue" + }, + { + "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": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": -1, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1100 + } + }, + { + "step": 3, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": -1, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1100 + } + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 1100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 1100, + "route": "queue", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": -1, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 1100 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "an already-due observation settles at processing time", + "start": 2000, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 100 + } + ] + }, + { + "advance": 0 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 2000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 2000 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 2000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "at": 2000 + }, + "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": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 2000 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 2000, + "route": "queue", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 2000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "at": 2000 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "a wait horizon starts when a source-timed judgment finishes", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 100 + } + ] + }, + { + "advance": 100 + }, + { + "inspect": "s" + }, + { + "advance": 9999 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 1100 + }, + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 11100 + } + ] + }, + "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": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 11100 + }, + "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": "waiting", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "waits": 1, + "until": 11100 + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 2, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 11100 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 11100 + } + }, + { + "step": 4, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 11100 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 11100 + } + } + ], + "records": { + "s": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 11100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 11100, + "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": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 11100 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "a retry and its leases keep processing time after an old observation", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "fail": "temporary" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 0 + } + ] + }, + { + "advance": 0 + }, + { + "inspect": "s" + }, + { + "advance": 999 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 1000 + }, + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 2000 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "at": 2000 + }, + "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": 2000, + "message": "temporary" + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 2000, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 2000 + } + }, + { + "step": 4, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 2000, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 2000 + } + } + ], + "records": { + "s": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 2000 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 2000, + "route": "queue", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1000 + }, + "at": 2000 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "older observations do not shorten a quiet deadline and implicit observations join it", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 900 + }, + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 100 + }, + { + "id": "c", + "name": "drag", + "text": "drag c" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 999 + }, + { + "inspect": "s" + }, + { + "advance": 1 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 900, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 2000 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 900, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "at": 2000 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "1a353cc02182e85a", + "reason": "stream_quiet", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "1a353cc02182e85a", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "1a353cc02182e85a", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "1a353cc02182e85a", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "1a353cc02182e85a" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 900, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 1000 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 2000 + } + }, + { + "step": 3, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 900, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 1000 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 2000 + } + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "1a353cc02182e85a", + "route": "note", + "at": 2000 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "1a353cc02182e85a", + "scope": "s", + "at": 2000, + "route": "note", + "body": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 900, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 2000 + }, + "at": 2000 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "old background observations are pruned behind newer observations", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "maxWindowMs": 200 + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "out", + "text": "out a", + "observedAt": 900 + }, + { + "id": "b", + "name": "out", + "text": "out b", + "observedAt": 100 + }, + { + "id": "c", + "name": "out", + "text": "out c", + "observedAt": 950 + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": {}, + "deliveries": {}, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "b", + "at": 0, + "name": "out", + "data": {}, + "text": "out b", + "observedAt": 100, + "kind": "consequence", + "seenAt": 1000 + } + ], + "why": "age" + }, + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + } + ] + }, + "results": [ + { + "step": 0, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "out", + "data": {}, + "text": "out a", + "observedAt": 900, + "kind": "consequence", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "out", + "data": {}, + "text": "out c", + "observedAt": 950, + "kind": "consequence", + "seenAt": 1000 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "out", + "data": {}, + "text": "out a", + "observedAt": 900, + "kind": "consequence", + "seenAt": 1000 + }, + { + "id": "c", + "at": 0, + "name": "out", + "data": {}, + "text": "out c", + "observedAt": 950, + "kind": "consequence", + "seenAt": 1000 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + } + }, + "log": [] + } + }, + { + "scenario": { + "name": "a future observation refuses the complete batch before any event is stored", + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 100 + }, + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 1001 + } + ] + }, + { + "inspect": "s" + }, + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 100 + } + ] + }, + { + "advance": 100 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 1100 + } + ] + }, + "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": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 1100 + }, + "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": "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": { + "name": "TypeError", + "message": "attend: observedAt must not be in the future" + } + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 1, + "scope": "s", + "record": null + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 1100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 1100, + "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": "drag", + "data": {}, + "text": "drag a", + "observedAt": 100, + "kind": "continuous", + "seenAt": 1000 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 1100 + }, + "at": 1100 + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "a closing act settles after the grace, is judged with the configured context, and is delivered", diff --git a/docs/reference.md b/docs/reference.md index f520b00..865e835 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -15,6 +15,37 @@ 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. +## Observation time + +An event can supply `observedAt` when its source observed it before delivering it to attend. It is a finite timestamp in the same millisecond coordinates as the engine's `Clock`. `push` and `attach` reject future values before admitting the batch. Convert a source clock to the engine's time coordinates before supplying it; attend does not clamp the value. + +| Field | Meaning | +|---|---| +| `at` | Informational time reported by the source. It does not set deadlines. | +| `observedAt` | Optional source observation time for quiet periods, the act age bound and background age pruning. | +| `seenAt` | Time the engine applies the input. The engine sets it and retains it even when `observedAt` is present. | + +When a kind includes an explicit observation time, its quiet period starts at the latest effective observation for that kind. The age bound uses the earliest effective act time once an act supplies `observedAt`. An omitted field uses that entry's `seenAt`. Kinds whose entries omit `observedAt` retain their existing handling of backwards engine clocks. Entry order and duplicate handling do not change. + +```ts +import { createAttend } from '@acquiredintelligence/attend'; +import { fakeClock } from '@acquiredintelligence/attend/testing'; + +const clock = fakeClock(1000); +const attend = createAttend({ + clock, + kind: { change: 'continuous' }, + judge: async () => ({ route: 'note' }), + sink: 'log', +}); +await attend.push('repo', { id: 'a', name: 'change', at: 0, observedAt: 100 }); +console.log((await attend.inspect('repo'))?.dueAt); // 1100 +``` + +An already-due observation settles through the normal runner at processing time. It never reopens a resolved window or backdates `settledAt`. A bulk push remains one batch. Flush, overflow and byte limits keep processing-time semantics. Waits, retries, leases, timeouts and decision timestamps also keep engine time. A stale background observation can be pruned as soon as it arrives, with the usual dropped count and trace. + +Both runtimes retain `observedAt` through snapshots, logged inputs, windows and decision records. See [storage](storage.md) for version coordination when sharing a store. + ## Routes | Route | The agent | Reaches the sink | diff --git a/docs/storage.md b/docs/storage.md index 4c11a5f..39ccc04 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -36,4 +36,6 @@ Each store also takes `retain` (decision rows kept by count or age), so the log Several processes can share one store. Any of them can `push`, and any number can `run` or serve the log: a write names the stored version it read, a writer that loses reloads and applies its input again, and every input is idempotent. Give every process the same `kind` function, because the process that ingests an event is the one that kinds it. A scope can take several sources at once; the record keeps one cursor per `Source.key`. Attach a given source to a scope from one process only, since two processes running the same source would overwrite each other's cursor, and a second `attend.attach` of the same key in one process throws. +Keep processes sharing a store on the same reducer version before using [observation time](reference.md#observation-time). A reducer-version mismatch triggers replay and a fresh snapshot; it does not fence out older readers or writers. Older entries without `observedAt` retain their stored `seenAt` during replay. The clock at replay time never replaces that timestamp. + 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`. diff --git a/python/README.md b/python/README.md index 83e79f6..6f75dfb 100644 --- a/python/README.md +++ b/python/README.md @@ -80,6 +80,7 @@ redis-py runs each concurrent command on a pooled connection of its own, and its - Keyword arguments and `settle` keys are snake_case, such as `create_attend(settle={"wait_horizon_ms": 5000})`. Every value that crosses a store or a judge (events, windows, decisions, dead letters, records, traces) is a dict with the TypeScript field names, such as `decision["window"]["settledAt"]`, so both runtimes share one persisted layout. - A judge, sink, dead-letter handler, `context` or `capture` is called with `(value, signal)`, where `signal` is an `aqi_attend.AbortSignal`. Honour it with `await signal.race(work)` or by checking `signal.aborted`. - `push`, `flush` and `end` return futures that resolve once the input is persisted. They take the input when called, as the TypeScript promises do. +- 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](../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](../docs/sinks.md#the-notice) says what it folds. - `fold_events(values, repeats=..., continues=...)` returns a tuple of frozen `EventFold` groups with `first`, `last`, `count` and `mode`. The endpoint values refer to your inputs. [Write your own folded notice](../docs/sinks.md#write-your-own-folded-notice) explains the comparisons and filtering. diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index 758422a..17bdc32 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -314,6 +314,8 @@ def _classify(self, given: Mapping[str, Any] | Sequence[Mapping[str, Any]]) -> l classified: list[KindedEvent] = [] for event in events: copied = copy_event(event, fill) + if "observedAt" in copied and copied["observedAt"] > self._clock.now(): + raise TypeError("attend: observedAt must not be in the future") kind = self._kind(copied) if kind not in KINDS: raise TypeError("attend: invalid event kind") diff --git a/python/src/aqi_attend/conformance.py b/python/src/aqi_attend/conformance.py index d174566..d960f9d 100644 --- a/python/src/aqi_attend/conformance.py +++ b/python/src/aqi_attend/conformance.py @@ -56,7 +56,16 @@ def logged(id: str, now: float = 1000) -> LoggedInput: def _window(id: str) -> Window: - entry: Entry = {"id": f"event:{id}", "at": 1, "name": "changed", "data": {"nested": [None, True, "héllo 🌍\u0000"]}, "text": "héllo 🌍\u0000", "kind": "closing", "seenAt": 2} + entry: Entry = { + "id": f"event:{id}", + "at": 1, + "observedAt": 1, + "name": "changed", + "data": {"nested": [None, True, "héllo 🌍\u0000"]}, + "text": "héllo 🌍\u0000", + "kind": "closing", + "seenAt": 2, + } return {"id": id, "events": [entry], "reason": "closing", "waits": 0, "dropped": 0, "gap": False, "settledAt": 3} @@ -303,7 +312,16 @@ async def snapshots(store: ScopeStore, w: _Watched) -> None: async def large(store: ScopeStore, w: _Watched) -> None: entries: list[Entry] = [ - {"id": f"e{i}", "at": i, "seenAt": i + 1, "name": "n", "text": "héllo 🌍\u0000", "data": {"i": i, "nested": [None, {"yes": True}]}, "kind": "passive"} + { + "id": f"e{i}", + "at": i, + "observedAt": i, + "seenAt": i + 1, + "name": "n", + "text": "héllo 🌍\u0000", + "data": {"i": i, "nested": [None, {"yes": True}]}, + "kind": "passive", + } for i in range(250) ] d = _decision("delivered", "s") diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index d83b4ef..d205b2c 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -45,7 +45,7 @@ window_shed, ) -REDUCER_VERSION = 1 +REDUCER_VERSION = 2 """Bumped whenever a release changes a transition. Stored with every snapshot.""" _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") diff --git a/python/src/aqi_attend/core/state.py b/python/src/aqi_attend/core/state.py index b754d3b..0cda789 100644 --- a/python/src/aqi_attend/core/state.py +++ b/python/src/aqi_attend/core/state.py @@ -6,7 +6,7 @@ from .reducer import next_due, same from .seen import seen_from, seen_ids from .types import Buffer, Entry, FnvState, HeldBatch, ScopeRecord, ScopeState, SettlePolicy -from .window import estimate_rendered_bytes, open_window, summarize, window_from +from .window import estimate_rendered_bytes, observation_time, open_window, summarize, window_from def initial_state(scope: str) -> ScopeState: @@ -110,5 +110,5 @@ def assert_invariants(state: ScopeState, policy: SettlePolicy) -> None: for lane in (state.decisions, state.dead_letters): if any(delivery["phase"]["phase"] == "inFlight" for delivery in lane[1:]): raise AssertionError("outbox: more than one in flight in a lane") - if open.monotone and any(b["seenAt"] < a["seenAt"] for a, b in zip(open.entries, open.entries[1:], strict=False)): - raise AssertionError("monotone: seenAt decreased") + if open.monotone and any(observation_time(b) < observation_time(a) for a, b in zip(open.entries, open.entries[1:], strict=False)): + raise AssertionError("monotone: observation time decreased") diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 09a774c..0f03a6d 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -30,6 +30,7 @@ class Event(TypedDict): id: str at: float + observedAt: NotRequired[float] name: str data: JsonObject text: NotRequired[str] @@ -511,10 +512,19 @@ class TriggerSummary: 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_stream_at: float = -math.inf + max_passive_at: float = -math.inf + min_act_at: float = math.inf + closing_observed: bool = False + stream_observed: bool = False + passive_observed: bool = False + act_observed: bool = False first_act_index: int = -1 prefix_min_sheddable_at: float = math.inf sheddable: int = 0 last_seen_at: float = math.nan + last_observation_at: float = math.nan @dataclass(slots=True) diff --git a/python/src/aqi_attend/core/window.py b/python/src/aqi_attend/core/window.py index 0cb71c7..c3ddea3 100644 --- a/python/src/aqi_attend/core/window.py +++ b/python/src/aqi_attend/core/window.py @@ -27,22 +27,47 @@ def estimate_rendered_bytes(event: Event) -> int: def _summarize_entry(summary: TriggerSummary, entry: Entry, index: int) -> None: kind = entry["kind"] seen_at = entry["seenAt"] + observed_at = observation_time(entry) + explicit = "observedAt" in entry if kind == "flush": summary.min_flush_at = _min(summary.min_flush_at, seen_at) elif kind == "closing": - summary.last_closing_at = seen_at + 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 elif kind == "continuous": - summary.last_stream_at = seen_at + summary.max_stream_at = _max(summary.max_stream_at, observed_at) + summary.stream_observed |= explicit + summary.last_stream_at = summary.max_stream_at if summary.stream_observed else seen_at elif kind == "passive": - summary.last_passive_at = seen_at + summary.max_passive_at = _max(summary.max_passive_at, observed_at) + summary.passive_observed |= explicit + summary.last_passive_at = summary.max_passive_at if summary.passive_observed else seen_at if summary.first_act_index == -1 and is_act(kind): summary.first_act_index = index summary.first_act_at = seen_at + if is_act(kind): + summary.min_act_at = _min(summary.min_act_at, observed_at) + summary.act_observed |= explicit + if summary.act_observed: + summary.first_act_at = summary.min_act_at if _sheddable(kind): summary.sheddable += 1 if summary.first_act_index == -1: - summary.prefix_min_sheddable_at = _min(summary.prefix_min_sheddable_at, seen_at) + summary.prefix_min_sheddable_at = _min(summary.prefix_min_sheddable_at, observed_at) summary.last_seen_at = seen_at + summary.last_observation_at = observed_at + + +def observation_time(entry: Entry) -> float: + return entry.get("observedAt", entry["seenAt"]) + + +def _max(a: float, b: float) -> float: + """``Math.max`` of two numbers, including NaN propagation.""" + if a != a or b != b: + return math.nan + return a if a >= b else b def _min(a: float, b: float) -> float: @@ -90,7 +115,7 @@ def window_from(scope: str, buffer: Buffer) -> OpenWindow: def window_append(open: OpenWindow, entry: Entry, size: int) -> None: """Appends an entry and updates sizes, summary, monotonicity and any valid hash in O(1).""" - if entry["seenAt"] < open.summary.last_seen_at: + if observation_time(entry) < open.summary.last_observation_at: open.monotone = False index = len(open.entries) open.entries.append(entry) @@ -109,8 +134,8 @@ def _prefix_minimum(open: OpenWindow) -> float: entry = entries[i] if _sheddable(entry["kind"]): if open.monotone: - return entry["seenAt"] - least = _min(least, entry["seenAt"]) + return observation_time(entry) + least = _min(least, observation_time(entry)) return least @@ -124,6 +149,7 @@ def _removed_from(open: OpenWindow, count: int, size: int, prefix_count: int) -> if prefix_count > 0: summary.prefix_min_sheddable_at = _prefix_minimum(open) summary.last_seen_at = open.entries[-1]["seenAt"] if open.entries else math.nan + summary.last_observation_at = observation_time(open.entries[-1]) if open.entries else math.nan open.hash_valid = False @@ -141,7 +167,7 @@ def window_prune(open: OpenWindow, max_window_ms: float, now: float) -> list[Ent read = 0 while read < end: entry = entries[read] - stale = entry["seenAt"] + max_window_ms <= now + stale = observation_time(entry) + max_window_ms <= now if not stale and open.monotone: break if stale and _sheddable(entry["kind"]): diff --git a/python/src/aqi_attend/shell/copy.py b/python/src/aqi_attend/shell/copy.py index 00bf3a6..1e463e7 100644 --- a/python/src/aqi_attend/shell/copy.py +++ b/python/src/aqi_attend/shell/copy.py @@ -4,6 +4,7 @@ import asyncio import math +import sys from collections.abc import Callable, Mapping, Sequence from typing import Any, cast @@ -53,6 +54,10 @@ def copy_event(event: Mapping[str, object], fill: tuple[Callable[[], str], Calla if not isinstance(data, Mapping): raise TypeError("attend: event data must be a JSON object") fields["data"] = _to_json(cast(Mapping[str, object], data), 1) + if "observedAt" in fields: + observed = fields["observedAt"] + if isinstance(observed, bool) or not isinstance(observed, (int, float)) or not -sys.float_info.max <= observed <= sys.float_info.max: + raise TypeError("attend: observedAt must be a finite number") if fill is not None: if "id" not in fields: fields["id"] = fill[0]() diff --git a/python/tests/scenario.py b/python/tests/scenario.py index 8f47b95..7c39520 100644 --- a/python/tests/scenario.py +++ b/python/tests/scenario.py @@ -248,7 +248,17 @@ async def result(index: int, work: asyncio.Future[None]) -> None: for index, step in enumerate(scenario["steps"]): if "push" in step: scopes.add(step["push"]) - events = [{"id": e["id"], "at": e.get("at", 0), "name": e["name"], "data": e.get("data", {}), **({"text": e["text"]} if "text" in e else {})} for e in step["events"]] + events = [ + { + "id": e["id"], + "at": e.get("at", 0), + "name": e["name"], + "data": e.get("data", {}), + **({"text": e["text"]} if "text" in e else {}), + **({"observedAt": e["observedAt"]} if "observedAt" in e else {}), + } + for e in step["events"] + ] await result(index, attend.push(step["push"], events)) elif "advance" in step: await clock.advance(step["advance"]) diff --git a/python/tests/test_observation_time.py b/python/tests/test_observation_time.py new file mode 100644 index 0000000..0c4cb9d --- /dev/null +++ b/python/tests/test_observation_time.py @@ -0,0 +1,304 @@ +"""Source observation and processing clocks remain independent.""" + +import asyncio +from collections.abc import Awaitable, Callable, Sequence + +import pytest + +from aqi_attend import AbortController, AbortSignal, JudgeInput, Judgment, create_attend, memory_store +from aqi_attend.core.step import initial_record +from aqi_attend.core.types import Buffer, Entry, Kind, SourceBatch, default_policy +from aqi_attend.core.window import deadline, window_deadline, window_from, window_prune +from aqi_attend.store.memory import MemoryStore +from aqi_attend.store.types import CommitOutcome, ScopeWrite +from aqi_attend.testing import ScriptedAnswer, fake_clock, harness, recording_sink, scripted_judge + + +def entry(id: str, seen_at: float, observed_at: float | None = None, kind: Kind = "continuous") -> Entry: + result: Entry = {"id": id, "at": -1, "name": "change", "data": {}, "kind": kind, "seenAt": seen_at} + if observed_at is not None: + result["observedAt"] = observed_at + return result + + +def buffer(*entries: Entry) -> Buffer: + return {"entries": list(entries), "dropped": 0, "gap": False, "forcedAt": None} + + +async def test_source_observation_sets_quiet_deadline_without_changing_other_clocks() -> None: + clock = fake_clock(1000) + judge = scripted_judge([{"route": "queue"}]) + sink = recording_sink() + attend = create_attend(clock=clock, kind={"change": "continuous"}, judge=judge, sink=sink) + running = asyncio.create_task(attend.run()) + try: + await attend.push("s", {"id": "a", "at": -1, "observedAt": 100, "name": "change"}) + record = await attend.inspect("s") + assert record is not None and record["dueAt"] == 1100 + await clock.advance(99) + assert len(judge.calls) == 0 + await clock.advance(1) + assert [call["window"]["settledAt"] for call in judge.calls] == [1100] + event = sink.delivered[0]["window"]["events"][0] + assert "observedAt" in event + assert (event["at"], event["observedAt"], event["seenAt"]) == (-1, 100, 1000) + assert sink.delivered[0]["at"] == 1100 + finally: + await attend.stop() + await running + await attend.store.close() + + +@pytest.mark.parametrize( + "observed_at", + [None, True, "100", float("nan"), float("inf"), -float("inf"), 1001, -(10**1000)], + ids=["null", "boolean", "string", "nan", "positive-infinity", "negative-infinity", "future", "outside-number-range"], +) +async def test_invalid_or_future_observation_is_rejected_before_admission(observed_at: object) -> None: + attend = create_attend(clock=fake_clock(1000), kind={"change": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + with pytest.raises(TypeError, match="observedAt"): + await attend.push("s", {"id": "a", "name": "change", "observedAt": observed_at}) + assert await attend.inspect("s") is None + finally: + await attend.stop() + await attend.store.close() + + +@pytest.mark.parametrize(("kind", "gap", "reason"), [("closing", 500, "closing"), ("continuous", 1000, "stream_quiet"), ("passive", 4000, "passive_quiet")]) +def test_out_of_order_observations_do_not_shorten_quiet_time(kind: Kind, gap: float, reason: str) -> None: + assert deadline(default_policy(), buffer(entry("a", 1000, 900, kind), entry("b", 1000, 100, kind))) == (900 + gap, reason) + + +def test_source_age_and_default_backward_clock_behavior() -> None: + policy = default_policy() + policy["streamGapMs"] = 100_000 + assert deadline(policy, buffer(entry("a", 1000, 900), entry("b", 1000, 0))) == (60_000, "age") + assert deadline(policy, buffer(entry("a", 1000), entry("b", 500))) == (61_000, "age") + assert deadline(default_policy(), buffer(entry("a", 1000), entry("b", 500))) == (1500, "stream_quiet") + assert deadline(default_policy(), buffer(entry("a", 1000), entry("b", 500, 350))) == (2000, "stream_quiet") + + +def test_old_background_observation_behind_fresh_is_pruned_in_arrival_order() -> None: + open = window_from("s", buffer(entry("fresh", 1000, 900, "context"), entry("old", 1000, 100, "context"), entry("latest", 1000, 950, "context"))) + removed = window_prune(open, 200, 1000) + assert removed is not None and [event["id"] for event in removed] == ["old"] + assert [event["id"] for event in open.entries] == ["fresh", "latest"] + assert open.dropped == 1 + assert window_deadline(default_policy(), open) is None + + +def test_flush_count_and_byte_deadlines_keep_ingestion_time() -> None: + policy = default_policy() + assert deadline(policy, buffer(entry("a", 1000, 100, "flush"))) == (1000, "flush") + policy["maxEvents"] = 0 + assert deadline(policy, buffer(entry("a", 1000, 100))) == (1000, "overflow") + policy = default_policy() + policy["maxWindowBytes"] = 0 + assert deadline(policy, buffer(entry("a", 1000, 100))) == (1000, "size") + + +async def test_late_settlement_and_judge_lease_use_processing_time() -> None: + clock = fake_clock(2000) + response: asyncio.Future[Judgment] = asyncio.get_running_loop().create_future() + calls = 0 + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + nonlocal calls + calls += 1 + return await response + + attend = create_attend(clock=clock, kind={"change": "continuous"}, judge=judge, sink="log", settle={"judge_timeout_ms": 100}) + running = asyncio.create_task(attend.run()) + try: + await attend.push("s", {"id": "a", "name": "change", "observedAt": 100}) + await clock.advance(0) + record = await attend.inspect("s") + assert record is not None and record["batch"] is not None + assert record["batch"]["window"]["settledAt"] == 2000 + phase = record["batch"]["phase"] + assert phase["phase"] == "judging" and phase["leaseUntil"] == 2200 + assert calls == 1 + await clock.advance(99) + assert calls == 1 + finally: + if not response.done(): + response.set_result({"route": "skip"}) + await clock.advance(0) + await attend.stop() + await running + await attend.store.close() + + +async def test_snapshot_and_tail_recovery_preserve_observation_clocks() -> None: + store = memory_store() + clock = fake_clock(1000) + first = create_attend(store=store, clock=clock, kind={"change": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + await first.push("s", {"id": "a", "name": "change", "observedAt": 100}) + await first.push("s", {"id": "b", "name": "change", "observedAt": 200}) + await first.stop() + stored = await store.load("s") + assert stored is not None and stored["snapshot"] is not None + assert stored["snapshot"]["record"]["buffer"]["entries"][0].get("observedAt") == 100 + assert len(stored["tail"]) > 0 + judge = scripted_judge([{"route": "queue"}]) + second = create_attend(store=store, clock=clock, kind={"change": "continuous"}, judge=judge, sink="log") + running = asyncio.create_task(second.run()) + try: + await second.push("s", []) + record = await second.inspect("s") + assert record is not None and record["dueAt"] == 1200 + await clock.advance(199) + assert len(judge.calls) == 0 + await clock.advance(1) + assert [(event["id"], event.get("observedAt"), event["seenAt"]) for event in judge.calls[0]["window"]["events"]] == [("a", 100, 1000), ("b", 200, 1000)] + assert judge.calls[0]["window"]["settledAt"] == 1200 + finally: + await second.stop() + await running + await store.close() + + +@pytest.mark.parametrize(("answer", "phase", "delay"), [({"route": "wait"}, "waiting", 10_000), ({"fail": "temporary"}, "retrying", 1000)]) +async def test_source_time_survives_crash_while_held(answer: ScriptedAnswer, phase: str, delay: float) -> None: + judge = scripted_judge([answer, {"route": "queue"}]) + h = await harness({"kind": {"change": "continuous"}, "judge": judge, "sink": recording_sink()}) + try: + await h.advance(1000) + await h.push([{"id": "a", "at": -1, "name": "change", "data": {}, "observedAt": 100}]) + await h.advance(100) + record = await h.inspect() + assert record is not None and record["batch"] is not None and record["batch"]["phase"]["phase"] == phase + h.crash() + await h.restart() + await h.advance(delay - 1) + assert len(judge.calls) == 1 + await h.advance(1) + assert [call["now"] for call in judge.calls] == [1100, 1100 + delay] + assert [call["window"]["settledAt"] for call in judge.calls] == [1100, 1100] + event = judge.calls[1]["window"]["events"][0] + assert (event.get("observedAt"), event["seenAt"]) == (100, 1000) + finally: + await h.stop() + + +@pytest.mark.parametrize("observed_at", [100, 1001]) +async def test_source_attachment_checks_observation_before_cursor_commit(observed_at: float) -> None: + clock = fake_clock(1000) + judge = scripted_judge([{"route": "queue"}]) + attend = create_attend(clock=clock, kind={"change": "continuous"}, judge=judge, sink="log") + controller = AbortController() + emitted = asyncio.Event() + refused = False + + class Feed: + key = "feed" + + async def subscribe(self, cursor: str | None, emit: Callable[[SourceBatch], Awaitable[None]], signal: AbortSignal) -> None: + nonlocal refused + try: + await emit({"events": [{"id": "a", "at": -1, "name": "change", "data": {}, "observedAt": observed_at}], "cursor": "1"}) + except TypeError: + refused = True + finally: + emitted.set() + ended = asyncio.Event() + remove = signal.add_listener(ended.set) + try: + if not signal.aborted: + await ended.wait() + finally: + remove() + + running = asyncio.create_task(attend.run()) + attached = asyncio.create_task(attend.attach("s", Feed(), signal=controller.signal)) + try: + await emitted.wait() + assert refused == (observed_at > 1000) + record = await attend.inspect("s") + if refused: + assert record is None + else: + assert record is not None and record["cursors"] == {"feed": "1"} + await clock.advance(100) + event = judge.calls[0]["window"]["events"][0] + assert (event.get("observedAt"), event["seenAt"]) == (100, 1000) + finally: + controller.abort() + await attached + await attend.stop() + await running + await attend.store.close() + + +async def test_prior_reducer_snapshot_and_tail_keep_ingestion_deadlines() -> None: + store = memory_store() + policy = default_policy() + record = initial_record("s") + record.update(version=1, seen=["a"], buffer=buffer(entry("a", 1000)), dueAt=2000) + checkpoint: ScopeWrite = { + "scope": "s", + "expectedVersion": 0, + "inputs": [{"now": 1000, "input": {"kind": "tick"}}], + "snapshot": {"version": 1, "record": record, "policy": policy, "reducer": 1}, + "appends": [], + } + tail: ScopeWrite = { + "scope": "s", + "expectedVersion": 1, + "snapshot": None, + "appends": [], + "inputs": [{"now": 1100, "input": {"kind": "events", "events": [{"id": "b", "at": -1, "name": "change", "data": {}, "kind": "continuous"}]}}], + } + assert await store.commit([checkpoint]) == ["ok"] + assert await store.commit([tail]) == ["ok"] + attend = create_attend(store=store, clock=fake_clock(1200), kind={"change": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + await attend.push("s", []) + loaded = await attend.inspect("s") + 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"] == 2 + finally: + await attend.stop() + await store.close() + + +async def test_conflicting_write_reloads_without_replacing_observation_time() -> None: + clock = fake_clock(1000) + raced = asyncio.Event() + + class RacingStore(MemoryStore): + injected = False + + async def commit(self, writes: Sequence[ScopeWrite]) -> list[CommitOutcome]: + if not self.injected: + self.injected = True + assert [write["scope"] for write in writes] == ["s"] + rival: ScopeWrite = { + "scope": "s", + "expectedVersion": 0, + "snapshot": None, + "appends": [], + "inputs": [{"now": 1000, "input": {"kind": "events", "events": [{"id": "racer", "at": 0, "name": "context", "kind": "context", "data": {}}]}}], + } + await super().commit([rival]) + raced.set() + return ["conflict" for _ in writes] + return await super().commit(writes) + + store = RacingStore() + attend = create_attend(store=store, clock=clock, kind={"change": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + try: + pushed = attend.push("s", {"id": "a", "name": "change", "observedAt": 100}) + await raced.wait() + await clock.advance(50) + await pushed + record = await attend.inspect("s") + assert record is not None and [event["id"] for event in record["buffer"]["entries"]] == ["racer", "a"] + assert record["buffer"]["entries"][1].get("observedAt") == 100 + assert record["dueAt"] == 1100 + finally: + await attend.stop() + await store.close() diff --git a/src/attend.ts b/src/attend.ts index db8de16..4198a7a 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -79,6 +79,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' const classified: EventsInput['events'] = new Array(length); for (let i = 0; i < length; i += 1) { const { event, bytes } = copyEventSized(events[i]! as Event, fill); + 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'); const entry = { ...event, kind }; diff --git a/src/core/reducer.ts b/src/core/reducer.ts index 70f3e99..271af81 100644 --- a/src/core/reducer.ts +++ b/src/core/reducer.ts @@ -9,7 +9,7 @@ import { seenAdmit, seenRelease, seenTrim } from './seen.js'; import { estimateRenderedBytes, openWindow, shedEntries, windowAppend, windowCompact, windowDeadline, windowPrune, windowShed, windowSize } from './window.js'; /** Bumped whenever a release changes a transition. Stored with every snapshot. */ -export const REDUCER_VERSION = 1; +export const REDUCER_VERSION = 2; /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { diff --git a/src/core/types.ts b/src/core/types.ts index 3ce31f2..778fff5 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -10,8 +10,10 @@ export type JsonObject = { [key: string]: JsonValue }; /** One event as a source hands it in. `id` is unique within the scope and is the dedup key. */ export interface Event { id: string; - /** ms since the epoch, as the source reports it. Informational: timers use `Entry.seenAt`. */ + /** ms since the epoch, as the source reports it. Informational. */ at: number; + /** Source observation time in the engine clock's coordinates. Omit to settle from ingestion. */ + observedAt?: number; name: string; data: JsonObject; /** One plain line describing the event. The judge never writes text; notices are built from these. */ @@ -500,8 +502,8 @@ export type KnownIds = Map; /** * Everything `deadline()` reads, kept O(1). Acts and flushes are never shed or pruned, so their - * fields only move forward. NaN means none for the `*At` fields; `minFlushAt` and - * `prefixMinSheddableAt` use Infinity for none. Equal to what a scan of the live entries derives. + * time summaries need no removal update. NaN marks absent times; minima start at Infinity and + * maxima at -Infinity. Equal to what a scan of the live entries derives. */ export interface TriggerSummary { minFlushAt: number; @@ -509,13 +511,23 @@ export interface TriggerSummary { lastStreamAt: number; lastPassiveAt: number; firstActAt: number; + /** Candidate extrema retain earlier entries before a kind first uses observation time. */ + maxClosingAt: number; + maxStreamAt: number; + maxPassiveAt: number; + minActAt: number; + closingObserved: boolean; + streamObserved: boolean; + passiveObserved: boolean; + actObserved: boolean; /** Index of the first act relative to `start`, or -1. Adjusted on removal, unchanged by compaction. */ firstActIndex: number; - /** Smallest `seenAt` among sheddable entries before the first act: the O(1) prune test. */ + /** Smallest effective observation time among sheddable entries before the first act: the O(1) prune test. */ prefixMinSheddableAt: number; /** Live consequence and context entries; zero means nothing can be shed. */ sheddable: number; lastSeenAt: number; + lastObservationAt: number; } /** The open window, appended in place by its single writer. Live entries are `entries[start..]`. */ @@ -536,7 +548,7 @@ export interface OpenWindow { hash: FnvState; /** False after a prune or shed inside the window; the settle then refolds the final list. */ hashValid: boolean; - /** False once an appended `seenAt` was smaller than the last one; prune then scans the whole prefix. */ + /** False once observation time decreases in arrival order; prune then scans the whole prefix. */ monotone: boolean; } diff --git a/src/core/window.ts b/src/core/window.ts index 1c955f1..9b157e3 100644 --- a/src/core/window.ts +++ b/src/core/window.ts @@ -19,23 +19,50 @@ function emptySummary(): TriggerSummary { return { minFlushAt: Infinity, lastClosingAt: NaN, lastStreamAt: NaN, lastPassiveAt: NaN, firstActAt: NaN, firstActIndex: -1, prefixMinSheddableAt: Infinity, sheddable: 0, lastSeenAt: NaN, + maxClosingAt: -Infinity, maxStreamAt: -Infinity, maxPassiveAt: -Infinity, minActAt: Infinity, + closingObserved: false, streamObserved: false, passiveObserved: false, actObserved: false, lastObservationAt: NaN, }; } function summarizeEntry(summary: TriggerSummary, entry: Entry, index: number): void { + const observedAt = observationTime(entry); + const explicit = entry.observedAt !== undefined; if (entry.kind === 'flush') summary.minFlushAt = Math.min(summary.minFlushAt, entry.seenAt); - if (entry.kind === 'closing') summary.lastClosingAt = entry.seenAt; - if (entry.kind === 'continuous') summary.lastStreamAt = entry.seenAt; - if (entry.kind === 'passive') summary.lastPassiveAt = 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.kind === 'continuous') { + summary.maxStreamAt = Math.max(summary.maxStreamAt, observedAt); + summary.streamObserved ||= explicit; + summary.lastStreamAt = summary.streamObserved ? summary.maxStreamAt : entry.seenAt; + } + if (entry.kind === 'passive') { + summary.maxPassiveAt = Math.max(summary.maxPassiveAt, observedAt); + summary.passiveObserved ||= explicit; + summary.lastPassiveAt = summary.passiveObserved ? summary.maxPassiveAt : entry.seenAt; + } if (summary.firstActIndex === -1 && isAct(entry)) { summary.firstActIndex = index; summary.firstActAt = entry.seenAt; } + if (isAct(entry)) { + summary.minActAt = Math.min(summary.minActAt, observedAt); + summary.actObserved ||= explicit; + if (summary.actObserved) summary.firstActAt = summary.minActAt; + } if (isSheddable(entry)) { summary.sheddable += 1; - if (summary.firstActIndex === -1) summary.prefixMinSheddableAt = Math.min(summary.prefixMinSheddableAt, entry.seenAt); + if (summary.firstActIndex === -1) summary.prefixMinSheddableAt = Math.min(summary.prefixMinSheddableAt, observedAt); } summary.lastSeenAt = entry.seenAt; + summary.lastObservationAt = observedAt; +} + +function observationTime(entry: Entry): number { + return entry.observedAt ?? entry.seenAt; } function summarize(entries: readonly Entry[], start = 0): TriggerSummary { @@ -89,7 +116,7 @@ export function windowCompact(open: OpenWindow): Entry[] { /** Appends an entry and updates sizes, summary, monotonicity and any valid hash in O(1). */ export function windowAppend(open: OpenWindow, entry: Entry, bytes: number): void { - if (entry.seenAt < open.summary.lastSeenAt) open.monotone = false; + if (observationTime(entry) < open.summary.lastObservationAt) open.monotone = false; const index = windowSize(open); open.entries.push(entry); open.sizes.push(bytes); @@ -104,8 +131,8 @@ function prefixMinimum(open: OpenWindow): number { for (let i = 0; i < end; i += 1) { const entry = open.entries[open.start + i]!; if (isSheddable(entry)) { - if (open.monotone) return entry.seenAt; - min = Math.min(min, entry.seenAt); + if (open.monotone) return observationTime(entry); + min = Math.min(min, observationTime(entry)); } } return min; @@ -118,6 +145,7 @@ function removedFrom(open: OpenWindow, count: number, bytes: number, prefixCount if (open.summary.firstActIndex !== -1) open.summary.firstActIndex -= prefixCount; if (prefixCount > 0) open.summary.prefixMinSheddableAt = prefixMinimum(open); open.summary.lastSeenAt = windowSize(open) === 0 ? NaN : open.entries[open.entries.length - 1]!.seenAt; + open.summary.lastObservationAt = windowSize(open) === 0 ? NaN : observationTime(open.entries[open.entries.length - 1]!); open.hashValid = false; } @@ -156,7 +184,7 @@ export function windowPrune(open: OpenWindow, maxWindowMs: number, now: number): let read = 0; for (; read < end; read += 1) { const entry = entries[start + read]!; - const stale = entry.seenAt + maxWindowMs <= now; + const stale = observationTime(entry) + maxWindowMs <= now; if (!stale && open.monotone) break; if (stale && isSheddable(entry)) { if (gone === null) gone = [entry]; @@ -301,7 +329,7 @@ export function assertWindow(scope: string, open: OpenWindow): void { } if (open.monotone) { for (let i = open.start + 1; i < open.entries.length; i += 1) { - if (open.entries[i]!.seenAt < open.entries[i - 1]!.seenAt) throw new Error('monotone: seenAt decreased'); + if (observationTime(open.entries[i]!) < observationTime(open.entries[i - 1]!)) throw new Error('monotone: observation time decreased'); } } } diff --git a/src/internal/shared.ts b/src/internal/shared.ts index d82678b..a0cd849 100644 --- a/src/internal/shared.ts +++ b/src/internal/shared.ts @@ -69,7 +69,9 @@ function copyObject(value: object, key: string | number, depth: number): JsonVal const object: JsonObject = {}; const source = value as Record; for (const name of keys(source)) { - const copied = toJson(source[name], name, depth + 1); + const field = source[name]; + if (depth === 0 && name === 'observedAt') checkObservation(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 }); else object[name] = copied; @@ -120,6 +122,7 @@ export function copyEvent(event: Event, defaultData = false): Event { const data = toJson(fields.data, 'data', 1); if (!isRecord(data)) throw new TypeError('attend: event data must be a JSON object'); fields.data = data; + checkObservation(fields.observedAt); return fields as unknown as Event; } return checkedEvent(toJson(fields, '', 0), defaultData); @@ -130,5 +133,10 @@ export function copyEvent(event: Event, defaultData = false): Event { function checkedEvent(copied: JsonValue | undefined, defaultData: boolean): Event { if (defaultData && isRecord(copied) && copied.data === undefined) copied.data = {}; if (!isRecord(copied) || !isRecord(copied.data)) throw new TypeError('attend: event data must be a JSON object'); + checkObservation(copied.observedAt); return copied as unknown as Event; } + +function checkObservation(value: unknown): void { + if (value !== undefined && (typeof value !== 'number' || !isFinite(value))) throw new TypeError('attend: observedAt must be a finite number'); +} diff --git a/src/shell/types.ts b/src/shell/types.ts index d53b64a..200d1d8 100644 --- a/src/shell/types.ts +++ b/src/shell/types.ts @@ -20,12 +20,10 @@ export interface AdmissionOptions { } /** An event as `push` takes it: `id` defaults to a random UUID, `at` to the clock and `data` to `{}`. Pass your own `id` to drop redeliveries. */ -export interface EventInput { - name: string; - id?: string; - at?: number; - data?: JsonObject; - text?: string; +export interface EventInput extends Omit { + id?: Event['id']; + at?: Event['at']; + data?: Event['data']; } /** Store, effects, policy and resource limits for an instance. */ diff --git a/src/testing.ts b/src/testing.ts index 5c1fb41..4fc7278 100644 --- a/src/testing.ts +++ b/src/testing.ts @@ -182,7 +182,7 @@ export function logConformance(make: () => Promise | EventLog, options [ 'events round-trip deep-equal', async (log) => { - const e: Event = { id: 'a', at: 7, name: 'x.y', data: { n: 1, s: 'ünï 🌍', l: [null, { k: false }] }, text: 'one line' }; + const e: Event = { id: 'a', at: 7, observedAt: 9, name: 'x.y', data: { n: 1, s: 'ünï 🌍', l: [null, { k: false }] }, text: 'one line' }; await log.append('s', [e]); assertEqual((await log.read('s', null, { limit: 1 }))[0]?.event, e, 'round trip'); }, diff --git a/src/testing/conformance.ts b/src/testing/conformance.ts index 7e5024b..17d0037 100644 --- a/src/testing/conformance.ts +++ b/src/testing/conformance.ts @@ -16,7 +16,7 @@ function logged(id: string, now = 1000): LoggedInput { function window(id: string): Window { return { - id, events: [{ id: `event:${id}`, at: 1, name: 'changed', data: { nested: [null, true, 'héllo 🌍\u0000'] }, text: 'héllo 🌍\u0000', kind: 'closing', seenAt: 2 }], + id, events: [{ id: `event:${id}`, at: 1, observedAt: 1, name: 'changed', data: { nested: [null, true, 'héllo 🌍\u0000'] }, text: 'héllo 🌍\u0000', kind: 'closing', seenAt: 2 }], reason: 'closing', waits: 0, dropped: 0, gap: false, settledAt: 3, }; } @@ -202,7 +202,7 @@ export function scopeStoreConformance(make: () => Promise | ScopeSto assertEqual(await store.load('s'), { version: 7, snapshot: replacement, tail: [] }, 'older snapshot replaced'); }], ['a snapshot and its tail round-trip with unicode, a NUL, a 250-entry window and a 1,000-id ring', async (store) => { - const entries: Entry[] = Array.from({ length: 250 }, (_, i) => ({ id: `e${i}`, at: i, seenAt: i + 1, name: 'n', text: 'héllo 🌍\u0000', data: { i, nested: [null, { yes: true }] }, kind: 'passive' })); + const entries: Entry[] = Array.from({ length: 250 }, (_, i) => ({ id: `e${i}`, at: i, observedAt: i, seenAt: i + 1, name: 'n', text: 'héllo 🌍\u0000', data: { i, nested: [null, { yes: true }] }, kind: 'passive' })); const d = decision('delivered', 's'); const l = letter('failed', 's'); if (l.kind !== 'deadLetter') throw new Error('expected dead letter'); diff --git a/test/conformance/scenario.ts b/test/conformance/scenario.ts index 2731cb8..a312352 100644 --- a/test/conformance/scenario.ts +++ b/test/conformance/scenario.ts @@ -52,6 +52,7 @@ export interface EventSpec { id: string; name: string; at?: number; + observedAt?: number; data?: JsonObject; text?: string; } @@ -267,7 +268,7 @@ export async function runScenario(scenario: Scenario): Promise { for (const [index, step] of scenario.steps.entries()) { if ('push' in step) { scopes.add(step.push); - 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 }) })); + 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 }) })); await result(index, () => attend.push(step.push, events)); } else if ('advance' in step) { await clock.advance(step.advance); diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index c45cfcc..93bba29 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,50 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'observation time sets a quiet deadline while at and seenAt remain distinct', + kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { at: -1, observedAt: 100 })), { inspect: 's' }, advance(99), { inspect: 's' }, advance(1)], + }, + { + name: 'an already-due observation settles at processing time', + start: 2000, + kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 100 })), advance(0)], + }, + { + name: 'a wait horizon starts when a source-timed judgment finishes', + kinds: KINDS, + judge: { '*': { answers: [{ route: 'wait' }, { route: 'note' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 100 })), advance(100), { inspect: 's' }, advance(9999), { inspect: 's' }, advance(1)], + }, + { + name: 'a retry and its leases keep processing time after an old observation', + kinds: KINDS, + judge: { '*': { answers: [{ fail: 'temporary' }, { route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 0 })), advance(0), { inspect: 's' }, advance(999), { inspect: 's' }, advance(1)], + }, + { + name: 'older observations do not shorten a quiet deadline and implicit observations join it', + kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 900 }), ev('b', 'drag', { observedAt: 100 }), ev('c', 'drag')), { inspect: 's' }, advance(999), { inspect: 's' }, advance(1)], + }, + { + name: 'old background observations are pruned behind newer observations', + kinds: KINDS, + settle: { maxWindowMs: 200 }, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('a', 'out', { observedAt: 900 }), ev('b', 'out', { observedAt: 100 }), ev('c', 'out', { observedAt: 950 })), { inspect: 's' }], + }, + { + name: 'a future observation refuses the complete batch before any event is stored', + kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('a', 'drag', { observedAt: 100 }), ev('b', 'drag', { observedAt: 1001 })), { inspect: 's' }, push('s', ev('a', 'drag', { observedAt: 100 })), advance(100)], + }, { name: 'a closing act settles after the grace, is judged with the configured context, and is delivered', from: `${T}: a closing act settles after the grace, is judged with the configured context, and is delivered`, diff --git a/test/core-inputs.test.ts b/test/core-inputs.test.ts index 7e4ba35..9771346 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, 1); + assert.equal(REDUCER_VERSION, 2); }); test('fromRecord accepts frozen oracle snapshots without changing them', () => { diff --git a/test/observation-admission.test.ts b/test/observation-admission.test.ts new file mode 100644 index 0000000..0c1e072 --- /dev/null +++ b/test/observation-admission.test.ts @@ -0,0 +1,53 @@ +import { expect, test } from 'vitest'; +import { createAttend } from '../src/index.js'; +import { fakeClock, scriptedJudge } from '../src/testing.js'; + +test.each([Symbol('time'), () => 100, { toJSON: () => undefined }])('an observation that JSON would omit still refuses the batch: %s', async (observedAt) => { + const attend = createAttend({ clock: fakeClock(200), kind: () => 'continuous', judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + // JavaScript input is not restricted by the declared numeric field. + // @ts-expect-error invalid observation is the boundary under test + await expect(attend.push('s', [{ id: 'a', name: 'move' }, { id: 'b', name: 'move', observedAt }])).rejects.toThrow('observedAt'); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test('a root toJSON result cannot erase its invalid observation', async () => { + let calls = 0; + const event = { id: 'a', name: 'move', toJSON() { calls += 1; return { id: 'a', name: 'move', observedAt: Symbol('time') }; } }; + const attend = createAttend({ clock: fakeClock(200), kind: () => 'continuous', judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + await expect(attend.push('s', event)).rejects.toThrow('observedAt'); + expect(calls).toBe(1); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test('an observation getter is read once before refusing its value', async () => { + let reads = 0; + const event = { id: 'a', name: 'move', get observedAt() { reads += 1; return reads === 1 ? Symbol('time') : 100; } }; + const attend = createAttend({ clock: fakeClock(200), kind: () => 'continuous', judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + // @ts-expect-error a getter may return a nonnumeric value at runtime + await expect(attend.push('s', event)).rejects.toThrow('observedAt'); + expect(reads).toBe(1); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test('timing names nested in data retain ordinary JSON normalization', async () => { + const attend = createAttend({ clock: fakeClock(200), kind: () => 'continuous', judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + // @ts-expect-error the JSON boundary intentionally omits callable data properties + await attend.push('s', { id: 'a', name: 'move', observedAt: 100, data: { observedAt: () => 100, quietForMs: Symbol('duration'), value: 1 } }); + expect((await attend.inspect('s'))?.buffer.entries[0]?.data).toEqual({ value: 1 }); + } finally { + await attend.stop(); + } +}); diff --git a/test/observation-time.test.ts b/test/observation-time.test.ts new file mode 100644 index 0000000..f0ebad0 --- /dev/null +++ b/test/observation-time.test.ts @@ -0,0 +1,247 @@ +import { expect, test } from 'vitest'; +import { createAttend, DEFAULT_POLICY, memoryStore } from '../src/index.js'; +import type { Buffer, Entry, Judgment, Kind, SettleReason, Source } from '../src/types.js'; +import type { ScopeStore } from '../src/store/types.js'; +import { assertWindow, deadline, windowFrom, windowPrune } from '../src/core/window.js'; +import { fakeClock, harness, recordingSink, scriptedJudge, type ScriptedAnswer } from '../src/testing.js'; +import { initialRecord } from '../src/step.js'; + +function entry(id: string, seenAt: number, observedAt?: number, kind: Kind = 'continuous'): Entry { + return { id, at: -1, name: 'change', data: {}, kind, seenAt, ...(observedAt === undefined ? {} : { observedAt }) }; +} + +function buffer(...entries: Entry[]): Buffer { + return { entries, dropped: 0, gap: false, forcedAt: null }; +} + +function gate() { + const opened = new AbortController(); + const promise = new Promise((resolve) => opened.signal.addEventListener('abort', () => resolve(), { once: true })); + return { promise, open: () => opened.abort() }; +} + +test('source observation sets the quiet deadline without changing the other clocks', async () => { + const clock = fakeClock(1000); + const judge = scriptedJudge([{ route: 'queue' }]); + const sink = recordingSink(); + const store = memoryStore(); + const attend = createAttend({ store, clock, kind: { change: 'continuous' }, judge, sink }); + const running = attend.run(); + try { + await attend.push('s', { id: 'a', at: -1, observedAt: 100, name: 'change' }); + expect((await attend.inspect('s'))?.dueAt).toBe(1100); + await clock.advance(99); + expect(judge.calls).toHaveLength(0); + await clock.advance(1); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([1100]); + expect(sink.delivered[0]?.window.events[0]).toMatchObject({ at: -1, observedAt: 100, seenAt: 1000 }); + expect(sink.delivered[0]?.at).toBe(1100); + } finally { + await attend.stop(); + await running; + } +}); + +test.each([null, true, '100', NaN, Infinity, -Infinity, 1001])('rejects invalid or future observation %s before admission', async (observedAt) => { + const store = memoryStore(); + const attend = createAttend({ store, clock: fakeClock(1000), kind: { change: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + // JavaScript and decoded input can violate the public type. + // @ts-expect-error invalid input is the boundary under test + await expect(attend.push('s', { id: 'a', name: 'change', observedAt })).rejects.toThrow('observedAt'); + expect(await attend.inspect('s')).toBeNull(); + } finally { + await attend.stop(); + } +}); + +test.each([ + { kind: 'closing', gap: DEFAULT_POLICY.closingGraceMs, reason: 'closing' }, + { kind: 'continuous', gap: DEFAULT_POLICY.streamGapMs, reason: 'stream_quiet' }, + { kind: 'passive', gap: DEFAULT_POLICY.passiveQuietMs, reason: 'passive_quiet' }, +] satisfies { kind: Kind; gap: number; reason: SettleReason }[])('older $kind observations do not shorten quiet time', ({ kind, gap, reason }) => { + expect(deadline(DEFAULT_POLICY, buffer(entry('a', 1000, 900, kind), entry('b', 1000, 100, kind)))).toEqual({ at: 900 + gap, reason }); +}); + +test('source age uses the oldest act while absent observations retain arrival behavior', () => { + const policy = { ...DEFAULT_POLICY, streamGapMs: 100_000 }; + expect(deadline(policy, buffer(entry('a', 1000, 900), entry('b', 1000, 0)))).toEqual({ at: 60_000, reason: 'age' }); + expect(deadline(policy, buffer(entry('a', 1000), entry('b', 500)))).toEqual({ at: 61_000, reason: 'age' }); + expect(deadline(DEFAULT_POLICY, buffer(entry('a', 1000), entry('b', 500)))).toEqual({ at: 1500, reason: 'stream_quiet' }); + expect(deadline(DEFAULT_POLICY, buffer(entry('a', 1000), entry('b', 500, 350)))).toEqual({ at: 2000, reason: 'stream_quiet' }); +}); + +test('an old background observation behind a fresh one is pruned without moving arrival order', () => { + const open = windowFrom('s', buffer(entry('fresh', 1000, 900, 'context'), entry('old', 1000, 100, 'context'), entry('latest', 1000, 950, 'context'))); + expect(windowPrune(open, 200, 1000)?.map((event) => event.id)).toEqual(['old']); + expect(open.entries.slice(open.start).map((event) => event.id)).toEqual(['fresh', 'latest']); + expect(open.dropped).toBe(1); + assertWindow('s', open); +}); + +test('flush, count and byte deadlines keep ingestion time', () => { + expect(deadline(DEFAULT_POLICY, buffer(entry('a', 1000, 100, 'flush')))).toEqual({ at: 1000, reason: 'flush' }); + expect(deadline({ ...DEFAULT_POLICY, maxEvents: 0 }, buffer(entry('a', 1000, 100)))).toEqual({ at: 1000, reason: 'overflow' }); + expect(deadline({ ...DEFAULT_POLICY, maxWindowBytes: 0 }, buffer(entry('a', 1000, 100)))).toEqual({ at: 1000, reason: 'size' }); +}); + +test('late settlement and the judge lease use processing time', async () => { + const clock = fakeClock(2000); + const response = gate(); + let calls = 0; + const judge = async (): Promise => { calls += 1; await response.promise; return { route: 'skip' }; }; + const attend = createAttend({ clock, kind: { change: 'continuous' }, judge, sink: 'log', settle: { judgeTimeoutMs: 100 } }); + const running = attend.run(); + try { + await attend.push('s', { id: 'a', name: 'change', observedAt: 100 }); + await clock.advance(0); + const batch = (await attend.inspect('s'))?.batch; + expect(batch?.window.settledAt).toBe(2000); + expect(batch?.phase).toMatchObject({ phase: 'judging', leaseUntil: 2200 }); + expect(calls).toBe(1); + await clock.advance(99); + expect(calls).toBe(1); + } finally { + response.open(); + await clock.advance(0); + await attend.stop(); + await running; + } +}); + +test('snapshot and tail recovery preserve observation clocks', async () => { + const store = memoryStore(); + const clock = fakeClock(1000); + const first = createAttend({ store, clock, kind: { change: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + await first.push('s', { id: 'a', name: 'change', observedAt: 100 }); + await first.push('s', { id: 'b', name: 'change', observedAt: 200 }); + await first.stop(); + const stored = await store.load('s'); + expect(stored?.snapshot?.record.buffer.entries[0]?.observedAt).toBe(100); + expect(stored?.tail.length).toBeGreaterThan(0); + const judge = scriptedJudge([{ route: 'queue' }]); + const second = createAttend({ store, clock, kind: { change: 'continuous' }, judge, sink: 'log' }); + const running = second.run(); + try { + await second.push('s', []); + expect((await second.inspect('s'))?.dueAt).toBe(1200); + await clock.advance(199); + expect(judge.calls).toHaveLength(0); + await clock.advance(1); + expect(judge.calls[0]?.window.events.map((event) => [event.id, event.observedAt, event.seenAt])).toEqual([['a', 100, 1000], ['b', 200, 1000]]); + expect(judge.calls[0]?.window.settledAt).toBe(1200); + } finally { + await second.stop(); + await running; + } +}); + +test.each([ + { answer: { route: 'wait' }, phase: 'waiting', delay: 10_000 }, + { answer: { fail: 'temporary' }, phase: 'retrying', delay: 1000 }, +] satisfies { answer: ScriptedAnswer; phase: string; delay: number }[])('source time survives a crash while $phase', async ({ answer, phase, delay }) => { + const judge = scriptedJudge([answer, { route: 'queue' }]); + const h = harness({ kind: () => 'continuous', judge, sink: recordingSink() }); + try { + await h.advance(1000); + await h.push([{ id: 'a', at: -1, name: 'change', data: {}, observedAt: 100 }]); + await h.advance(100); + expect((await h.inspect())?.batch?.phase.phase).toBe(phase); + h.crash(); + await h.restart(); + await h.advance(delay - 1); + expect(judge.calls).toHaveLength(1); + await h.advance(1); + expect(judge.calls.map((call) => call.now)).toEqual([1100, 1100 + delay]); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([1100, 1100]); + expect(judge.calls[1]?.window.events[0]).toMatchObject({ observedAt: 100, seenAt: 1000 }); + } finally { + await h.stop(); + } +}); + +test.each([100, 1001])('source attachment validates observation %s before its cursor commits', async (observedAt) => { + const clock = fakeClock(1000); + const judge = scriptedJudge([{ route: 'queue' }]); + const attend = createAttend({ clock, kind: { change: 'continuous' }, judge, sink: 'log' }); + const controller = new AbortController(); + const emitted = gate(); + let refused = false; + const source: Source = { + key: 'feed', + async subscribe(_cursor, emit, signal) { + try { await emit({ events: [{ id: 'a', at: -1, name: 'change', data: {}, observedAt }], cursor: '1' }); } + catch (error) { if (!(error instanceof TypeError)) throw error; refused = true; } + finally { emitted.open(); } + if (!signal.aborted) await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })); + }, + }; + const running = attend.run(); + const attached = attend.attach('s', source, { signal: controller.signal }); + try { + await emitted.promise; + expect(refused).toBe(observedAt > 1000); + const record = await attend.inspect('s'); + if (refused) expect(record).toBeNull(); + else { + expect(record?.cursors).toEqual({ feed: '1' }); + await clock.advance(100); + expect(judge.calls[0]?.window.events[0]).toMatchObject({ observedAt: 100, seenAt: 1000 }); + } + } finally { + controller.abort(); + await attached; + await attend.stop(); + await running; + } +}); + +test('a prior reducer snapshot and tail retain ingestion-time deadlines on upgrade', async () => { + const store = memoryStore(); + const record = { ...initialRecord('s'), version: 1, seen: ['a'], buffer: buffer(entry('a', 1000)), dueAt: 2000 }; + expect(await store.commit([{ scope: 's', expectedVersion: 0, inputs: [{ now: 1000, input: { kind: 'tick' } }], snapshot: { version: 1, record, policy: DEFAULT_POLICY, reducer: 1 }, appends: [] }])).toEqual(['ok']); + expect(await store.commit([{ scope: 's', expectedVersion: 1, inputs: [{ now: 1100, input: { kind: 'events', events: [{ id: 'b', at: -1, name: 'change', data: {}, kind: 'continuous' }] } }], snapshot: null, appends: [] }])).toEqual(['ok']); + const attend = createAttend({ store, clock: fakeClock(1200), kind: { change: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + await attend.push('s', []); + 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(2); + } finally { + await attend.stop(); + } +}); + +test('a conflicting write reloads without replacing observation time', async () => { + const inner = memoryStore(); + const clock = fakeClock(1000); + const raced = gate(); + let injected = false; + const store: ScopeStore = { + ...inner, + async commit(writes) { + if (!injected) { + injected = true; + expect(writes.map((write) => write.scope)).toEqual(['s']); + await inner.commit([{ scope: 's', expectedVersion: 0, inputs: [{ now: 1000, input: { kind: 'events', events: [{ id: 'racer', at: 0, name: 'context', kind: 'context', data: {} }] } }], snapshot: null, appends: [] }]); + raced.open(); + return writes.map(() => 'conflict'); + } + return inner.commit(writes); + }, + }; + const attend = createAttend({ store, clock, kind: { change: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + try { + const pushed = attend.push('s', { id: 'a', name: 'change', observedAt: 100 }); + await raced.promise; + await clock.advance(50); + await pushed; + const record = await attend.inspect('s'); + expect(record?.buffer.entries.map((event) => event.id)).toEqual(['racer', 'a']); + expect(record?.buffer.entries[1]?.observedAt).toBe(100); + expect(record?.dueAt).toBe(1100); + } finally { + await attend.stop(); + } +}); diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 3644463..6b28080 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, 1); + assert.equal(snapshot.reducerVersion, 2); 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 });