From 054f3d736cb736cc3e834e86ab2dcc052f5eb504 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 10:57:28 -0600 Subject: [PATCH 1/5] test(intake): require preparation cleanup before close completes A cancelled receipt can precede cooperative callback cleanup. Pin close and stop ownership, earlier withdrawn work, shared waiter cancellation, and a callback factory that aborts before handing back its task. --- python/tests/test_intake.py | 5 +- python/tests/test_intake_cleanup.py | 134 ++++++++++++++++++++++++++++ test/intake-cleanup.test.ts | 60 +++++++++++++ test/intake.test.ts | 5 +- 4 files changed, 202 insertions(+), 2 deletions(-) create mode 100644 python/tests/test_intake_cleanup.py create mode 100644 test/intake-cleanup.test.ts diff --git a/python/tests/test_intake.py b/python/tests/test_intake.py index 306e8e3..1d321bd 100644 --- a/python/tests/test_intake.py +++ b/python/tests/test_intake.py @@ -703,9 +703,12 @@ async def late(signal: AbortSignal) -> SourceBatch: controller.abort() with pytest.raises(AbortError): await pending - await intake.close() + closing = asyncio.create_task(intake.close()) + await drain() + assert not closing.done() release.set() await returned.wait() + await closing await drain() assert await attend.inspect("s") is None finally: diff --git a/python/tests/test_intake_cleanup.py b/python/tests/test_intake_cleanup.py new file mode 100644 index 0000000..cf0d5b0 --- /dev/null +++ b/python/tests/test_intake_cleanup.py @@ -0,0 +1,134 @@ +"""A withdrawn receipt and a finished preparation callback are different facts.""" + +import asyncio + +import pytest + +from aqi_attend import AbortController, AbortSignal, IntakeError, SourceBatch, create_attend +from aqi_attend.signal import AbortError +from aqi_attend.testing import fake_clock, scripted_judge + + +@pytest.mark.parametrize("via", ["close", "stop", "cancel_runner"]) +async def test_close_joins_cooperative_preparation_cleanup(via: str) -> None: + clock = fake_clock() + engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log") + intake = engine.open_intake("scope") + running = asyncio.create_task(engine.run()) + started, cleaning, release, ended = [asyncio.Event() for _ in range(4)] + + async def prepare(signal: AbortSignal) -> SourceBatch: + started.set() + try: + await asyncio.Event().wait() + finally: + cleaning.set() + await release.wait() + ended.set() + return {"events": []} + + try: + receipt = intake.submit(prepare) + await started.wait() + closing = asyncio.create_task(intake.close() if via == "close" else engine.stop()) + await cleaning.wait() + await clock.advance(0) + assert receipt.done() + with pytest.raises(IntakeError): + await receipt + assert not closing.done() and not ended.is_set() + if via == "cancel_runner": + running.cancel() + await clock.advance(0) + assert not closing.done() + other = asyncio.create_task(intake.close()) + await clock.advance(0) + assert not other.done() + release.set() + await closing + await intake.close() + assert ended.is_set() + assert await engine.inspect("scope") is None + finally: + release.set() + await engine.stop() + await asyncio.gather(running, return_exceptions=True) + + +async def test_close_joins_an_earlier_withdrawn_callback_without_delaying_its_receipt() -> None: + clock = fake_clock() + engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log", max_queued_inputs=1) + intake = engine.open_intake("scope") + running = asyncio.create_task(engine.run()) + started, cleaning, release = [asyncio.Event() for _ in range(3)] + controller = AbortController() + + async def prepare(signal: AbortSignal) -> SourceBatch: + started.set() + try: + await asyncio.Event().wait() + finally: + cleaning.set() + await release.wait() + return {"events": [], "cursor": "late"} + + async def next_input(signal: AbortSignal) -> SourceBatch: + return {"events": [], "cursor": "kept"} + + try: + receipt = intake.submit(prepare, source="feed", signal=controller.signal) + await started.wait() + controller.abort() + with pytest.raises(AbortError): + await receipt + await cleaning.wait() + await intake.submit(next_input, source="feed") + closing = asyncio.create_task(intake.close()) + cancelled_waiter = asyncio.create_task(intake.close()) + await clock.advance(0) + cancelled_waiter.cancel() + await asyncio.gather(cancelled_waiter, return_exceptions=True) + assert not closing.done() + release.set() + await closing + record = await engine.inspect("scope") + assert record is not None and record["cursors"] == {"feed": "kept"} + finally: + release.set() + await engine.stop() + await running + + +async def test_abort_during_callback_creation_cancels_the_returned_task() -> None: + clock = fake_clock() + engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log") + intake = engine.open_intake("scope") + running = asyncio.create_task(engine.run()) + controller = AbortController() + called: list[bool] = [] + created: list[asyncio.Task[SourceBatch]] = [] + + async def work() -> SourceBatch: + called.append(True) + await asyncio.Event().wait() + return {"events": []} + + def prepare(signal: AbortSignal) -> asyncio.Task[SourceBatch]: + controller.abort() + task = asyncio.create_task(work()) + created.append(task) + return task + + try: + with pytest.raises(AbortError): + await intake.submit(prepare, signal=controller.signal) + await clock.advance(0) + assert called == [] + assert created[0].cancelled() + await intake.close() + finally: + for task in created: + task.cancel() + await asyncio.gather(*created, return_exceptions=True) + await engine.stop() + await running diff --git a/test/intake-cleanup.test.ts b/test/intake-cleanup.test.ts new file mode 100644 index 0000000..d5d5bb0 --- /dev/null +++ b/test/intake-cleanup.test.ts @@ -0,0 +1,60 @@ +import { expect, test } from 'vitest'; +import { createAttend } from '../src/index.js'; +import { openIntake } from '../src/intake.js'; +import { fakeClock, scriptedJudge } from '../src/testing.js'; + +function gate() { + const controller = new AbortController(); + const promise = new Promise((resolve) => controller.signal.addEventListener('abort', () => resolve(), { once: true })); + return { promise, open: () => controller.abort() }; +} + +test.each(['close', 'stop'])('%s joins cooperative preparation cleanup', async (via) => { + const clock = fakeClock(), engine = createAttend({ clock, kind: {}, judge: scriptedJudge([]), sink: 'log' }); + const intake = openIntake(engine, 'scope'), running = engine.run(); + const started = gate(), cleaning = gate(), release = gate(), ended = gate(); + let closed = false, receiptDone = false; + try { + const receipt = intake.submit(async signal => { + started.open(); + try { await new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })); } + finally { cleaning.open(); await release.promise; ended.open(); } + return { events: [] }; + }); + void receipt.then(() => { receiptDone = true; }, () => { receiptDone = true; }); + await started.promise; + const closing = (via === 'close' ? intake.close() : engine.stop()).then(() => { closed = true; }); + await cleaning.promise; await clock.advance(0); + expect(receiptDone).toBe(true); + expect(closed).toBe(false); + release.open(); await ended.promise; await closing; + await expect(receipt).rejects.toThrow('closed'); + expect(await engine.inspect('scope')).toBeNull(); + } finally { release.open(); await engine.stop(); await running; } +}); + +test('close joins previously withdrawn work and preserves prompt receipt/capacity release', async () => { + const clock = fakeClock(), engine = createAttend({ clock, kind: {}, judge: scriptedJudge([]), sink: 'log', admission: { maxQueuedInputs: 1 } }); + const intake = openIntake(engine, 'scope'), running = engine.run(); + const started = gate(), cleaning = gate(), release = gate(); + const controller = new AbortController(); + let closed = false; + try { + const receipt = intake.submit(async signal => { + started.open(); + try { await new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })); } + finally { cleaning.open(); await release.promise; } + return { events: [], cursor: 'late' }; + }, { source: 'feed', signal: controller.signal }); + await started.promise; controller.abort(); + await expect(receipt).rejects.toBeDefined(); + await cleaning.promise; + await intake.submit(async () => ({ events: [], cursor: 'kept' }), { source: 'feed' }); + const shared = intake.close(); + expect(intake.close()).toBe(shared); + const closing = shared.then(() => { closed = true; }); + await clock.advance(0); expect(closed).toBe(false); + release.open(); await closing; + expect((await engine.inspect('scope'))?.cursors).toEqual({ feed: 'kept' }); + } finally { release.open(); await engine.stop(); await running; } +}); diff --git a/test/intake.test.ts b/test/intake.test.ts index 62eb00e..0ec39f6 100644 --- a/test/intake.test.ts +++ b/test/intake.test.ts @@ -417,7 +417,10 @@ test('late preparation cannot admit after withdrawal', async () => { 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(); + let closed = false; + const closing = intake.close().then(() => { closed = true; }); + await drain(); expect(closed).toBe(false); + release.open(); await returned.promise; await closing; await drain(); expect(await attend.inspect('s')).toBeNull(); } finally { release.open(); await attend.stop(); await running; } }); From 69e2d2ed3e6c1a790be0a2a4519561be29583b6f Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 11:11:07 -0600 Subject: [PATCH 2/5] fix(intake): join every started preparation before closing Retain direct preparation awaitables beyond withdrawal so close and engine shutdown wait for cooperative cleanup. Preserve prompt input rejection and logical queue progress, cancel tasks returned after a factory abort, and shield shared close completion from shutdown waiter cancellation. --- DEVIATIONS.md | 2 ++ docs/reference.md | 2 +- python/README.md | 2 ++ python/src/aqi_attend/attend.py | 2 +- python/src/aqi_attend/shell/intake.py | 14 ++++++++- python/src/aqi_attend/signal.py | 7 +++-- python/tests/test_intake_cleanup.py | 45 +++++++++++++++++++++++++-- src/shell/intake.ts | 8 ++++- test/intake-cleanup.test.ts | 16 ++++++++++ 9 files changed, 90 insertions(+), 8 deletions(-) diff --git a/DEVIATIONS.md b/DEVIATIONS.md index c6924b5..9a8d68c 100644 --- a/DEVIATIONS.md +++ b/DEVIATIONS.md @@ -12,6 +12,8 @@ The optional serial intake owns registration, asynchronous preparation and immed The queue, callbacks and catch-up metadata are local and are never stored. Serial intake introduced no new persisted inputs or reducer-version change. 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. +Intake also retains each started preparation awaitable until it settles. Withdrawal can reject its receipt before cleanup ends, but close and engine shutdown join that cleanup, including work withdrawn before close. This changes no reducer transition or saved state. Python's shared close completion is shielded from shutdown-waiter cancellation. + ## 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. diff --git a/docs/reference.md b/docs/reference.md index 9fec866..1524e71 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -128,7 +128,7 @@ An opted-in scope refuses ordinary `push`, `attach`, `flush` and `end`, includin `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. +Abort before application prevents event and cursor admission. An input already applied may still commit; abort does not roll it back. A withdrawn submission can reject promptly and release its admission slot while its callback finishes cancellation cleanup. Later submissions can proceed. `close()` fences new work synchronously, aborts preparation and active effect signals, and joins every preparation awaitable the intake started, including earlier withdrawn work, plus owned immediate effects. 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 settles can keep it pending. Callbacks must await their own dependency cleanup; arbitrary detached child work is not joined. 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. diff --git a/python/README.md b/python/README.md index 70d6eba..688bc68 100644 --- a/python/README.md +++ b/python/README.md @@ -115,6 +115,8 @@ async def accept(): `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. +A withdrawn receipt can fail before preparation cleanup finishes; intake close joins every preparation task it started. Outside that ownership, `AbortSignal.race(work)` requests cancellation without waiting for cleanup. Keep a task handle and join it when its resource lifetime matters. A callback that detaches child work remains responsible for joining it. + ## 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/attend.py b/python/src/aqi_attend/attend.py index e2eb990..15d93e4 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -759,7 +759,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) + await asyncio.gather(*(asyncio.shield(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/shell/intake.py b/python/src/aqi_attend/shell/intake.py index feb1352..56b09e0 100644 --- a/python/src/aqi_attend/shell/intake.py +++ b/python/src/aqi_attend/shell/intake.py @@ -74,6 +74,7 @@ def __init__( self._work_done.set() self._closed: asyncio.Future[None] | None = None self._tasks: set[asyncio.Task[None]] = set() + self._preparations: set[asyncio.Future[SourceBatch]] = set() self._completion = AbortController() @property @@ -173,7 +174,12 @@ async def _perform(self, activity: _Activity) -> None: return signal = operation.controller.signal signal.throw_if_aborted() - batch = await signal.race(operation.prepare(signal)) + preparation = asyncio.ensure_future(operation.prepare(signal)) + self._preparations.add(preparation) + preparation.add_done_callback(self._prepared) + if signal.aborted: + preparation.cancel() + batch = await signal.race(preparation) signal.throw_if_aborted() events = self._classify(batch["events"]) input: EventsInput = {"kind": "events", "events": events} @@ -210,6 +216,11 @@ async def _perform(self, activity: _Activity) -> None: activity.finished.set_result(None) self._pump() + def _prepared(self, future: asyncio.Future[SourceBatch]) -> None: + self._preparations.discard(future) + if not future.cancelled(): + future.exception() + def _begin_work(self) -> _Activity | None: self._work += 1 self._work_done.clear() @@ -271,6 +282,7 @@ async def join() -> None: if activity is not None: await activity.finished await self._work_done.wait() + await asyncio.gather(*tuple(self._preparations), return_exceptions=True) if activity is not None and activity.failure is not None: raise activity.failure future.set_result(None) diff --git a/python/src/aqi_attend/signal.py b/python/src/aqi_attend/signal.py index c1e7f50..29e9bb8 100644 --- a/python/src/aqi_attend/signal.py +++ b/python/src/aqi_attend/signal.py @@ -78,7 +78,10 @@ async def wait(self) -> None: remove() async def race(self, work: Awaitable[T]) -> T: - """Awaits ``work`` unless the signal aborts first, then cancels it and raises the reason.""" + """Awaits work unless aborted; requests cancellation without joining its cleanup. + + Keep an owned task and join it separately when cleanup completion matters. + """ self.throw_if_aborted() task = asyncio.ensure_future(work) aborted = asyncio.ensure_future(self.wait()) @@ -86,7 +89,7 @@ async def race(self, work: Awaitable[T]) -> T: await asyncio.wait({task, aborted}, return_when=asyncio.FIRST_COMPLETED) finally: aborted.cancel() - # Also when the awaiting task is cancelled, so the work never outlives its caller. + # Request cancellation when the awaiting task is cancelled too. if not task.done(): task.cancel() if task.done() and not task.cancelled(): diff --git a/python/tests/test_intake_cleanup.py b/python/tests/test_intake_cleanup.py index cf0d5b0..3c2c318 100644 --- a/python/tests/test_intake_cleanup.py +++ b/python/tests/test_intake_cleanup.py @@ -99,7 +99,12 @@ async def next_input(signal: AbortSignal) -> SourceBatch: await running -async def test_abort_during_callback_creation_cancels_the_returned_task() -> None: +@pytest.mark.parametrize("eager", [False, True]) +async def test_abort_during_callback_creation_cancels_the_returned_task(eager: bool) -> None: + loop = asyncio.get_running_loop() + previous_factory = loop.get_task_factory() + if eager: + loop.set_task_factory(asyncio.eager_task_factory) clock = fake_clock() engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log") intake = engine.open_intake("scope") @@ -123,7 +128,7 @@ def prepare(signal: AbortSignal) -> asyncio.Task[SourceBatch]: with pytest.raises(AbortError): await intake.submit(prepare, signal=controller.signal) await clock.advance(0) - assert called == [] + assert called == ([True] if eager else []) assert created[0].cancelled() await intake.close() finally: @@ -132,3 +137,39 @@ def prepare(signal: AbortSignal) -> asyncio.Task[SourceBatch]: await asyncio.gather(*created, return_exceptions=True) await engine.stop() await running + loop.set_task_factory(previous_factory) + + +async def test_close_consumes_a_withdrawn_callback_that_later_fails() -> None: + clock = fake_clock() + engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log") + intake = engine.open_intake("scope") + running = asyncio.create_task(engine.run()) + started, cleaning, release = [asyncio.Event() for _ in range(3)] + + async def prepare(signal: AbortSignal) -> SourceBatch: + started.set() + try: + await asyncio.Event().wait() + except asyncio.CancelledError: + cleaning.set() + await release.wait() + raise ValueError("late failure") + return {"events": []} + + try: + receipt = intake.submit(prepare) + await started.wait() + closing = asyncio.create_task(intake.close()) + await cleaning.wait() + await clock.advance(0) + assert not closing.done() + release.set() + await closing + with pytest.raises(IntakeError): + await receipt + assert await engine.inspect("scope") is None + finally: + release.set() + await engine.stop() + await running diff --git a/src/shell/intake.ts b/src/shell/intake.ts index 49f3feb..f9b7d40 100644 --- a/src/shell/intake.ts +++ b/src/shell/intake.ts @@ -65,6 +65,7 @@ interface Runtime { export class IntakeQueue implements Intake { private readonly owner: IntakeOwner; private readonly queue = new Set(); + private readonly preparations = new Set>(); private active: Activity | null = null; private timerPending = false; private work = 0; @@ -138,7 +139,11 @@ export class IntakeQueue implements Intake { 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); } + try { + const preparation = operation.prepare(signal).then(success, failure); + this.preparations.add(preparation); + void preparation.then(() => { this.preparations.delete(preparation); }); + } catch (error) { failure(error); } }); } @@ -209,6 +214,7 @@ export class IntakeQueue implements Intake { void (async () => { await activity?.finished.promise; await this.workDone?.promise; + await Promise.all([...this.preparations]); if (activity?.failure) throw activity.failure.error; })().then(closing.resolve, closing.reject); return closing.promise; diff --git a/test/intake-cleanup.test.ts b/test/intake-cleanup.test.ts index d5d5bb0..0ce061b 100644 --- a/test/intake-cleanup.test.ts +++ b/test/intake-cleanup.test.ts @@ -58,3 +58,19 @@ test('close joins previously withdrawn work and preserves prompt receipt/capacit expect((await engine.inspect('scope'))?.cursors).toEqual({ feed: 'kept' }); } finally { release.open(); await engine.stop(); await running; } }); + +test('close joins a withdrawn callback that later rejects', async () => { + const clock = fakeClock(), engine = createAttend({ clock, kind: {}, judge: scriptedJudge([]), sink: 'log' }); + const intake = openIntake(engine, 'scope'), running = engine.run(); + const started = gate(), release = gate(); + let closed = false; + try { + const receipt = intake.submit(async () => { started.open(); await release.promise; throw new Error('late failure'); }); + await started.promise; + const closing = intake.close().then(() => { closed = true; }); + await clock.advance(0); expect(closed).toBe(false); + release.open(); await closing; + await expect(receipt).rejects.toThrow('closed'); + expect(await engine.inspect('scope')).toBeNull(); + } finally { release.open(); await engine.stop(); await running; } +}); From 1a8f8560312043fb0400498cac2955e4945ddd39 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 11:11:52 -0600 Subject: [PATCH 3/5] test(intake): make late cleanup failure explicit The regression intentionally replaces cancellation with a late callback error; suppress the cancelled exception context so the test states that outcome directly. --- python/tests/test_intake_cleanup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/tests/test_intake_cleanup.py b/python/tests/test_intake_cleanup.py index 3c2c318..abd08eb 100644 --- a/python/tests/test_intake_cleanup.py +++ b/python/tests/test_intake_cleanup.py @@ -154,7 +154,7 @@ async def prepare(signal: AbortSignal) -> SourceBatch: except asyncio.CancelledError: cleaning.set() await release.wait() - raise ValueError("late failure") + raise ValueError("late failure") from None return {"events": []} try: From 3b80acc7abaa334940d871a542bd73b5753e7f97 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 11:22:05 -0600 Subject: [PATCH 4/5] test(intake): reproduce repeated cancellation and self-stop cycles A second runner cancellation can publish completion before cleanup, while stop awaited from its own preparation waits on itself. Pin both lifecycle boundaries before fixing shutdown ownership. --- python/tests/test_intake_cleanup.py | 8 ++++++-- test/intake-cleanup.test.ts | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/python/tests/test_intake_cleanup.py b/python/tests/test_intake_cleanup.py index abd08eb..32d4bde 100644 --- a/python/tests/test_intake_cleanup.py +++ b/python/tests/test_intake_cleanup.py @@ -9,7 +9,7 @@ from aqi_attend.testing import fake_clock, scripted_judge -@pytest.mark.parametrize("via", ["close", "stop", "cancel_runner"]) +@pytest.mark.parametrize("via", ["close", "stop", "cancel_runner", "cancel_runner_twice"]) async def test_close_joins_cooperative_preparation_cleanup(via: str) -> None: clock = fake_clock() engine = create_attend(clock=clock, kind={}, judge=scripted_judge([]), sink="log") @@ -37,10 +37,14 @@ async def prepare(signal: AbortSignal) -> SourceBatch: with pytest.raises(IntakeError): await receipt assert not closing.done() and not ended.is_set() - if via == "cancel_runner": + if via in ("cancel_runner", "cancel_runner_twice"): running.cancel() await clock.advance(0) assert not closing.done() + if via == "cancel_runner_twice": + running.cancel() + await clock.advance(0) + assert not closing.done() and not running.done() other = asyncio.create_task(intake.close()) await clock.advance(0) assert not other.done() diff --git a/test/intake-cleanup.test.ts b/test/intake-cleanup.test.ts index 0ce061b..4fa3db5 100644 --- a/test/intake-cleanup.test.ts +++ b/test/intake-cleanup.test.ts @@ -74,3 +74,22 @@ test('close joins a withdrawn callback that later rejects', async () => { expect(await engine.inspect('scope')).toBeNull(); } finally { release.open(); await engine.stop(); await running; } }); + +test('stop refuses to join its own preparation callback', async () => { + const clock = fakeClock(), engine = createAttend({ clock, kind: {}, judge: scriptedJudge([]), sink: 'log' }); + const intake = openIntake(engine, 'scope'), running = engine.run(), started = gate(), rescue = gate(); + let outcome = 'pending'; + try { + const receipt = intake.submit(async () => { + started.open(); + await Promise.race([ + engine.stop().then(() => { outcome = 'accepted'; }, (error: unknown) => { outcome = error instanceof Error ? error.message : 'wrong error'; }), + rescue.promise, + ]); + return { events: [] }; + }); + await started.promise; await clock.advance(0); + expect(outcome).toContain('own callback'); + await receipt; + } finally { rescue.open(); await intake.close(); await engine.stop(); await running; } +}); From b107204c15aa935150ff977b4ad2102a6d0a57c0 Mon Sep 17 00:00:00 2001 From: asher-aqi Date: Thu, 12 Nov 2026 11:26:49 -0600 Subject: [PATCH 5/5] fix(intake): keep shutdown owned through repeated cancellation Run shutdown once in its own shielded task and publish completion only after it joins. Refuse stop from an intake callback context so cleanup cannot await itself; callers can request stop through the run signal. --- docs/reference.md | 2 ++ python/README.md | 2 ++ python/src/aqi_attend/attend.py | 34 +++++++++++++-------- python/src/aqi_attend/shell/intake.py | 5 +++ python/tests/test_intake_cleanup.py | 44 ++++++++++++++++++++++++++- src/attend.ts | 3 ++ src/shell/intake.ts | 2 ++ test/intake-cleanup.test.ts | 17 +++++++++++ 8 files changed, 95 insertions(+), 14 deletions(-) diff --git a/docs/reference.md b/docs/reference.md index 1524e71..66bc30a 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -126,6 +126,8 @@ The promise covers the input write and the immediate chain of judgments, deliver An opted-in scope refuses ordinary `push`, `attach`, `flush` and `end`, including after close. Same-engine, same-scope `submit` or `close` from preparation, context, judge or delivery rejects with `IntakeError`; awaiting it would wait on itself. Other scopes progress independently. Do not create cycles by awaiting each other's intakes from callbacks. +An engine's `stop()` also rejects from its own intake callback context, because shutdown joins that callback. To request shutdown from a callback, abort the signal supplied to `run()` and return; await stop from outside the callback. + `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. A withdrawn submission can reject promptly and release its admission slot while its callback finishes cancellation cleanup. Later submissions can proceed. `close()` fences new work synchronously, aborts preparation and active effect signals, and joins every preparation awaitable the intake started, including earlier withdrawn work, plus owned immediate effects. 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 settles can keep it pending. Callbacks must await their own dependency cleanup; arbitrary detached child work is not joined. Repeated close calls join the same cleanup. diff --git a/python/README.md b/python/README.md index 688bc68..16de69b 100644 --- a/python/README.md +++ b/python/README.md @@ -117,6 +117,8 @@ async def accept(): A withdrawn receipt can fail before preparation cleanup finishes; intake close joins every preparation task it started. Outside that ownership, `AbortSignal.race(work)` requests cancellation without waiting for cleanup. Keep a task handle and join it when its resource lifetime matters. A callback that detaches child work remains responsible for joining it. +Repeated cancellation of the runner does not skip its cleanup join. `stop()` rejects from the engine's own intake callback context; use the caller-owned run signal to request shutdown there and return without awaiting that shutdown. + ## 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/attend.py b/python/src/aqi_attend/attend.py index 15d93e4..e0737a9 100644 --- a/python/src/aqi_attend/attend.py +++ b/python/src/aqi_attend/attend.py @@ -53,7 +53,7 @@ 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.intake import Intake, owns_callback from .shell.read import read_record from .shell.scheduler import Scheduler from .shell.scope import Scopes @@ -688,16 +688,18 @@ def run(self, *, signal: AbortSignal | None = None, sweep_ms: float = 1000, swee async def _run(self, signal: AbortSignal, own: AbortController, finished: asyncio.Future[None], sweep_ms: float, sweep_limit: int) -> None: try: await self._run_loop(signal, sweep_ms, sweep_limit) - except asyncio.CancelledError: - own.abort() - await self._shutdown() - raise finally: - if not finished.done(): - finished.set_result(None) + own.abort() + try: + await self._join_shutdown() + finally: + if not finished.done(): + finished.set_result(None) async def stop(self) -> None: """Stops the run, whether or not it was given a signal, and returns when it has finished.""" + if owns_callback(self._intake_identity): + raise IntakeError("attend: cannot stop an engine from its own callback") if self._stopper is not None: self._stopper.abort() if self._finished is not None: @@ -731,7 +733,6 @@ def _on_abort(self) -> None: async def _run_loop(self, signal: AbortSignal, sweep_ms: float, sweep_limit: int) -> None: self._running = signal remove = signal.add_listener(self._on_abort) - shutdown = True try: if signal.aborted: return @@ -741,14 +742,21 @@ async def _run_loop(self, signal: AbortSignal, sweep_ms: float, sweep_limit: int await self._sweep(self._clock.now(), sweep_limit, False) self._scopes.evict() await sleep(self._clock, sweep_ms, signal) - except asyncio.CancelledError: - shutdown = False - raise finally: self._on_abort() remove() - if shutdown: - await self._shutdown() + + async def _join_shutdown(self) -> None: + cleanup = asyncio.create_task(self._shutdown()) + interrupted: asyncio.CancelledError | None = None + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError as error: + interrupted = error + cleanup.result() + if interrupted is not None: + raise interrupted async def _shutdown(self) -> None: writes = self._scopes.pending() diff --git a/python/src/aqi_attend/shell/intake.py b/python/src/aqi_attend/shell/intake.py index 56b09e0..02b1f44 100644 --- a/python/src/aqi_attend/shell/intake.py +++ b/python/src/aqi_attend/shell/intake.py @@ -19,6 +19,11 @@ _owner: ContextVar[tuple[object, str] | None] = ContextVar("attend_intake_owner", default=None) +def owns_callback(identity: object) -> bool: + owner = _owner.get() + return owner is not None and owner[0] is identity + + def _consume(future: asyncio.Future[None]) -> None: if not future.cancelled(): future.exception() diff --git a/python/tests/test_intake_cleanup.py b/python/tests/test_intake_cleanup.py index 32d4bde..f813fc2 100644 --- a/python/tests/test_intake_cleanup.py +++ b/python/tests/test_intake_cleanup.py @@ -4,7 +4,8 @@ import pytest -from aqi_attend import AbortController, AbortSignal, IntakeError, SourceBatch, create_attend +from aqi_attend import AbortController, AbortSignal, Decision, IntakeError, JudgeInput, Judgment, SourceBatch, create_attend +from aqi_attend.attend import JudgeContext from aqi_attend.signal import AbortError from aqi_attend.testing import fake_clock, scripted_judge @@ -177,3 +178,44 @@ async def prepare(signal: AbortSignal) -> SourceBatch: release.set() await engine.stop() await running + + +@pytest.mark.parametrize("where", ["prepare", "context", "judge", "sink"]) +async def test_stop_refuses_to_join_an_owned_callback(where: str) -> None: + reached: list[str] = [] + + async def stop_inside() -> None: + with pytest.raises(IntakeError, match="own callback"): + await engine.stop() + reached.append(where) + + async def context(scope: str, signal: AbortSignal) -> JudgeContext: + if where == "context": + await stop_inside() + return {} + + async def judge(input: JudgeInput, signal: AbortSignal) -> Judgment: + if where == "judge": + await stop_inside() + return {"route": "queue"} + + async def sink(decision: Decision, signal: AbortSignal) -> None: + if where == "sink": + await stop_inside() + + async def prepare(signal: AbortSignal) -> SourceBatch: + if where == "prepare": + await stop_inside() + return {"events": [{"id": "a", "name": "message", "at": 0, "data": {}}]} + + engine = create_attend(clock=fake_clock(), kind={"message": "flush"}, context=context, judge=judge, sink=sink) + intake = engine.open_intake("scope") + running = asyncio.create_task(engine.run()) + try: + await intake.submit(prepare) + assert reached == [where] + assert engine.running + finally: + await intake.close() + await engine.stop() + await running diff --git a/src/attend.ts b/src/attend.ts index c0019e1..f051ea5 100644 --- a/src/attend.ts +++ b/src/attend.ts @@ -365,6 +365,9 @@ export function createAttendInternal(config: AttendConfig, snapshot: 'ratio' | ' }, async stop() { + for (const intake of intakes.values()) { + if (intake.ownsCurrentCallback()) throw new IntakeError('attend: cannot stop an engine from its own callback'); + } stopper?.abort(); await finished; }, diff --git a/src/shell/intake.ts b/src/shell/intake.ts index f9b7d40..7c766a1 100644 --- a/src/shell/intake.ts +++ b/src/shell/intake.ts @@ -80,6 +80,8 @@ export class IntakeQueue implements Intake { get closed(): boolean { return this.closing !== null; } get completionSignal(): AbortSignal { return this.completion.signal; } + ownsCurrentCallback(): boolean { return this.context.getStore()?.engine === this.owner.engine; } + 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'); diff --git a/test/intake-cleanup.test.ts b/test/intake-cleanup.test.ts index 4fa3db5..c726e85 100644 --- a/test/intake-cleanup.test.ts +++ b/test/intake-cleanup.test.ts @@ -93,3 +93,20 @@ test('stop refuses to join its own preparation callback', async () => { await receipt; } finally { rescue.open(); await intake.close(); await engine.stop(); await running; } }); + +test.each(['prepare', 'context', 'judge', 'sink'])('stop refuses its own %s callback without stopping other work', async (where) => { + const reached: string[] = []; + const stopInside = async () => { await expect(engine.stop()).rejects.toThrow('own callback'); reached.push(where); }; + const engine = createAttend({ clock: fakeClock(), kind: { message: 'flush' }, + context: async () => { if (where === 'context') await stopInside(); return {}; }, + judge: async () => { if (where === 'judge') await stopInside(); return { route: 'queue' }; }, + sink: async () => { if (where === 'sink') await stopInside(); }, + }); + const intake = openIntake(engine, 'scope'), running = engine.run(); + try { + await intake.submit(async () => { if (where === 'prepare') await stopInside(); return { events: [{ id: 'a', name: 'message', at: 0, data: {} }] }; }); + expect(reached).toEqual([where]); + await intake.submit(async () => ({ events: [], cursor: '2' }), { source: 'feed' }); + expect((await engine.inspect('scope'))?.cursors).toEqual({ feed: '2' }); + } finally { await intake.close(); await engine.stop(); await running; } +});