diff --git a/DEVIATIONS.md b/DEVIATIONS.md index 44d7ea0..ea41931 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -1,5 +1,11 @@ # Shell changes from the frozen shell +## Independent event limits + +The optional `settle.eventLimits` pair separates an inclusive counted trigger from FIFO background retention. It requires accumulating continuation and replaces the scalar total limit. Omission preserves the existing scalar path. Retention applies across unresolved held and fresh entries, including transitions from a live offer; it never mutates that offer or drops counted entries. Reducer revision 5 stores the opt-in policy. [Independent event limits](docs/reference.md#independent-event-limits) defines the contract and writer-change boundary. + +TypeScript writer startup now replays stored tails with the saved policy, even when its runtime options contain a different policy. Spreading that options object previously replaced the saved policy and could resurrect already completed input. `test/policy-replay.test.ts` pins the correction; frozen ordinary-policy cases remain unchanged. + ## Accumulating continuation The optional `settle.continuation = 'accumulate'` reoffers waits within their allowance, retains provider failures across waits and absorbs admitted input at a strict retry not-before time. Whole-window count, rendered bytes and age constrain wait eligibility, including ties. Ordinary continuation keeps the frozen behavior. The existing reducer and delivery machinery remain in use; no host timer or alternate scheduler is introduced. diff --git a/conformance/fixtures/event-limits-legacy.json b/conformance/fixtures/event-limits-legacy.json new file mode 100644 index 0000000..d0dac76 --- /dev/null +++ b/conformance/fixtures/event-limits-legacy.json @@ -0,0 +1,1419 @@ +{ + "writerCommit": "b107204c15aa935150ff977b4ad2102a6d0a57c0", + "reducer": 4, + "cases": [ + { + "name": "background", + "mode": "accumulate", + "now": 15, + "writes": [ + [ + { + "scope": "s", + "expectedVersion": 0, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "a", + "name": "meta", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "context" + } + ] + }, + "now": 0 + } + ], + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "meta", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "context", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "appends": [], + "due": null + } + ], + [ + { + "scope": "s", + "expectedVersion": 1, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ], + "snapshot": null, + "appends": [] + } + ] + ], + "stored": { + "version": 2, + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "meta", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "context", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "tail": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ] + }, + "expected": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "meta", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "context", + "seenAt": 0 + }, + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + } + }, + { + "name": "waiting", + "mode": "accumulate", + "now": 15, + "writes": [ + [ + { + "scope": "s", + "expectedVersion": 0, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous" + } + ] + }, + "now": 0 + } + ], + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 1, + "inputs": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 31000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 2, + "inputs": [ + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "wait" + } + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 3, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ], + "snapshot": null, + "appends": [] + } + ] + ], + "stored": { + "version": 4, + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "tail": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + }, + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "wait" + } + }, + "now": 10 + }, + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ] + }, + "expected": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 30, + "failures": 0 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 30 + } + }, + { + "name": "retrying", + "mode": "accumulate", + "now": 15, + "writes": [ + [ + { + "scope": "s", + "expectedVersion": 0, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous" + } + ] + }, + "now": 0 + } + ], + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 1, + "inputs": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 31000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 2, + "inputs": [ + { + "input": { + "kind": "judgeFailed", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "message": "controlled", + "permanent": false + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 3, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ], + "snapshot": null, + "appends": [] + } + ] + ], + "stored": { + "version": 4, + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "tail": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + }, + { + "input": { + "kind": "judgeFailed", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "message": "controlled", + "permanent": false + }, + "now": 10 + }, + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ] + }, + "expected": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 40, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 40 + } + }, + { + "name": "separate", + "mode": "separate", + "now": 15, + "writes": [ + [ + { + "scope": "s", + "expectedVersion": 0, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous" + } + ] + }, + "now": 0 + } + ], + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "separate" + }, + "reducer": 4 + }, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 1, + "inputs": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 31000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 2, + "inputs": [ + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "wait" + } + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 3, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ], + "snapshot": null, + "appends": [] + } + ] + ], + "stored": { + "version": 4, + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "separate" + }, + "reducer": 4 + }, + "tail": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + }, + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "wait" + } + }, + "now": 10 + }, + { + "input": { + "kind": "events", + "events": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context" + } + ] + }, + "now": 15 + } + ] + }, + "expected": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "b", + "name": "meta", + "at": 15, + "data": {}, + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 30 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 30 + } + }, + { + "name": "complete", + "mode": "accumulate", + "now": 10, + "writes": [ + [ + { + "scope": "s", + "expectedVersion": 0, + "inputs": [ + { + "input": { + "kind": "events", + "events": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous" + } + ] + }, + "now": 0 + } + ], + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "appends": [], + "due": 1000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 1, + "inputs": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [], + "due": 31000 + } + ], + [ + { + "scope": "s", + "expectedVersion": 2, + "inputs": [ + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "queue" + } + }, + "now": 10 + } + ], + "snapshot": null, + "appends": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 10, + "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", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "at": 10 + } + } + ], + "due": null + } + ] + ], + "stored": { + "version": 3, + "snapshot": { + "version": 1, + "record": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [ + { + "id": "a", + "name": "reading", + "at": 0, + "text": "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq", + "data": {}, + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 10 + }, + "policy": { + "closingGraceMs": 500, + "streamGapMs": 10, + "passiveQuietMs": 4000, + "waitHorizonMs": 20, + "maxWaits": 2, + "maxEvents": 250, + "maxWindowMs": 60000, + "retryBackoffMs": [ + 30, + 60 + ], + "judgeTimeoutMs": 15000, + "deliveryTimeoutMs": 10000, + "recentCount": 8, + "seenCount": 500, + "maxOutbox": 1000, + "maxDeadLetters": 1000, + "deadLetterBackoffMaxMs": 60000, + "continuation": "accumulate" + }, + "reducer": 4 + }, + "tail": [ + { + "input": { + "kind": "tick" + }, + "now": 10 + }, + { + "input": { + "kind": "judged", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "judgment": { + "route": "queue" + } + }, + "now": 10 + } + ] + }, + "expected": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 10 + } + ], + "dueAt": null + } + } + ] +} diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index 55380b6..2625d95 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,4893 @@ { "scenarios": [ + { + "scenario": { + "name": "independent limits settle counted equality while retaining background", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + } + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "x", + "name": "said", + "text": "said x" + }, + { + "id": "y", + "name": "out", + "text": "out y" + } + ] + }, + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a" + }, + { + "id": "b", + "name": "drag", + "text": "drag b" + } + ] + }, + { + "inspect": "s" + }, + { + "submit": "s", + "events": [ + { + "id": "c", + "name": "drag", + "text": "drag c" + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "4f289193e8bb6b95", + "events": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 0 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "4f289193e8bb6b95", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "4f289193e8bb6b95", + "events": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "4f289193e8bb6b95", + "reason": "overflow", + "count": 5, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "4f289193e8bb6b95", + "attempt": 1, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "4f289193e8bb6b95", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "4f289193e8bb6b95", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "4f289193e8bb6b95" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 1, + "error": null + }, + { + "step": 3, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 2, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "y", + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1000 + } + }, + { + "step": 4, + "scope": "s", + "record": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "y", + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "4f289193e8bb6b95", + "route": "queue", + "at": 0 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "y", + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "4f289193e8bb6b95", + "route": "queue", + "at": 0 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "4f289193e8bb6b95", + "scope": "s", + "at": 0, + "route": "queue", + "body": { + "id": "4f289193e8bb6b95", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "4f289193e8bb6b95", + "events": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent background retention uses arrival order despite observation order", + "start": 20, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + } + }, + "judge": { + "*": { + "answers": [ + { + "route": "skip" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "x", + "name": "said", + "text": "said x", + "observedAt": 20 + }, + { + "id": "y", + "name": "out", + "text": "out y", + "observedAt": 10 + }, + { + "id": "z", + "name": "said", + "text": "said z", + "observedAt": 0 + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": {}, + "deliveries": {}, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "observedAt": 20, + "kind": "context", + "seenAt": 20 + } + ], + "why": "overflow" + }, + { + "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": [ + "x", + "y", + "z" + ], + "buffer": { + "entries": [ + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "observedAt": 10, + "kind": "consequence", + "seenAt": 20 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "observedAt": 0, + "kind": "context", + "seenAt": 20 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 1, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "y", + "z" + ], + "buffer": { + "entries": [ + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "observedAt": 10, + "kind": "consequence", + "seenAt": 20 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "observedAt": 0, + "kind": "context", + "seenAt": 20 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": null + } + }, + "log": [] + } + }, + { + "scenario": { + "name": "independent zero background retains an atomic counted overshoot", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 2, + "background": 0 + } + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "x", + "name": "out", + "text": "out x" + }, + { + "id": "a", + "name": "drag", + "text": "drag a" + }, + { + "id": "b", + "name": "drag", + "text": "drag b" + }, + { + "id": "y", + "name": "said", + "text": "said y" + }, + { + "id": "c", + "name": "drag", + "text": "drag c" + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 2, + "gap": false, + "settledAt": 0 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 0 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 2, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "out", + "data": {}, + "text": "out x", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "said", + "data": {}, + "text": "said y", + "kind": "context", + "seenAt": 0 + } + ], + "why": "overflow" + }, + { + "kind": "ingested", + "scope": "s", + "count": 5, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "1a353cc02182e85a", + "reason": "overflow", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "1a353cc02182e85a", + "attempt": 1, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "1a353cc02182e85a", + "route": "queue" + }, + { + "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": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "a", + "b", + "y", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "1a353cc02182e85a", + "route": "queue", + "at": 0 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "x", + "a", + "b", + "y", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "1a353cc02182e85a", + "route": "queue", + "at": 0 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "1a353cc02182e85a", + "scope": "s", + "at": 0, + "route": "queue", + "body": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "overflow", + "waits": 0, + "dropped": 2, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent retention trims held and fresh immediately while wait", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + }, + "waitHorizonMs": 20, + "retryBackoffMs": [ + 30 + ] + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + }, + { + "id": "x", + "name": "said", + "text": "said x" + }, + { + "id": "y", + "name": "out", + "text": "out y" + } + ] + }, + { + "advance": 15 + }, + { + "submit": "s", + "events": [ + { + "id": "z", + "name": "said", + "text": "said z" + } + ], + "truncated": true + }, + { + "inspect": "s" + }, + { + "advance": 25 + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 1, + "gap": true, + "settledAt": 30 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 30 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "521b6c7f38956602", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 1, + "gap": true, + "settledAt": 30 + }, + "at": 30 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "reason": "stream_quiet", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "attempt": 1, + "offerWait": true + }, + { + "kind": "waiting", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "waits": 1, + "until": 30 + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + } + ], + "why": "overflow" + }, + { + "kind": "gap", + "scope": "s", + "source": null, + "cursor": null + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "521b6c7f38956602", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "521b6c7f38956602", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "521b6c7f38956602", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "521b6c7f38956602", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "521b6c7f38956602" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [ + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": true, + "forcedAt": null + }, + "batch": { + "window": { + "id": "f9dfa2a2df12a3bb", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 1, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 30, + "failures": 0 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 30 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "521b6c7f38956602", + "route": "queue", + "at": 30 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "521b6c7f38956602", + "route": "queue", + "at": 30 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "521b6c7f38956602", + "scope": "s", + "at": 30, + "route": "queue", + "body": { + "id": "521b6c7f38956602", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 1, + "gap": true, + "settledAt": 30 + }, + "at": 30 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent retention trims held and fresh immediately while retry", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + }, + "waitHorizonMs": 20, + "retryBackoffMs": [ + 30 + ] + }, + "judge": { + "*": { + "answers": [ + { + "fail": "outage" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + }, + { + "id": "x", + "name": "said", + "text": "said x" + }, + { + "id": "y", + "name": "out", + "text": "out y" + } + ] + }, + { + "advance": 15 + }, + { + "submit": "s", + "events": [ + { + "id": "z", + "name": "said", + "text": "said z" + } + ], + "truncated": true + }, + { + "inspect": "s" + }, + { + "advance": 25 + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 1, + "gap": true, + "settledAt": 40 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 40 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "521b6c7f38956602", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 1, + "gap": true, + "settledAt": 40 + }, + "at": 40 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "reason": "stream_quiet", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "attempt": 1, + "offerWait": true + }, + { + "kind": "retrying", + "scope": "s", + "stage": "judge", + "id": "03dac378c3e6f75e", + "attempt": 1, + "at": 40, + "message": "outage" + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + } + ], + "why": "overflow" + }, + { + "kind": "gap", + "scope": "s", + "source": null, + "cursor": null + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "521b6c7f38956602", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "521b6c7f38956602", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "521b6c7f38956602", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "521b6c7f38956602", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "521b6c7f38956602" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [ + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": true, + "forcedAt": null + }, + "batch": { + "window": { + "id": "f9dfa2a2df12a3bb", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 1, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 40, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 40 + } + }, + { + "step": 5, + "scope": "s", + "record": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "521b6c7f38956602", + "route": "queue", + "at": 40 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "521b6c7f38956602", + "route": "queue", + "at": 40 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "521b6c7f38956602", + "scope": "s", + "at": 40, + "route": "queue", + "body": { + "id": "521b6c7f38956602", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "521b6c7f38956602", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + }, + { + "id": "z", + "at": 0, + "name": "said", + "data": {}, + "text": "said z", + "kind": "context", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 1, + "gap": true, + "settledAt": 40 + }, + "at": 40 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent retention combines direct input when a live offer enters wait", + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + }, + "waitHorizonMs": 20, + "retryBackoffMs": [ + 30 + ] + }, + "judge": { + "*": { + "answers": [ + { + "hold": "call" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + }, + { + "id": "x", + "name": "said", + "text": "said x" + }, + { + "id": "y", + "name": "out", + "text": "out y" + } + ] + }, + { + "advance": 10 + }, + { + "push": "s", + "events": [ + { + "id": "z", + "name": "out", + "text": "out z" + }, + { + "id": "w", + "name": "said", + "text": "said w" + }, + { + "id": "v", + "name": "out", + "text": "out v" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 5 + }, + { + "release": "call", + "answer": { + "route": "wait" + } + }, + { + "inspect": "s" + }, + { + "advance": 30 + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 3, + "gap": false, + "settledAt": 35 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 35 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3cfef46fc6912a3c", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 3, + "gap": false, + "settledAt": 35 + }, + "at": 35 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "reason": "stream_quiet", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "attempt": 1, + "offerWait": true + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "z", + "at": 0, + "name": "out", + "data": {}, + "text": "out z", + "kind": "consequence", + "seenAt": 10 + } + ], + "why": "overflow" + }, + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "waiting", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "waits": 1, + "until": 35 + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "why": "overflow" + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3cfef46fc6912a3c", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3cfef46fc6912a3c" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [ + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "judging", + "attempt": 1, + "failures": 0, + "leaseUntil": 30010, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 30010 + } + }, + { + "step": 6, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [ + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 2, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 35, + "failures": 0 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 35 + } + }, + { + "step": 8, + "scope": "s", + "record": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3cfef46fc6912a3c", + "route": "queue", + "at": 35 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3cfef46fc6912a3c", + "route": "queue", + "at": 35 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3cfef46fc6912a3c", + "scope": "s", + "at": 35, + "route": "queue", + "body": { + "id": "3cfef46fc6912a3c", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 3, + "gap": false, + "settledAt": 35 + }, + "at": 35 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent retention combines direct input when a live offer enters retry", + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + }, + "waitHorizonMs": 20, + "retryBackoffMs": [ + 30 + ] + }, + "judge": { + "*": { + "answers": [ + { + "hold": "call" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + }, + { + "id": "x", + "name": "said", + "text": "said x" + }, + { + "id": "y", + "name": "out", + "text": "out y" + } + ] + }, + { + "advance": 10 + }, + { + "push": "s", + "events": [ + { + "id": "z", + "name": "out", + "text": "out z" + }, + { + "id": "w", + "name": "said", + "text": "said w" + }, + { + "id": "v", + "name": "out", + "text": "out v" + } + ] + }, + { + "inspect": "s" + }, + { + "advance": 5 + }, + { + "release": "call", + "fail": "outage" + }, + { + "inspect": "s" + }, + { + "advance": 30 + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 3, + "gap": false, + "settledAt": 45 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 45 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3cfef46fc6912a3c", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 3, + "gap": false, + "settledAt": 45 + }, + "at": 45 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "reason": "stream_quiet", + "count": 3, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "03dac378c3e6f75e", + "attempt": 1, + "offerWait": true + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "z", + "at": 0, + "name": "out", + "data": {}, + "text": "out z", + "kind": "consequence", + "seenAt": 10 + } + ], + "why": "overflow" + }, + { + "kind": "ingested", + "scope": "s", + "count": 3, + "duplicates": 0 + }, + { + "kind": "retrying", + "scope": "s", + "stage": "judge", + "id": "03dac378c3e6f75e", + "attempt": 1, + "at": 45, + "message": "outage" + }, + { + "kind": "dropped", + "scope": "s", + "entries": [ + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "why": "overflow" + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3cfef46fc6912a3c", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3cfef46fc6912a3c", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3cfef46fc6912a3c" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [ + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "03dac378c3e6f75e", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "x", + "at": 0, + "name": "said", + "data": {}, + "text": "said x", + "kind": "context", + "seenAt": 0 + }, + { + "id": "y", + "at": 0, + "name": "out", + "data": {}, + "text": "out y", + "kind": "consequence", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "judging", + "attempt": 1, + "failures": 0, + "leaseUntil": 30010, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 30010 + } + }, + { + "step": 6, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [ + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "dropped": 1, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 2, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 45, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 45 + } + }, + { + "step": 8, + "scope": "s", + "record": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3cfef46fc6912a3c", + "route": "queue", + "at": 45 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "x", + "y", + "z", + "w", + "v" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3cfef46fc6912a3c", + "route": "queue", + "at": 45 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3cfef46fc6912a3c", + "scope": "s", + "at": 45, + "route": "queue", + "body": { + "id": "3cfef46fc6912a3c", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3cfef46fc6912a3c", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "w", + "at": 0, + "name": "said", + "data": {}, + "text": "said w", + "kind": "context", + "seenAt": 10 + }, + { + "id": "v", + "at": 0, + "name": "out", + "data": {}, + "text": "out v", + "kind": "consequence", + "seenAt": 10 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 3, + "gap": false, + "settledAt": 45 + }, + "at": 45 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent counted crossing preserves retry not-before and forced retries", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 3, + "background": 2 + }, + "retryBackoffMs": [ + 30, + 60 + ] + }, + "judge": { + "*": { + "answers": [ + { + "fail": "outage" + }, + { + "fail": "outage" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + } + ] + }, + { + "advance": 15 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "quietForMs": 100 + }, + { + "id": "c", + "name": "drag", + "text": "drag c", + "quietForMs": 100 + } + ] + }, + { + "advance": 24 + }, + { + "inspect": "s" + }, + { + "advance": 1 + }, + { + "inspect": "s" + }, + { + "advance": 60 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 40 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 40 + }, + { + "scope": "s", + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 40 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 40 + }, + "at": 100 + }, + "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": 40, + "message": "outage" + }, + { + "kind": "ingested", + "scope": "s", + "count": 2, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "1a353cc02182e85a", + "reason": "stream_quiet", + "count": 3, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "1a353cc02182e85a", + "attempt": 2, + "offerWait": false + }, + { + "kind": "retrying", + "scope": "s", + "stage": "judge", + "id": "1a353cc02182e85a", + "attempt": 2, + "at": 100, + "message": "outage" + }, + { + "kind": "judging", + "scope": "s", + "batchId": "1a353cc02182e85a", + "attempt": 3, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "1a353cc02182e85a", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "1a353cc02182e85a", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "1a353cc02182e85a" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 4, + "scope": "s", + "record": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [ + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "phase": { + "phase": "retrying", + "attempt": 1, + "failures": 1, + "at": 40, + "offerWait": true + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 40 + } + }, + { + "step": 6, + "scope": "s", + "record": { + "version": 6, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 40 + }, + "phase": { + "phase": "retrying", + "attempt": 2, + "failures": 2, + "at": 100, + "offerWait": false + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 100 + } + } + ], + "records": { + "s": { + "version": 9, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "1a353cc02182e85a", + "route": "queue", + "at": 100 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "1a353cc02182e85a", + "scope": "s", + "at": 100, + "route": "queue", + "body": { + "id": "1a353cc02182e85a", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "1a353cc02182e85a", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + }, + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 15 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 40 + }, + "at": 100 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "independent counted equality withholds wait even when quiet fires first", + "start": 0, + "intakes": [ + "s" + ], + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "continuation": "accumulate", + "eventLimits": { + "counted": 2, + "background": 1 + }, + "waitHorizonMs": 20 + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 10 + } + ] + }, + { + "advance": 20 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 0, + "quietForMs": 10 + } + ] + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 10 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 10 + }, + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 0, + "quietForMs": 10, + "kind": "continuous", + "seenAt": 20 + } + ], + "reason": "overflow", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 20 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 20 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 0, + "quietForMs": 10, + "kind": "continuous", + "seenAt": 20 + } + ], + "reason": "overflow", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 20 + }, + "at": 20 + }, + "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": 30 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "overflow", + "count": 2, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 2, + "offerWait": false + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 2, + "error": null + } + ], + "inspections": [ + { + "step": 3, + "scope": "s", + "record": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 20 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 7, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 20 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 20, + "route": "queue", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 10, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 0, + "quietForMs": 10, + "kind": "continuous", + "seenAt": 20 + } + ], + "reason": "overflow", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 20 + }, + "at": 20 + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "accumulating retry attributes empty gap metadata to held input", diff --git a/docs/reference.md b/docs/reference.md index 66bc30a..597cd47 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -159,6 +159,33 @@ Wait count, provider failures and the native attempt token are separate. Release Continuation is saved with the snapshot. A live writer cannot change between modes while a held batch or fresh entries remain. Empty scopes can change mode while retaining recent decisions and outbox work. In particular, an old separate waiting snapshot has no historic failure count to recover; switching it to accumulate is refused. `inspect` reads using the saved policy. See [storage](storage.md) for version coordination. +## Independent event limits + +Accumulating continuation can separate the counted settlement threshold from background retention: + +```ts +import { createAttend } from '@acquiredintelligence/attend'; + +const attend = createAttend({ + kind: { reading: 'continuous', state: 'context' }, + judge: async () => ({ route: 'queue' }), + sink: 'log', + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 } }, +}); +``` + +Python uses `event_limits` for the outer key; both members keep the same names. Both are required safe integers: `counted` is positive and `background` is nonnegative. Zero background capacity retains none. The option requires explicit `accumulate` and rejects an explicit `maxEvents` (`max_events` in Python). Omission preserves the scalar limit in both continuation modes. + +`closing`, `continuous`, `passive` and `flush` count toward the threshold. `context` and `consequence` share the background capacity. Deduplication runs first. Excess background leaves oldest-admitted first, regardless of observation timestamps; surviving entries keep their order and identity. Counted entries never leave to meet a capacity. Background alone never triggers settlement. + +Reaching the counted threshold makes an initial or waiting candidate due and withholds wait, even if quiet supplied the reason. It cannot advance retry before its not-before deadline. Existing age, byte and wait limits remain in force. A forced no-wait state and the failure allowance survive later retries. + +Retention covers the whole unresolved held-plus-fresh state during waiting and retry. A live offer stays immutable while fresh input is bounded separately. If it transitions to wait, retry, release or defer, the combined state is bounded before that transition commits. Drop/gap metadata and known identities follow the retained entries, and changed held membership gets its new window ID before the next attempt. Completed decisions and outbox records do not change. + +One accepted source batch is still one admission. It can exceed the counted trigger and produce one larger window; it is not split and no counted excess is discarded. Raw-intake capacity counts unfinished operations, not events in an accepted batch. Neither limit is a hard memory-allocation bound. + +The pair persists with the snapshot at reducer revision 5. Tails and inspection use the saved policy. Adding, removing or changing the pair is refused before writes or effects while open entries or an unresolved batch remain. Empty scopes may adopt it while retaining recent decisions and outbox work. Old records without the pair keep scalar behavior. Coordinate writer versions: this is not a fence against older code that lacks the check. + ## Guarantees - **One snapshot and a short tail per scope.** The snapshot holds the open window, the judge slot and the outbox. A write appends the inputs that changed state, and a snapshot replaces the tail once it grows past the snapshot's own size. A source's cursor commits in the same write as the events it covers. @@ -181,6 +208,7 @@ These are round starting points, not tuned values. Override any of them with `se | `waitHorizonMs` | 10000 | How long a waiting window waits for the next window before attend judges it alone | | `maxWaits` | 2 | How many times one window may wait | | `maxEvents` | 250 | Events one window holds. Past it, attend drops consequence and context events, then settles. | +| `eventLimits` | omitted | In explicit accumulating mode, an inclusive counted trigger and independent background capacity; replaces the scalar limit. | | `maxWindowMs` | 60000 | Age of the first act at which the window settles | | `windowShare` (a `createAttend` option) | 0.5 | Share of the judge's context budget a window may fill before it settles with reason `size` | | `actThreshold` (a `createAttend` option) | off | Act when p(interrupt) + p(ask) reaches it | diff --git a/docs/storage.md b/docs/storage.md index 9e0743e..d7fc229 100644 --- a/docs/storage.md +++ b/docs/storage.md @@ -40,4 +40,6 @@ Keep processes sharing a store on the same reducer version before using [observa [Accumulating continuation](reference.md#accumulating-continuation) uses reducer revision 4 and retains failures in waiting state. Choose the same mode in every writer of a scope. A writer refuses a mode change while the replayed scope has a held batch or fresh entries; finish them under the saved mode first, or use a new scope. Recent decisions and outbox work can remain. Old separate waiting snapshots lack historic failure counts and stay on their old semantics. Read-only inspection uses the saved policy. This check does not fence older writers that lack it. +[Independent event limits](reference.md#independent-event-limits) uses revision 5. The optional pair persists with the policy, and tails replay under that saved policy before a writer can adopt its configuration. A writer refuses adding, removing or changing the pair while open entries or an unresolved held batch remain, including background-only and released state. Empty scopes may adopt it without changing completed recent/outbox entries. Records without the pair keep scalar limits. Writers must use compatible revisions; this check cannot fence an older writer that lacks it. + Each adapter also has an `EventLog`: `memoryLog`, `sqliteLog`, `postgresLog` and `redisLog`. When producers live in other processes and you want a durable shared log in front of attend, append to the log and attach `logSource(log, scope)` instead of calling `push`. diff --git a/python/README.md b/python/README.md index 5bca50f..bdb17de 100644 --- a/python/README.md +++ b/python/README.md @@ -81,6 +81,7 @@ redis-py runs each concurrent command on a pooled connection of its own, and its - 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. - `settle={"continuation": "accumulate"}` retains one unresolved window through waits and retries. [Accumulating continuation](../docs/reference.md#accumulating-continuation) defines its bounds, failure allowance and stored-mode boundary. +- Add `"event_limits": {"counted": 3, "background": 2}` to that setting for an independent counted trigger and background capacity. Both numbers are required; do not also supply `max_events`. [Independent event limits](../docs/reference.md#independent-event-limits) defines retention, atomic input and saved-policy rules. - A continuous event can carry `quietForMs` in its wire dictionary. [Continuous quiet duration](../docs/reference.md#continuous-quiet-duration) defines its validation, defaults and recovery. - 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. diff --git a/python/src/aqi_attend/__init__.py b/python/src/aqi_attend/__init__.py index cadaf4c..7163e7d 100644 --- a/python/src/aqi_attend/__init__.py +++ b/python/src/aqi_attend/__init__.py @@ -16,6 +16,7 @@ DeliveredRoute, Entry, Event, + EventLimits, JudgeBudget, JudgeImage, JudgeInput, @@ -55,6 +56,7 @@ "Entry", "Event", "EventFold", + "EventLimits", "EventLog", "Intake", "IntakeError", diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index e0737a9..caa6cfe 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -27,6 +27,7 @@ DeliveryReleasedInput, Effect, Event, + EventLimits, EventsInput, Input, InputKind, @@ -104,6 +105,7 @@ def subscribe(self, cursor: str | None, emit: Callable[[SourceBatch], Awaitable[ _SETTLE_KEYS: dict[str, str] = { + "event_limits": "eventLimits", "continuation": "continuation", "closing_grace_ms": "closingGraceMs", "stream_gap_ms": "streamGapMs", @@ -124,8 +126,23 @@ def subscribe(self, cursor: str | None, emit: Callable[[SourceBatch], Awaitable[ } +def _event_limits(value: object) -> EventLimits: + message = "attend: eventLimits requires positive counted and nonnegative background safe integers" + if not isinstance(value, Mapping): + raise ValueError(message) + fields = cast(Mapping[object, object], value) + if set(fields) != {"counted", "background"}: + raise ValueError(message) + counted, background = fields["counted"], fields["background"] + if type(counted) is not int or type(background) is not int or not 0 < counted <= 9007199254740991 or not 0 <= background <= 9007199254740991: + raise ValueError(message) + return {"counted": counted, "background": background} + + def settle_policy(settle: Mapping[str, Any] | None = None) -> SettlePolicy: """The defaults with ``settle`` (snake_case names, as ``create_attend`` takes them) applied.""" + if settle is not None and "event_limits" in settle and (settle.get("continuation") != "accumulate" or "max_events" in settle): + raise ValueError("attend: eventLimits requires accumulate and replaces maxEvents") policy = cast(dict[str, Any], dict(DEFAULT_POLICY)) policy["retryBackoffMs"] = list(DEFAULT_POLICY["retryBackoffMs"]) for name, value in (settle or {}).items(): @@ -134,7 +151,7 @@ def settle_policy(settle: Mapping[str, Any] | None = None) -> SettlePolicy: raise TypeError(f"attend: unknown settle option {name!r}") if name == "continuation" and (not isinstance(value, str) or value not in ("separate", "accumulate")): raise ValueError("attend: continuation must be separate or accumulate") - policy[key] = list(value) if name == "retry_backoff_ms" else value + policy[key] = list(value) if name == "retry_backoff_ms" else _event_limits(value) if name == "event_limits" else value return cast(SettlePolicy, policy) diff --git a/python/src/aqi_attend/core/reducer.py b/python/src/aqi_attend/core/reducer.py index a22b035..74cadf7 100644 --- a/python/src/aqi_attend/core/reducer.py +++ b/python/src/aqi_attend/core/reducer.py @@ -37,6 +37,7 @@ ) from .window import ( estimate_rendered_bytes, + is_background, observation_time, open_window, shed_entries, @@ -46,7 +47,7 @@ window_shed, ) -REDUCER_VERSION = 4 +REDUCER_VERSION = 5 """Bumped whenever a release changes a transition. Stored with every snapshot.""" _LANES: tuple[OutboxLane, OutboxLane] = ("decisions", "deadLetters") @@ -188,6 +189,8 @@ def apply(config: ApplyConfig, state: ScopeState, logged: LoggedInput, out: Appl raise ValueError(f"attend: unknown input kind {kind!r}") if swept: _sweep(ctx, state) + if config.policy.get("eventLimits") is not None and kind != "events": + _removed(ctx, state, _retain_background(config.policy, state), "overflow") due = next_due(config.policy, state) if not same(state.due_at, due): state.due_at = due @@ -223,7 +226,7 @@ def _ingest(ctx: _Ctx, state: ScopeState, input: EventsInput) -> None: ctx.out.changed = True seen_trim(state, policy["seenCount"]) _prune(ctx, state) - _removed(ctx, state, window_shed(state.open, policy["maxEvents"]), "overflow") + _removed(ctx, state, _retain_background(policy, state), "overflow") if not state.open.entries: state.open.ended_at = None source = input.get("source") @@ -240,16 +243,53 @@ def _ingest(ctx: _Ctx, state: ScopeState, input: EventsInput) -> None: ctx.trace({"kind": "ingested", "scope": state.scope, "count": len(input["events"]) - duplicates, "duplicates": duplicates}) +def _retain_background(policy: SettlePolicy, state: ScopeState) -> list[Entry] | None: + limits = policy.get("eventLimits") + open = state.open + if limits is None: + return window_shed(open, policy["maxEvents"]) + held = state.batch + if held is None or held.phase["phase"] == "judging": + return window_shed(open, len(open.entries) - max(0, open.summary.sheddable - limits["background"])) + background = sum(is_background(entry["kind"]) for entry in held.window["events"]) + excess = background + open.summary.sheddable - limits["background"] + if excess <= 0: + return None + retained = list(held.window["events"]) + old = shed_entries(retained, max(0, len(retained) - excess)) + if old is not None: + hash = fnv_start(state.scope) + for entry in retained: + fold_id(hash, entry["id"]) + held.window = {**held.window, "events": retained, "id": fnv_hex(hash), "dropped": held.window["dropped"] + len(old)} + held.hash = hash + remaining = excess - (len(old) if old is not None else 0) + fresh = window_shed(open, len(open.entries) - remaining) if remaining > 0 else None + if not open.entries: + open.ended_at = None + return [*(old or []), *(fresh or [])] + + +def _shed_candidate(policy: SettlePolicy, entries: list[Entry]) -> list[Entry] | None: + limits = policy.get("eventLimits") + if limits is None: + return shed_entries(entries, policy["maxEvents"]) + background = sum(is_background(entry["kind"]) for entry in entries) + return shed_entries(entries, len(entries) - max(0, background - limits["background"])) + + def _continuation_entries(policy: SettlePolicy, state: ScopeState) -> list[Entry]: entries = [*(state.batch.window["events"] if state.batch is not None else []), *state.open.entries] - shed_entries(entries, policy["maxEvents"]) + _shed_candidate(policy, entries) return entries def _size_bound(policy: SettlePolicy, entries: list[Entry]) -> SettleReason | None: if not entries: return None - if len(entries) > policy["maxEvents"]: + limits = policy.get("eventLimits") + full = sum(not is_background(entry["kind"]) for entry in entries) >= limits["counted"] if limits is not None else len(entries) > policy["maxEvents"] + if full: return "overflow" limit = policy.get("maxWindowBytes") if limit is not None and sum(estimate_rendered_bytes(entry) for entry in entries) >= limit: @@ -379,7 +419,7 @@ def _settle_buffer(ctx: _Ctx, state: ScopeState, fired: SettleReason, may_wait: gap = open.gap or (held.window["gap"] if held is not None else False) waits = held.window["waits"] if held is not None else 0 forced = forced or (held is not None and held.window["reason"] == "forced") - gone = shed_entries(events, ctx.config.policy["maxEvents"]) + gone = _shed_candidate(ctx.config.policy, events) _removed(ctx, state, gone, "overflow") dropped += len(gone) if gone is not None else 0 if held is None and gone is None and open.hash_valid: diff --git a/python/src/aqi_attend/core/types.py b/python/src/aqi_attend/core/types.py index 00aa8de..8fc0ba6 100644 --- a/python/src/aqi_attend/core/types.py +++ b/python/src/aqi_attend/core/types.py @@ -47,10 +47,18 @@ class Entry(KindedEvent): seenAt: float +class EventLimits(TypedDict): + """Independent settlement and FIFO retention limits, selected together.""" + + counted: int + background: int + + class SettlePolicy(TypedDict): """Round starting points, not tuned values. Every number is in ms unless it is a count.""" continuation: NotRequired[Literal["separate", "accumulate"]] + eventLimits: NotRequired[EventLimits] closingGraceMs: float streamGapMs: float passiveQuietMs: float diff --git a/python/src/aqi_attend/core/window.py b/python/src/aqi_attend/core/window.py index f3fffe7..4f40498 100644 --- a/python/src/aqi_attend/core/window.py +++ b/python/src/aqi_attend/core/window.py @@ -14,7 +14,7 @@ def is_act(kind: Kind) -> bool: return kind == "closing" or kind == "continuous" or kind == "passive" -def _sheddable(kind: Kind) -> bool: +def is_background(kind: Kind) -> bool: return kind == "consequence" or kind == "context" @@ -55,7 +55,7 @@ def _summarize_entry(summary: TriggerSummary, entry: Entry, index: int) -> None: summary.act_observed |= explicit if summary.act_observed: summary.first_act_at = summary.min_act_at - if _sheddable(kind): + if is_background(kind): summary.sheddable += 1 if summary.first_act_index == -1: summary.prefix_min_sheddable_at = _min(summary.prefix_min_sheddable_at, observed_at) @@ -136,7 +136,7 @@ def _prefix_minimum(open: OpenWindow) -> float: least = math.inf for i in range(end): entry = entries[i] - if _sheddable(entry["kind"]): + if is_background(entry["kind"]): if open.monotone: return observation_time(entry) least = _min(least, observation_time(entry)) @@ -174,7 +174,7 @@ def window_prune(open: OpenWindow, max_window_ms: float, now: float) -> list[Ent stale = observation_time(entry) + max_window_ms <= now if not stale and open.monotone: break - if stale and _sheddable(entry["kind"]): + if stale and is_background(entry["kind"]): if gone is None: gone = [entry] else: @@ -210,7 +210,7 @@ def _shed(entries: list[Entry], max_events: int, open: OpenWindow | None) -> lis read = 0 while read < length and (gone is None or len(gone) < excess): entry = entries[read] - if _sheddable(entry["kind"]): + if is_background(entry["kind"]): if gone is None: gone = [entry] else: @@ -261,7 +261,9 @@ def window_deadline(policy: SettlePolicy, open: OpenWindow) -> tuple[float, Sett if open.ended_at is not None and (reason is None or open.ended_at < at): at = open.ended_at reason = "closing" - if size > 0 and size > policy["maxEvents"] and (reason is None or s.last_seen_at < at): + limits = policy.get("eventLimits") + full = size - s.sheddable >= limits["counted"] if limits is not None else size > policy["maxEvents"] + if size > 0 and full and (reason is None or s.last_seen_at < at): at = s.last_seen_at reason = "overflow" if s.min_flush_at != math.inf and (reason is None or s.min_flush_at < at): diff --git a/python/src/aqi_attend/shell/scope.py b/python/src/aqi_attend/shell/scope.py index 7a42f88..b81cc44 100644 --- a/python/src/aqi_attend/shell/scope.py +++ b/python/src/aqi_attend/shell/scope.py @@ -193,6 +193,9 @@ async def _load_now(self, slot: ScopeSlot) -> None: prior_mode = snapshot["policy"].get("continuation", "separate") if snapshot is not None else "separate" if stored is not None and prior_mode != config.policy.get("continuation", "separate") and (slot.state.batch is not None or slot.state.open.entries): raise ValueError("attend: cannot change continuation while a window is unresolved") + prior_limits = snapshot["policy"].get("eventLimits") if snapshot is not None else None + if stored is not None and prior_limits != config.policy.get("eventLimits") and (slot.state.batch is not None or slot.state.open.entries): + raise ValueError("attend: cannot change event limits while a window is unresolved") slot.tail_count = len(stored["tail"]) if stored is not None else 0 slot.tail_bytes = sum(self._input_bytes(logged) for logged in stored["tail"]) if stored is not None else 0 slot.snapshot_bytes = self._bytes(snapshot["record"]) if snapshot is not None else 0 diff --git a/python/tests/interop/event-limits-ts.mjs b/python/tests/interop/event-limits-ts.mjs new file mode 100644 index 0000000..93f146b --- /dev/null +++ b/python/tests/interop/event-limits-ts.mjs @@ -0,0 +1,52 @@ +import assert from 'node:assert/strict'; +import { createAttend } from '../../../dist/index.js'; +import { openIntake } from '../../../dist/intake.js'; +import { fakeClock } from '../../../dist/testing.js'; +import { openStore } from './store.mjs'; + +const [kind, url, prefix, mode, scope, phase] = process.argv.slice(2); +const owned = await openStore(kind, url, prefix); +const clock = fakeClock(mode === 'write' ? 10000 : 10015); +const done = new AbortController(); +const finished = new Promise((resolve) => done.signal.addEventListener('abort', resolve, { once: true })); +const calls = []; +const event = (id, name = 'reading') => ({ id, name, at: clock.now(), data: {}, text: 'q'.repeat(128) }); +const engine = createAttend({ store: owned.store, clock, kind: { reading: 'continuous', meta: 'context', result: 'consequence' }, sink: 'log', + settle: { continuation: 'accumulate', eventLimits: { counted: mode === 'refuse' ? 4 : 3, background: 2 }, streamGapMs: 10, waitHorizonMs: 20, retryBackoffMs: [30] }, + judge: async (input) => { + calls.push({ at: clock.now(), ids: input.window.events.map((e) => e.id), wait: input.routes.some((r) => r.route === 'wait'), dropped: input.window.dropped, gap: input.window.gap }); + if (mode === 'write' && phase === 'retrying') throw new Error('controlled'); + return { route: mode === 'write' ? 'wait' : 'queue' }; + }, + observe(trace) { + if ((mode === 'write' && (trace.kind === 'waiting' || trace.kind === 'retrying')) || (mode === 'continue' && trace.kind === 'judged')) done.abort(); + }, +}); +try { + if (mode === 'read') { + console.log(JSON.stringify({ record: await engine.inspect(scope) })); + } else if (mode === 'refuse') { + const before = await owned.store.load(scope); + await assert.rejects(engine.push(scope, event('refused', 'meta')), /unresolved/); + assert.deepEqual(await owned.store.load(scope), before); + console.log(JSON.stringify({ rejected: true, unchanged: true })); + } else { + const intake = openIntake(engine, scope), running = engine.run(); + try { + if (mode === 'write') { + await intake.submit(async () => ({ events: [event('a'), event('x', 'meta'), event('y', 'result')], cursor: '1' }), { source: 'feed' }); + await clock.advance(10); await finished; + await clock.advance(5); + await intake.submit(async () => ({ events: [event('z', 'meta')], cursor: '2', truncated: true }), { source: 'feed' }); + } else { + await intake.submit(async () => ({ events: [event('b'), event('c')], cursor: '3' }), { source: 'feed' }); + if (phase === 'retrying') { + await clock.advance(24); assert.equal(calls.length, 0); + await clock.advance(1); + } + await finished; + } + } finally { await intake.close(); await engine.stop(); await running; } + console.log(JSON.stringify({ record: await engine.inspect(scope), calls })); + } +} finally { await owned.close(); } diff --git a/python/tests/scenario.py b/python/tests/scenario.py index bfa22a0..90a2920 100644 --- a/python/tests/scenario.py +++ b/python/tests/scenario.py @@ -31,6 +31,7 @@ def event_spec(spec: Mapping[str, Any]) -> Event: _SETTLE = { + "eventLimits": "event_limits", "continuation": "continuation", "closingGraceMs": "closing_grace_ms", "streamGapMs": "stream_gap_ms", diff --git a/python/tests/test_continuation.py b/python/tests/test_continuation.py index db90148..8d0e28d 100644 --- a/python/tests/test_continuation.py +++ b/python/tests/test_continuation.py @@ -226,7 +226,7 @@ async def test_revision_three_read_and_mode_boundary(item: dict[str, Any]) -> No stored = await store.load("scope") assert stored is not None and stored["snapshot"] is not None assert stored["snapshot"]["policy"].get("continuation") == "accumulate" - assert stored["snapshot"]["reducer"] == 4 + assert stored["snapshot"]["reducer"] == 5 record = await engine.inspect("scope") assert record is not None and record["recent"] == item["expected"]["recent"] else: diff --git a/python/tests/test_continuous_quiet.py b/python/tests/test_continuous_quiet.py index a06e135..3454b3b 100644 --- a/python/tests/test_continuous_quiet.py +++ b/python/tests/test_continuous_quiet.py @@ -254,7 +254,7 @@ async def test_revision_two_snapshot_and_mixed_tail_rebuild_end_times() -> None: assert loaded is not None and loaded["dueAt"] == 200 assert [(event["id"], event.get("quietForMs"), event["seenAt"]) for event in loaded["buffer"]["entries"]] == [("a", None, 100), ("b", 90, 120), ("c", None, 120)] stored = await store.load("s") - assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 4 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 5 finally: await attend.stop() await store.close() diff --git a/python/tests/test_event_limits.py b/python/tests/test_event_limits.py new file mode 100644 index 0000000..b9169d3 --- /dev/null +++ b/python/tests/test_event_limits.py @@ -0,0 +1,312 @@ +"""Independent counted triggers and background retention through the native API.""" + +import asyncio +import json +from collections.abc import AsyncGenerator, Awaitable, Callable +from contextlib import asynccontextmanager +from pathlib import Path +from typing import Any, Literal, TypedDict + +import pytest + +from aqi_attend import AbortSignal, Attend, Event, JudgeInput, Judgment, SourceBatch, Window, create_attend, memory_store +from aqi_attend._json import clone +from aqi_attend.core.reducer import apply +from aqi_attend.core.state import assert_invariants, initial_state, to_record +from aqi_attend.core.types import ApplyConfig, ApplyOutput, Input, default_policy +from aqi_attend.testing import FakeClock, fake_clock + +type Answer = Literal["wait", "queue", "fail"] + + +class Offer(TypedDict): + at: float + window: Window + wait: bool + + +def event(id: str, at: float = 0, name: str = "reading") -> Event: + value: Event = {"id": id, "at": at, "observedAt": at, "name": name, "data": {}} + if name == "reading": + value["quietForMs"] = 10 + return value + + +async def skip(input: JudgeInput, signal: AbortSignal) -> Judgment: + return {"route": "skip"} + + +@asynccontextmanager +async def run( + answers: list[Answer], options: dict[str, Any] | None = None +) -> AsyncGenerator[tuple[FakeClock, Callable[[list[Event]], Awaitable[None]], list[Offer], Attend], None]: + clock = fake_clock() + offers: list[Offer] = [] + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + offers.append({"at": clock.now(), "window": input["window"], "wait": any(r["route"] == "wait" for r in input["routes"])}) + answer = answers[len(offers) - 1] if len(offers) <= len(answers) else "queue" + if answer == "fail": + raise RuntimeError("controlled failure") + return {"route": answer} + + attend = create_attend( + clock=clock, + kind={"reading": "continuous", "meta": "context", "result": "consequence"}, + judge=judge, + sink="log", + settle={"continuation": "accumulate", "event_limits": {"counted": 3, "background": 2}, "wait_horizon_ms": 20, "retry_backoff_ms": [30], **(options or {})}, + ) + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + + async def put(events: list[Event]) -> None: + async def prepare(signal: AbortSignal) -> SourceBatch: + return {"events": events} + + await intake.submit(prepare) + + try: + yield clock, put, offers, attend + finally: + await intake.close() + await attend.stop() + await running + + +async def test_counted_equality_preserves_independent_background() -> None: + async with run(["queue"]) as (_, put, offers, _attend): + await put([event("x", 0, "meta"), event("y", 0, "result")]) + await put([event("a"), event("b")]) + assert offers == [] + await put([event("c")]) + assert [([e["id"] for e in o["window"]["events"]], o["wait"], o["window"]["dropped"]) for o in offers] == [(["x", "y", "a", "b", "c"], False, 0)] + + +async def test_background_retention_is_fifo_without_settling() -> None: + async with run([]) as (_, put, offers, attend): + await put([event("x", 0, "meta"), event("y", 0, "result"), event("z", 0, "meta")]) + assert offers == [] + state = await attend.inspect("s") + assert state is not None + assert [e["id"] for e in state["buffer"]["entries"]] == ["y", "z"] + assert state["buffer"]["dropped"] == 1 + + +@pytest.mark.parametrize("answer", ["wait", "fail"]) +async def test_retention_spans_held_and_fresh_immediately(answer: Answer) -> None: + async with run([answer, "queue"]) as (clock, put, offers, attend): + await put([event("a"), event("x", 0, "meta"), event("y", 0, "result")]) + await clock.advance(10) + await put([event("z", 10, "meta")]) + state = await attend.inspect("s") + assert state is not None and state["batch"] is not None + assert [e["id"] for e in state["batch"]["window"]["events"]] == ["a", "y"] + assert state["batch"]["window"]["dropped"] == 1 + assert [e["id"] for e in state["buffer"]["entries"]] == ["z"] + await clock.advance(20 if answer == "wait" else 30) + assert [e["id"] for e in offers[1]["window"]["events"]] == ["a", "y", "z"] + assert offers[1]["window"]["dropped"] == 1 + + +async def test_atomic_input_does_not_split_or_lose_counted_events() -> None: + async with run(["queue"]) as (_, put, offers, _attend): + await put([event("a"), event("x", 0, "meta"), event("b"), event("y", 0, "result"), event("c"), event("z", 0, "meta"), event("d")]) + assert len(offers) == 1 + assert [e["id"] for e in offers[0]["window"]["events"]] == ["a", "b", "y", "c", "z", "d"] + assert offers[0]["wait"] is False + assert offers[0]["window"]["dropped"] == 1 + + +async def test_zero_background_retains_counted_events() -> None: + async with run(["queue"], {"event_limits": {"counted": 1, "background": 0}}) as (_, put, offers, _attend): + await put([event("x", 0, "meta"), event("a"), event("y", 0, "result")]) + assert [e["id"] for e in offers[0]["window"]["events"]] == ["a"] + assert offers[0]["window"]["dropped"] == 2 + + +@pytest.mark.parametrize("continuation", [None, "separate"]) +def test_independent_limits_require_explicit_accumulate(continuation: str | None) -> None: + with pytest.raises((TypeError, ValueError)): + create_attend(kind={}, judge=skip, sink="log", settle={"continuation": continuation, "event_limits": {"counted": 3, "background": 2}}) + + +def test_independent_limits_refuse_explicit_scalar() -> None: + with pytest.raises((TypeError, ValueError)): + create_attend(kind={}, judge=skip, sink="log", settle={"continuation": "accumulate", "event_limits": {"counted": 3, "background": 2}, "max_events": 9}) + + +@pytest.mark.parametrize("limits", [None, {"counted": 4, "background": 2}, {"counted": 3, "background": 1}]) +async def test_unresolved_policy_change_rejects_without_write(limits: dict[str, int] | None) -> None: + store = memory_store() + clock = fake_clock() + first = create_attend( + store=store, clock=clock, kind={"meta": "context"}, judge=skip, sink="log", settle={"continuation": "accumulate", "event_limits": {"counted": 3, "background": 2}} + ) + await first.push("s", event("x", 0, "meta")) + before = await store.load("s") + changed = {} if limits is None else {"event_limits": limits} + second = create_attend(store=store, clock=clock, kind={"meta": "context"}, judge=skip, sink="log", settle={"continuation": "accumulate", **changed}) + with pytest.raises(ValueError, match="unresolved"): + await second.push("s", event("y", 0, "meta")) + assert await store.load("s") == before + + +@pytest.mark.parametrize("kind", ["judged", "judgeFailed", "judgeReleased", "judgeDeferred"]) +def test_direct_writer_transition_retains_state_without_mutating_offer(kind: str) -> None: + policy = default_policy() + policy.update(continuation="accumulate", eventLimits={"counted": 3, "background": 2}, seenCount=0, retryBackoffMs=[30]) + config = ApplyConfig(policy, "log", "log", True) + state = initial_state("s") + + def send(input: Input, now: float) -> ApplyOutput: + out = ApplyOutput() + apply(config, state, {"input": input, "now": now}, out) + assert_invariants(state, policy) + return out + + send({"kind": "events", "events": [{**event("a"), "kind": "continuous"}, {**event("x", 0, "meta"), "kind": "context"}, {**event("y", 0, "result"), "kind": "consequence"}]}, 0) + started = next(e for e in send({"kind": "tick"}, 10).effects if e["kind"] == "judge") + assert started["kind"] == "judge" + original = clone(started["window"]) + send( + { + "kind": "events", + "truncated": True, + "events": [{**event("z", 11, "meta"), "kind": "context"}, {**event("w", 11, "result"), "kind": "consequence"}, {**event("v", 11, "meta"), "kind": "context"}], + }, + 11, + ) + assert started["window"] == original + completion: Input + if kind == "judged": + completion = {"kind": "judged", "batchId": original["id"], "attempt": started["attempt"], "judgment": {"route": "wait"}} + elif kind == "judgeFailed": + completion = {"kind": "judgeFailed", "batchId": original["id"], "attempt": started["attempt"], "message": "controlled", "permanent": False} + elif kind == "judgeDeferred": + completion = {"kind": "judgeDeferred", "batchId": original["id"], "attempt": started["attempt"], "until": 42} + else: + completion = {"kind": "judgeReleased", "batchId": original["id"], "attempt": started["attempt"]} + send(completion, 12) + assert started["window"] == original + record = to_record(state) + assert record["batch"] is not None + assert [e["id"] for e in record["batch"]["window"]["events"]] == ["a"] + assert record["batch"]["window"]["dropped"] == 2 + assert [e["id"] for e in record["buffer"]["entries"]] == ["w", "v"] + assert record["buffer"]["dropped"] == 1 + assert record["buffer"]["gap"] is True + assert state.known == {"a": 1, "w": 1, "v": 1} + assert record["batch"]["window"]["id"] != original["id"] + + +@pytest.mark.parametrize( + "limits", + [ + None, + [], + {}, + {"counted": 0, "background": 1}, + {"counted": True, "background": 1}, + {"counted": 1.5, "background": 1}, + {"counted": 1, "background": -1}, + {"counted": 1, "background": float("inf")}, + {"counted": 2**53, "background": 0}, + {"counted": 1}, + {"counted": 1, "background": 0, "extra": 1}, + ], +) +def test_invalid_limits_are_refused(limits: object) -> None: + with pytest.raises(ValueError): + create_attend(kind={}, judge=skip, sink="log", settle={"continuation": "accumulate", "event_limits": limits}) + + +async def test_supplied_pair_is_copied() -> None: + limits = {"counted": 2, "background": 1} + async with run(["queue"], {"event_limits": limits}) as (_, put, offers, _attend): + limits["counted"] = 9 + await put([event("a"), event("b")]) + assert len(offers) == 1 + assert offers[0]["wait"] is False + + +async def test_deduplication_precedes_counted_equality() -> None: + async with run(["queue"]) as (_, put, offers, _attend): + await put([event("a"), event("a"), event("b")]) + assert offers == [] + await put([event("c")]) + assert [e["id"] for e in offers[0]["window"]["events"]] == ["a", "b", "c"] + + +LEGACY = json.loads((Path(__file__).resolve().parents[2] / "conformance/fixtures/event-limits-legacy.json").read_text()) + + +@pytest.mark.parametrize("item", LEGACY["cases"], ids=[c["name"] for c in LEGACY["cases"]]) +async def test_revision_four_snapshots_and_tails_keep_saved_policy(item: dict[str, Any]) -> None: + store, clock = memory_store(), fake_clock(item["now"]) + for writes in item["writes"]: + assert await store.commit(writes) == ["ok"] * len(writes) + assert await store.load("s") == item["stored"] + assert item["stored"]["snapshot"]["reducer"] == 4 and item["stored"]["tail"] + engine = create_attend( + store=store, clock=clock, kind={"meta": "context"}, judge=skip, sink="log", settle={"continuation": "accumulate", "event_limits": {"counted": 3, "background": 2}} + ) + assert await engine.inspect("s") == item["expected"] + write = engine.push("s", event("next", item["now"], "meta")) + if item["name"] == "complete": + await write + stored = await store.load("s") + assert stored is not None and stored["snapshot"] is not None + assert stored["snapshot"]["reducer"] == 5 + assert stored["snapshot"]["policy"].get("eventLimits") == {"counted": 3, "background": 2} + record = await engine.inspect("s") + assert record is not None and record["recent"] == item["expected"]["recent"] + else: + with pytest.raises(ValueError, match="unresolved"): + await write + assert await store.load("s") == item["stored"] + + +@pytest.mark.parametrize("answer", ["wait", "fail"]) +async def test_same_policy_resumes_persisted_state(answer: Answer) -> None: + clock, store = fake_clock(), memory_store() + settle = {"continuation": "accumulate", "event_limits": {"counted": 3, "background": 2}, "wait_horizon_ms": 20, "retry_backoff_ms": [30]} + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + if answer == "fail": + raise RuntimeError("controlled") + return {"route": answer} + + first = create_attend(store=store, clock=clock, kind={"reading": "continuous", "meta": "context"}, judge=judge, sink="log", settle=settle) + intake = first.open_intake("s") + run = asyncio.create_task(first.run()) + + async def initial(signal: AbortSignal) -> SourceBatch: + return {"events": [event("a"), event("x", 0, "meta"), event("y", 0, "meta")]} + + async def fresh(signal: AbortSignal) -> SourceBatch: + return {"events": [event("z", 15, "meta")]} + + await intake.submit(initial) + await clock.advance(15) + await intake.submit(fresh) + await intake.close() + await first.stop() + await run + before = await first.inspect("s") + seen: list[list[str]] = [] + + async def finish(input: JudgeInput, signal: AbortSignal) -> Judgment: + seen.append([e["id"] for e in input["window"]["events"]]) + return {"route": "queue"} + + second = create_attend(store=store, clock=clock, kind={}, judge=finish, sink="log", settle=settle) + running = asyncio.create_task(second.run()) + try: + await second.push("s", []) + assert await second.inspect("s") == before + await clock.advance(25) + assert seen == [["a", "y", "z"]] + finally: + await second.stop() + await running diff --git a/python/tests/test_event_limits_interop.py b/python/tests/test_event_limits_interop.py new file mode 100644 index 0000000..7257d5b --- /dev/null +++ b/python/tests/test_event_limits_interop.py @@ -0,0 +1,141 @@ +"""Both runtimes continue and fence independent limits on shared stores.""" + +import asyncio +import json +from pathlib import Path +from typing import Any + +import pytest + +from aqi_attend import AbortSignal, Event, JudgeInput, Judgment, SourceBatch, Trace, create_attend +from aqi_attend.testing import fake_clock + +from .stores import POSTGRES_URL, REDIS_URL, make_postgres, make_redis +from .test_interop import BACKENDS, ENABLED + +SCRIPT = Path(__file__).with_name("interop") / "event-limits-ts.mjs" + + +async def typescript(kind: str, prefix: str, mode: str, scope: str, phase: str) -> dict[str, Any]: + url = REDIS_URL if kind == "redis" else POSTGRES_URL + assert url is not None + process = await asyncio.create_subprocess_exec("node", str(SCRIPT), kind, url, prefix, mode, scope, phase, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + try: + out, err = await process.communicate() + assert process.returncode == 0, err.decode() + return json.loads(out) + finally: + if process.returncode is None: + process.terminate() + await process.wait() + + +async def python(store: Any, mode: str, scope: str, phase: str) -> dict[str, Any]: + clock = fake_clock(10000 if mode == "write" else 10015) + done = asyncio.Event() + calls: list[dict[str, Any]] = [] + + def event(id: str, name: str = "reading") -> Event: + return {"id": id, "name": name, "at": clock.now(), "data": {}, "text": "q" * 128} + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + calls.append( + { + "at": clock.now(), + "ids": [e["id"] for e in input["window"]["events"]], + "wait": any(r["route"] == "wait" for r in input["routes"]), + "dropped": input["window"]["dropped"], + "gap": input["window"]["gap"], + } + ) + if mode == "write" and phase == "retrying": + raise RuntimeError("controlled") + return {"route": "wait" if mode == "write" else "queue"} + + def observe(trace: Trace) -> None: + if (mode == "write" and trace["kind"] in ("waiting", "retrying")) or (mode == "continue" and trace["kind"] == "judged"): + done.set() + + engine = create_attend( + store=store, + clock=clock, + kind={"reading": "continuous", "meta": "context", "result": "consequence"}, + judge=judge, + sink="log", + observe=observe, + settle={ + "continuation": "accumulate", + "event_limits": {"counted": 4 if mode == "refuse" else 3, "background": 2}, + "stream_gap_ms": 10, + "wait_horizon_ms": 20, + "retry_backoff_ms": [30], + }, + ) + if mode == "read": + return {"record": await engine.inspect(scope)} + if mode == "refuse": + before = await store.load(scope) + with pytest.raises(ValueError, match="unresolved"): + await engine.push(scope, event("refused", "meta")) + assert await store.load(scope) == before + return {"rejected": True, "unchanged": True} + intake = engine.open_intake(scope) + running = asyncio.create_task(engine.run()) + try: + if mode == "write": + + async def initial(signal: AbortSignal) -> SourceBatch: + return {"events": [event("a"), event("x", "meta"), event("y", "result")], "cursor": "1"} + + await intake.submit(initial, source="feed") + await clock.advance(10) + await done.wait() + await clock.advance(5) + + async def fresh(signal: AbortSignal) -> SourceBatch: + return {"events": [event("z", "meta")], "cursor": "2", "truncated": True} + + await intake.submit(fresh, source="feed") + else: + + async def more(signal: AbortSignal) -> SourceBatch: + return {"events": [event("b"), event("c")], "cursor": "3"} + + await intake.submit(more, source="feed") + if phase == "retrying": + await clock.advance(24) + assert calls == [] + await clock.advance(1) + await done.wait() + finally: + await intake.close() + await engine.stop() + await running + return {"record": await engine.inspect(scope), "calls": calls} + + +@pytest.mark.skipif(not ENABLED or not BACKENDS, reason="needs ATTEND_INTEROP=1, built dist/, node, and Redis or Postgres") +@pytest.mark.parametrize("kind", BACKENDS) +@pytest.mark.parametrize("phase", ["waiting", "retrying"]) +@pytest.mark.parametrize("writer", ["python", "typescript"]) +async def test_independent_limits_continue_across_runtimes(kind: str, phase: str, writer: str) -> None: + owned = await (make_redis() if kind == "redis" else make_postgres()) + inner: Any = owned.inner + prefix = str(inner._prefix if kind == "redis" else inner.prefix) + scope = "independent-" + phase + "-" + writer + try: + written = await (python(owned, "write", scope, phase) if writer == "python" else typescript(kind, prefix, "write", scope, phase)) + stored = await owned.load(scope) + assert stored is not None and stored["snapshot"] is not None + assert stored["snapshot"]["reducer"] == 5 and stored["tail"] + assert stored["snapshot"]["policy"].get("eventLimits") == {"counted": 3, "background": 2} + read = await (typescript(kind, prefix, "read", scope, phase) if writer == "python" else python(owned, "read", scope, phase)) + assert read["record"] == written["record"] + refused = await (typescript(kind, prefix, "refuse", scope, phase) if writer == "python" else python(owned, "refuse", scope, phase)) + assert refused == {"rejected": True, "unchanged": True} + continued = await (typescript(kind, prefix, "continue", scope, phase) if writer == "python" else python(owned, "continue", scope, phase)) + assert continued["calls"] == [{"at": 10040 if phase == "retrying" else 10015, "ids": ["a", "y", "z", "b", "c"], "wait": False, "dropped": 1, "gap": True}] + assert continued["record"]["batch"] is None + assert continued["record"]["cursors"] == {"feed": "3"} + finally: + await owned.close() diff --git a/python/tests/test_interop.py b/python/tests/test_interop.py index ee12d51..f117bbc 100644 --- a/python/tests/test_interop.py +++ b/python/tests/test_interop.py @@ -156,7 +156,7 @@ async def test_intake_snapshot_and_tail_continue_without_intake_in_other_runtime assert written["record"]["cursors"] == {"feed": "3"} stored = await owned.load(scope) assert stored is not None and stored["snapshot"] is not None - assert stored["snapshot"]["reducer"] == 4 and stored["tail"] + assert stored["snapshot"]["reducer"] == 5 and stored["tail"] encoded = json.dumps(stored) assert all(field not in encoded for field in ('"catchUp"', '"catch_up"', '"prepare"', '"owner"')) read = await (typescript(kind, prefix, "read", scope) if writer == "python" else python(owned, "read", scope)) diff --git a/python/tests/test_observation_time.py b/python/tests/test_observation_time.py index 6a2f585..26c57f5 100644 --- a/python/tests/test_observation_time.py +++ b/python/tests/test_observation_time.py @@ -259,7 +259,7 @@ async def test_prior_reducer_snapshot_and_tail_keep_ingestion_deadlines() -> Non assert loaded is not None and loaded["dueAt"] == 2100 assert [(event["id"], event["seenAt"], event.get("observedAt")) for event in loaded["buffer"]["entries"]] == [("a", 1000, None), ("b", 1100, None)] stored = await store.load("s") - assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 4 + assert stored is not None and stored["snapshot"] is not None and stored["snapshot"]["reducer"] == 5 finally: await attend.stop() await store.close() diff --git a/src/attend.ts b/src/attend.ts index 0ee5fe6..d2d012f 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -39,6 +39,19 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' if (policy.continuation !== undefined && policy.continuation !== 'separate' && policy.continuation !== 'accumulate') { throw new TypeError('attend: continuation must be separate or accumulate'); } + if (config.settle && Object.hasOwn(config.settle, 'eventLimits')) { + const limits = config.settle.eventLimits; + if (policy.continuation !== 'accumulate' || Object.hasOwn(config.settle, 'maxEvents')) { + throw new TypeError('attend: eventLimits requires accumulate and replaces maxEvents'); + } + if (typeof limits !== 'object' || limits === null || Array.isArray(limits) + || Reflect.ownKeys(limits).length !== 2 || !Object.hasOwn(limits, 'counted') || !Object.hasOwn(limits, 'background') + || !Number.isSafeInteger(limits.counted) || limits.counted <= 0 + || !Number.isSafeInteger(limits.background) || limits.background < 0) { + throw new TypeError('attend: eventLimits requires positive counted and nonnegative background safe integers'); + } + policy.eventLimits = { counted: limits.counted, background: limits.background }; + } if (config.judge.budget) { const bytes = windowBytesFor(config.judge.budget, share); if (!Number.isFinite(bytes) || bytes <= 0) throw new RangeError('attend: judge window budget must be positive and finite'); diff --git a/src/core/reducer.ts b/src/core/reducer.ts index f9d80a4..c09f403 100644 --- a/src/core/reducer.ts +++ b/src/core/reducer.ts @@ -6,10 +6,10 @@ import type { import { ROUTES } from './types.js'; import { fnvHex, fnvStart, foldId } from './ids.js'; import { seenAdmit, seenRelease, seenTrim } from './seen.js'; -import { estimateRenderedBytes, observationTime, openWindow, shedEntries, windowAppend, windowCompact, windowDeadline, windowEntries, windowPrune, windowShed, windowSize } from './window.js'; +import { estimateRenderedBytes, isBackground, observationTime, openWindow, shedEntries, windowAppend, windowCompact, windowDeadline, windowEntries, windowPrune, windowShed, windowSize } from './window.js'; /** Bumped whenever a release changes a transition. Stored with every snapshot. */ -export const REDUCER_VERSION = 4; +export const REDUCER_VERSION = 5; /** An empty output. One output may collect several inputs: `apply` only ever sets `changed`. */ export function newOutput(): ApplyOutput { @@ -102,6 +102,7 @@ export function apply(config: ApplyConfig, state: ScopeState, logged: LoggedInpu default: input satisfies never; } if (swept) sweep(ctx, state); + if (config.policy.eventLimits && input.kind !== 'events') removed(ctx, state, retainBackground(config.policy, state), 'overflow'); const due = nextDue(config.policy, state); if (!Object.is(state.dueAt, due)) { state.dueAt = due; @@ -132,7 +133,7 @@ function ingest(ctx: Ctx, state: ScopeState, input: EventsInput): void { if (state.seen.size > Math.max(0, ctx.config.policy.seenCount)) ctx.out.changed = true; seenTrim(state, ctx.config.policy.seenCount); prune(ctx, state); - removed(ctx, state, windowShed(state.open, ctx.config.policy.maxEvents), 'overflow'); + removed(ctx, state, retainBackground(ctx.config.policy, state), 'overflow'); if (windowSize(state.open) === 0) state.open.endedAt = null; const source = input.source ?? null; if (source !== null && input.cursor !== undefined @@ -148,15 +149,48 @@ function ingest(ctx: Ctx, state: ScopeState, input: EventsInput): void { if (ctx.config.traces) ctx.out.effects.push({ kind: 'trace', trace: { kind: 'ingested', scope: state.scope, count: input.events.length - duplicates, duplicates } }); } +function retainBackground(policy: SettlePolicy, state: ScopeState): Entry[] | null { + const limits = policy.eventLimits, open = state.open; + if (!limits) return windowShed(open, policy.maxEvents); + const held = state.batch; + if (held === null || held.phase.phase === 'judging') { + return windowShed(open, windowSize(open) - Math.max(0, open.summary.sheddable - limits.background)); + } + const heldBackground = held.window.events.reduce((count, entry) => count + Number(isBackground(entry)), 0); + const excess = heldBackground + open.summary.sheddable - limits.background; + if (excess <= 0) return null; + const retained = [...held.window.events]; + const old = shedEntries(retained, Math.max(0, retained.length - excess)); + if (old !== null) { + const hash = fnvStart(state.scope); + for (const entry of retained) foldId(hash, entry.id); + held.window = { ...held.window, events: retained, id: fnvHex(hash), dropped: held.window.dropped + old.length }; + held.hash = hash; + } + const remaining = excess - (old?.length ?? 0); + const fresh = remaining > 0 ? windowShed(open, windowSize(open) - remaining) : null; + if (windowSize(open) === 0) open.endedAt = null; + return [...(old ?? []), ...(fresh ?? [])]; +} + +function shedCandidate(policy: SettlePolicy, entries: Entry[]): Entry[] | null { + if (!policy.eventLimits) return shedEntries(entries, policy.maxEvents); + const background = entries.reduce((count, entry) => count + Number(isBackground(entry)), 0); + return shedEntries(entries, entries.length - Math.max(0, background - policy.eventLimits.background)); +} + function continuationEntries(policy: SettlePolicy, state: ScopeState): Entry[] { const entries = [...(state.batch?.window.events ?? []), ...windowEntries(state.open)]; - shedEntries(entries, policy.maxEvents); + shedCandidate(policy, entries); return entries; } function sizeBound(policy: SettlePolicy, entries: readonly Entry[]): SettleReason | null { if (entries.length === 0) return null; - if (entries.length > policy.maxEvents) return 'overflow'; + const full = policy.eventLimits + ? entries.reduce((count, entry) => count + Number(!isBackground(entry)), 0) >= policy.eventLimits.counted + : entries.length > policy.maxEvents; + if (full) return 'overflow'; if (policy.maxWindowBytes !== undefined && entries.reduce((bytes, entry) => bytes + estimateRenderedBytes(entry), 0) >= policy.maxWindowBytes) return 'size'; return null; } @@ -268,7 +302,7 @@ function settleBuffer(ctx: Ctx, state: ScopeState, fired: SettleReason, mayWait: const gap = open.gap || (held?.window.gap ?? false); const waits = held?.window.waits ?? 0; forced = forced || held?.window.reason === 'forced'; - const gone = shedEntries(events, ctx.config.policy.maxEvents); + const gone = shedCandidate(ctx.config.policy, events); removed(ctx, state, gone, 'overflow'); dropped += gone?.length ?? 0; let hash: FnvState; diff --git a/src/core/types.ts b/src/core/types.ts index fb27d0f..3a9b99b 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -59,10 +59,17 @@ export type DeliveredRoute = Exclude; export type SettleReason = 'closing' | 'flush' | 'stream_quiet' | 'passive_quiet' | 'overflow' | 'age' | 'forced' | 'size'; +/** Independent settlement and FIFO retention limits, selected together. */ +export interface EventLimits { + counted: number; + background: number; +} + /** Round starting points, not tuned values. Every number is in ms unless it is a count. */ export interface SettlePolicy { /** Keep one unresolved window through waits and retries. Omitted means separate. */ continuation?: 'separate' | 'accumulate'; + eventLimits?: EventLimits; closingGraceMs: number; streamGapMs: number; passiveQuietMs: number; diff --git a/src/core/window.ts b/src/core/window.ts index 402367a..218c511 100644 --- a/src/core/window.ts +++ b/src/core/window.ts @@ -6,7 +6,7 @@ export function isAct(entry: { kind: Kind }): boolean { return entry.kind === 'closing' || entry.kind === 'continuous' || entry.kind === 'passive'; } -function isSheddable(entry: { kind: Kind }): boolean { +export function isBackground(entry: { kind: Kind }): boolean { return entry.kind === 'consequence' || entry.kind === 'context'; } @@ -56,7 +56,7 @@ function summarizeEntry(summary: TriggerSummary, entry: Entry, index: number): v summary.actObserved ||= explicit; if (summary.actObserved) summary.firstActAt = summary.minActAt; } - if (isSheddable(entry)) { + if (isBackground(entry)) { summary.sheddable += 1; if (summary.firstActIndex === -1) summary.prefixMinSheddableAt = Math.min(summary.prefixMinSheddableAt, observedAt); } @@ -133,7 +133,7 @@ function prefixMinimum(open: OpenWindow): number { let min = Infinity; for (let i = 0; i < end; i += 1) { const entry = open.entries[open.start + i]!; - if (isSheddable(entry)) { + if (isBackground(entry)) { if (open.monotone) return observationTime(entry); min = Math.min(min, observationTime(entry)); } @@ -189,7 +189,7 @@ export function windowPrune(open: OpenWindow, maxWindowMs: number, now: number): const entry = entries[start + read]!; const stale = observationTime(entry) + maxWindowMs <= now; if (!stale && open.monotone) break; - if (stale && isSheddable(entry)) { + if (stale && isBackground(entry)) { if (gone === null) gone = [entry]; else gone.push(entry); bytes += sizes[start + read]!; @@ -222,7 +222,7 @@ function shed(entries: Entry[], maxEvents: number, open: OpenWindow | null): Ent let read = 0; for (; read < length && (gone === null || gone.length < excess); read += 1) { const entry = entries[start + read]!; - if (isSheddable(entry)) { + if (isBackground(entry)) { if (gone === null) gone = [entry]; else gone.push(entry); if (sizes !== null) bytes += sizes[start + read]!; @@ -266,7 +266,8 @@ export function windowDeadline(policy: SettlePolicy, open: OpenWindow): { at: nu at = open.endedAt; reason = 'closing'; } - if (size > 0 && size > policy.maxEvents && (reason === null || s.lastSeenAt < at)) { + const full = policy.eventLimits ? size - s.sheddable >= policy.eventLimits.counted : size > policy.maxEvents; + if (size > 0 && full && (reason === null || s.lastSeenAt < at)) { at = s.lastSeenAt; reason = 'overflow'; } diff --git a/src/index.ts b/src/index.ts index 71fd9ee..02f013b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ export type { Delivery, Entry, Event, + EventLimits, EventLog, Judge, JudgeImage, diff --git a/src/shell/read.ts b/src/shell/read.ts index 8d4b1b8..ea37f26 100644 --- a/src/shell/read.ts +++ b/src/shell/read.ts @@ -8,7 +8,7 @@ export function replay(scope: string, stored: StoredScope, modes: Pick 0)) { throw new Error('attend: cannot change continuation while a window is unresolved'); } + const priorLimits = stored?.snapshot?.policy.eventLimits, limits = config.policy.eventLimits; + if (stored !== null && (priorLimits?.counted !== limits?.counted || priorLimits?.background !== limits?.background) + && (slot.state.batch !== null || windowSize(slot.state.open) > 0)) { + throw new Error('attend: cannot change event limits while a window is unresolved'); + } slot.tailCount = stored?.tail.length ?? 0; slot.tailBytes = stored?.tail.reduce((sum, logged) => sum + inputBytes(logged), 0) ?? 0; slot.snapshotBytes = stored?.snapshot ? bytes(stored.snapshot.record) : 0; diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index a92a678..294f67c 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,64 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'independent limits settle counted equality while retaining background', + start: 0, intakes: ['s'], kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 } }, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('x', 'said'), ev('y', 'out')] }, + { submit: 's', events: [ev('a', 'drag'), ev('b', 'drag')] }, { inspect: 's' }, + { submit: 's', events: [ev('c', 'drag')] }, { inspect: 's' }], + }, + { + name: 'independent background retention uses arrival order despite observation order', + start: 20, kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 } }, + judge: { '*': { answers: [{ route: 'skip' }] } }, + steps: [push('s', ev('x', 'said', { observedAt: 20 }), ev('y', 'out', { observedAt: 10 }), ev('z', 'said', { observedAt: 0 })), { inspect: 's' }], + }, + { + name: 'independent zero background retains an atomic counted overshoot', + start: 0, intakes: ['s'], kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 2, background: 0 } }, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('x', 'out'), ev('a', 'drag'), ev('b', 'drag'), ev('y', 'said'), ev('c', 'drag')] }, { inspect: 's' }], + }, + ...['wait', 'retry'].map((phase): Scenario => ({ + name: `independent retention trims held and fresh immediately while ${phase}`, + start: 0, intakes: ['s'], kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 }, waitHorizonMs: 20, retryBackoffMs: [30] }, + judge: { '*': { answers: [phase === 'wait' ? { route: 'wait' } : { fail: 'outage' }, { route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('a', 'drag', { quietForMs: 10 }), ev('x', 'said'), ev('y', 'out')] }, advance(15), + { submit: 's', events: [ev('z', 'said')], truncated: true }, { inspect: 's' }, advance(25), { inspect: 's' }], + })), + ...['wait', 'retry'].map((phase): Scenario => ({ + name: `independent retention combines direct input when a live offer enters ${phase}`, + start: 0, kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 }, waitHorizonMs: 20, retryBackoffMs: [30] }, + judge: { '*': { answers: [{ hold: 'call' }, { route: 'queue' }] } }, + steps: [push('s', ev('a', 'drag', { quietForMs: 10 }), ev('x', 'said'), ev('y', 'out')), advance(10), + push('s', ev('z', 'out'), ev('w', 'said'), ev('v', 'out')), { inspect: 's' }, advance(5), + phase === 'wait' ? { release: 'call', answer: { route: 'wait' } } : { release: 'call', fail: 'outage' }, + { inspect: 's' }, advance(30), { inspect: 's' }], + })), + { + name: 'independent counted crossing preserves retry not-before and forced retries', + start: 0, intakes: ['s'], kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 }, retryBackoffMs: [30, 60] }, + judge: { '*': { answers: [{ fail: 'outage' }, { fail: 'outage' }, { route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('a', 'drag', { quietForMs: 10 })] }, advance(15), + { submit: 's', events: [ev('b', 'drag', { quietForMs: 100 }), ev('c', 'drag', { quietForMs: 100 })] }, + advance(24), { inspect: 's' }, advance(1), { inspect: 's' }, advance(60)], + }, + { + name: 'independent counted equality withholds wait even when quiet fires first', + start: 0, intakes: ['s'], kinds: KINDS, + settle: { continuation: 'accumulate', eventLimits: { counted: 2, background: 1 }, waitHorizonMs: 20 }, + judge: { '*': { answers: [{ route: 'wait' }, { route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('a', 'drag', { quietForMs: 10 })] }, advance(20), + { submit: 's', events: [ev('b', 'drag', { observedAt: 0, quietForMs: 10 })] }, { inspect: 's' }], + }, ...['gap', 'dropped'].map((metadata): Scenario => ({ name: `accumulating retry attributes empty ${metadata} metadata to held input`, start: 0, intakes: ['s'], kinds: KINDS, diff --git a/test/continuation.test.ts b/test/continuation.test.ts index 514533d..b16e774 100644 --- a/test/continuation.test.ts +++ b/test/continuation.test.ts @@ -170,7 +170,7 @@ test.each(legacy.cases)('reads revision-3 $name and refuses an unresolved mode s await pending; const stored = await store.load('scope'); expect(stored?.snapshot?.policy.continuation).toBe('accumulate'); - expect(stored?.snapshot?.reducer).toBe(4); + expect(stored?.snapshot?.reducer).toBe(5); expect((await engine.inspect('scope'))?.recent).toEqual(item.expected.recent); } else { await expect(pending).rejects.toThrow('continuation'); diff --git a/test/continuous-quiet.test.ts b/test/continuous-quiet.test.ts index 35072eb..39e2a3c 100644 --- a/test/continuous-quiet.test.ts +++ b/test/continuous-quiet.test.ts @@ -204,7 +204,7 @@ test('a revision-two snapshot and mixed tail rebuild continuous end times', asyn const loaded = await attend.inspect('s'); expect(loaded?.dueAt).toBe(200); expect(loaded?.buffer.entries.map((event) => [event.id, event.quietForMs, event.seenAt])).toEqual([['a', undefined, 100], ['b', 90, 120], ['c', undefined, 120]]); - expect((await store.load('s'))?.snapshot?.reducer).toBe(4); + expect((await store.load('s'))?.snapshot?.reducer).toBe(5); } finally { await attend.stop(); } diff --git a/test/core-inputs.test.ts b/test/core-inputs.test.ts index 0fb70f3..1038637 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, 4); + assert.equal(REDUCER_VERSION, 5); }); test('fromRecord accepts frozen oracle snapshots without changing them', () => { diff --git a/test/event-limits.test.ts b/test/event-limits.test.ts new file mode 100644 index 0000000..5a425f2 --- /dev/null +++ b/test/event-limits.test.ts @@ -0,0 +1,210 @@ +import { expect, test } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { createAttend, memoryStore } from '../src/index.js'; +import { openIntake } from '../src/intake.js'; +import { fakeClock } from '../src/testing.js'; +import { apply, newOutput } from '../src/core/reducer.js'; +import { assertInvariants, initialState, toRecord } from '../src/core/state.js'; +import { DEFAULT_POLICY } from '../src/types.js'; +import type { ApplyConfig, Event, Input, ScopeRecord, ScopeWrite, SettlePolicy, StoredScope, Window } from '../src/types.js'; + +type Answer = 'wait' | 'queue' | 'fail'; +interface Offer { at: number; window: Window; wait: boolean } +const event = (id: string, at = 0, name = 'reading'): Event => ({ id, at, observedAt: at, name, data: {}, ...(name === 'reading' ? { quietForMs: 10 } : {}) }); + +async function run(answers: Answer[], body: (clock: ReturnType, put: (events: Event[]) => Promise, offers: Offer[], inspect: () => ReturnType['inspect']>) => Promise, options: Record = {}) { + const clock = fakeClock(), offers: Offer[] = []; + const limits = { eventLimits: { counted: 3, background: 2 }, ...options }; + const attend = createAttend({ clock, kind: { reading: 'continuous', meta: 'context', result: 'consequence' }, sink: 'log', + settle: { continuation: 'accumulate', waitHorizonMs: 20, retryBackoffMs: [30], ...limits }, + judge: async (input) => { + offers.push({ at: clock.now(), window: structuredClone(input.window), wait: input.routes.some((r) => r.route === 'wait') }); + const answer = answers[offers.length - 1] ?? 'queue'; + if (answer === 'fail') throw new Error('controlled failure'); + return { route: answer }; + }, + }); + const intake = openIntake(attend, 's'), running = attend.run(); + try { await body(clock, (events) => intake.submit(async () => ({ events })), offers, () => attend.inspect('s')); } + finally { await intake.close(); await attend.stop(); await running; } +} + +test('counted equality settles without spending independent background capacity', async () => { + await run(['queue'], async (_clock, put, offers) => { + await put([event('x', 0, 'meta'), event('y', 0, 'result')]); + await put([event('a'), event('b')]); + expect(offers).toHaveLength(0); + await put([event('c')]); + expect(offers.map((o) => [o.window.events.map((e) => e.id), o.wait, o.window.dropped])).toEqual([[['x', 'y', 'a', 'b', 'c'], false, 0]]); + }); +}); + +test('background retention is FIFO and does not settle alone', async () => { + await run([], async (_clock, put, offers, inspect) => { + await put([event('x', 0, 'meta'), event('y', 0, 'result'), event('z', 0, 'meta')]); + expect(offers).toHaveLength(0); + const state = await inspect(); + expect(state?.buffer.entries.map((e) => e.id)).toEqual(['y', 'z']); + expect(state?.buffer.dropped).toBe(1); + }); +}); + +test.each(['wait', 'fail'])('retention spans held and fresh state immediately after %s', async (answer) => { + await run([answer, 'queue'], async (clock, put, offers, inspect) => { + await put([event('a'), event('x', 0, 'meta'), event('y', 0, 'result')]); + await clock.advance(10); + await put([event('z', 10, 'meta')]); + const state = await inspect(); + expect(state?.batch?.window.events.map((e) => e.id)).toEqual(['a', 'y']); + expect(state?.batch?.window.dropped).toBe(1); + expect(state?.buffer.entries.map((e) => e.id)).toEqual(['z']); + await clock.advance(answer === 'wait' ? 20 : 30); + expect(offers[1]?.window.events.map((e) => e.id)).toEqual(['a', 'y', 'z']); + expect(offers[1]?.window.dropped).toBe(1); + }); +}); + +test('atomic input may exceed the trigger without splitting or losing counted entries', async () => { + await run(['queue'], async (_clock, put, offers) => { + await put([event('a'), event('x', 0, 'meta'), event('b'), event('y', 0, 'result'), event('c'), event('z', 0, 'meta'), event('d')]); + expect(offers).toHaveLength(1); + expect(offers[0]?.window.events.map((e) => e.id)).toEqual(['a', 'b', 'y', 'c', 'z', 'd']); + expect(offers[0]?.wait).toBe(false); + expect(offers[0]?.window.dropped).toBe(1); + }); +}); + +test('zero background capacity keeps counted input', async () => { + await run(['queue'], async (_clock, put, offers) => { + await put([event('x', 0, 'meta'), event('a'), event('y', 0, 'result')]); + expect(offers[0]?.window.events.map((e) => e.id)).toEqual(['a']); + expect(offers[0]?.window.dropped).toBe(2); + }, { eventLimits: { counted: 1, background: 0 } }); +}); + +test.each<'separate' | undefined>([undefined, 'separate'])('independent limits require explicit accumulate: %s', (continuation) => { + const options = continuation === undefined ? { eventLimits: { counted: 3, background: 2 } } : { continuation, eventLimits: { counted: 3, background: 2 } }; + expect(() => createAttend({ kind: {}, judge: async () => ({ route: 'skip' }), sink: 'log', settle: options })).toThrow(); +}); + +test('independent limits refuse an explicit scalar', () => { + const options = { eventLimits: { counted: 3, background: 2 }, maxEvents: 9 }; + expect(() => createAttend({ kind: {}, judge: async () => ({ route: 'skip' }), sink: 'log', settle: { continuation: 'accumulate', ...options } })).toThrow(); +}); + +test.each([undefined, { counted: 4, background: 2 }, { counted: 3, background: 1 }])('unresolved policy changes reject without a write: %j', async (eventLimits) => { + const store = memoryStore(), clock = fakeClock(); + const options = { eventLimits: { counted: 3, background: 2 } }; + const first = createAttend({ store, clock, kind: { meta: 'context' }, judge: async () => ({ route: 'skip' }), sink: 'log', settle: { continuation: 'accumulate', ...options } }); + await first.push('s', event('x', 0, 'meta')); + const before = await store.load('s'); + const changed = eventLimits === undefined ? {} : { eventLimits }; + const second = createAttend({ store, clock, kind: { meta: 'context' }, judge: async () => ({ route: 'skip' }), sink: 'log', settle: { continuation: 'accumulate', ...changed } }); + await expect(second.push('s', event('y', 0, 'meta'))).rejects.toThrow('unresolved'); + expect(await store.load('s')).toEqual(before); +}); + +type Completion = 'judged' | 'judgeFailed' | 'judgeReleased' | 'judgeDeferred'; +test.each(['judged', 'judgeFailed', 'judgeReleased', 'judgeDeferred'])('direct-writer %s bounds retained state without mutating the live offer', (kind) => { + const config: ApplyConfig = { policy: { ...DEFAULT_POLICY, continuation: 'accumulate', eventLimits: { counted: 3, background: 2 }, seenCount: 0, retryBackoffMs: [30] }, decisions: 'log', deadLetters: 'log', traces: true }; + const state = initialState('s', config.policy); + function send(input: Input, now: number) { + const out = newOutput(); + apply(config, state, { input, now }, out); + assertInvariants(state, config.policy); + return out; + } + send({ kind: 'events', events: [{ ...event('a'), kind: 'continuous' }, { ...event('x', 0, 'meta'), kind: 'context' }, { ...event('y', 0, 'result'), kind: 'consequence' }] }, 0); + const started = send({ kind: 'tick' }, 10).effects.find((e) => e.kind === 'judge'); + if (!started || started.kind !== 'judge') throw new Error('expected a live offer'); + const original = structuredClone(started.window); + send({ kind: 'events', truncated: true, events: [{ ...event('z', 11, 'meta'), kind: 'context' }, { ...event('w', 11, 'result'), kind: 'consequence' }, { ...event('v', 11, 'meta'), kind: 'context' }] }, 11); + expect(started.window).toEqual(original); + const token = { batchId: original.id, attempt: started.attempt }; + let completion: Input; + if (kind === 'judged') completion = { kind, ...token, judgment: { route: 'wait' } }; + else if (kind === 'judgeFailed') completion = { kind, ...token, message: 'controlled', permanent: false }; + else if (kind === 'judgeDeferred') completion = { kind, ...token, until: 42 }; + else completion = { kind, ...token }; + send(completion, 12); + expect(started.window).toEqual(original); + const record = toRecord(state); + expect(record.batch?.window.events.map((e) => e.id)).toEqual(['a']); + expect(record.batch?.window.dropped).toBe(2); + expect(record.buffer.entries.map((e) => e.id)).toEqual(['w', 'v']); + expect(record.buffer.dropped).toBe(1); + expect(record.buffer.gap).toBe(true); + expect([...state.known]).toEqual([['a', 1], ['w', 1], ['v', 1]]); + expect(record.batch?.window.id).not.toBe(original.id); +}); + +test.each([null, [], {}, { counted: 0, background: 1 }, { counted: true, background: 1 }, { counted: 1.5, background: 1 }, { counted: 1, background: -1 }, { counted: 1, background: Infinity }, { counted: 2 ** 53, background: 0 }, { counted: 1 }, { counted: 1, background: 0, extra: 1 }])('invalid independent limits are refused: %j', (eventLimits) => { + expect(() => Reflect.apply(createAttend, undefined, [{ kind: {}, judge: async () => ({ route: 'skip' }), sink: 'log', settle: { continuation: 'accumulate', eventLimits } }])).toThrow(); +}); + +test('mutating the supplied pair cannot alter the live policy', async () => { + const eventLimits = { counted: 2, background: 1 }; + await run(['queue'], async (_clock, put, offers) => { + eventLimits.counted = 9; + await put([event('a'), event('b')]); + expect(offers).toHaveLength(1); + expect(offers[0]?.wait).toBe(false); + }, { eventLimits }); +}); + +test('native deduplication happens before counted equality', async () => { + await run(['queue'], async (_clock, put, offers) => { + await put([event('a'), event('a'), event('b')]); + expect(offers).toHaveLength(0); + await put([event('c')]); + expect(offers[0]?.window.events.map((e) => e.id)).toEqual(['a', 'b', 'c']); + }); +}); + +interface Legacy { name: string; now: number; writes: ScopeWrite[][]; stored: StoredScope; expected: ScopeRecord } +const legacy: { cases: Legacy[] } = JSON.parse(readFileSync(new URL('../conformance/fixtures/event-limits-legacy.json', import.meta.url), 'utf8')); +test.each(legacy.cases)('revision-four $name snapshot and tail retain their saved policy', async (item) => { + const store = memoryStore(), clock = fakeClock(item.now); + for (const writes of item.writes) expect(await store.commit(writes)).toEqual(writes.map(() => 'ok')); + expect(await store.load('s')).toEqual(item.stored); + expect(item.stored.snapshot?.reducer).toBe(4); + expect(item.stored.tail.length).toBeGreaterThan(0); + const engine = createAttend({ store, clock, kind: { meta: 'context' }, judge: async () => ({ route: 'queue' }), sink: 'log', + settle: { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 } }, + }); + expect(await engine.inspect('s')).toEqual(item.expected); + const write = engine.push('s', event('next', item.now, 'meta')); + if (item.name === 'complete') { + await write; + const stored = await store.load('s'); + expect(stored?.snapshot?.reducer).toBe(5); + expect(stored?.snapshot?.policy.eventLimits).toEqual({ counted: 3, background: 2 }); + expect((await engine.inspect('s'))?.recent).toEqual(item.expected.recent); + } else { + await expect(write).rejects.toThrow('unresolved'); + expect(await store.load('s')).toEqual(item.stored); + } +}); + +test.each(['wait', 'fail'])('same independent policy resumes persisted %s state', async (answer) => { + const clock = fakeClock(), store = memoryStore(); + const settle = { continuation: 'accumulate', eventLimits: { counted: 3, background: 2 }, waitHorizonMs: 20, retryBackoffMs: [30] } satisfies Partial; + const first = createAttend({ store, clock, kind: { reading: 'continuous', meta: 'context' }, sink: 'log', settle, + judge: async () => { if (answer === 'fail') throw new Error('controlled'); return { route: answer }; }, + }); + const intake = openIntake(first, 's'), run = first.run(); + await intake.submit(async () => ({ events: [event('a'), event('x', 0, 'meta'), event('y', 0, 'meta')] })); + await clock.advance(15); + await intake.submit(async () => ({ events: [event('z', 15, 'meta')] })); + await intake.close(); await first.stop(); await run; + const before = await first.inspect('s'); + const seen: string[][] = []; + const second = createAttend({ store, clock, kind: {}, sink: 'log', settle, judge: async ({ window }) => { seen.push(window.events.map((e) => e.id)); return { route: 'queue' }; } }); + const running = second.run(); + try { + await second.push('s', []); + expect(await second.inspect('s')).toEqual(before); + await clock.advance(25); + expect(seen).toEqual([['a', 'y', 'z']]); + } finally { await second.stop(); await running; } +}); diff --git a/test/observation-time.test.ts b/test/observation-time.test.ts index d06f3a0..802805f 100644 --- a/test/observation-time.test.ts +++ b/test/observation-time.test.ts @@ -207,7 +207,7 @@ test('a prior reducer snapshot and tail retain ingestion-time deadlines on upgra const loaded = await attend.inspect('s'); expect(loaded?.dueAt).toBe(2100); expect(loaded?.buffer.entries.map((event) => [event.id, event.seenAt, event.observedAt])).toEqual([['a', 1000, undefined], ['b', 1100, undefined]]); - expect((await store.load('s'))?.snapshot?.reducer).toBe(4); + expect((await store.load('s'))?.snapshot?.reducer).toBe(5); } finally { await attend.stop(); } diff --git a/test/policy-replay.test.ts b/test/policy-replay.test.ts new file mode 100644 index 0000000..7e8cc05 --- /dev/null +++ b/test/policy-replay.test.ts @@ -0,0 +1,18 @@ +import { expect, test } from 'vitest'; +import { createAttend, memoryStore } from '../src/index.js'; +import { fakeClock } from '../src/testing.js'; + +test('a changed writer policy cannot reinterpret an already completed tail', async () => { + const store = memoryStore(), clock = fakeClock(); + const first = createAttend({ store, clock, kind: { reading: 'continuous' }, judge: async () => ({ route: 'queue' }), sink: 'log', settle: { streamGapMs: 10 } }); + const running = first.run(); + await first.push('s', { id: 'a', name: 'reading', at: 0, data: {} }); + await clock.advance(10); + await first.stop(); await running; + expect((await store.load('s'))?.tail.length).toBeGreaterThan(0); + expect((await first.inspect('s'))?.batch).toBeNull(); + expect((await first.inspect('s'))?.buffer.entries).toEqual([]); + const second = createAttend({ store, clock, kind: { reading: 'continuous' }, judge: async () => ({ route: 'queue' }), sink: 'log', settle: { streamGapMs: 100 } }); + await second.push('s', { id: 'b', name: 'reading', at: 10, data: {} }); + expect((await second.inspect('s'))?.buffer.entries.map((e) => e.id)).toEqual(['b']); +}); diff --git a/test/recovery.test.ts b/test/recovery.test.ts index 6585d30..4c08fcd 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, 4); + assert.equal(snapshot.reducerVersion, 5); 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 });