diff --git a/DEVIATIONS.md b/DEVIATIONS.md index 234425c..da5e702 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -1,5 +1,11 @@ # Shell changes from the frozen shell +## Serial intake + +The optional serial intake owns registration, asynchronous preparation and immediate effects for one scope. It gives registered raw work precedence over an idle deferred timer and suppresses the pre-input catch-up tick for that owned input only. The existing reducer tick runs after a nonempty batch. Ordinary input and frozen differential cases retain their prior scheduling. + +The queue, callbacks and catch-up metadata are local and are never stored. Persisted inputs and reducer revision 3 are unchanged. Closing fences unapplied completion results and joins their native release writes. This is local ordering, not distributed scope ownership. [Serial intake](docs/reference.md#serial-intake) defines the boundary and limits. + ## Continuous quiet duration An optional `Event.quietForMs` gives a continuous event its own quiet duration. Once any continuous entry supplies it, the continuous deadline is the latest of the entries' individual end times. Entries without a duration use the policy's `streamGapMs`. Other kinds keep their independent triggers. With no explicit duration, the frozen default behavior remains unchanged, including backwards clocks. @@ -95,6 +101,7 @@ A Python coroutine runs on without yielding until it reaches real I/O, while eve ## Intake +- Python exposes `Attend.open_intake`; TypeScript exposes `openIntake` from its Node-only `/intake` entry. Both register synchronously. Cancelling a Python submission future detaches the observer, while its explicit abort signal withdraws work. Python `close()` fences synchronously and returns a cancellation-shielded coroutine; TypeScript returns the shared completion promise. - `push`, `flush` and `end` return asyncio futures and take their input when called, as the TypeScript promises do, so concurrent pushes merge and group exactly as there. Each caller gets a future of its own, so cancelling one never cancels another push merged into the same input. The input is still applied. - `run()` starts when called, as in TypeScript, and returns the coroutine to await or run as a task, so `stop()` straight after `create_task(attend.run())` stops it. - Event data must hold JSON values: dicts with string keys, lists or tuples, strings, ints, floats, booleans and None. NaN and the infinities become null and -0.0 becomes 0, as JSON writes them. Any other value raises `TypeError`, where TypeScript would call its `toJSON` (a `Date`) or drop it (`undefined`, a function). diff --git a/conformance/fixtures/scenarios.json b/conformance/fixtures/scenarios.json index 6c14eb2..7bb2588 100644 --- a/conformance/fixtures/scenarios.json +++ b/conformance/fixtures/scenarios.json @@ -1,5 +1,2070 @@ { "scenarios": [ + { + "scenario": { + "name": "serial intake keeps registered backlog ahead of a timer during preparation", + "intakes": [ + "s" + ], + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "observedAt": 0, + "quietForMs": 100 + } + ] + }, + { + "advance": 90 + }, + { + "submit": "s", + "events": [], + "prepareMs": 200, + "source": "feed", + "cursor": "1" + }, + { + "advance": 5 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 95, + "quietForMs": 300 + } + ] + }, + { + "advance": 195 + }, + { + "inspect": "s" + }, + { + "advance": 105 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 95, + "quietForMs": 300, + "kind": "continuous", + "seenAt": 290 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 395 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 395 + } + ] + }, + "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", + "observedAt": 0, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 95, + "quietForMs": 300, + "kind": "continuous", + "seenAt": 290 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 395 + }, + "at": 395 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 0, + "duplicates": 0 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 1, + "offerWait": true + }, + { + "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 + }, + { + "step": 4, + "error": null + } + ], + "inspections": [ + { + "step": 6, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": { + "feed": "1" + }, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "observedAt": 0, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 95, + "quietForMs": 300, + "kind": "continuous", + "seenAt": 290 + } + ], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 395 + } + } + ], + "records": { + "s": { + "version": 6, + "scope": "s", + "cursors": { + "feed": "1" + }, + "seen": [ + "a", + "b" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "f9df8ba2df127ca6", + "route": "queue", + "at": 395 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 395, + "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", + "observedAt": 0, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 95, + "quietForMs": 300, + "kind": "continuous", + "seenAt": 290 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 395 + }, + "at": 395 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "serial intake waits for a judgment and its delivery before the next preparation", + "intakes": [ + "s" + ], + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "hold": "judge" + }, + { + "route": "queue" + } + ] + } + }, + "sink": { + "*": { + "attempts": [ + { + "hold": "sink" + }, + "ok" + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 100 + } + ] + }, + { + "advance": 100 + }, + { + "advance": 50 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 150, + "quietForMs": 100 + } + ] + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "c", + "name": "drag", + "text": "drag c", + "observedAt": 160, + "quietForMs": 100 + } + ] + }, + { + "advance": 340 + }, + { + "release": "judge", + "answer": { + "route": "queue" + } + }, + { + "inspect": "s" + }, + { + "advance": 200 + }, + { + "release": "sink" + }, + { + "inspect": "s" + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + }, + { + "scope": "s", + "window": { + "id": "3ecbd5f2ef91c942", + "events": [ + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 150, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 500 + } + ], + "now": 700 + }, + { + "scope": "s", + "window": { + "id": "3ecbd6f2ef91caf5", + "events": [ + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "observedAt": 160, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 500 + }, + { + "id": "3ecbd5f2ef91c942", + "route": "queue", + "at": 700 + } + ], + "now": 700 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 500 + }, + "outcome": "hold: sink" + }, + { + "decision": { + "id": "3ecbd5f2ef91c942", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd5f2ef91c942", + "events": [ + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 150, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "at": 700 + }, + "outcome": "ok" + }, + { + "decision": { + "id": "3ecbd6f2ef91caf5", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd6f2ef91caf5", + "events": [ + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "observedAt": 160, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "at": 700 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd5f2ef91c942", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd5f2ef91c942", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd5f2ef91c942" + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd6f2ef91caf5", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd6f2ef91caf5", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd6f2ef91caf5", + "route": "queue" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd6f2ef91caf5", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd6f2ef91caf5" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 3, + "error": null + }, + { + "step": 5, + "error": null + } + ], + "inspections": [ + { + "step": 8, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [ + { + "item": { + "id": "3ecbd4f2ef91c78f", + "kind": "decision", + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 500 + } + }, + "phase": { + "phase": "inFlight", + "attempt": 1, + "failures": 0, + "leaseUntil": 10500 + } + } + ], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 500 + } + ], + "dueAt": 10500 + } + }, + { + "step": 11, + "scope": "s", + "record": { + "version": 12, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 500 + }, + { + "id": "3ecbd5f2ef91c942", + "route": "queue", + "at": 700 + }, + { + "id": "3ecbd6f2ef91caf5", + "route": "queue", + "at": 700 + } + ], + "dueAt": null + } + } + ], + "records": { + "s": { + "version": 12, + "scope": "s", + "cursors": {}, + "seen": [ + "a", + "b", + "c" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "queue", + "at": 500 + }, + { + "id": "3ecbd5f2ef91c942", + "route": "queue", + "at": 700 + }, + { + "id": "3ecbd6f2ef91caf5", + "route": "queue", + "at": 700 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 500, + "route": "queue", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "at": 500 + }, + "position": "1" + }, + { + "kind": "decision", + "id": "3ecbd5f2ef91c942", + "scope": "s", + "at": 700, + "route": "queue", + "body": { + "id": "3ecbd5f2ef91c942", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd5f2ef91c942", + "events": [ + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 150, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "at": 700 + }, + "position": "2" + }, + { + "kind": "decision", + "id": "3ecbd6f2ef91caf5", + "scope": "s", + "at": 700, + "route": "queue", + "body": { + "id": "3ecbd6f2ef91caf5", + "scope": "s", + "route": "queue", + "probabilities": { + "interrupt": 0, + "queue": 1, + "note": 0, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd6f2ef91caf5", + "events": [ + { + "id": "c", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag c", + "observedAt": 160, + "quietForMs": 100, + "kind": "continuous", + "seenAt": 700 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 700 + }, + "at": 700 + }, + "position": "3" + } + ] + } + }, + { + "scenario": { + "name": "closing serial intake cancels preparation without advancing its cursor", + "intakes": [ + "s" + ], + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "queue" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a" + } + ], + "prepareMs": 100, + "source": "feed", + "cursor": "1" + }, + { + "advance": 20 + }, + { + "closeIntake": "s" + }, + { + "advance": 100 + } + ] + }, + "expected": { + "judgeCalls": {}, + "deliveries": {}, + "deadLetterCalls": {}, + "traces": {}, + "results": [ + { + "step": 0, + "error": { + "name": "IntakeError", + "message": "attend: intake closed" + } + }, + { + "step": 2, + "error": null + } + ], + "inspections": [], + "records": { + "s": null + }, + "log": [] + } + }, + { + "scenario": { + "name": "owned scopes reject ordinary ingress without affecting serial submissions", + "intakes": [ + "s" + ], + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "judge": { + "*": { + "answers": [ + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "push": "s", + "events": [ + { + "id": "other", + "name": "drag", + "text": "drag other" + } + ] + }, + { + "flush": "s" + }, + { + "end": "s" + }, + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 0 + } + ] + }, + { + "advance": 0 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 0 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "outcome": "ok" + } + ] + }, + "deadLetterCalls": {}, + "traces": { + "s": [ + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "reason": "stream_quiet", + "count": 1, + "merged": false + }, + { + "kind": "judging", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "attempt": 1, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "3ecbd4f2ef91c78f", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "3ecbd4f2ef91c78f" + } + ] + }, + "results": [ + { + "step": 0, + "error": { + "name": "IntakeError", + "message": "attend: scope has exclusive intake" + } + }, + { + "step": 1, + "error": { + "name": "IntakeError", + "message": "attend: scope has exclusive intake" + } + }, + { + "step": 2, + "error": { + "name": "IntakeError", + "message": "attend: scope has exclusive intake" + } + }, + { + "step": 3, + "error": null + } + ], + "inspections": [], + "records": { + "s": { + "version": 4, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": null, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [ + { + "id": "3ecbd4f2ef91c78f", + "route": "note", + "at": 0 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "at": 0, + "route": "note", + "body": { + "id": "3ecbd4f2ef91c78f", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 0, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 0 + }, + "at": 0 + }, + "position": "1" + } + ] + } + }, + { + "scenario": { + "name": "serial intake permits fresh input while a resolved wait is pending", + "intakes": [ + "s" + ], + "start": 0, + "kinds": { + "close": "closing", + "say": "flush", + "drag": "continuous", + "look": "passive", + "out": "consequence", + "said": "context" + }, + "settle": { + "waitHorizonMs": 1000 + }, + "judge": { + "*": { + "answers": [ + { + "route": "wait" + }, + { + "route": "note" + } + ] + } + }, + "steps": [ + { + "submit": "s", + "events": [ + { + "id": "a", + "name": "drag", + "text": "drag a", + "quietForMs": 100 + } + ] + }, + { + "advance": 100 + }, + { + "inspect": "s" + }, + { + "advance": 10 + }, + { + "submit": "s", + "events": [ + { + "id": "b", + "name": "drag", + "text": "drag b", + "observedAt": 110, + "quietForMs": 20 + } + ] + }, + { + "advance": 20 + } + ] + }, + "expected": { + "judgeCalls": { + "s": [ + { + "scope": "s", + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 0, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 100 + }, + { + "scope": "s", + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 110, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 110 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 130 + }, + "routes": [ + { + "route": "interrupt" + }, + { + "route": "queue" + }, + { + "route": "note" + }, + { + "route": "ask" + }, + { + "route": "skip" + }, + { + "route": "wait" + } + ], + "predicates": [], + "facts": {}, + "recent": [], + "now": 130 + } + ] + }, + "deliveries": { + "s": [ + { + "decision": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 110, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 110 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 130 + }, + "at": 130 + }, + "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": 1100 + }, + { + "kind": "ingested", + "scope": "s", + "count": 1, + "duplicates": 0 + }, + { + "kind": "settled", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "reason": "stream_quiet", + "count": 2, + "merged": true + }, + { + "kind": "judging", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "attempt": 2, + "offerWait": true + }, + { + "kind": "judged", + "scope": "s", + "batchId": "f9df8ba2df127ca6", + "route": "note" + }, + { + "kind": "delivering", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6", + "attempt": 1 + }, + { + "kind": "delivered", + "scope": "s", + "deliveryId": "f9df8ba2df127ca6" + } + ] + }, + "results": [ + { + "step": 0, + "error": null + }, + { + "step": 4, + "error": null + } + ], + "inspections": [ + { + "step": 2, + "scope": "s", + "record": { + "version": 3, + "scope": "s", + "cursors": {}, + "seen": [ + "a" + ], + "buffer": { + "entries": [], + "dropped": 0, + "gap": false, + "forcedAt": null + }, + "batch": { + "window": { + "id": "3ecbd4f2ef91c78f", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 100 + }, + "phase": { + "phase": "waiting", + "attempt": 1, + "until": 1100 + } + }, + "outbox": { + "decisions": [], + "deadLetters": [] + }, + "recent": [], + "dueAt": 1100 + } + } + ], + "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": "note", + "at": 130 + } + ], + "dueAt": null + } + }, + "log": [ + { + "kind": "decision", + "id": "f9df8ba2df127ca6", + "scope": "s", + "at": 130, + "route": "note", + "body": { + "id": "f9df8ba2df127ca6", + "scope": "s", + "route": "note", + "probabilities": { + "interrupt": 0, + "queue": 0, + "note": 1, + "ask": 0, + "skip": 0, + "wait": 0 + }, + "predicates": {}, + "confidence": null, + "window": { + "id": "f9df8ba2df127ca6", + "events": [ + { + "id": "a", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag a", + "quietForMs": 100, + "kind": "continuous", + "seenAt": 0 + }, + { + "id": "b", + "at": 0, + "name": "drag", + "data": {}, + "text": "drag b", + "observedAt": 110, + "quietForMs": 20, + "kind": "continuous", + "seenAt": 110 + } + ], + "reason": "stream_quiet", + "waits": 1, + "dropped": 0, + "gap": false, + "settledAt": 130 + }, + "at": 130 + }, + "position": "1" + } + ] + } + }, { "scenario": { "name": "different continuous durations settle after the latest event end", diff --git a/docs/reference.md b/docs/reference.md index cca094f..b42828e 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -86,6 +86,52 @@ When every continuous entry omits `quietForMs`, existing timing remains unchange attend picks the route, and your sink carries it out. `routes()` makes you write a handler for each of the four delivered routes. +## Serial intake + +Use serial intake when asynchronous preparation belongs to a scope's event order. It registers raw work before preparation starts, then runs one preparation and its immediate effects at a time. Ordinary `push` keeps its existing behavior. + +In Node, import `openIntake` from `@acquiredintelligence/attend/intake`. This optional entry uses Node's async context; the default package entry does not import it. Open the handle before this engine has touched the scope through input, attachment or a runner sweep. `inspect` only reads the store and does not claim a scope. Start `run()` before submitting; it starts synchronously when called. + +```ts +import { createAttend } from '@acquiredintelligence/attend'; +import { openIntake } from '@acquiredintelligence/attend/intake'; + +const attend = createAttend({ + kind: { message: 'flush' }, + judge: async () => ({ route: 'note' }), + sink: 'log', +}); +const intake = openIntake(attend, 'channel', { capacity: 100 }); +const running = attend.run(); +try { + await intake.submit(async (signal) => { + signal.throwIfAborted(); + return { + events: [{ id: 'a', name: 'message', at: Date.now(), data: {} }], + cursor: '1', + }; + }, { source: 'feed' }); +} finally { + await intake.close(); + await attend.stop(); + await running; +} +``` + +`submit(prepare, { source?, signal? })` registers synchronously and returns a promise. Preparation returns a native `SourceBatch`; provide `source` to commit its cursor with the events. An empty batch can advance the cursor without settling a window. A preparation error commits nothing. Keep preparation free of writes or other external effects, and honor its abort signal. + +A timer claims the scope before its write starts. During preparation or immediate effects, timer wakes coalesce. Registered raw work gets the next turn before an idle deferred timer, which checks the current deadline again. An admitted nonempty batch uses the existing reducer tick after admission. No stored window policy changes. + +The promise covers the input write and the immediate chain of judgments, deliveries and their completion, release or deferral writes. A failed immediate write rejects it. A persisted wait or retry with a future deadline releases the turn; the promise does not wait for that future attempt or an open window's quiet deadline. A cursor can therefore already be committed when a later effect write fails. A caller that retries must supply stable event ids and make external delivery idempotent. + +An opted-in scope refuses ordinary `push`, `attach`, `flush` and `end`, including after close. Same-engine, same-scope `submit` or `close` from preparation, context, judge or delivery rejects with `IntakeError`; awaiting it would wait on itself. Other scopes progress independently. Do not create cycles by awaiting each other's intakes from callbacks. + +`capacity` is a positive safe integer, default 20,000. It bounds queued and active submissions on this handle. Registered preparation also shares `admission.maxQueuedInputs` with ordinary traffic in this engine. The reservation transfers into normal input admission without double charging. These are counts per engine, not byte limits or limits across multiple engines. Full queues reject with `BackpressureError`; they do not silently drop work. + +Abort before application prevents event and cursor admission. An input already applied may still commit; abort does not roll it back. `close()` fences new work synchronously, aborts preparation and active effect signals, and waits for owned immediate work. Late preparation results are discarded. Normal effect results still awaiting application become native releases after close. Close cannot undo an external delivery, and a callback or store that never returns can keep it pending. Repeated close calls join the same cleanup. + +The handle is terminal after close or engine shutdown. Recreate the engine and open a new handle before running to resume committed state. Raw registrations and callbacks are not durable. Snapshots and tails contain only the existing reducer inputs; another runtime can read them without an intake. This provides local ordering in one engine, not ownership across processes sharing a store. + ## 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. diff --git a/package.json b/package.json index 789b486..1aab167 100644 --- a/package.json +++ b/package.json @@ -73,13 +73,18 @@ "types": "./dist/testing.d.ts", "default": "./dist/testing.js" }, + "./intake": { + "types": "./dist/intake.d.ts", + "default": "./dist/intake.js" + }, "./package.json": "./package.json" }, "scripts": { "build": "tsc -p tsconfig.build.json", "typecheck": "tsc -p tsconfig.json --noEmit", "test": "vitest run", - "check": "pnpm typecheck && pnpm test && pnpm build && pnpm check:docs", + "check": "pnpm typecheck && pnpm test && pnpm build && pnpm check:docs && pnpm check:browser", + "check:browser": "node --experimental-vm-modules scripts/check-browser-root.mjs", "demo": "pnpm build && node --experimental-strip-types examples/demo.ts", "check:docs": "node scripts/check-snippets.mjs", "test:oracle": "vitest run -c vitest.oracle.config.ts", diff --git a/python/README.md b/python/README.md index 7bba71d..13a6f3c 100644 --- a/python/README.md +++ b/python/README.md @@ -88,6 +88,33 @@ redis-py runs each concurrent command on a pooled connection of its own, and its [DEVIATIONS.md](../DEVIATIONS.md#python-port) lists every difference. +## Serial intake + +`attend.open_intake(scope, capacity=20000)` owns preparation and immediate effects for an untouched scope. The shared [serial-intake contract](../docs/reference.md#serial-intake) defines ordering, admission, cancellation and recovery. + +```python +from aqi_attend import AbortSignal, SourceBatch, create_attend + + +async def prepare(signal: AbortSignal) -> SourceBatch: + signal.throw_if_aborted() + return {"events": [{"id": "a", "name": "message", "at": 0, "data": {}}], "cursor": "1"} + + +async def accept(): + attend = create_attend(kind={"message": "flush"}, judge=judge, sink="log") + intake = attend.open_intake("channel", capacity=100) + running = asyncio.create_task(attend.run()) + try: + await intake.submit(prepare, source="feed") + finally: + await intake.close() + await attend.stop() + await running +``` + +`submit` registers when called, before returning its future. Cancelling that future only detaches its observer; pass an `AbortSignal` to withdraw work. `close()` also fences when called, before its returned coroutine is awaited. Cancelling one close waiter does not cancel shared cleanup. Python uses `ContextVar` to reject same-scope reentrant calls. The TypeScript counterpart uses its Node-only `/intake` entry. + ## Judges `aqi_attend.judges` has `jev_judge` (TypeSafe's Jev, with your own key), `decisions_judge` (the OpenAI Decisions API) and `llm_judge`, which wraps any structured-output call you pass as `complete`. They send the same requests as the TypeScript judges, byte for byte. [Choose a judge](../docs/judges.md) explains each one, the window budget and the act threshold. diff --git a/python/src/aqi_attend/__init__.py b/python/src/aqi_attend/__init__.py index 914b25c..cadaf4c 100644 --- a/python/src/aqi_attend/__init__.py +++ b/python/src/aqi_attend/__init__.py @@ -25,12 +25,14 @@ ScopeRecord, SettlePolicy, SettleReason, + SourceBatch, Trace, Window, ) -from .errors import BackpressureError, ConflictError, OutboxFullError, PermanentError, is_permanent +from .errors import BackpressureError, ConflictError, IntakeError, OutboxFullError, PermanentError, is_permanent from .fold import EventFold, fold_events from .notice import default_notice +from .shell.intake import Intake, Prepare from .signal import AbortController, AbortSignal from .sources import EventLog, log_source, memory_log from .store.memory import memory_store @@ -54,6 +56,8 @@ "Event", "EventFold", "EventLog", + "Intake", + "IntakeError", "Judge", "JudgeBudget", "JudgeContext", @@ -63,6 +67,7 @@ "Kind", "OutboxFullError", "PermanentError", + "Prepare", "Route", "ScopeRecord", "ScopeStore", @@ -70,6 +75,7 @@ "SettleReason", "Sink", "Source", + "SourceBatch", "Trace", "Window", "create_attend", diff --git a/python/src/aqi_attend/attend.py b/python/src/aqi_attend/attend.py index f62fa31..b610e30 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -20,8 +20,11 @@ ApplyConfig, DeadLetter, Decision, + DeliveredInput, DeliveredRoute, DeliverEffect, + DeliveryFailedInput, + DeliveryReleasedInput, Effect, Event, EventsInput, @@ -29,23 +32,28 @@ InputKind, JsonObject, JudgeBudget, + JudgedInput, JudgeEffect, + JudgeFailedInput, JudgeImage, JudgeInput, + JudgeReleasedInput, Judgment, Kind, KindedEvent, OfferedRoute, + ReleasedInput, Route, ScopeRecord, SettlePolicy, SourceBatch, Trace, ) -from .errors import ConflictError, is_permanent, message_of +from .errors import ConflictError, IntakeError, is_permanent, message_of from .shell.budget import window_bytes_for from .shell.copy import copy_decision, copy_event, copy_letter, copy_window from .shell.decisions import DecisionCursorPage, read_decisions +from .shell.intake import Intake from .shell.read import read_record from .shell.scheduler import Scheduler from .shell.scope import Scopes @@ -54,6 +62,7 @@ from .store.types import DecisionKind, ScopeStore type MaybeAwaitable[T] = T | Awaitable[T] +type EffectResult = JudgedInput | JudgeFailedInput | DeliveredInput | DeliveryFailedInput | ReleasedInput class JudgeContext(TypedDict, total=False): @@ -211,7 +220,9 @@ def __init__( self._judge_concurrency = judge_concurrency self._modes: tuple[Literal["lane", "log"], Literal["lane", "log"]] = ("log" if self._sink == "log" else "lane", "log" if dead_letter == "log" else "lane") self._sources: set[AbortController] = set() - self._attached: set[str] = set() + self._attached: set[tuple[str, str]] = set() + self._intakes: dict[str, Intake] = {} + self._intake_identity = object() self._calls: dict[asyncio.Task[None], float] = {} self._releases: set[asyncio.Future[None]] = set() self._running: AbortSignal | None = None @@ -237,6 +248,25 @@ def __init__( def store(self) -> ScopeStore: return self._store + def open_intake(self, scope: str, *, capacity: int = 20_000) -> Intake: + """Own local input preparation and immediate work for an untouched scope.""" + if type(capacity) is not int or not 0 < capacity <= 9007199254740991: + raise ValueError("attend: intake capacity must be a positive safe integer") + if scope in self._intakes or self._scopes.has(scope) or any(owner == scope for owner, _ in self._attached): + raise IntakeError("attend: scope already active") + intake = Intake( + scope, + identity=self._intake_identity, + scopes=self._scopes, + clock=self._clock, + classify=self._classify, + running=lambda: self.running, + observe=self._observe, + capacity=capacity, + ) + self._intakes[scope] = intake + return intake + @property def running(self) -> bool: """True from ``run()`` until it is stopped.""" @@ -255,16 +285,22 @@ def push(self, scope: str, events: Mapping[str, Any] | Sequence[Mapping[str, Any redeliveries), ``at`` (default the clock), ``data`` (default ``{}``) and ``text``. """ try: + if scope in self._intakes: + raise IntakeError("attend: scope has exclusive intake") return self._scopes.submit(scope, {"kind": "events", "events": self._classify(events)}, True) except Exception as error: return self._failed(error) def end(self, scope: str) -> asyncio.Future[None]: """Settles the open window at the next tick, reason ``closing``, with ``wait`` still offered.""" + if scope in self._intakes: + return self._failed(IntakeError("attend: scope has exclusive intake")) return self._scopes.submit(scope, {"kind": "end"}, True) def flush(self, scope: str) -> asyncio.Future[None]: """Settles the open window at the next tick, reason ``forced``, with ``wait`` withheld.""" + if scope in self._intakes: + return self._failed(IntakeError("attend: scope has exclusive intake")) return self._scopes.submit(scope, {"kind": "flush"}, True) async def inspect(self, scope: str) -> ScopeRecord | None: @@ -342,10 +378,15 @@ def _on_due(self, scope: str) -> None: self._tick(scope) def _tick(self, scope: str) -> None: + if (intake := self._intakes.get(scope)) is not None: + intake.wake() + return self._background(scope, "tick", self._scopes.submit(scope, {"kind": "tick"})) def _background(self, scope: str, input: InputKind, future: asyncio.Future[None]) -> asyncio.Future[None]: """Observes a failure of background work as a ``failed`` trace. The returned future never fails.""" + if (intake := self._intakes.get(scope)) is not None: + intake.track_receipt(future) settled: asyncio.Future[None] = asyncio.get_running_loop().create_future() def done(f: asyncio.Future[None]) -> None: @@ -364,12 +405,21 @@ def _release(self, scope: str, release: Input) -> None: self._releases.add(released) released.add_done_callback(self._releases.discard) - def _call(self, lease_until: float, work: Awaitable[None]) -> None: - task = asyncio.ensure_future(work) + def _call(self, scope: str, lease_until: float, work: Awaitable[None]) -> None: + intake = self._intakes.get(scope) + task = asyncio.ensure_future(intake.callback(work) if intake is not None else work) self._calls[task] = lease_until task.add_done_callback(lambda t: self._calls.pop(t, None)) def _execute(self, scope: str, effect: Effect) -> None: + intake = self._intakes.get(scope) + if intake is not None and intake.closed and effect["kind"] != "trace": + if effect["kind"] == "judge": + self._release(scope, {"kind": "judgeReleased", "batchId": effect["batchId"], "attempt": effect["attempt"]}) + else: + delivery = effect["delivery"] + self._release(scope, {"kind": "deliveryReleased", "deliveryId": delivery["item"]["id"], "attempt": delivery["phase"]["attempt"]}) + return if effect["kind"] == "trace": self._observe(effect["trace"]) elif effect["kind"] == "judge": @@ -383,23 +433,35 @@ def _execute(self, scope: str, effect: Effect) -> None: ) return self._judges += 1 - controller = AbortController() - cancel = self._clock.at(self._clock.now() + self._policy["judgeTimeoutMs"], lambda: controller.abort(Exception("attend: judge timed out"))) - self._call(effect["leaseUntil"], self._run_judge(scope, effect, controller, cancel)) + controller, cancel = self._effect_controller(scope, self._clock.now() + self._policy["judgeTimeoutMs"], "attend: judge timed out") + self._call(scope, effect["leaseUntil"], self._run_judge(scope, effect, controller, cancel)) else: if self._running is None: self._release(scope, {"kind": "deliveryReleased", "deliveryId": effect["delivery"]["item"]["id"], "attempt": effect["delivery"]["phase"]["attempt"]}) return - controller = AbortController() - cancel = self._clock.at(effect["delivery"]["phase"]["leaseUntil"], lambda: controller.abort(Exception("attend: delivery timed out"))) - self._call(effect["delivery"]["phase"]["leaseUntil"], self._run_deliver(scope, effect, controller, cancel)) + controller, cancel = self._effect_controller(scope, effect["delivery"]["phase"]["leaseUntil"], "attend: delivery timed out") + self._call(scope, effect["delivery"]["phase"]["leaseUntil"], self._run_deliver(scope, effect, controller, cancel)) + + def _effect_controller(self, scope: str, deadline: float, message: str) -> tuple[AbortController, Callable[[], None]]: + controller = AbortController() + timer = self._clock.at(deadline, lambda: controller.abort(Exception(message))) + intake = self._intakes.get(scope) + remove = intake.completion_signal.add_listener(lambda: controller.abort(intake.completion_signal.reason)) if intake is not None else lambda: None + + def cancel() -> None: + timer() + remove() + + return controller, cancel async def _run_judge(self, scope: str, effect: JudgeEffect, controller: AbortController, cancel: Callable[[], None]) -> None: batch_id = effect["batchId"] attempt = effect["attempt"] signal = controller.signal - result: Input + result: JudgedInput | JudgeFailedInput | JudgeReleasedInput try: + if scope in self._intakes: + signal.throw_if_aborted() live: JudgeContext = await _maybe(self._context(scope, signal)) if self._context is not None else {} routes: list[OfferedRoute] = [] for route in effect["offered"]: @@ -417,10 +479,16 @@ async def _run_judge(self, scope: str, effect: JudgeEffect, controller: AbortCon } if self._guidance is not None: input["guidance"] = self._guidance + if scope in self._intakes: + signal.throw_if_aborted() images = await self._captured(scope, batch_id, signal) if self._capture is not None else [] if images: input["images"] = images + if scope in self._intakes: + signal.throw_if_aborted() judgment: object = await self._judge(input, signal) + if scope in self._intakes: + signal.throw_if_aborted() if _is_judgment(judgment): threshold = None if self._act_threshold is None else threshold_route(judgment, effect["offered"], self._act_threshold) if threshold is not None: @@ -429,12 +497,17 @@ async def _run_judge(self, scope: str, effect: JudgeEffect, controller: AbortCon result = {"kind": "judged", "batchId": batch_id, "attempt": attempt, "judgment": cast(Judgment, clone(chosen))} else: result = {"kind": "judgeFailed", "batchId": batch_id, "attempt": attempt, "message": "malformed judgment", "permanent": False} + except asyncio.CancelledError: + intake = self._intakes.get(scope) + if intake is None or not intake.closed: + raise + result = {"kind": "judgeReleased", "batchId": batch_id, "attempt": attempt} except Exception as error: result = {"kind": "judgeFailed", "batchId": batch_id, "attempt": attempt, "message": message_of(error), "permanent": is_permanent(error)} finally: cancel() self._judges -= 1 - await self._background(scope, "judged", self._scopes.submit(scope, result)) + await self._background(scope, "judgeReleased" if result["kind"] == "judgeReleased" else "judged", self._submit_completion(scope, result)) async def _captured(self, scope: str, batch_id: str, judge_signal: AbortSignal) -> list[JudgeImage]: capture = self._capture @@ -455,26 +528,67 @@ async def _captured(self, scope: str, batch_id: str, judge_signal: AbortSignal) async def _run_deliver(self, scope: str, effect: DeliverEffect, controller: AbortController, cancel: Callable[[], None]) -> None: item = effect["delivery"]["item"] attempt = effect["delivery"]["phase"]["attempt"] - result: Input + result: DeliveredInput | DeliveryFailedInput | DeliveryReleasedInput try: + if scope in self._intakes: + controller.signal.throw_if_aborted() sink = self._sink handler = self._dead_letter if item["kind"] == "decision" and not isinstance(sink, str): - await _maybe(sink.deliver(await copy_decision(item["decision"]), controller.signal)) + decision = await copy_decision(item["decision"]) + if scope in self._intakes: + controller.signal.throw_if_aborted() + await _maybe(sink.deliver(decision, controller.signal)) elif item["kind"] == "deadLetter" and not isinstance(handler, str): - await _maybe(handler(await copy_letter(item["letter"]), controller.signal)) + letter = await copy_letter(item["letter"]) + if scope in self._intakes: + controller.signal.throw_if_aborted() + await _maybe(handler(letter, controller.signal)) result = {"kind": "delivered", "deliveryId": item["id"], "attempt": attempt} + except asyncio.CancelledError: + intake = self._intakes.get(scope) + if intake is None or not intake.closed: + raise + result = {"kind": "deliveryReleased", "deliveryId": item["id"], "attempt": attempt} except Exception as error: result = {"kind": "deliveryFailed", "deliveryId": item["id"], "attempt": attempt, "message": message_of(error), "permanent": is_permanent(error)} finally: cancel() - await self._background(scope, "delivered", self._scopes.submit(scope, result)) + await self._background(scope, "deliveryReleased" if result["kind"] == "deliveryReleased" else "delivered", self._submit_completion(scope, result)) # ─── sources ───────────────────────────────────────────────────────────── + def _submit_completion(self, scope: str, result: EffectResult) -> asyncio.Future[None]: + if result["kind"] == "judgeReleased" or result["kind"] == "deliveryReleased": + return self._scopes.submit(scope, result) + intake = self._intakes.get(scope) + if intake is None: + return self._scopes.submit(scope, result) + release: ReleasedInput + if result["kind"] == "judged" or result["kind"] == "judgeFailed": + release = {"kind": "judgeReleased", "batchId": result["batchId"], "attempt": result["attempt"]} + else: + release = {"kind": "deliveryReleased", "deliveryId": result["deliveryId"], "attempt": result["attempt"]} + if intake.closed: + return self._scopes.submit(scope, release) + signal = intake.completion_signal + pending = self._scopes.submit(scope, result, signal=signal) + + async def finish() -> None: + try: + await pending + except BaseException as error: + if not signal.aborted or error is not signal.reason: + raise + await self._scopes.submit(scope, release) + + return asyncio.create_task(finish()) + async def attach(self, scope: str, source: Source, *, signal: AbortSignal | None = None) -> None: """Subscribes ``scope`` to ``source`` from its persisted cursor, and resubscribes after a backoff until stopped.""" - slot = f"{scope}\n{source.key}" + if scope in self._intakes: + raise IntakeError("attend: scope has exclusive intake") + slot = (scope, source.key) if slot in self._attached: raise RuntimeError(f'attend: source "{source.key}" is already attached to scope "{scope}"') self._attached.add(slot) @@ -604,6 +718,8 @@ async def _sweep(self, now: float, limit: int, warm: bool) -> None: self._observe({"kind": "failed", "scope": "*", "input": "tick", "message": message_of(error)}) def _on_abort(self) -> None: + for intake in self._intakes.values(): + intake.fence() self._running = None self._scheduler.stop() for source in list(self._sources): @@ -640,6 +756,7 @@ async def _shutdown(self) -> None: for task in list(self._calls): if not task.done(): task.cancel() + await asyncio.gather(*(intake.fence() for intake in self._intakes.values()), return_exceptions=True) async def _settled_or_expired(self, task: asyncio.Task[None], lease_until: float) -> None: if lease_until <= self._clock.now() or task.done(): diff --git a/python/src/aqi_attend/errors.py b/python/src/aqi_attend/errors.py index dbb74de..b7dd4e6 100644 --- a/python/src/aqi_attend/errors.py +++ b/python/src/aqi_attend/errors.py @@ -5,6 +5,10 @@ from .core.types import OutboxLane +class IntakeError(RuntimeError): + """An operation conflicts with an intake's local ownership or lifecycle.""" + + class PermanentError(Exception): """Raise from a judge, a sink or a source to skip retries: the judge or sink dead-letters at once, and ``attach`` stops.""" diff --git a/python/src/aqi_attend/shell/intake.py b/python/src/aqi_attend/shell/intake.py new file mode 100644 index 0000000..feb1352 --- /dev/null +++ b/python/src/aqi_attend/shell/intake.py @@ -0,0 +1,291 @@ +"""Exclusive local ordering for preparation, writes and immediate effects.""" + +from __future__ import annotations + +import asyncio +from collections import deque +from collections.abc import Awaitable, Callable, Coroutine, Sequence +from contextvars import ContextVar +from dataclasses import dataclass +from typing import Any + +from ..clock import Clock +from ..core.types import Event, EventsInput, KindedEvent, SourceBatch, Trace +from ..errors import BackpressureError, IntakeError, message_of +from ..signal import AbortController, AbortSignal +from .scope import Scopes + +type Prepare = Callable[[AbortSignal], Awaitable[SourceBatch]] +_owner: ContextVar[tuple[object, str] | None] = ContextVar("attend_intake_owner", default=None) + + +def _consume(future: asyncio.Future[None]) -> None: + if not future.cancelled(): + future.exception() + + +@dataclass(slots=True, eq=False) +class _Operation: + prepare: Prepare + source: str | None + controller: AbortController + done: asyncio.Future[None] + unlink: Callable[[], None] + release_capacity: Callable[[], None] + + +@dataclass(slots=True) +class _Activity: + """None identifies a timer operation; either kind owns a completion barrier.""" + + operation: _Operation | None + finished: asyncio.Future[None] + failure: BaseException | None = None + + +class Intake: + """Registers raw preparation in order and awaits its immediate causal work.""" + + def __init__( + self, + scope: str, + *, + identity: object, + scopes: Scopes, + clock: Clock, + classify: Callable[[Sequence[Event]], list[KindedEvent]], + running: Callable[[], bool], + observe: Callable[[Trace], None], + capacity: int, + ) -> None: + self.scope = scope + self._identity = identity + self._scopes = scopes + self._clock = clock + self._classify = classify + self._running = running + self._observe = observe + self._capacity = capacity + self._queue: deque[_Operation] = deque() + self._active: _Activity | None = None + self._timer_pending = False + self._work = 0 + self._work_done = asyncio.Event() + self._work_done.set() + self._closed: asyncio.Future[None] | None = None + self._tasks: set[asyncio.Task[None]] = set() + self._completion = AbortController() + + @property + def closed(self) -> bool: + return self._closed is not None + + @property + def completion_signal(self) -> AbortSignal: + return self._completion.signal + + def _check_context(self) -> None: + if _owner.get() == (self._identity, self.scope): + raise IntakeError("attend: cannot await this intake from its own callback") + + def submit(self, prepare: Prepare, *, source: str | None = None, signal: AbortSignal | None = None) -> asyncio.Future[None]: + """Register before returning. Cancelling the returned future only detaches its observer.""" + self._check_context() + if self.closed: + raise IntakeError("attend: intake closed") + if not self._running(): + raise IntakeError("attend: intake requires a running engine") + pending = len(self._queue) + int(self._active is not None and self._active.operation is not None) + if pending >= self._capacity: + raise BackpressureError(100, pending) + controller = AbortController() + unlink = signal.add_listener(lambda: controller.abort(signal.reason)) if signal is not None else lambda: None + try: + controller.signal.throw_if_aborted() + release_capacity = self._scopes.reserve_input() + except BaseException: + unlink() + raise + done: asyncio.Future[None] = asyncio.get_running_loop().create_future() + done.add_done_callback(_consume) + operation = _Operation(prepare, source, controller, done, unlink, release_capacity) + self._queue.append(operation) + + def withdraw() -> None: + if operation in self._queue: + self._queue.remove(operation) + operation.unlink() + operation.release_capacity() + if not done.done(): + reason = controller.signal.reason + assert reason is not None + done.set_exception(reason) + + controller.signal.add_listener(withdraw) + self._pump() + return done + + def wake(self) -> None: + if not self.closed: + self._timer_pending = True + self._pump() + + def _spawn(self, work: Coroutine[Any, Any, None]) -> None: + def start() -> None: + task = asyncio.create_task(work) + self._tasks.add(task) + task.add_done_callback(self._tasks.discard) + task.add_done_callback(_consume) + + asyncio.get_running_loop().call_soon(start) + + def _pump(self) -> None: + if self.closed or self._active is not None: + return + operation = self._queue.popleft() if self._queue else None + if operation is None: + if not self._timer_pending: + return + self._timer_pending = False + due = self._scopes.due(self.scope) + if due is None or due > self._clock.now(): + return + activity = _Activity(operation, asyncio.get_running_loop().create_future()) + self._active = activity + self._spawn(self._perform(activity)) + + async def _settle(self, activity: _Activity) -> None: + try: + await self._scopes.submit(self.scope, {"kind": "tick"}) + except BaseException as error: + activity.failure = error + raise + await self._work_done.wait() + if activity.failure is not None: + raise activity.failure + + async def _perform(self, activity: _Activity) -> None: + token = _owner.set((self._identity, self.scope)) + operation = activity.operation + try: + if operation is None: + await self._settle(activity) + return + signal = operation.controller.signal + signal.throw_if_aborted() + batch = await signal.race(operation.prepare(signal)) + signal.throw_if_aborted() + events = self._classify(batch["events"]) + input: EventsInput = {"kind": "events", "events": events} + if operation.source is not None: + input["source"] = operation.source + if "cursor" in batch: + input["cursor"] = batch["cursor"] + if batch.get("truncated"): + input["truncated"] = True + # Transfer this slot to Scopes synchronously; it must not be charged twice. + operation.release_capacity() + try: + await self._scopes.submit(self.scope, input, True, signal, catch_up=False) + except BaseException as error: + if not signal.aborted: + activity.failure = error + raise + if events: + await self._settle(activity) + if not operation.done.done(): + operation.done.set_result(None) + except BaseException as error: + if operation is not None: + if not operation.done.done(): + operation.done.set_exception(error) + elif not isinstance(error, asyncio.CancelledError): + self._observe({"kind": "failed", "scope": self.scope, "input": "tick", "message": message_of(error)}) + finally: + if operation is not None: + operation.unlink() + operation.release_capacity() + _owner.reset(token) + self._active = None + activity.finished.set_result(None) + self._pump() + + def _begin_work(self) -> _Activity | None: + self._work += 1 + self._work_done.clear() + return self._active + + def _end_work(self, activity: _Activity | None, error: BaseException | None = None) -> None: + if activity is not None and error is not None and activity.failure is None: + activity.failure = error + self._work -= 1 + if self._work == 0: + self._work_done.set() + + def track_receipt(self, future: asyncio.Future[None]) -> None: + """Internal writes without user callbacks still belong to the causal chain.""" + activity = self._begin_work() + + def finished(done: asyncio.Future[None]) -> None: + error = asyncio.CancelledError() if done.cancelled() else done.exception() + self._end_work(activity, error) + + future.add_done_callback(finished) + + def callback(self, work: Awaitable[None]) -> Coroutine[Any, Any, None]: + activity = self._begin_work() + + async def run() -> None: + token = _owner.set((self._identity, self.scope)) + error: BaseException | None = None + try: + await work + except BaseException as failed: + if not self.closed: + error = failed + raise + finally: + _owner.reset(token) + self._end_work(activity, error) + + return run() + + def fence(self) -> asyncio.Future[None]: + """Fence before returning; engine shutdown may call this from an owned callback.""" + if self._closed is not None: + return self._closed + future: asyncio.Future[None] = asyncio.get_running_loop().create_future() + future.add_done_callback(_consume) + self._closed = future + self._timer_pending = False + reason = IntakeError("attend: intake closed") + self._completion.abort(reason) + for operation in list(self._queue): + operation.controller.abort(reason) + activity = self._active + if activity is not None and activity.operation is not None: + activity.operation.controller.abort(reason) + + async def join() -> None: + try: + if activity is not None: + await activity.finished + await self._work_done.wait() + if activity is not None and activity.failure is not None: + raise activity.failure + future.set_result(None) + except BaseException as error: + future.set_exception(error) + + self._spawn(join()) + return future + + def close(self) -> Coroutine[Any, Any, None]: + """Stop new admission and join owned work. This does not resolve future retries.""" + self._check_context() + future = self.fence() + + async def wait() -> None: + await asyncio.shield(future) + + return wait() diff --git a/python/src/aqi_attend/shell/scope.py b/python/src/aqi_attend/shell/scope.py index 8a0c618..a59ae91 100644 --- a/python/src/aqi_attend/shell/scope.py +++ b/python/src/aqi_attend/shell/scope.py @@ -44,6 +44,7 @@ class RawInput: done: asyncio.Future[None] count: int = 1 conflicts: int = 0 + catch_up: bool = True def resolve(self) -> None: if not self.done.done(): @@ -146,6 +147,7 @@ def __init__( self._staged: dict[ScopeSlot, None] = {} self._pending: set[asyncio.Future[None]] = set() self._queued = 0 + self._reserved = 0 self._committing = False self._scheduled = False self._tasks: set[asyncio.Task[None]] = set() @@ -277,9 +279,13 @@ def _apply_raw(self, slot: ScopeSlot, raw: RawInput) -> None: state = slot.state assert state is not None slot.last_touch = self._clock.now() + if raw.signal is not None and raw.signal.aborted: + reason = raw.signal.reason + assert reason is not None + self._reject(raw, reason) + self._request_flush() + return try: - if raw.signal is not None: - raw.signal.throw_if_aborted() input = raw.input policy = self._config.policy if input["kind"] == "events" and input["events"]: @@ -288,7 +294,7 @@ def _apply_raw(self, slot: ScopeSlot, raw: RawInput) -> None: if len(state.dead_letters) >= policy["maxDeadLetters"]: raise OutboxFullError(slot.scope, "deadLetters", len(state.dead_letters)) now = self._clock.now() - if self._running() and input["kind"] in ("events", "flush", "end") and state.due_at is not None and state.due_at < now: + if raw.catch_up and self._running() and input["kind"] in ("events", "flush", "end") and state.due_at is not None and state.due_at < now: self._transition(slot, state, {"kind": "tick"}, now) current = self._transition(slot, state, input, now) if current is not None: @@ -315,6 +321,35 @@ def _pump(self, slot: ScopeSlot) -> None: self._queued -= raw.count self._apply_raw(slot, raw) + def _admission_error(self) -> BackpressureError | None: + lag = self._scheduler.lag_ms() + queued = self._queued + self._reserved + over_queue = queued >= self._max_queued + over_lag = self._max_lag_ms is not None and lag > self._max_lag_ms + if not over_queue and not over_lag: + return None + self._observe({"kind": "backpressure", "queued": queued, "lagMs": lag}) + return BackpressureError(math.ceil(lag) if over_lag else 100, queued) + + def reserve_input(self) -> Callable[[], None]: + """Hold one engine-wide pending slot until preparation transfers it or aborts.""" + error = self._admission_error() + if error is not None: + raise error + self._reserved += 1 + released = False + + def release() -> None: + nonlocal released + if not released: + released = True + self._reserved -= 1 + + return release + + def has(self, scope: str) -> bool: + return scope in self._slots + def submit( self, scope: str, @@ -322,15 +357,13 @@ def submit( external: bool = False, signal: AbortSignal | None = None, reject_hook: Callable[[BaseException], None] | None = None, + *, + catch_up: bool = True, ) -> asyncio.Future[None]: loop = asyncio.get_running_loop() if external: - lag = self._scheduler.lag_ms() - over_queue = self._queued >= self._max_queued - over_lag = self._max_lag_ms is not None and lag > self._max_lag_ms - if over_queue or over_lag: - error = BackpressureError(math.ceil(lag) if over_lag else 100, self._queued) - self._observe({"kind": "backpressure", "queued": self._queued, "lagMs": lag}) + error = self._admission_error() + if error is not None: if reject_hook is not None: reject_hook(error) failed: asyncio.Future[None] = loop.create_future() @@ -339,7 +372,14 @@ def submit( return failed slot = self._slot_for(scope) last = slot.queued[-1] if slot.queued else None - if last is not None and input["kind"] == "events" and last.input["kind"] == "events" and last.input.get("source") == input.get("source") and last.signal is signal: + if ( + last is not None + and input["kind"] == "events" + and last.input["kind"] == "events" + and last.input.get("source") == input.get("source") + and last.signal is signal + and last.catch_up == catch_up + ): merged: EventsInput = last.input merged["events"].extend(input["events"]) if "cursor" in input: @@ -353,7 +393,7 @@ def submit( return _follow(last.done) done: asyncio.Future[None] = loop.create_future() done.add_done_callback(_consume) - raw = RawInput(input, signal, reject_hook, done) + raw = RawInput(input, signal, reject_hook, done, catch_up=catch_up) self._pending.add(done) done.add_done_callback(self._pending.discard) slot.queued.append(raw) diff --git a/python/tests/interop/attend-ts.mjs b/python/tests/interop/attend-ts.mjs index ff8afc7..f51d4d7 100644 --- a/python/tests/interop/attend-ts.mjs +++ b/python/tests/interop/attend-ts.mjs @@ -1,10 +1,11 @@ // The TypeScript half of python/tests/test_interop.py. Runs the built package in dist/ over the same Redis or // Postgres the Python test uses. Usage: node attend-ts.mjs import { createAttend } from '../../../dist/index.js'; +import { openIntake } from '../../../dist/intake.js'; import { fakeClock } from '../../../dist/testing.js'; const [kind, url, prefix, mode, scope] = process.argv.slice(2); -const kinds = { close: 'closing', say: 'flush', look: 'passive', out: 'consequence' }; +const kinds = { close: 'closing', say: 'flush', look: 'passive', out: 'consequence', move: 'continuous' }; const judge = async ({ window, routes }) => ({ route: window.events.some((e) => e.name === 'look') && routes.some((r) => r.route === 'wait') ? 'wait' : 'interrupt' }); const delivered = []; @@ -27,9 +28,15 @@ if (kind === 'redis') { const clock = fakeClock(10_000); const attend = createAttend({ store, clock, kind: kinds, judge, sink: (d) => { delivered.push(d.id); }, settle: { closingGraceMs: 100 } }); +const intake = mode === 'intake-write' ? openIntake(attend, scope) : null; const controller = new AbortController(); const running = attend.run({ signal: controller.signal, sweepMs: 60_000 }); -if (mode === 'write') { +if (intake) { + await intake.submit(async () => ({ events: [{ id: 'raw-a', name: 'move', at: 10_000, data: {}, text: 'x'.repeat(2000) }], cursor: '1' }), { source: 'feed' }); + await intake.submit(async () => ({ events: [], cursor: '2' }), { source: 'feed' }); + await intake.submit(async () => ({ events: [{ id: 'raw-b', name: 'move', at: 10_000, data: {} }], cursor: '3' }), { source: 'feed' }); + await intake.close(); +} else if (mode === 'write') { await attend.push(scope, [{ id: 'a', name: 'close', text: 'close a' }, { id: 'b', name: 'out', data: { n: 1.5, s: 'ünï 🌍' } }]); await clock.advance(100); // The store does real I/O, which advancing the fake clock does not wait for. @@ -39,6 +46,12 @@ if (mode === 'write') { await attend.push(scope, [{ id: 'd', name: 'out', text: 'out d' }]); } else if (mode === 'pending') { await attend.push(scope, [{ id: 'p', name: 'close', text: 'close p' }]); +} else if (mode === 'continue') { + await attend.push(scope, [{ id: 'e', name: 'say', text: 'say e' }]); + for (let i = 0; i < 500 && delivered.length === 0; i += 1) { + await clock.advance(0); + await new Promise((resolve) => setTimeout(resolve, 5)); + } } controller.abort(); await running; diff --git a/python/tests/scenario.py b/python/tests/scenario.py index b7c1782..68eece7 100644 --- a/python/tests/scenario.py +++ b/python/tests/scenario.py @@ -10,14 +10,26 @@ from aqi_attend import PermanentError, create_attend, memory_store from aqi_attend._json import stable_json from aqi_attend.attend import JudgeContext -from aqi_attend.clock import drain -from aqi_attend.core.types import DeadLetter, Decision, JudgeImage, JudgeInput, Judgment, Trace +from aqi_attend.clock import drain, sleep +from aqi_attend.core.types import DeadLetter, Decision, Event, JudgeImage, JudgeInput, Judgment, SourceBatch, Trace from aqi_attend.errors import message_of, name_of from aqi_attend.signal import AbortController, AbortSignal from aqi_attend.testing import fake_clock UNCOMPARED_TRACES = {"backpressure"} + +def event_spec(spec: Mapping[str, Any]) -> Event: + event: Event = {"id": spec["id"], "at": spec.get("at", 0), "name": spec["name"], "data": spec.get("data", {})} + if "text" in spec: + event["text"] = spec["text"] + if "observedAt" in spec: + event["observedAt"] = spec["observedAt"] + if "quietForMs" in spec: + event["quietForMs"] = spec["quietForMs"] + return event + + _SETTLE = { "closingGraceMs": "closing_grace_ms", "streamGapMs": "stream_gap_ms", @@ -233,10 +245,12 @@ async def capture(scope: str, signal: AbortSignal) -> JudgeImage | list[JudgeIma observe=observe, **options, ) + intakes = {scope: attend.open_intake(scope) for scope in scenario.get("intakes", [])} + receipts: list[asyncio.Task[None]] = [] controller = AbortController() running = asyncio.ensure_future(attend.run(signal=controller.signal, sweep_ms=scenario.get("sweepMs", 1000))) await drain() - scopes: set[str] = set() + scopes: set[str] = set(scenario.get("intakes", [])) async def result(index: int, work: asyncio.Future[None]) -> None: try: @@ -246,21 +260,34 @@ async def result(index: int, work: asyncio.Future[None]) -> None: observed["results"].append({"step": index, "error": {"name": name_of(error), "message": message_of(error)}}) for index, step in enumerate(scenario["steps"]): - if "push" in step: - scopes.add(step["push"]) - events = [ - { - "id": e["id"], - "at": e.get("at", 0), - "name": e["name"], - "data": e.get("data", {}), - **({"text": e["text"]} if "text" in e else {}), - **({"observedAt": e["observedAt"]} if "observedAt" in e else {}), - **({"quietForMs": e["quietForMs"]} if "quietForMs" in e else {}), - } - for e in step["events"] - ] - await result(index, attend.push(step["push"], events)) + if "push" in step or "submit" in step: + scope = step.get("push", step.get("submit")) + scopes.add(scope) + events = [event_spec(event) for event in step["events"]] + if "push" in step: + await result(index, attend.push(scope, events)) + else: + source_batch: SourceBatch = {"events": events} + if "cursor" in step: + source_batch["cursor"] = step["cursor"] + + async def prepare( + signal: AbortSignal, batch: SourceBatch = source_batch, delay: float = step.get("prepareMs", 0), fail: str | None = step.get("prepareFail") + ) -> SourceBatch: + if delay: + await sleep(clock, delay, signal) + if fail is not None: + raise Exception(fail) + return batch + + try: + receipt = intakes[scope].submit(prepare, source=step.get("source")) + except Exception as error: + receipt = loop.create_future() + receipt.set_exception(error) + receipts.append(asyncio.create_task(result(index, receipt))) + elif "closeIntake" in step: + receipts.append(asyncio.create_task(result(index, asyncio.ensure_future(intakes[step["closeIntake"]].close())))) elif "advance" in step: await clock.advance(step["advance"]) elif "flush" in step: @@ -281,6 +308,7 @@ async def result(index: int, work: asyncio.Future[None]) -> None: await drain() controller.abort() await running + await asyncio.gather(*receipts) for scope in sorted(scopes, key=lambda s: s.encode("utf-16-be", "surrogatepass")): observed["records"][scope] = plain(await attend.inspect(scope)) observed["log"] = plain((await store.log.read({"after": None, "limit": 10_000}))["rows"]) diff --git a/python/tests/test_intake.py b/python/tests/test_intake.py new file mode 100644 index 0000000..306e8e3 --- /dev/null +++ b/python/tests/test_intake.py @@ -0,0 +1,824 @@ +"""Local intake owns raw ordering before preparation can yield.""" + +import asyncio +from collections.abc import Awaitable, Callable, Sequence +from dataclasses import dataclass + +import pytest + +from aqi_attend import AbortController, AbortSignal, BackpressureError, Decision, IntakeError, JudgeInput, Judgment, create_attend +from aqi_attend.clock import drain +from aqi_attend.core.types import SourceBatch +from aqi_attend.signal import AbortError +from aqi_attend.store.memory import MemoryStore +from aqi_attend.store.types import CommitOutcome, ScopeWrite +from aqi_attend.testing import fake_clock, scripted_judge + + +def batch(id: str, at: float = 0, quiet: float = 100) -> SourceBatch: + return {"events": [{"id": id, "name": "move", "at": at, "observedAt": at, "quietForMs": quiet, "data": {}}]} + + +async def test_preparation_owns_timer_and_registered_backlog() -> None: + clock = fake_clock() + judge = scripted_judge([{"route": "queue"}]) + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=judge, sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def first(signal: AbortSignal) -> SourceBatch: + return batch("a") + + await intake.submit(first) + await clock.advance(90) + release = asyncio.Event() + + async def filtered(signal: AbortSignal) -> SourceBatch: + await release.wait() + return {"events": [], "cursor": "1"} + + filtering = intake.submit(filtered, source="feed") + await clock.advance(5) + + async def later(signal: AbortSignal) -> SourceBatch: + return batch("b", 95, 300) + + queued = intake.submit(later) + await clock.advance(195) + assert judge.calls == [] + release.set() + await filtering + await queued + assert judge.calls == [] + await clock.advance(105) + assert [call["window"]["settledAt"] for call in judge.calls] == [395] + assert [event["id"] for event in judge.calls[0]["window"]["events"]] == ["a", "b"] + record = await attend.inspect("s") + assert record is not None and record["cursors"] == {"feed": "1"} + finally: + await intake.close() + await attend.stop() + await running + + +async def test_raw_arrivals_wait_for_judgment_and_delivery() -> None: + clock = fake_clock() + started = asyncio.Event() + release = asyncio.Event() + sink_started = asyncio.Event() + sink_release = asyncio.Event() + offers: list[tuple[float, list[str]]] = [] + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + offers.append((clock.now(), [event["id"] for event in input["window"]["events"]])) + if len(offers) == 1: + started.set() + await release.wait() + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + if decision["window"]["events"][0]["id"] == "a": + sink_started.set() + await sink_release.wait() + + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=judge, sink=sink) + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + prepared: list[str] = [] + try: + + async def first(signal: AbortSignal) -> SourceBatch: + return batch("a") + + await intake.submit(first) + await clock.advance(100) + await started.wait() + await clock.advance(50) + + async def second(signal: AbortSignal) -> SourceBatch: + prepared.append("b") + return batch("b", 150) + + pending = intake.submit(second) + release.set() + await clock.advance(0) + await sink_started.wait() + await clock.advance(550) + assert prepared == [] + sink_release.set() + await pending + assert offers == [(100, ["a"]), (700, ["b"])] + finally: + release.set() + sink_release.set() + await intake.close() + await attend.stop() + await running + + +async def test_abort_before_callback_and_owned_scope_refusal() -> None: + clock = fake_clock() + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + called: list[bool] = [] + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + called.append(True) + return batch("a") + + controller = AbortController() + pending = intake.submit(prepare, signal=controller.signal) + controller.abort() + with pytest.raises(AbortError): + await pending + assert called == [] + assert await attend.inspect("s") is None + with pytest.raises(Exception, match="intake"): + await attend.push("s", {"id": "other", "name": "move"}) + with pytest.raises(IntakeError): + await attend.end("s") + with pytest.raises(IntakeError): + await attend.flush("s") + + class RefusedSource: + key = "feed" + + async def subscribe(self, cursor: str | None, emit: Callable[[SourceBatch], Awaitable[None]], signal: AbortSignal, /) -> None: + raise AssertionError("must not subscribe") + + with pytest.raises(IntakeError): + await attend.attach("s", RefusedSource()) + with pytest.raises(IntakeError, match="already active"): + attend.open_intake("s") + finally: + await intake.close() + await attend.stop() + await running + + +async def test_queued_abort_refunds_its_reservation_without_preparing() -> None: + attend = create_attend(clock=fake_clock(), max_queued_inputs=2, kind={}, judge=scripted_judge([]), sink="log") + intake = attend.open_intake("s") + started, release = asyncio.Event(), asyncio.Event() + called: list[bool] = [] + + async def first(signal: AbortSignal) -> SourceBatch: + started.set() + await release.wait() + return {"events": []} + + async def second(signal: AbortSignal) -> SourceBatch: + called.append(True) + return {"events": [], "cursor": "bad"} + + with pytest.raises(IntakeError, match="running"): + intake.submit(first) + running = asyncio.create_task(attend.run()) + try: + pending = intake.submit(first) + await started.wait() + controller = AbortController() + queued = intake.submit(second, source="feed", signal=controller.signal) + controller.abort() + with pytest.raises(AbortError): + await queued + await attend.push("other", {"id": "c", "name": "output"}) + release.set() + await pending + assert not called + record = await attend.inspect("s") + assert record is None or record["cursors"] == {} + with pytest.raises(IntakeError, match="already active"): + attend.open_intake("other") + finally: + release.set() + await intake.close() + await attend.stop() + await running + + +@dataclass +class Timer: + at: float + callback: Callable[[], None] + cancelled: bool = False + + +class ManualClock: + def __init__(self) -> None: + self.time: float = 0 + self.timers: list[Timer] = [] + + def now(self) -> float: + return self.time + + def at(self, at: float, fn: Callable[[], None]) -> Callable[[], None]: + timer = Timer(at, fn) + self.timers.append(timer) + + def cancel() -> None: + timer.cancelled = True + + return cancel + + def fire(self, at: float) -> None: + self.time = at + for timer in sorted([t for t in self.timers if not t.cancelled and t.at <= at], key=lambda t: t.at): + timer.cancelled = True + timer.callback() + + +class GatedStore(MemoryStore): + def __init__(self) -> None: + super().__init__() + self.gates: dict[str, asyncio.Event] = {} + self.entered: dict[str, asyncio.Event] = {} + + def hold(self, kind: str) -> None: + self.gates[kind] = asyncio.Event() + self.entered[kind] = asyncio.Event() + + def release_all(self) -> None: + for gate in self.gates.values(): + gate.set() + + async def commit(self, writes: Sequence[ScopeWrite]) -> list[CommitOutcome]: + for write in writes: + for logged in write["inputs"]: + kind = logged["input"]["kind"] + if kind in self.gates and not self.gates[kind].is_set(): + self.entered[kind].set() + await self.gates[kind].wait() + return await super().commit(writes) + + +async def test_timer_claims_intake_before_its_commit() -> None: + clock = ManualClock() + first_result = asyncio.Event() + first_delivery = asyncio.Event() + calls: list[tuple[float, str]] = [] + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + id = input["window"]["events"][0]["id"] + calls.append((clock.now(), id)) + if id == "a": + await first_result.wait() + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + if decision["window"]["events"][0]["id"] == "a": + await first_delivery.wait() + + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=judge, sink=sink) + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run(sweep_ms=10**12)) + prepared: list[float] = [] + try: + + async def first(signal: AbortSignal) -> SourceBatch: + return batch("a") + + await intake.submit(first) + clock.fire(100) + stored = await attend.inspect("s") + assert stored is not None and stored["batch"] is None + + async def second(signal: AbortSignal) -> SourceBatch: + prepared.append(clock.now()) + return batch("b", 100) + + pending = intake.submit(second) + await drain() + assert calls == [(100, "a")] + clock.fire(150) + first_result.set() + await drain() + clock.fire(200) + await drain() + assert prepared == [] and calls == [(100, "a")] + clock.fire(700) + first_delivery.set() + await pending + assert prepared == [700] and calls == [(100, "a"), (700, "b")] + finally: + first_result.set() + first_delivery.set() + await attend.stop() + await running + + +@pytest.mark.parametrize("timer", [False, True]) +async def test_close_and_receipt_wait_for_release_commit(timer: bool) -> None: + store = GatedStore() + clock = fake_clock() + judge = scripted_judge([{"route": "queue"}]) + attend = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=judge, sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run(sweep_ms=10**12)) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=100 if timer else 0) + + store.hold("judgeReleased") + if timer: + await intake.submit(prepare) + store.hold("tick") + await clock.advance(100) + receipt = None + held = "tick" + else: + store.hold("events") + receipt = intake.submit(prepare) + held = "events" + await store.entered[held].wait() + closed = asyncio.create_task(intake.close()) + store.gates[held].set() + await store.entered["judgeReleased"].wait() + await drain() + assert not closed.done() + assert receipt is None or not receipt.done() + assert judge.calls == [] + store.gates["judgeReleased"].set() + await closed + if receipt is not None: + await receipt + record = await attend.inspect("s") + assert record is not None and record["batch"] is not None and record["batch"]["phase"]["phase"] == "retrying" + finally: + store.release_all() + await attend.stop() + await running + + +async def test_deferral_commit_belongs_to_the_receipt_but_future_retry_does_not() -> None: + store = GatedStore() + store.hold("judgeDeferred") + clock = fake_clock() + started, release = asyncio.Event(), asyncio.Event() + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + started.set() + await release.wait() + return {"route": "skip"} + + attend = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=judge, sink="log", judge_concurrency=1) + first, second = attend.open_intake("first"), attend.open_intake("second") + running = asyncio.create_task(attend.run(sweep_ms=10**12)) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=0) + + one = first.submit(prepare) + await started.wait() + two = second.submit(prepare) + await store.entered["judgeDeferred"].wait() + await drain() + assert not two.done() + store.gates["judgeDeferred"].set() + await two + record = await attend.inspect("second") + assert record is not None and record["batch"] is not None and record["batch"]["phase"]["phase"] == "retrying" + assert not one.done() + finally: + store.release_all() + release.set() + await attend.stop() + await running + + +async def test_normal_result_queued_before_close_is_fenced_until_application() -> None: + store = GatedStore() + store.hold("delivered") + clock = fake_clock() + release_b, returned_b = asyncio.Event(), asyncio.Event() + deliveries = 0 + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + if input["window"]["events"][0]["id"] == "b": + await release_b.wait() + returned_b.set() + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + nonlocal deliveries + deliveries += 1 + if deliveries == 1: + raise RuntimeError("controlled failure") + + attend = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=judge, sink=sink, settle={"retry_backoff_ms": [1000]}) + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run(sweep_ms=10**12)) + try: + + async def first(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=0) + + async def second(signal: AbortSignal) -> SourceBatch: + return batch("b", quiet=1000) + + await intake.submit(first) + await intake.submit(second) + await clock.advance(1000) + await store.entered["delivered"].wait() + release_b.set() + await returned_b.wait() + closed = asyncio.create_task(intake.close()) + await clock.advance(10) + store.gates["delivered"].set() + await closed + record = await attend.inspect("s") + assert record is not None and record["batch"] is not None and record["batch"]["phase"]["phase"] == "retrying" + assert record["outbox"]["decisions"] == [] and len(record["recent"]) == 1 + finally: + store.release_all() + release_b.set() + await attend.stop() + await running + + +async def test_engine_budget_reserves_preparation_and_refunds_cancellation() -> None: + clock = fake_clock() + attend = create_attend(clock=clock, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log", max_queued_inputs=1) + first, second = attend.open_intake("first"), attend.open_intake("second") + running = asyncio.create_task(attend.run()) + release = asyncio.Event() + controller = AbortController() + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + await release.wait() + return batch("a") + + pending = first.submit(prepare, signal=controller.signal) + with pytest.raises(BackpressureError): + second.submit(prepare) + with pytest.raises(BackpressureError): + await attend.push("ordinary", {"id": "ordinary", "name": "move"}) + controller.abort() + with pytest.raises(AbortError): + await pending + release.set() + await second.submit(prepare) + await attend.push("ordinary", {"id": "ordinary", "name": "move"}) + finally: + release.set() + await attend.stop() + await running + + +@pytest.mark.parametrize("during", ["prepare", "judge", "sink"]) +async def test_same_scope_reentrancy_refuses_without_deadlock(during: str) -> None: + refused: list[str] = [] + + async def nested(signal: AbortSignal) -> SourceBatch: + return batch("nested") + + def attempt() -> None: + with pytest.raises(IntakeError, match="own callback"): + intake.submit(nested) + with pytest.raises(IntakeError, match="own callback"): + _closed = intake.close() + refused.append(during) + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + if during == "judge": + attempt() + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + if during == "sink": + attempt() + + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=judge, sink=sink) + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + if during == "prepare": + attempt() + return batch("a", quiet=0) + + await intake.submit(prepare) + assert refused == [during] + finally: + await attend.stop() + await running + + +async def test_preparation_failure_keeps_cursor_and_allows_next_registration() -> None: + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def failed(signal: AbortSignal) -> SourceBatch: + raise ValueError("controlled preparation failure") + + with pytest.raises(ValueError, match="controlled preparation"): + await intake.submit(failed, source="feed") + assert await attend.inspect("s") is None + + async def filtered(signal: AbortSignal) -> SourceBatch: + return {"events": [], "cursor": "2"} + + await intake.submit(filtered, source="feed") + record = await attend.inspect("s") + assert record is not None and record["cursors"] == {"feed": "2"} + finally: + await attend.stop() + await running + + +async def test_observer_cancellation_does_not_withdraw_registered_input() -> None: + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + release = asyncio.Event() + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + await release.wait() + return batch("a") + + receipt = intake.submit(prepare) + receipt.cancel() + release.set() + await drain() + record = await attend.inspect("s") + assert record is not None and record["seen"] == ["a"] + finally: + release.set() + await attend.stop() + await running + + +async def test_close_during_load_refuses_unapplied_input() -> None: + entered, release = asyncio.Event(), asyncio.Event() + + class Store(MemoryStore): + async def load(self, scope: str): + entered.set() + await release.wait() + return await super().load(scope) + + attend = create_attend(store=Store(), clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a") + + pending = intake.submit(prepare) + await entered.wait() + closed = asyncio.create_task(intake.close()) + release.set() + await closed + with pytest.raises(IntakeError, match="closed"): + await pending + assert await attend.inspect("s") is None + finally: + release.set() + await attend.stop() + await running + + +async def test_applied_prefix_can_commit_after_close() -> None: + store = GatedStore() + store.hold("events") + clock = fake_clock() + attend = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a") + + pending = intake.submit(prepare) + await store.entered["events"].wait() + await clock.advance(10) + closed = asyncio.create_task(intake.close()) + await clock.advance(10) + store.release_all() + await pending + await closed + record = await attend.inspect("s") + assert record is not None and record["buffer"]["entries"][0]["seenAt"] == 0 + finally: + store.release_all() + await attend.stop() + await running + + +async def test_internal_write_failure_rejects_the_operation_without_undoing_input() -> None: + class Store(MemoryStore): + async def commit(self, writes: Sequence[ScopeWrite]) -> list[CommitOutcome]: + if any(logged["input"]["kind"] == "judged" for write in writes for logged in write["inputs"]): + raise RuntimeError("controlled completion failure") + return await super().commit(writes) + + attend = create_attend(store=Store(), clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=0) + + with pytest.raises(RuntimeError, match="controlled completion"): + await intake.submit(prepare) + record = await attend.inspect("s") + assert record is not None and record["seen"] == ["a"] and record["recent"] == [] + finally: + await attend.stop() + await running + + +async def test_retained_store_recreation_resumes_native_release() -> None: + store = MemoryStore() + clock = fake_clock() + release = asyncio.Event() + entered = asyncio.Event() + + async def held(input: JudgeInput, signal: AbortSignal) -> Judgment: + entered.set() + await release.wait() + return {"route": "queue"} + + first = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=held, sink="log") + intake = first.open_intake("s") + run_first = asyncio.create_task(first.run()) + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=0) + + receipt = intake.submit(prepare) + await entered.wait() + close = asyncio.create_task(intake.close()) + release.set() + await close + await receipt + await first.stop() + await run_first + judge = scripted_judge([{"route": "queue"}]) + second = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=judge, sink="log") + second.open_intake("s") + run_second = asyncio.create_task(second.run()) + try: + await clock.advance(0) + assert [event["id"] for event in judge.calls[0]["window"]["events"]] == ["a"] + record = await second.inspect("s") + assert record is not None and record["batch"] is None and record["recent"][0]["route"] == "queue" + finally: + await second.stop() + await run_second + + +async def test_late_preparation_cannot_admit_after_withdrawal() -> None: + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + started, release, returned = asyncio.Event(), asyncio.Event(), asyncio.Event() + controller = AbortController() + try: + + async def late(signal: AbortSignal) -> SourceBatch: + started.set() + try: + await release.wait() + except asyncio.CancelledError: + await release.wait() + returned.set() + return batch("late") + + pending = intake.submit(late, signal=controller.signal) + await started.wait() + controller.abort() + with pytest.raises(AbortError): + await pending + await intake.close() + release.set() + await returned.wait() + await drain() + assert await attend.inspect("s") is None + finally: + release.set() + await attend.stop() + await running + + +async def test_other_owned_scope_progresses_during_preparation() -> None: + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + first, second = attend.open_intake("first"), attend.open_intake("second") + running = asyncio.create_task(attend.run()) + release = asyncio.Event() + try: + + async def blocked(signal: AbortSignal) -> SourceBatch: + await release.wait() + return batch("a") + + async def immediate(signal: AbortSignal) -> SourceBatch: + return batch("b", quiet=0) + + pending = first.submit(blocked) + await second.submit(immediate) + assert not pending.done() + record = await attend.inspect("second") + assert record is not None and record["recent"][0]["route"] == "queue" + release.set() + await pending + finally: + release.set() + await attend.stop() + await running + + +@pytest.mark.parametrize("capacity", [0, -1, True, 2**53]) +def test_capacity_is_a_positive_portable_integer(capacity: int) -> None: + attend = create_attend(clock=fake_clock(), kind={"move": "continuous"}, judge=scripted_judge([{"route": "queue"}]), sink="log") + with pytest.raises(ValueError, match="capacity"): + attend.open_intake("s", capacity=capacity) + + +@pytest.mark.parametrize("during", ["judge", "sink"]) +async def test_cancelled_error_on_close_releases_for_immediate_recovery(during: str) -> None: + clock, store, entered = fake_clock(), MemoryStore(), asyncio.Event() + + async def cancel(signal: AbortSignal) -> None: + entered.set() + await signal.wait() + raise asyncio.CancelledError + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + if during == "judge": + await cancel(signal) + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + await cancel(signal) + + async def prepare(signal: AbortSignal) -> SourceBatch: + return batch("a", quiet=0) + + attend = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=judge, sink=sink if during == "sink" else "log") + intake = attend.open_intake("s") + running = asyncio.create_task(attend.run()) + try: + pending = intake.submit(prepare) + await entered.wait() + await intake.close() + await pending + record = await attend.inspect("s") + assert record is not None + if during == "judge": + assert record["batch"] is not None + assert record["batch"]["phase"]["phase"] == "retrying" + else: + assert record["outbox"]["decisions"][0]["phase"]["phase"] == "retrying" + finally: + await attend.stop() + await running + + recovered_judge = scripted_judge([{"route": "queue"}]) + delivered: list[str] = [] + recovered = create_attend(store=store, clock=clock, kind={"move": "continuous"}, judge=recovered_judge, sink=lambda d, s: delivered.append(d["id"])) + resumed_intake = recovered.open_intake("s") + resumed = asyncio.create_task(recovered.run()) + try: + await clock.advance(0) + assert len(delivered) == 1 + assert len(recovered_judge.calls) == (1 if during == "judge" else 0) + finally: + await resumed_intake.close() + await recovered.stop() + await resumed + + +async def test_cancelled_error_signal_during_load_refuses_unapplied_input() -> None: + entered, release = asyncio.Event(), asyncio.Event() + + class Store(MemoryStore): + async def load(self, scope: str): + entered.set() + await release.wait() + return await super().load(scope) + + attend = create_attend(store=Store(), clock=fake_clock(), kind={}, judge=scripted_judge([]), sink="log") + controller = AbortController() + pending = attend._scopes.submit("s", {"kind": "events", "events": [], "source": "feed", "cursor": "bad"}, True, controller.signal) # pyright: ignore[reportPrivateUsage] + await entered.wait() + controller.abort(asyncio.CancelledError()) + release.set() + await drain() + assert pending.done() + with pytest.raises(asyncio.CancelledError): + await pending + assert await attend.inspect("s") is None diff --git a/python/tests/test_interop.py b/python/tests/test_interop.py index 5c2bb33..e2f7fe3 100644 --- a/python/tests/test_interop.py +++ b/python/tests/test_interop.py @@ -15,7 +15,7 @@ import pytest -from aqi_attend import AbortController, JudgeInput, Judgment, Kind, create_attend, window_id +from aqi_attend import AbortController, JudgeInput, Judgment, Kind, SourceBatch, create_attend, window_id from aqi_attend.signal import AbortSignal from aqi_attend.testing import fake_clock @@ -25,7 +25,7 @@ ROOT = Path(__file__).resolve().parents[2] SCRIPT = Path(__file__).with_name("interop") / "attend-ts.mjs" ENABLED = os.environ.get("ATTEND_INTEROP") == "1" and (ROOT / "dist" / "index.js").exists() and shutil.which("node") is not None -KINDS: dict[str, Kind] = {"close": "closing", "say": "flush", "look": "passive", "out": "consequence"} +KINDS: dict[str, Kind] = {"close": "closing", "say": "flush", "look": "passive", "out": "consequence", "move": "continuous"} BACKENDS = [name for name, url in (("redis", REDIS_URL), ("postgres", POSTGRES_URL)) if url] @@ -48,10 +48,26 @@ async def python(store: Any, mode: str, scope: str) -> dict[str, Any]: clock = fake_clock(10_000) delivered: list[str] = [] attend = create_attend(store=store, clock=clock, kind=KINDS, judge=judge, sink=lambda d, s: delivered.append(d["id"]), settle={"closing_grace_ms": 100}) + intake = attend.open_intake(scope) if mode == "intake-write" else None controller = AbortController() running = asyncio.ensure_future(attend.run(signal=controller.signal, sweep_ms=60_000)) await asyncio.sleep(0) - if mode == "write": + if intake is not None: + + async def first(signal: AbortSignal) -> SourceBatch: + return {"events": [{"id": "raw-a", "name": "move", "at": 10_000, "data": {}, "text": "x" * 2000}], "cursor": "1"} + + async def filtered(signal: AbortSignal) -> SourceBatch: + return {"events": [], "cursor": "2"} + + async def second(signal: AbortSignal) -> SourceBatch: + return {"events": [{"id": "raw-b", "name": "move", "at": 10_000, "data": {}}], "cursor": "3"} + + await intake.submit(first, source="feed") + await intake.submit(filtered, source="feed") + await intake.submit(second, source="feed") + await intake.close() + elif mode == "write": await attend.push(scope, [{"id": "a", "name": "close", "text": "close a"}, {"id": "b", "name": "out", "data": {"n": 1.5, "s": "ünï 🌍"}}]) await clock.advance(100) for _ in range(500): @@ -124,3 +140,29 @@ async def test_python_and_typescript_share_one_store(kind: str) -> None: assert picked["record"]["dueAt"] is None finally: await owned.close() + + +@pytest.mark.skipif(not ENABLED or not BACKENDS, reason="needs ATTEND_INTEROP=1, a built dist/, node, and Redis or Postgres") +@pytest.mark.parametrize("kind", BACKENDS) +async def test_intake_snapshot_and_tail_continue_without_intake_in_other_runtime(kind: 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) + try: + for writer in ("python", "typescript"): + scope = "intake-" + writer + written = await (python(owned, "intake-write", scope) if writer == "python" else typescript(kind, prefix, "intake-write", scope)) + assert written["delivered"] == [] + 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"] == 3 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)) + assert read == written + continued = await (typescript(kind, prefix, "continue", scope) if writer == "python" else python(owned, "continue", scope)) + assert continued["delivered"] == [window_id(scope, ["raw-a", "raw-b", "e"])] + assert continued["record"]["cursors"] == {"feed": "3"} + finally: + await owned.close() diff --git a/scripts/check-browser-root.mjs b/scripts/check-browser-root.mjs new file mode 100644 index 0000000..84d052f --- /dev/null +++ b/scripts/check-browser-root.mjs @@ -0,0 +1,49 @@ +import assert from 'node:assert/strict'; +import { webcrypto } from 'node:crypto'; +import { readFile } from 'node:fs/promises'; +import { createContext, SourceTextModule } from 'node:vm'; + +// Preserve Node-free root linking and initialization; this is not an event-processing browser test. +const context = createContext({ + AbortController, AbortSignal, DOMException, TextEncoder, TextDecoder, URL, + crypto: webcrypto, performance, structuredClone, queueMicrotask, setTimeout, clearTimeout, +}); +const modules = new Map(); +async function load(url) { + const cached = modules.get(url.href); + if (cached) return cached; + const module = new SourceTextModule(await readFile(url, 'utf8'), { context, identifier: url.href }); + modules.set(url.href, module); + return module; +} +const root = await load(new URL('../dist/index.js', import.meta.url)); +await root.link(async (specifier, referencing) => { + assert.ok(specifier.startsWith('.'), `core imported a nonportable dependency: ${specifier}`); + return load(new URL(specifier, referencing.identifier)); +}); +await root.evaluate(); + +const timers = new Set(); +const clock = { + now: () => 0, + at(at, fn) { + const timer = { active: true }; + timers.add(timer); + if (at <= 0) queueMicrotask(() => { + if (!timer.active) return; + timer.active = false; + timers.delete(timer); + fn(); + }); + return () => { timer.active = false; timers.delete(timer); }; + }, +}; +const attend = root.namespace.createAttend({ + clock, kind: { change: 'closing' }, settle: { closingGraceMs: 0 }, sink: 'log', + judge: async () => { throw new Error('initialization must not judge'); }, +}); +const running = attend.run(); +await attend.stop(); +await running; +assert.equal(timers.size, 0); +console.log(JSON.stringify({ linkedCoreModules: modules.size, nodeImports: 0, initialized: true, remainingTimers: 0 })); diff --git a/src/attend.ts b/src/attend.ts index b25d0c7..ce05b9d 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -1,4 +1,4 @@ -import { ConflictError, isPermanent } from './errors.js'; +import { ConflictError, IntakeError, isPermanent } from './errors.js'; import { foldEvents, type EventFold } from './fold.js'; import { sleep, systemClock } from './internal/clock.js'; import { arrayLength, assertNever, messageOf } from './internal/shared.js'; @@ -13,6 +13,7 @@ import { windowBytesFor } from './shell/budget.js'; import { readRecord } from './shell/read.js'; import { readDecisions } from './shell/decisions.js'; import { thresholdRoute } from './core/threshold.js'; +import { IntakeQueue, registerIntakes } from './shell/intake.js'; /** Errors raised by intake and effect handlers. */ export { BackpressureError, ConflictError, OutboxFullError, PermanentError } from './errors.js'; @@ -48,7 +49,9 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' const fill = { id: () => globalThis.crypto.randomUUID(), at: () => clock.now() }; const modes = { decisions: sink === 'log' ? 'log' : 'lane', deadLetters: deadLetter === 'log' ? 'log' : 'lane' } as const; const sources = new Set(); - const attached = new Set(); + const attached = new Map>(); + const intakes = new Map(); + const intakeIdentity = {}; const sizedEvents = new WeakMap(); const calls = new Map, number>(); const releases = new Set>(); @@ -91,17 +94,20 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' } function tick(scope: string): void { + const intake = intakes.get(scope); + if (intake) { intake.wake(); return; } void background(scope, 'tick', () => submit(scope, { kind: 'tick' })); } function background(scope: string, input: Input['kind'], work: () => Promise): Promise { - return work().catch((error: unknown) => { + const intake = intakes.get(scope); + return (intake ? intake.track(work) : work()).catch((error: unknown) => { if (!(error instanceof ConflictError)) observe({ kind: 'failed', scope, input, message: messageOf(error) }); }); } function call(scope: string, result: Input['kind'], leaseUntil: number, work: () => Promise, release: ReleasedInput): void { - if (!running) { + if (!running || intakes.get(scope)?.closed) { const released = background(scope, release.kind, () => submit(scope, release)).finally(() => releases.delete(released)); releases.add(released); return; @@ -127,7 +133,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' observe(effect.trace); return; case 'judge': - if (running && judges >= (config.judgeConcurrency ?? Infinity)) { + if (running && !intakes.get(scope)?.closed && judges >= (config.judgeConcurrency ?? Infinity)) { void background(scope, 'judgeDeferred', () => submit(scope, { kind: 'judgeDeferred', batchId: effect.batchId, attempt: effect.attempt, until: clock.now() + 100 })); return; } @@ -145,13 +151,37 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' } } + function effectController(scope: string, at: number, message: string) { + const controller = new AbortController(); + const cancelTimer = clock.at(at, () => controller.abort(new Error(message))); + const signal = intakes.get(scope)?.completionSignal; + const abort = () => controller.abort(signal?.reason); + signal?.addEventListener('abort', abort, { once: true }); + if (signal?.aborted) abort(); + return { controller, cancel() { cancelTimer(); signal?.removeEventListener('abort', abort); } }; + } + + function submitCompletion(scope: string, result: Extract): Promise { + const intake = intakes.get(scope); + if (!intake) return submit(scope, result); + const release: ReleasedInput = result.kind === 'judged' || result.kind === 'judgeFailed' + ? { kind: 'judgeReleased', batchId: result.batchId, attempt: result.attempt } + : { kind: 'deliveryReleased', deliveryId: result.deliveryId, attempt: result.attempt }; + if (intake.closed) return submit(scope, release); + const signal = intake.completionSignal; + return submit(scope, result, false, signal).catch((error: unknown) => { + if (signal.aborted && error === signal.reason) return submit(scope, release); + throw error; + }); + } + async function runJudge(scope: string, effect: JudgeEffect): Promise { judges += 1; - const controller = new AbortController(); - const cancel = clock.at(clock.now() + policy.judgeTimeoutMs, () => controller.abort(new Error('attend: judge timed out'))); + const { controller, cancel } = effectController(scope, clock.now() + policy.judgeTimeoutMs, 'attend: judge timed out'); const { batchId, attempt } = effect; - let result: Input; + let result: Extract; try { + if (intakes.has(scope)) controller.signal.throwIfAborted(); const live = config.context ? await config.context(scope, controller.signal) : {}; const window = copyWindowSliced(effect.window); const input: JudgeInput = { @@ -167,9 +197,12 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' now: clock.now(), }; if (config.guidance !== undefined) input.guidance = config.guidance; + if (intakes.has(scope)) controller.signal.throwIfAborted(); const images = config.capture ? await capture(config.capture, scope, batchId, controller.signal) : []; if (images.length > 0) input.images = images; + if (intakes.has(scope)) controller.signal.throwIfAborted(); const judgment: unknown = await config.judge(input, controller.signal); + if (intakes.has(scope)) controller.signal.throwIfAborted(); if (isJudgment(judgment)) { const threshold = config.actThreshold === undefined ? null : thresholdRoute(judgment, effect.offered, config.actThreshold); if (threshold) observe({ kind: 'routeThresholded', scope, batchId, from: judgment.route, to: threshold.route, act: threshold.act }); @@ -181,7 +214,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' cancel(); } judges -= 1; - await submit(scope, result); + await submitCompletion(scope, result); } async function capture(fn: NonNullable, scope: string, batchId: string, judgeSignal: AbortSignal): Promise { @@ -206,16 +239,20 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' async function runDeliver(scope: string, effect: DeliverEffect): Promise { const { item, phase } = effect.delivery; - const controller = new AbortController(); - const cancel = clock.at(phase.leaseUntil, () => controller.abort(new Error('attend: delivery timed out'))); - let result: Input; + const { controller, cancel } = effectController(scope, phase.leaseUntil, 'attend: delivery timed out'); + let result: Extract; try { + if (intakes.has(scope)) controller.signal.throwIfAborted(); if (item.kind === 'decision' && sink !== 'log') { const decision = copyDecision(item.decision); - await sink.deliver(decision instanceof Promise ? await decision : decision, controller.signal); + const copied = decision instanceof Promise ? await decision : decision; + if (intakes.has(scope)) controller.signal.throwIfAborted(); + await sink.deliver(copied, controller.signal); } else if (item.kind === 'deadLetter' && deadLetter !== 'log') { const letter = copyLetter(item.letter); - await deadLetter(letter instanceof Promise ? await letter : letter, controller.signal); + const copied = letter instanceof Promise ? await letter : letter; + if (intakes.has(scope)) controller.signal.throwIfAborted(); + await deadLetter(copied, controller.signal); } result = { kind: 'delivered', deliveryId: item.id, attempt: phase.attempt }; } catch (error) { @@ -223,7 +260,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' } finally { cancel(); } - await submit(scope, result); + await submitCompletion(scope, result); } async function sweep(now: number, limit: number, warm: boolean): Promise { @@ -242,20 +279,25 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' } catch (error) { observe({ kind: 'failed', scope: '*', input: 'tick', message: messageOf(error) }); } } - return { + const attend: Attend = { push(scope, events) { - try { return submit(scope, { kind: 'events', events: classify(events) }, true); } + try { + if (intakes.has(scope)) throw new IntakeError('attend: scope has exclusive intake'); + return submit(scope, { kind: 'events', events: classify(events) }, true); + } catch (error) { return Promise.reject(error); } }, - flush: (scope) => submit(scope, { kind: 'flush' }, true), - end: (scope) => submit(scope, { kind: 'end' }, true), + flush: (scope) => intakes.has(scope) ? Promise.reject(new IntakeError('attend: scope has exclusive intake')) : submit(scope, { kind: 'flush' }, true), + end: (scope) => intakes.has(scope) ? Promise.reject(new IntakeError('attend: scope has exclusive intake')) : submit(scope, { kind: 'end' }, true), inspect: (scope) => readRecord(store, scope, modes), decisions: (filter, options) => readDecisions(store.log, clock, filter, options), async attach(scope, source, options) { - const slot = `${scope}\n${source.key}`; - if (attached.has(slot)) throw new Error(`attend: source "${source.key}" is already attached to scope "${scope}"`); - attached.add(slot); + if (intakes.has(scope)) throw new IntakeError('attend: scope has exclusive intake'); + const keys = attached.get(scope) ?? new Set(); + if (keys.has(source.key)) throw new Error(`attend: source "${source.key}" is already attached to scope "${scope}"`); + keys.add(source.key); + attached.set(scope, keys); const controller = new AbortController(); const abort = () => controller.abort(); options?.signal?.addEventListener('abort', abort, { once: true }); @@ -304,7 +346,8 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' } } } finally { - attached.delete(slot); + keys.delete(source.key); + if (keys.size === 0) attached.delete(scope); sources.delete(controller); options?.signal?.removeEventListener('abort', abort); } @@ -325,9 +368,22 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' }, }; + registerIntakes(attend, (scope, options, context) => { + const capacity = options?.capacity ?? 20000; + if (!Number.isSafeInteger(capacity) || capacity <= 0) throw new RangeError('attend: intake capacity must be a positive safe integer'); + if (intakes.has(scope) || scopes.has(scope) || attached.has(scope)) throw new IntakeError('attend: scope already active'); + const intake = new IntakeQueue(scope, { identity: intakeIdentity, scopes, clock, classify, running: () => running !== null, observe }, context, capacity); + intakes.set(scope, intake); + return intake; + }); + return attend; + async function runLoop(signal: AbortSignal, sweepMs: number, sweepLimit: number): Promise { running = { signal }; - const onAbort = () => { running = null; scheduler.stop(); for (const source of sources) source.abort(); }; + const onAbort = () => { + for (const intake of intakes.values()) void intake.fence(); + running = null; scheduler.stop(); for (const source of sources) source.abort(); + }; signal.addEventListener('abort', onAbort, { once: true }); try { if (signal.aborted) return; @@ -345,6 +401,7 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' await Promise.all([...calls].map(([done, leaseUntil]) => settledOrExpired(done, leaseUntil))); await writes; while (releases.size > 0) await Promise.all(releases); + await Promise.allSettled([...intakes.values()].map((intake) => intake.fence())); } } } diff --git a/src/errors.ts b/src/errors.ts index ad9d963..8335461 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -1,5 +1,10 @@ import type { OutboxLane } from './types.js'; +/** An operation conflicts with an intake's local ownership or lifecycle. */ +export class IntakeError extends Error { + constructor(message: string) { super(message); this.name = 'IntakeError'; } +} + /** Throw from a judge, a sink or a source to skip retries: the judge or sink dead-letters at once, and `attach` stops. */ export class PermanentError extends Error { readonly permanent = true as const; diff --git a/src/intake.ts b/src/intake.ts new file mode 100644 index 0000000..a976eea --- /dev/null +++ b/src/intake.ts @@ -0,0 +1,13 @@ +import { AsyncLocalStorage } from 'node:async_hooks'; +import type { Attend, Intake, IntakeOptions } from './shell/types.js'; +import { openRegisteredIntake, type IntakeOwner } from './shell/intake.js'; + +export type { Intake, IntakeOptions, Prepare } from './shell/types.js'; +export { IntakeError } from './errors.js'; + +const context = new AsyncLocalStorage(); + +/** Own local input preparation and immediate work for an untouched scope. */ +export function openIntake(attend: Attend, scope: string, options?: IntakeOptions): Intake { + return openRegisteredIntake(attend, scope, options, context); +} diff --git a/src/shell/intake.ts b/src/shell/intake.ts new file mode 100644 index 0000000..49f3feb --- /dev/null +++ b/src/shell/intake.ts @@ -0,0 +1,218 @@ +import type { Clock, Event, EventsInput, SourceBatch, Trace } from '../core/types.js'; +import { BackpressureError, IntakeError } from '../errors.js'; +import { messageOf } from '../internal/shared.js'; +import type { createScopes } from './scope.js'; +import type { Attend, Intake, IntakeOptions, Prepare } from './types.js'; + +export interface IntakeOwner { readonly engine: object; readonly scope: string } +export interface IntakeContext { + getStore(): IntakeOwner | undefined; + run(owner: IntakeOwner, callback: () => T): T; +} + +type Factory = (scope: string, options: IntakeOptions | undefined, context: IntakeContext) => Intake; +const factories = new WeakMap(); + +/** The optional Node entry uses this capability without adding Node imports to the core. */ +export function registerIntakes(attend: Attend, factory: Factory): void { factories.set(attend, factory); } + +export function openRegisteredIntake(attend: Attend, scope: string, options: IntakeOptions | undefined, context: IntakeContext): Intake { + const factory = factories.get(attend); + if (!factory) throw new IntakeError('attend: intake requires an engine from this package instance'); + return factory(scope, options, context); +} + +interface Receipt { + promise: Promise; + resolve(): void; + reject(error: unknown): void; +} + +function receipt(): Receipt { + // The native Promise constructor calls its executor before returning. + let resolve!: () => void; + let reject!: (error: unknown) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + void promise.catch(() => undefined); + return { promise, resolve, reject }; +} + +interface Operation { + prepare: Prepare; + source: string | undefined; + controller: AbortController; + done: Receipt; + unlink(): void; + releaseCapacity(): void; +} + +interface Activity { + operation: Operation | null; + finished: Receipt; + failure: { error: unknown } | null; +} + +interface Runtime { + identity: object; + scopes: ReturnType; + clock: Clock; + classify(events: readonly Event[]): EventsInput['events']; + running(): boolean; + observe(trace: Trace): void; +} + +/** Owns local raw ordering; reducer records remain the only window state. */ +export class IntakeQueue implements Intake { + private readonly owner: IntakeOwner; + private readonly queue = new Set(); + private active: Activity | null = null; + private timerPending = false; + private work = 0; + private workDone: Receipt | null = null; + private closing: Receipt | null = null; + private readonly completion = new AbortController(); + + constructor(readonly scope: string, private readonly runtime: Runtime, private readonly context: IntakeContext, private readonly capacity: number) { + this.owner = { engine: runtime.identity, scope }; + } + + get closed(): boolean { return this.closing !== null; } + get completionSignal(): AbortSignal { return this.completion.signal; } + + private checkContext(): void { + const active = this.context.getStore(); + if (active?.engine === this.owner.engine && active.scope === this.scope) throw new IntakeError('attend: cannot await this intake from its own callback'); + } + + submit(prepare: Prepare, options?: { source?: string; signal?: AbortSignal }): Promise { + this.checkContext(); + if (this.closed) throw new IntakeError('attend: intake closed'); + if (!this.runtime.running()) throw new IntakeError('attend: intake requires a running engine'); + const count = this.queue.size + (this.active?.operation ? 1 : 0); + if (count >= this.capacity) throw new BackpressureError(100, count); + options?.signal?.throwIfAborted(); + const releaseCapacity = this.runtime.scopes.reserveInput(); + const controller = new AbortController(); + const abort = () => controller.abort(options?.signal?.reason); + const operation: Operation = { + prepare, source: options?.source, controller, done: receipt(), releaseCapacity, + unlink: () => options?.signal?.removeEventListener('abort', abort), + }; + this.queue.add(operation); + controller.signal.addEventListener('abort', () => { + if (this.queue.delete(operation)) { + operation.unlink(); operation.releaseCapacity(); operation.done.reject(controller.signal.reason); + } + }, { once: true }); + options?.signal?.addEventListener('abort', abort, { once: true }); + if (options?.signal?.aborted) abort(); + this.pump(); + return operation.done.promise; + } + + wake(): void { + if (!this.closed) { this.timerPending = true; this.pump(); } + } + + private pump(): void { + if (this.closed || this.active !== null) return; + const next = this.queue.values().next(); + const operation = next.done ? null : next.value; + if (operation) this.queue.delete(operation); + else { + if (!this.timerPending) return; + this.timerPending = false; + const due = this.runtime.scopes.due(this.scope); + if (due === null || due > this.runtime.clock.now()) return; + } + const activity: Activity = { operation, finished: receipt(), failure: null }; + this.active = activity; + queueMicrotask(() => { void this.context.run(this.owner, () => this.perform(activity)); }); + } + + private prepare(operation: Operation): Promise { + const signal = operation.controller.signal; + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const abort = () => { signal.removeEventListener('abort', abort); reject(signal.reason); }; + const success = (batch: SourceBatch) => { signal.removeEventListener('abort', abort); resolve(batch); }; + const failure = (error: unknown) => { signal.removeEventListener('abort', abort); reject(error); }; + signal.addEventListener('abort', abort, { once: true }); + try { void operation.prepare(signal).then(success, failure); } + catch (error) { failure(error); } + }); + } + + private async settle(activity: Activity): Promise { + try { await this.runtime.scopes.submit(this.scope, { kind: 'tick' }); } + catch (error) { activity.failure = { error }; throw error; } + await this.workDone?.promise; + if (activity.failure) throw activity.failure.error; + } + + private async perform(activity: Activity): Promise { + const operation = activity.operation; + try { + if (!operation) { await this.settle(activity); return; } + const signal = operation.controller.signal; + const batch = await this.prepare(operation); + signal.throwIfAborted(); + const events = this.runtime.classify(batch.events); + const input: EventsInput = { kind: 'events', events }; + if (operation.source !== undefined) { + input.source = operation.source; + if (batch.cursor !== undefined) input.cursor = batch.cursor; + } + if (batch.truncated) input.truncated = true; + // Transfer the reservation without yielding or charging the input twice. + operation.releaseCapacity(); + try { await this.runtime.scopes.submit(this.scope, input, true, signal, undefined, false); } + catch (error) { if (!signal.aborted) activity.failure = { error }; throw error; } + if (events.length > 0) await this.settle(activity); + operation.done.resolve(); + } catch (error) { + if (operation) operation.done.reject(error); + else this.runtime.observe({ kind: 'failed', scope: this.scope, input: 'tick', message: messageOf(error) }); + } finally { + if (operation) { operation.unlink(); operation.releaseCapacity(); } + this.active = null; + activity.finished.resolve(); + this.pump(); + } + } + + track(work: () => Promise): Promise { + if (this.work === 0) this.workDone = receipt(); + this.work += 1; + const activity = this.active; + const finish = (failure: { error: unknown } | null) => { + if (failure && activity && !activity.failure) activity.failure = failure; + this.work -= 1; + if (this.work === 0) this.workDone?.resolve(); + }; + let pending: Promise; + try { pending = this.context.run(this.owner, work); } + catch (error) { finish({ error }); return Promise.reject(error); } + return pending.then(() => finish(null), (error: unknown) => { finish({ error }); throw error; }); + } + + fence(): Promise { + if (this.closing) return this.closing.promise; + const closing = receipt(); + this.closing = closing; + this.timerPending = false; + const reason = new IntakeError('attend: intake closed'); + this.completion.abort(reason); + for (const operation of this.queue) operation.controller.abort(reason); + const activity = this.active; + activity?.operation?.controller.abort(reason); + void (async () => { + await activity?.finished.promise; + await this.workDone?.promise; + if (activity?.failure) throw activity.failure.error; + })().then(closing.resolve, closing.reject); + return closing.promise; + } + + close(): Promise { this.checkContext(); return this.fence(); } +} diff --git a/src/shell/scope.ts b/src/shell/scope.ts index 39f0ac1..9b800a1 100644 --- a/src/shell/scope.ts +++ b/src/shell/scope.ts @@ -30,6 +30,7 @@ export function createScopes(options: Options) { const staged = new Set(); const pending = new Set>(); let queued = 0; + let reserved = 0; let committing = false; let scheduled = false; @@ -148,7 +149,7 @@ export function createScopes(options: Options) { if (state.outbox.deadLetters.length >= config.policy.maxDeadLetters) throw new OutboxFullError(slot.scope, 'deadLetters', state.outbox.deadLetters.length); } const now = clock.now(); - if (options.running() && (input.kind === 'events' || input.kind === 'flush' || input.kind === 'end') && state.dueAt !== null && state.dueAt < now) { + if (raw.catchUp && options.running() && (input.kind === 'events' || input.kind === 'flush' || input.kind === 'end') && state.dueAt !== null && state.dueAt < now) { transition(slot, state, { kind: 'tick' }, now); } const current = transition(slot, state, input, now); @@ -176,21 +177,35 @@ export function createScopes(options: Options) { } } - function submit(scope: string, input: Input, external = false, signal?: AbortSignal, rejectHook?: (error: unknown) => void): Promise { + function admissionError(): BackpressureError | null { + const lagMs = scheduler.lagMs(); + const count = queued + reserved; + const overQueue = count >= (options.admission?.maxQueuedInputs ?? 20000); + const overLag = options.admission?.maxLagMs !== undefined && lagMs > options.admission.maxLagMs; + if (!overQueue && !overLag) return null; + options.observe({ kind: 'backpressure', queued: count, lagMs }); + return new BackpressureError(overLag ? Math.ceil(lagMs) : 100, count); + } + + function reserveInput(): () => void { + const error = admissionError(); + if (error) throw error; + reserved += 1; + let released = false; + return () => { if (!released) { released = true; reserved -= 1; } }; + } + + function submit(scope: string, input: Input, external = false, signal?: AbortSignal, rejectHook?: (error: unknown) => void, catchUp = true): Promise { if (external) { - const lagMs = scheduler.lagMs(); - const overQueue = queued >= (options.admission?.maxQueuedInputs ?? 20000); - const overLag = options.admission?.maxLagMs !== undefined && lagMs > options.admission.maxLagMs; - if (overQueue || overLag) { - const error = new BackpressureError(overLag ? Math.ceil(lagMs) : 100, queued); - options.observe({ kind: 'backpressure', queued, lagMs }); + const error = admissionError(); + if (error) { rejectHook?.(error); return Promise.reject(error); } } const slot = slotFor(scope); const last = slot.queued.at(-1); - if (last && input.kind === 'events' && last.input.kind === 'events' && last.input.source === input.source && last.signal === signal) { + if (last && input.kind === 'events' && last.input.kind === 'events' && last.input.source === input.source && last.signal === signal && last.catchUp === catchUp) { last.input.events.push(...input.events); if (input.cursor !== undefined) last.input.cursor = input.cursor; if (input.truncated) last.input.truncated = true; @@ -202,7 +217,7 @@ export function createScopes(options: Options) { let resolve!: () => void; let fail!: (error: unknown) => void; const done = new Promise((yes, no) => { resolve = yes; fail = no; }); - const raw: Raw = { input, signal, rejectHook, done, resolve, reject: fail, count: 1, conflicts: 0 }; + const raw: Raw = { input, signal, rejectHook, done, resolve, reject: fail, count: 1, conflicts: 0, catchUp }; pending.add(done); void done.then(() => pending.delete(done), () => pending.delete(done)); slot.queued.push(raw); @@ -302,6 +317,8 @@ export function createScopes(options: Options) { return { submit, + reserveInput, + has(scope: string): boolean { return slots.has(scope); }, async touch(scope: string): Promise { const slot = slotFor(scope); if (!slot.state) await load(slot); diff --git a/src/shell/types.ts b/src/shell/types.ts index 200d1d8..af3c5e8 100644 --- a/src/shell/types.ts +++ b/src/shell/types.ts @@ -1,4 +1,4 @@ -import type { Clock, DeadLetter, Decision, DeliveredRoute, Effect, Event, Input, JsonObject, Judge, JudgeImage, Kind, Route, ScopeRecord, ScopeState, SettlePolicy, DecisionAppend, LoggedInput, Sink, Source, Trace } from '../core/types.js'; +import type { Clock, DeadLetter, Decision, DeliveredRoute, Effect, Event, Input, JsonObject, Judge, JudgeImage, Kind, Route, ScopeRecord, ScopeState, SettlePolicy, DecisionAppend, LoggedInput, Sink, Source, SourceBatch, Trace } from '../core/types.js'; import type { DecisionKind, DecisionRow, ScopeStore, ScopeWrite, SerializedWrite } from '../store/types.js'; /** A handler for a window that exhausted judge or sink delivery. */ @@ -11,9 +11,9 @@ export interface JudgeContext { predicates?: Record; } -/** Process-wide intake limits. */ +/** Intake limits shared by scopes in one engine. */ export interface AdmissionOptions { - /** Raw, loading and unapplied inputs per process before push rejects with BackpressureError. Default 20,000. */ + /** Registered preparation, loading and unapplied inputs per engine before admission rejects. Default 20,000. */ maxQueuedInputs?: number; /** Shed load once scheduler lag exceeds this many ms. */ maxLagMs?: number; @@ -111,6 +111,20 @@ export interface Attend { stop(): Promise; } +export type Prepare = (signal: AbortSignal) => Promise; + +export interface IntakeOptions { + /** Queued and active submissions for this handle. Default 20,000. */ + capacity?: number; +} + +export interface Intake { + /** Register before returning; await the input and its immediate causal work. */ + submit(prepare: Prepare, options?: { source?: string; signal?: AbortSignal }): Promise; + /** Fence synchronously and join owned work. The handle cannot reopen. */ + close(): Promise; +} + /** An input and its callers, retained until commit or abandonment. */ export interface RawInput { input: Input; @@ -121,6 +135,7 @@ export interface RawInput { reject(error: unknown): void; count: number; conflicts: number; + catchUp: boolean; } /** The owned state, queued callers and persistence accounting for one scope. */ diff --git a/test/conformance/scenario.ts b/test/conformance/scenario.ts index 5889f01..0501e07 100644 --- a/test/conformance/scenario.ts +++ b/test/conformance/scenario.ts @@ -7,10 +7,12 @@ */ import { createAttend, PermanentError } from '../../src/attend.js'; import { memoryStore } from '../../src/memory.js'; +import { openIntake } from '../../src/intake.js'; +import { sleep } from '../../src/internal/clock.js'; import { drain, fakeClock } from '../../src/testing.js'; import type { DeadLetter, Decision, DecisionRow, DeliveredRoute, JsonObject, JsonValue, Judge, JudgeBudget, JudgeImage, JudgeInput, Judgment, Kind, Route, ScopeRecord, - SettlePolicy, Trace, + SettlePolicy, SourceBatch, Trace, } from '../../src/types.js'; /** What a scripted judge does on one call. */ @@ -60,6 +62,8 @@ export interface EventSpec { export type Step = | { push: string; events: EventSpec[] } + | { submit: string; events: EventSpec[]; prepareMs?: number; source?: string; cursor?: string | null; prepareFail?: string } + | { closeIntake: string } | { advance: number } | { flush: string } | { end: string } @@ -68,6 +72,7 @@ export type Step = export interface Scenario { name: string; + intakes?: string[]; /** The TypeScript test this scenario mirrors, when there is one. */ from?: string; /** The fake clock's start. Default 1000. */ @@ -254,9 +259,11 @@ export async function runScenario(scenario: Scenario): Promise { ...(scenario.settle ? { settle: scenario.settle } : {}), }); + const intakes = new Map((scenario.intakes ?? []).map((scope) => [scope, openIntake(attend, scope)])); + const receipts: Promise[] = []; const controller = new AbortController(); const running = attend.run({ signal: controller.signal, sweepMs: scenario.sweepMs ?? 1000 }); - const scopes = new Set(); + const scopes = new Set(scenario.intakes ?? []); const result = async (step: number, work: () => Promise) => { try { await work(); @@ -267,10 +274,25 @@ export async function runScenario(scenario: Scenario): Promise { }; for (const [index, step] of scenario.steps.entries()) { - if ('push' in step) { - scopes.add(step.push); + if ('push' in step || 'submit' in step) { + const scope = 'push' in step ? step.push : step.submit; + scopes.add(scope); const events = step.events.map((e) => ({ id: e.id, at: e.at ?? 0, name: e.name, data: e.data ?? {}, ...(e.text === undefined ? {} : { text: e.text }), ...(e.observedAt === undefined ? {} : { observedAt: e.observedAt }), ...(e.quietForMs === undefined ? {} : { quietForMs: e.quietForMs }) })); - await result(index, () => attend.push(step.push, events)); + if ('push' in step) await result(index, () => attend.push(scope, events)); + else { + const intake = intakes.get(scope); + if (!intake) throw new Error('scenario intake is not open'); + const batch: SourceBatch = { events, ...(step.cursor === undefined ? {} : { cursor: step.cursor }) }; + receipts.push(result(index, () => intake.submit(async (signal) => { + if (step.prepareMs) await sleep(clock, step.prepareMs, signal); + if (step.prepareFail !== undefined) throw new Error(step.prepareFail); + return batch; + }, step.source === undefined ? undefined : { source: step.source }))); + } + } else if ('closeIntake' in step) { + const intake = intakes.get(step.closeIntake); + if (!intake) throw new Error('scenario intake is not open'); + receipts.push(result(index, () => intake.close())); } else if ('advance' in step) { await clock.advance(step.advance); } else if ('flush' in step) { @@ -293,6 +315,7 @@ export async function runScenario(scenario: Scenario): Promise { } controller.abort(); await running; + await Promise.all(receipts); for (const scope of [...scopes].sort()) observed.records[scope] = json(await attend.inspect(scope)); observed.log = json((await store.log.read({ after: null, limit: 10_000 })).rows); return observed; diff --git a/test/conformance/scenarios.ts b/test/conformance/scenarios.ts index 8e9021b..a9717e8 100644 --- a/test/conformance/scenarios.ts +++ b/test/conformance/scenarios.ts @@ -14,6 +14,52 @@ const advance = (ms: number) => ({ advance: ms }); const T = 'test/attend.test.ts'; export const SCENARIOS: Scenario[] = [ + { + name: 'serial intake keeps registered backlog ahead of a timer during preparation', + intakes: ['s'], start: 0, kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [ + { submit: 's', events: [ev('a', 'drag', { observedAt: 0, quietForMs: 100 })] }, + advance(90), { submit: 's', events: [], prepareMs: 200, source: 'feed', cursor: '1' }, + advance(5), { submit: 's', events: [ev('b', 'drag', { observedAt: 95, quietForMs: 300 })] }, + advance(195), { inspect: 's' }, advance(105), + ], + }, + { + name: 'serial intake waits for a judgment and its delivery before the next preparation', + intakes: ['s'], start: 0, kinds: KINDS, + judge: { '*': { answers: [{ hold: 'judge' }, { route: 'queue' }] } }, + sink: { '*': { attempts: [{ hold: 'sink' }, 'ok'] } }, + steps: [ + { submit: 's', events: [ev('a', 'drag', { quietForMs: 100 })] }, advance(100), + advance(50), { submit: 's', events: [ev('b', 'drag', { observedAt: 150, quietForMs: 100 })] }, + advance(10), { submit: 's', events: [ev('c', 'drag', { observedAt: 160, quietForMs: 100 })] }, + advance(340), { release: 'judge', answer: { route: 'queue' } }, { inspect: 's' }, + advance(200), { release: 'sink' }, { inspect: 's' }, + ], + }, + { + name: 'closing serial intake cancels preparation without advancing its cursor', + intakes: ['s'], start: 0, kinds: KINDS, + judge: { '*': { answers: [{ route: 'queue' }] } }, + steps: [{ submit: 's', events: [ev('a', 'drag')], prepareMs: 100, source: 'feed', cursor: '1' }, advance(20), { closeIntake: 's' }, advance(100)], + }, + { + name: 'owned scopes reject ordinary ingress without affecting serial submissions', + intakes: ['s'], start: 0, kinds: KINDS, + judge: { '*': { answers: [{ route: 'note' }] } }, + steps: [push('s', ev('other', 'drag')), { flush: 's' }, { end: 's' }, { submit: 's', events: [ev('a', 'drag', { quietForMs: 0 })] }, advance(0)], + }, + { + name: 'serial intake permits fresh input while a resolved wait is pending', + intakes: ['s'], start: 0, kinds: KINDS, + settle: { waitHorizonMs: 1000 }, + judge: { '*': { answers: [{ route: 'wait' }, { route: 'note' }] } }, + steps: [ + { submit: 's', events: [ev('a', 'drag', { quietForMs: 100 })] }, advance(100), { inspect: 's' }, + advance(10), { submit: 's', events: [ev('b', 'drag', { observedAt: 110, quietForMs: 20 })] }, advance(20), + ], + }, { name: 'different continuous durations settle after the latest event end', start: 100, diff --git a/test/intake.test.ts b/test/intake.test.ts new file mode 100644 index 0000000..62eb00e --- /dev/null +++ b/test/intake.test.ts @@ -0,0 +1,442 @@ +import { expect, test } from 'vitest'; +import { BackpressureError, createAttend, memoryStore } from '../src/index.js'; +import { openIntake } from '../src/intake.js'; +import type { Clock, Input, ScopeStore, SourceBatch } from '../src/types.js'; +import { drain } from '../src/internal/clock.js'; +import { fakeClock, scriptedJudge } from '../src/testing.js'; + +const batch = (id: string, at = 0, quietForMs = 100): SourceBatch => ({ events: [{ id, at, observedAt: at, quietForMs, name: 'move', data: {} }] }); + +function gate() { + const controller = new AbortController(); + const promise = new Promise((resolve) => controller.signal.addEventListener('abort', () => resolve(), { once: true })); + return { promise, open: () => controller.abort() }; +} + +test('preparation owns the timer and registered backlog', async () => { + const clock = fakeClock(); + const judge = scriptedJudge([{ route: 'queue' }]); + const attend = createAttend({ clock, kind: { move: 'continuous' }, judge, sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + await intake.submit(async () => batch('a')); + await clock.advance(90); + const release = gate(); + const filtering = intake.submit(async () => { await release.promise; return { events: [], cursor: '1' }; }, { source: 'feed' }); + await clock.advance(5); + const queued = intake.submit(async () => batch('b', 95, 300)); + await clock.advance(195); + expect(judge.calls).toHaveLength(0); + release.open(); + await filtering; + await queued; + expect(judge.calls).toHaveLength(0); + await clock.advance(105); + expect(judge.calls.map((call) => call.window.settledAt)).toEqual([395]); + expect(judge.calls[0]?.window.events.map((event) => event.id)).toEqual(['a', 'b']); + expect((await attend.inspect('s'))?.cursors).toEqual({ feed: '1' }); + } finally { + await intake.close(); + await attend.stop(); + await running; + } +}); + +test('raw arrivals wait for judgment and delivery', async () => { + const clock = fakeClock(); + const started = gate(), release = gate(), sinkStarted = gate(), sinkRelease = gate(); + const offers: { at: number; ids: string[] }[] = []; + const attend = createAttend({ clock, kind: { move: 'continuous' }, + judge: async (input) => { + offers.push({ at: clock.now(), ids: input.window.events.map((event) => event.id) }); + if (offers.length === 1) { started.open(); await release.promise; } + return { route: 'queue' }; + }, + sink: async (decision) => { if (decision.window.events[0]?.id === 'a') { sinkStarted.open(); await sinkRelease.promise; } }, + }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + const prepared: string[] = []; + try { + await intake.submit(async () => batch('a')); + await clock.advance(100); + await started.promise; + await clock.advance(50); + const pending = intake.submit(async () => { prepared.push('b'); return batch('b', 150); }); + release.open(); + await clock.advance(0); + await sinkStarted.promise; + await clock.advance(550); + expect(prepared).toEqual([]); + sinkRelease.open(); + await pending; + expect(offers).toEqual([{ at: 100, ids: ['a'] }, { at: 700, ids: ['b'] }]); + } finally { + release.open(); sinkRelease.open(); + await intake.close(); + await attend.stop(); + await running; + } +}); + +test('abort before callback and owned-scope refusal', async () => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + let called = false; + try { + const controller = new AbortController(); + const pending = intake.submit(async () => { called = true; return batch('a'); }, { signal: controller.signal }); + controller.abort(); + await expect(pending).rejects.toBeDefined(); + expect(called).toBe(false); + expect(await attend.inspect('s')).toBeNull(); + await expect(attend.push('s', { id: 'other', name: 'move' })).rejects.toThrow('intake'); + await expect(attend.end('s')).rejects.toThrow('intake'); + await expect(attend.flush('s')).rejects.toThrow('intake'); + await expect(attend.attach('s', { key: 'feed', async subscribe() { throw new Error('must not subscribe'); } })).rejects.toThrow('intake'); + expect(() => openIntake(attend, 's')).toThrow('already active'); + } finally { + await intake.close(); + await attend.stop(); + await running; + } +}); + +test('queued abort refunds its reservation without preparing', async () => { + const attend = createAttend({ clock: fakeClock(), admission: { maxQueuedInputs: 2 }, kind: {}, judge: scriptedJudge([]), sink: 'log' }); + const intake = openIntake(attend, 's'); + expect(() => intake.submit(async () => ({ events: [] }))).toThrow('running'); + const running = attend.run(), started = gate(), release = gate(); + try { + const first = intake.submit(async () => { started.open(); await release.promise; return { events: [] }; }); + await started.promise; + const controller = new AbortController(); + let called = false; + const queued = intake.submit(async () => { called = true; return { events: [], cursor: 'bad' }; }, { source: 'feed', signal: controller.signal }); + controller.abort(); + await expect(queued).rejects.toBeDefined(); + await attend.push('other', { id: 'c', name: 'output' }); + release.open(); await first; + expect(called).toBe(false); + expect((await attend.inspect('s'))?.cursors ?? {}).toEqual({}); + expect(() => openIntake(attend, 'other')).toThrow('already active'); + } finally { release.open(); await intake.close(); await attend.stop(); await running; } +}); + +class ManualClock implements Clock { + time = 0; + readonly timers: { at: number; callback: () => void; cancelled: boolean }[] = []; + now() { return this.time; } + at(at: number, callback: () => void) { + const timer = { at, callback, cancelled: false }; + this.timers.push(timer); + return () => { timer.cancelled = true; }; + } + fire(at: number) { + this.time = at; + for (const timer of this.timers.filter((t) => !t.cancelled && t.at <= at).sort((a, b) => a.at - b.at)) { + timer.cancelled = true; + timer.callback(); + } + } +} + +function gatedStore() { + const inner = memoryStore(); + const gates = new Map; release: ReturnType }>(); + const store: ScopeStore = { ...inner, async commit(writes) { + for (const write of writes) for (const logged of write.inputs) { + const held = gates.get(logged.input.kind); + if (held) { held.entered.open(); await held.release.promise; } + } + return inner.commit(writes); + } }; + return { store, + hold(kind: Input['kind']) { + const held = { entered: gate(), release: gate() }; + gates.set(kind, held); + return { entered: held.entered.promise, release: held.release.open }; + }, + releaseAll() { for (const held of gates.values()) held.release.open(); }, + }; +} + +test('a timer owns intake before its commit', async () => { + const clock = new ManualClock(); + const firstResult = gate(), firstDelivery = gate(); + const calls: { at: number; ids: string[] }[] = []; + const attend = createAttend({ clock, kind: { move: 'continuous' }, + judge: async (input) => { + const ids = input.window.events.map((event) => event.id); + calls.push({ at: clock.now(), ids }); + if (ids[0] === 'a') await firstResult.promise; + return { route: 'queue' }; + }, + sink: async (decision) => { if (decision.window.events[0]?.id === 'a') await firstDelivery.promise; }, + }); + const intake = openIntake(attend, 's'); + const running = attend.run({ sweepMs: 10 ** 12 }); + const prepared: number[] = []; + try { + await intake.submit(async () => batch('a')); + clock.fire(100); + expect((await attend.inspect('s'))?.batch).toBeNull(); + const pending = intake.submit(async () => { prepared.push(clock.now()); return batch('b', 100); }); + await drain(); + expect(calls).toEqual([{ at: 100, ids: ['a'] }]); + clock.fire(150); firstResult.open(); await drain(); + clock.fire(200); await drain(); + expect(prepared).toEqual([]); + clock.fire(700); firstDelivery.open(); await pending; + expect(prepared).toEqual([700]); + expect(calls).toEqual([{ at: 100, ids: ['a'] }, { at: 700, ids: ['b'] }]); + } finally { + firstResult.open(); firstDelivery.open(); + await attend.stop(); await running; + } +}); + +test.each([false, true])('close and receipt wait for release commit, timer=%s', async (timer) => { + const clock = fakeClock(); + const held = gatedStore(); + const judge = scriptedJudge([{ route: 'queue' }]); + const attend = createAttend({ clock, store: held.store, kind: { move: 'continuous' }, judge, sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run({ sweepMs: 10 ** 12 }); + let acknowledged = false, closed = false; + try { + const released = held.hold('judgeReleased'); + let receipt: Promise | undefined; + let blocked: ReturnType; + if (timer) { + await intake.submit(async () => batch('a')); + blocked = held.hold('tick'); + await clock.advance(100); + } else { + blocked = held.hold('events'); + receipt = intake.submit(async () => batch('a', 0, 0)); + void receipt.then(() => { acknowledged = true; }); + } + await blocked.entered; + const closing = intake.close().then(() => { closed = true; }); + blocked.release(); + await released.entered; + await drain(); + expect(closed).toBe(false); + expect(acknowledged).toBe(false); + expect(judge.calls).toHaveLength(0); + released.release(); + await closing; await receipt; + expect((await attend.inspect('s'))?.batch?.phase.phase).toBe('retrying'); + } finally { + held.releaseAll(); await attend.stop(); await running; + } +}); + +test('deferral commit belongs to the receipt but future retry does not', async () => { + const held = gatedStore(); + const deferred = held.hold('judgeDeferred'); + const started = gate(), release = gate(); + const attend = createAttend({ clock: fakeClock(), store: held.store, kind: { move: 'continuous' }, judgeConcurrency: 1, + judge: async () => { started.open(); await release.promise; return { route: 'skip' }; }, sink: 'log' }); + const first = openIntake(attend, 'first'), second = openIntake(attend, 'second'); + const running = attend.run({ sweepMs: 10 ** 12 }); + let done = false; + try { + const one = first.submit(async () => batch('a', 0, 0)); + await started.promise; + const two = second.submit(async () => batch('b', 0, 0)).then(() => { done = true; }); + await deferred.entered; await drain(); + expect(done).toBe(false); + deferred.release(); await two; + expect((await attend.inspect('second'))?.batch?.phase.phase).toBe('retrying'); + release.open(); await one; + } finally { + held.releaseAll(); release.open(); await attend.stop(); await running; + } +}); + +test('a normal result queued before close is fenced until application', async () => { + const held = gatedStore(); + const delivered = held.hold('delivered'); + const clock = fakeClock(); + const releaseB = gate(), returnedB = gate(); + let deliveries = 0; + const attend = createAttend({ clock, store: held.store, kind: { move: 'continuous' }, settle: { retryBackoffMs: [1000] }, + judge: async (input) => { if (input.window.events[0]?.id === 'b') { await releaseB.promise; returnedB.open(); } return { route: 'queue' }; }, + sink: async () => { deliveries += 1; if (deliveries === 1) throw new Error('controlled failure'); }, + }); + const intake = openIntake(attend, 's'); + const running = attend.run({ sweepMs: 10 ** 12 }); + try { + await intake.submit(async () => batch('a', 0, 0)); + await intake.submit(async () => batch('b', 0, 1000)); + await clock.advance(1000); + await delivered.entered; + releaseB.open(); await returnedB.promise; await drain(); + const closed = intake.close(); + await clock.advance(10); + delivered.release(); await closed; + const record = await attend.inspect('s'); + expect(record?.batch?.phase.phase).toBe('retrying'); + expect(record?.outbox.decisions).toEqual([]); + expect(record?.recent).toHaveLength(1); + } finally { + held.releaseAll(); releaseB.open(); await attend.stop(); await running; + } +}); + +test('engine budget reserves preparation and refunds cancellation', async () => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log', admission: { maxQueuedInputs: 1 } }); + const first = openIntake(attend, 'first'), second = openIntake(attend, 'second'); + const running = attend.run(); + const release = gate(), controller = new AbortController(); + const prepare = async () => { await release.promise; return batch('a'); }; + try { + const pending = first.submit(prepare, { signal: controller.signal }); + expect(() => second.submit(prepare)).toThrow(BackpressureError); + await expect(attend.push('ordinary', { id: 'ordinary', name: 'move' })).rejects.toThrow(BackpressureError); + controller.abort(); await expect(pending).rejects.toBeDefined(); + release.open(); await second.submit(prepare); + await attend.push('ordinary', { id: 'ordinary', name: 'move' }); + } finally { + release.open(); await attend.stop(); await running; + } +}); + +test.each(['prepare', 'judge', 'sink'])('same-scope reentrancy during %s refuses without deadlock', async (during) => { + const refused: string[] = []; + const attempt = () => { + expect(() => intake.submit(async () => batch('nested'))).toThrow('own callback'); + expect(() => intake.close()).toThrow('own callback'); + refused.push(during); + }; + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, + judge: async () => { if (during === 'judge') attempt(); return { route: 'queue' }; }, + sink: async () => { if (during === 'sink') attempt(); }, + }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + await intake.submit(async () => { if (during === 'prepare') attempt(); return batch('a', 0, 0); }); + expect(refused).toEqual([during]); + } finally { + await attend.stop(); await running; + } +}); + +test('preparation failure keeps the cursor and permits another registration', async () => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + await expect(intake.submit(async () => { throw new Error('controlled preparation failure'); }, { source: 'feed' })).rejects.toThrow('controlled preparation'); + expect(await attend.inspect('s')).toBeNull(); + await intake.submit(async () => ({ events: [], cursor: '2' }), { source: 'feed' }); + expect((await attend.inspect('s'))?.cursors).toEqual({ feed: '2' }); + } finally { await attend.stop(); await running; } +}); + +test('close during load refuses unapplied input', async () => { + const inner = memoryStore(), entered = gate(), release = gate(); + const store: ScopeStore = { ...inner, async load(scope) { entered.open(); await release.promise; return inner.load(scope); } }; + const attend = createAttend({ store, clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + const pending = intake.submit(async () => batch('a')); + await entered.promise; + const closed = intake.close(); + release.open(); await closed; + await expect(pending).rejects.toThrow('closed'); + expect(await attend.inspect('s')).toBeNull(); + } finally { release.open(); await attend.stop(); await running; } +}); + +test('an applied prefix can commit after close', async () => { + const held = gatedStore(), events = held.hold('events'); + const clock = fakeClock(); + const attend = createAttend({ store: held.store, clock, kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + const pending = intake.submit(async () => batch('a')); + await events.entered; await clock.advance(10); + const closed = intake.close(); + await clock.advance(10); events.release(); + await pending; await closed; + expect((await attend.inspect('s'))?.buffer.entries[0]?.seenAt).toBe(0); + } finally { held.releaseAll(); await attend.stop(); await running; } +}); + +test('internal write failure rejects the operation without undoing accepted input', async () => { + const inner = memoryStore(); + const store: ScopeStore = { ...inner, async commit(writes) { + if (writes.some((write) => write.inputs.some((logged) => logged.input.kind === 'judged'))) throw new Error('controlled completion failure'); + return inner.commit(writes); + } }; + const attend = createAttend({ store, clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'); + const running = attend.run(); + try { + await expect(intake.submit(async () => batch('a', 0, 0))).rejects.toThrow('controlled completion'); + const record = await attend.inspect('s'); + expect(record?.seen).toEqual(['a']); expect(record?.recent).toEqual([]); + } finally { await attend.stop(); await running; } +}); + +test('retained-store recreation resumes a native release', async () => { + const store = memoryStore(), clock = fakeClock(), entered = gate(), release = gate(); + const first = createAttend({ store, clock, kind: { move: 'continuous' }, sink: 'log', + judge: async () => { entered.open(); await release.promise; return { route: 'queue' }; }, + }); + const intake = openIntake(first, 's'); + const running = first.run(); + const pending = intake.submit(async () => batch('a', 0, 0)); + await entered.promise; + const closed = intake.close(); release.open(); + await closed; await pending; await first.stop(); await running; + const judge = scriptedJudge([{ route: 'queue' }]); + const second = createAttend({ store, clock, kind: { move: 'continuous' }, judge, sink: 'log' }); + openIntake(second, 's'); + const resumed = second.run(); + try { + await clock.advance(0); + expect(judge.calls[0]?.window.events.map((event) => event.id)).toEqual(['a']); + expect((await second.inspect('s'))?.recent[0]?.route).toBe('queue'); + } finally { await second.stop(); await resumed; } +}); + +test('late preparation cannot admit after withdrawal', async () => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const intake = openIntake(attend, 's'), started = gate(), release = gate(), returned = gate(); + const running = attend.run(), controller = new AbortController(); + try { + const pending = intake.submit(async () => { started.open(); await release.promise; returned.open(); return batch('late'); }, { signal: controller.signal }); + await started.promise; + controller.abort(); await expect(pending).rejects.toBeDefined(); + await intake.close(); release.open(); await returned.promise; await drain(); + expect(await attend.inspect('s')).toBeNull(); + } finally { release.open(); await attend.stop(); await running; } +}); + +test('another owned scope progresses during preparation', async () => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + const first = openIntake(attend, 'first'), second = openIntake(attend, 'second'), release = gate(); + const running = attend.run(); + let done = false; + try { + const pending = first.submit(async () => { await release.promise; return batch('a'); }).then(() => { done = true; }); + await second.submit(async () => batch('b', 0, 0)); + expect(done).toBe(false); + expect((await attend.inspect('second'))?.recent[0]?.route).toBe('queue'); + release.open(); await pending; + } finally { release.open(); await attend.stop(); await running; } +}); + +test.each([0, -1, NaN, Infinity, 1.5, Number.MAX_SAFE_INTEGER + 1])('capacity %s must be a positive portable integer', (capacity) => { + const attend = createAttend({ clock: fakeClock(), kind: { move: 'continuous' }, judge: scriptedJudge([{ route: 'queue' }]), sink: 'log' }); + expect(() => openIntake(attend, 's', { capacity })).toThrow('capacity'); +});