Skip to content

feat(daemon): Make the service inventory total and retain orphan ownership - #5351

Merged
Sinity merged 7 commits into
masterfrom
feat/daemon-service-registry
Sep 21, 2026
Merged

Sinity merged 7 commits into
masterfrom
feat/daemon-service-registry

Conversation

@Sinity

@Sinity Sinity commented Sep 21, 2026

Copy link
Copy Markdown
Owner

Summary

polylogue-avmq's registry, supervisor and halt store already existed at head
from 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,
ServiceProfile selection and the halt store landed in an earlier batch (the
bead's own comment says it landed "without satisfying every criterion"). Its AC
text says "roughly ten … services" and "~19 while True loops in daemon/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 still
exist and its content matches the AC set. The write_scope is stale.

AC1 — the inventory now takes its denominator from the event loop

The old helper patched asyncio.create_task and then filtered to callers in
daemon/cli.py
, so a child spawned via ensure_future or from any other module
was 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-asyncio
file:line. Verified empirically that this single point catches create_task,
ensure_future and loop.create_task. Nothing in the helper imports
daemon.services — the denominator is what the loop built. The partition is then:
daemon.service.* names must resolve via service_spec, everything else must
match a declared unsupervised prefix with a named owner, and an anonymous Task-N
matches 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_future reports "the
composition route spawned a task no owner declares: Task-2 (cli.py:2513)"
;
deleting a registration raises UnknownServiceError; dropping a start call
reports "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.incomplete is
deliberately distinct from clean: a FAILED service already terminated with an
exception 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), and
identifies 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

PeriodicRunner gained PassOutcome and per-loop drain state; the transition
counts 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. Two
regressions, both with a _PassBarrier opened one pass at a time; no timeout
runs
. Mutations: dropping the edge guard → assert 4 == 1; dropping
wakeup.clear() → assert 19 == 3.

The vacuity found in an already-shipped assertion

test_daemon_status_names_every_halted_unit_and_is_not_ok claimed in its own
docstring
that dropping and not halted_units reddens it. Executed: it stayed
green.
On the bare tmp directory the fixture used, raw_failure_lifecycle_available
was already False, so ok was False before any halt was recorded. Repaired by
initializing the archive root and reading the payload twice, asserting the pre-halt
read is ok: true. The same mutation now gives assert True is False.

The source-grain gap in the halt ruling

UnitKind.SOURCE existed in the enum and was rendered by status but had zero
production producers and zero planner consumers
— and the grain was wrong:
build_intake_adapters multiplexes every non-browser configured source into one
configured_local dispatcher, so the existing class-grain test asserts against a
unit shape production does not have. In production, halting that class would stop
every configured source.

Closed with a SubUnitHaltPolicy: a sub-adapter's CLASS_TERMINAL becomes a
durable source:<name> halt plus a per-item terminal, and halted sources are
excluded in discover(). The policy is two callables supplied by the composition
root, not an import, so no operations→daemon edge is added (gate layering
confirms).

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 failures
across 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 Future
has no set_name. Guarded with isinstance(task, asyncio.Task), proven by running
that 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 rebase
  • devtools render all --check — exit 0, grep -c 'out of sync' = 0
  • Focused 12-module daemon selection — 7 failures of 397, all proven inherited:
    the identical 7 node ids fail at origin/master in the same worktree detached at
    the rebase base, matching the known-red file's recorded cause
  • devtools schema closure: all 12 changed Python files out. The derived
    identity does NOT move; no reconvergence is forced by this branch.

One earlier quick run exited 3 on gate layering solely because a uv sync had
dropped the audit group (grimp missing); re-synced and it passes.

Residuals

  • AC6 unverified — not met, not refuted. EventBus, the reconciliation
    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.
    StatusSnapshot is polylogue-20d.17's and was untouched.
  • AC7 partial: partial-start rollback has no test, and the requested
    old-vs-new orphan/latency/polling graph needs a running daemon — live dogfood,
    not code-now.
  • The epic's completion report (old vs new task owners, lifecycle branches,
    production/test LOC) was not reconstructed; the deletion it describes already
    landed in the prior batch, verified by grep (one DaemonSupervisor class, one
    construction site, services.py the only registry).
  • polylogue-kqrbw should now close under the source-grain halt, but only the
    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 any
    live refusal. Wiring a real terminal-refusal producer is the remaining half.
  • The halt is consulted where work is selected, so the page carrying a source's
    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_scale hit
    the 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_scope are confined to polylogue/daemon,
polylogue/operations/intake_adapters.py and tests/unit/daemon. The composition
root is daemon/cli.py — there is no separate composition module — so AC1's
inventory 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

Sinity and others added 7 commits September 21, 2026 14:08
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
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@coderabbitai

coderabbitai Bot commented Sep 21, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 28 minutes.

Check out review usage here.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: ca1da275-5b3d-4bb5-836a-043e5b8ca335

📥 Commits

Reviewing files that changed from the base of the PR and between d531c27 and 21985e2.

📒 Files selected for processing (13)
  • docs/daemon.md
  • polylogue/daemon/cli.py
  • polylogue/daemon/drive_catchup.py
  • polylogue/daemon/embedding_backlog.py
  • polylogue/daemon/intake_adapters.py
  • polylogue/daemon/periodic.py
  • polylogue/daemon/supervisor.py
  • polylogue/daemon/write_coordinator.py
  • polylogue/operations/intake_adapters.py
  • tests/unit/daemon/test_daemon_cli.py
  • tests/unit/daemon/test_fair_resumable_intake.py
  • tests/unit/daemon/test_periodic_runner.py
  • tests/unit/daemon/test_status_observations.py

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 21, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-21T12:24:28.647690Z 21985e2 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Sinity Sinity changed the title feat(daemon): Make the service inventory total and retain ownership on orphaned shutdown feat(daemon): Make the service inventory total and retain orphan ownership Sep 21, 2026
@Sinity
Sinity enabled auto-merge (squash) September 21, 2026 12:13
@Sinity
Sinity merged commit 540228b into master Sep 21, 2026
3 checks passed
@Sinity
Sinity deleted the feat/daemon-service-registry branch September 21, 2026 12:22

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread polylogue/operations/intake_adapters.py Resolved
Comment thread polylogue/daemon/cli.py Resolved
Comment thread polylogue/daemon/embedding_backlog.py Resolved
@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

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.

@Sinity

Sinity commented Sep 29, 2026

Copy link
Copy Markdown
Owner Author

Closing out open Codex review threads on this PR (evidence checked against master at 64a9bd0):

  • P1 polylogue/operations/intake_adapters.py:710: Fixed on master (checked at 64a9bd0): MultiplexIntakeAdapter.schedulable_adapters reads the ingest source_halt, copies it into the halt policy, and drops the halted source from planning (polylogue/operations/intake_adapters.py:1152-1181).

Resolving every thread listed; confirmed defects are fixed under the named bead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant