Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions DEVIATIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
4 changes: 3 additions & 1 deletion docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,11 @@ 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. `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.

Expand Down
4 changes: 4 additions & 0 deletions python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,10 @@ 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.

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.
Expand Down
36 changes: 22 additions & 14 deletions python/src/aqi_attend/attend.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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()
Expand All @@ -759,7 +767,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():
Expand Down
19 changes: 18 additions & 1 deletion python/src/aqi_attend/shell/intake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -74,6 +79,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
Expand Down Expand Up @@ -173,7 +179,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}
Expand Down Expand Up @@ -210,6 +221,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()
Expand Down Expand Up @@ -271,6 +287,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)
Expand Down
7 changes: 5 additions & 2 deletions python/src/aqi_attend/signal.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,15 +78,18 @@ 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())
try:
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():
Expand Down
5 changes: 4 additions & 1 deletion python/tests/test_intake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading
Loading