Repository navigation
feat(daemon): Make the service inventory total and retain orphan ownership - #5351
Conversation
The composition-route inventory that proves every daemon task is declared
read its denominator from `asyncio.create_task` alone, filtered to tasks
whose immediate caller was `polylogue/daemon/cli.py`. A child spawned with
`asyncio.ensure_future`, with `loop.create_task`, or from any other daemon
module was invisible to it, so "the registry accounts for every spawned
task" was only ever checked for one spelling in one file.
The inventory now installs a task factory on the loop the composition route
runs on. Every `create_task`, `ensure_future` and `loop.create_task` funnels
through that one construction point, so the denominator is what the loop
actually built and nothing in it consults the service registry. Tasks are
then partitioned into supervisor-owned (which must resolve in the registry)
and a declared table of bounded per-operation children with named owners;
anything else fails with its name and the `file:line` that created it.
Two production child tasks were anonymous, which an inventory cannot
attribute: `DaemonWriteThreadBridge.run_async` and `DriveCatchupExecution.settle`
now name theirs. `settle` only names a task it actually created -- a Future
handed in by `loop.run_in_executor` is already owned by its scheduler.
Verification: devtools test tests/unit/daemon/test_daemon_cli.py::test_the_composition_route_spawns_only_declared_supervised_services (exit 0)
Anti-vacuity, executed:
* `asyncio.ensure_future(asyncio.sleep(0))` in `run_daemon_services` ->
"spawned a task no owner declares: Task-2 (.../daemon/cli.py:2513)"
* deleting the `secret_scan_sweep` registration ->
"UnknownServiceError: no daemon service named 'secret_scan_sweep' is declared"
* dropping its `supervisor.start` call ->
"declared services the composition route never resolved: ['secret_scan_sweep']"
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
`DaemonSupervisor.shutdown` already cancels every child, awaits it inside its declared deadline, and names whatever is still running as an orphan. The composition root then logged that fact and released ownership anyway: `writer_drained` came only from the write coordinator, so the pidfile, the process-lifetime rebuild exclusion and the durable archive lease were all dropped while a cancelled child was still executing. An offline rebuild, a second daemon, or an interactive CLI mutation could start beside code that could still commit. Ownership now asks one question -- does this process still contain anything that can write -- and two independent facts answer it. An undrained coordinator has admitted work in flight; an orphaned service is a child the supervisor could not prove had stopped. `ShutdownReport.incomplete` names the second, deliberately distinct from `clean`: a `failed` service already terminated with an exception and cannot write, so it does not retain ownership. The retained pidfile and the `daemon.stopped` outcome now carry the actual reason rather than always attributing retention to the writer coordinator. Verification: devtools test tests/unit/daemon/test_daemon_cli.py::test_an_orphaned_service_retains_archive_ownership_on_the_production_route (exit 0) Anti-vacuity, executed: replacing `orphaned_services=shutdown_report.orphaned` with `()` reddens with "the durable archive lease was released beside a still-running child". Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
The embedding backlog loop is woken by every committed ingest and cadenced
behind that. When the backlog is already empty each wake produced another
identical completion report, so "the backlog drained" was indistinguishable
from "the backlog drained a hundred times" -- the shape behind
polylogue-09rn, where an idle loop turned into a 300-second spin.
The runner now accounts for drain *cycles*. A loop whose work callable
returns a `PassOutcome` gets `drained`, `drain_transitions` and
`last_drained_at` in the per-loop state the status and metrics surfaces
already render. The transition is counted on the progressed -> drained edge
only; a pass that does work re-arms the cycle. Loops with no backlog of
their own return nothing and are unaffected.
`periodic_embedding_backlog_check` reports its outcome: a converged pass
that moved messages is PROGRESSED, a converged pass that found none is
DRAINED, and a policy deferral or failure reports nothing at all -- a
refusal to do the work is not a pass that found none of it.
Verification: devtools test tests/unit/daemon/test_periodic_runner.py
tests/unit/daemon/test_event_bus_ingest_wakeup.py
tests/unit/daemon/test_embedding_convergence_progress.py
tests/unit/daemon/test_catch_up_gate_timeout.py
tests/unit/daemon/test_daemon_status.py (exit 0)
Both regressions are proved with a controlled barrier rather than repeated
wall-clock timeout runs. Anti-vacuity, executed:
* dropping the `state.drained is not True` edge guard -> 4 transitions
reported for one drained backlog instead of 1;
* dropping `wakeup.clear()` from the cadence wait -> 19 passes instead of
3 for two wakes, i.e. the loop never parks again.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
`test_daemon_status_names_every_halted_unit_and_is_not_ok` asserted that a daemon holding a halt reports `ok: false`, and named "drop `and not halted_units`" as the mutation that reddens it. It does not. On the bare tmp directory the fixture used, `raw_failure_lifecycle_available` is already False, so `ok` was False before the halt was ever recorded and stayed False with the halt term removed -- the assertion was about an unavailable archive, not about halts. The archive root is now initialized and the payload read twice: the pre-halt read must be `ok: true`, which is what makes the post-halt `false` evidence about the halt. Verification: devtools test tests/unit/daemon/test_status_observations.py (exit 0) Anti-vacuity, executed: removing `and not halted_units` now fails with `assert True is False`; before this change the same mutation left the test green. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
The composition root opened an archive generation, registered every intake
adapter and began a cold-build generation before asking whether anything
would consume them. Under a focused profile that declares no intake service
all of that was real archive work whose products were discarded at
shutdown, which is what AC4's fixture was paying for: measured across five
runs at head it took 1.15-7.76 s against its own ten-second budget, and the
7.76 s peak is close enough to that budget to fail on a contended host.
The route now asks the supervisor -- `is_schedulable("fair_intake") or
is_schedulable("watcher")` -- which is also the one place a durable halt is
consulted, so intake that has been halted is not constructed either. The
production profile schedules `fair_intake` unconditionally, so production
takes the same branch it always did; only RESIDENT_CORE and SURFACES skip,
which is exactly what those profiles declare. The skip event now names
whether the watcher was preflight-blocked or simply not scheduled by the
profile, rather than always reporting `schema_blocked`.
Measured after: 0.47-1.48 s across three runs.
Verification: devtools test tests/unit/daemon/test_daemon_cli.py (exit 1;
7 failures, all a strict subset of the 8 the same selection fails at
origin/master -- inherited, see polylogue-known-red)
Anti-vacuity, executed: dropping the `intake_scheduled` guard makes the new
`intake_builds == []` assertion fail naming the constructed
`DaemonIntakeContext`.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
…class
The halt property covers "service, source, intake class, derivation
domain", but in production a *source* had no halt at either end. Every
configured source is multiplexed into one `configured_local` dispatcher
class, so the only available halt was class-grain: `UnitKind.SOURCE` had no
producer and no planner consumer at all. That left the two failure modes the
property exists to remove, one on each side -- halting the class stops every
healthy sibling, and halting nothing is polylogue-kqrbw, where a source
logged "refusing further ingest until restart" once and the planner kept
selecting its files for the remaining 95% of the run while 926 empty chunks
each took the writer lease for 1.0-3.1 s.
`MultiplexIntakeAdapter` now consults a `SubUnitHaltPolicy`. A sub-adapter's
CLASS_TERMINAL becomes a durable halt on *that source* plus a per-item
TERMINAL, so the class survives and the siblings keep draining; a halted
source is then excluded in `discover`, where work is selected. The policy is
two callables supplied by the composition root rather than an import of the
daemon's halt store, so the product layer does not acquire an edge onto the
daemon ring to ask a yes/no question.
Because the halt lands in the same durable registry the supervisor and the
dispatcher already read, compact status names `source:<name>` and reports
not-ok, and the next process refuses to plan it, with no further wiring.
Verification: devtools test tests/unit/daemon/test_fair_resumable_intake.py
tests/unit/daemon/test_intake_backlog_drain.py
tests/unit/daemon/test_dispatcher_intake_measurement.py
tests/unit/daemon/test_ingest_worker_handoff.py
tests/unit/daemon/test_live_watcher_concurrency.py (exit 0)
Anti-vacuity, all three executed against an endless-backlog source, which is
the shape that made the original waste unbounded:
* removing the `schedulable_adapters` filter from `discover` ->
"a halted source kept taking the writer lease: assert 46 == 8";
* returning the CLASS_TERMINAL unchanged -> the class itself halts and the
live sibling stops draining;
* making the halt process-local -> the restarted dispatcher plans the dead
source again.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
`docs/daemon.md` described shutdown as "reported by name as an orphan" and stopped there, which is the half that was already true. It now states what an incomplete shutdown does to ownership, why a `failed` service is treated differently from an orphaned one, that a profile which schedules no intake does not build the intake stack, that a drained cadence loop counts edges rather than passes, and that a terminally-refusing source halts at its own grain inside a multiplexed class. Also resolves three mypy findings the new code introduced: a conditional import reached from a wider branch, a `list.append(...) or ()` test stub, and reading `service_spec` through the supervisor module rather than its owner. Verification: devtools verify --quick (exit 0, 24 gates); devtools render all --check (exit 0, zero "out of sync") Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq
|
You have reached your Codex usage limits for security reviews. Please try again later. |
|
Warning Review limit reachedNext included review available in 28 minutes. View limit detailsLimit details: You’ve used the included review currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: 📒 Files selected for processing (13)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 21985e2a39
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
|
Closing out open Codex review threads on this PR (evidence checked against master at ef10e59):
Resolving the fixed, stale and refuted threads; tracked threads stay open. |
|
Closing out open Codex review threads on this PR (evidence checked against master at 64a9bd0):
Resolving every thread listed; confirmed defects are fixed under the named bead. |
Summary
polylogue-avmq's registry, supervisor and halt store already existed at headfrom a prior batch. Rather than re-implement them, each acceptance criterion was
verified against code — which found four real gaps and one vacuous assertion
that was already shipped.
What differed from the bead
The bead reads as if nothing exists. In fact
daemon/{services,supervisor,service_halt,periodic}.py,ServiceProfileselection and the halt store landed in an earlier batch (thebead's own comment says it landed "without satisfying every criterion"). Its AC
text says "roughly ten … services" and "~19
while Trueloops indaemon/cli.py";at head the registry declares 22 services, 16 PERIODIC, and zero hand-written
while-loops — they are all on
PeriodicRunner. The referenced spec does stillexist and its content matches the AC set. The
write_scopeis stale.AC1 — the inventory now takes its denominator from the event loop
The old helper patched
asyncio.create_taskand then filtered to callers indaemon/cli.py, so a child spawned viaensure_futureor from any other modulewas invisible. The denominator came from a subset of the thing it was measuring.
It now installs a task factory on the loop the production route runs on
(
loop.set_task_factory), recording each task's name and innermost non-asynciofile:line. Verified empirically that this single point catchescreate_task,ensure_futureandloop.create_task. Nothing in the helper importsdaemon.services— the denominator is what the loop built. The partition is then:daemon.service.*names must resolve viaservice_spec, everything else mustmatch a declared unsupervised prefix with a named owner, and an anonymous
Task-Nmatches nothing.
Measured production inventory: 17 supervised services + 15 writer-coordinator
children, nothing else. Stated coverage limit, in the helper's own docstring: a
task created on a different loop inside a worker thread is not seen.
Three mutations executed — an unregistered
ensure_futurereports "thecomposition route spawned a task no owner declares: Task-2 (cli.py:2513)";
deleting a registration raises
UnknownServiceError; dropping astartcallreports "declared services the composition route never resolved".
AC2 — incomplete shutdown retains ownership
A still-running orphan no longer has the pidfile, rebuild exclusion and durable
archive lease released out from under it.
ShutdownReport.incompleteisdeliberately distinct from
clean: a FAILED service already terminated with anexception and cannot write, so it does not retain ownership; only ORPHANED
does. Mutation executed: "the durable archive lease was released beside a
still-running child."
The test drives the real route, narrows one spec's shutdown deadline via
dataclasses.replace(a controllable barrier, not a wall-clock wait), andidentifies the lease by object — startup reconciliation acquires and releases a
second ownership token of its own, so a class-level release spy would be wrong.
AC5 — one terminal transition per drain cycle
PeriodicRunnergainedPassOutcomeand per-loop drain state; the transitioncounts the progressed→drained edge, not each wake. A policy deferral or failure
returns
None— a refusal to do the work is not a pass that found none of it. Tworegressions, both with a
_PassBarrieropened one pass at a time; no timeoutruns. Mutations: dropping the edge guard →
assert 4 == 1; droppingwakeup.clear()→assert 19 == 3.The vacuity found in an already-shipped assertion
test_daemon_status_names_every_halted_unit_and_is_not_okclaimed in its owndocstring that dropping
and not halted_unitsreddens it. Executed: it stayedgreen. On the bare tmp directory the fixture used,
raw_failure_lifecycle_availablewas already False, so
okwas False before any halt was recorded. Repaired byinitializing the archive root and reading the payload twice, asserting the pre-halt
read is
ok: true. The same mutation now givesassert True is False.The source-grain gap in the halt ruling
UnitKind.SOURCEexisted in the enum and was rendered by status but had zeroproduction producers and zero planner consumers — and the grain was wrong:
build_intake_adaptersmultiplexes every non-browser configured source into oneconfigured_localdispatcher, so the existing class-grain test asserts against aunit shape production does not have. In production, halting that class would stop
every configured source.
Closed with a
SubUnitHaltPolicy: a sub-adapter'sCLASS_TERMINALbecomes adurable
source:<name>halt plus a per-item terminal, and halted sources areexcluded in
discover(). The policy is two callables supplied by the compositionroot, not an import, so no operations→daemon edge is added (
gate layeringconfirms).
All three directions of the 2026-09-05 ruling executed, at service, intake-class
and source grain: (a) "a halted source kept taking the writer lease" —
assert 46 == 8; (b) repaired first, then red; (c) process-local halt → 2 failuresacross two grains.
AC4 — measured, then improved
The fixture already selected a named profile through the production registry.
Measured: 1.15–7.76 s against a 10 s budget (one in-test elapsed of 5.72 s).
After not constructing the intake stack for services the profile never schedules:
0.47–1.48 s. The property is now pinned — mutation: "the intake stack was
built for services this profile never schedules."
A bug introduced and caught
Naming the drive-catchup child unconditionally broke 11 tests, because
ensure_future(pending)returns the same Future when handed one, and a Futurehas no
set_name. Guarded withisinstance(task, asyncio.Task), proven by runningthat file at
origin/master(passed), on the branch (failed), and after the fix(passed).
Verification
devtools verify --quick— exit 0, 24 gates, re-run after the final rebasedevtools render all --check— exit 0,grep -c 'out of sync'= 0the identical 7 node ids fail at
origin/masterin the same worktree detached atthe rebase base, matching the known-red file's recorded cause
devtools schema closure: all 12 changed Python filesout. The derivedidentity does NOT move; no reconvergence is forced by this branch.
One earlier quick run exited 3 on
gate layeringsolely because auv synchaddropped the audit group (grimp missing); re-synced and it passes.
Residuals
heartbeats and the process heartbeat do consume the contract at head and no
parallel lifecycle owner was found, but no test was built that would fail if one
were reintroduced.
StatusSnapshotis polylogue-20d.17's and was untouched.old-vs-new orphan/latency/polling graph needs a running daemon — live dogfood,
not code-now.
production/test LOC) was not reconstructed; the deletion it describes already
landed in the prior batch, verified by grep (one
DaemonSupervisorclass, oneconstruction site,
services.pythe only registry).planner side is proven: no production path yet produces a source-level
CLASS_TERMINAL, so the halt is reachable by design and by test but not by anylive refusal. Wiring a real terminal-refusal producer is the remaining half.
refusal is still admitted — one bounded page, deliberately, per the ruling's
"excluded where SELECTED, not refused where EXECUTED". Eliminating that page's
cost is a different design and contradicts the ruling as written.
test_dispatcher_page_compaction_cost_is_one_scoped_hold_at_archive_scalehitthe 120 s pytest timeout once, then passed three times. Contention, not
reproducible — but it is slow and near its timeout.
Scope
Edits outside the bead's stale
write_scopeare confined topolylogue/daemon,polylogue/operations/intake_adapters.pyandtests/unit/daemon. The compositionroot is
daemon/cli.py— there is no separate composition module — so AC1'sinventory and AC2's ownership decision cannot live anywhere else, and their tests
belong where the production-route startup stubs already are. Duplicating that
startup chain into an in-scope file is exactly the "duplicate test-only startup
chains" the bead says to delete.
Advances polylogue-avmq. AC1, AC2, AC3 and AC5 met; AC4 advanced and measured;
AC6 and AC7 open.
🤖 Generated with Claude Code
https://claude.ai/code/session_015WCh9YW3cRfsg3CZBKU7Fq