Skip to content

feat(persona): spawn_persona_service helper (#133 slice 12) - #1508

Merged
joelteply merged 1 commit into
canaryfrom
feat/persona-headless-host-loop
Jun 2, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/persona-headless-host-loop

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • Adds spawn_persona_service(hosted, runtime, opts, rt_handle) -> JoinHandle<Result<ServeOutcome, String>> — the composition seam between the substrate's planning surface (slices 5-11, merged in feat(persona): citizen substrate + cognition cache hierarchy foundation (slices 1-6) #1507) and the headless boot loop.
  • Net-additive only: no change to crate::ipc::start_server's existing bootstrap loop. Slice 13 wires this helper into the boot path.
  • 3-line composition: up-cast Arc<Airc> to Arc<dyn AircTranscriptReader> (zero-cost; impl at airc_source.rs:74), construct AircPersonaConversation, rt_handle.spawn(serve_persona_loop(...)).

Doctrine

  • [[no-stdio-piping-for-process-ipc]]: substrate talks to airc only via Arc<PersonaAircRuntime> + airc-lib sockets — no stdin/stdout.
  • [[substrate-is-a-good-citizen-on-the-host]]: caller controls tokio scheduling pool via the supplied Handle; no hidden thread spawns.
  • [[no-fallbacks-ever]]: JoinHandle resolves with Err(message) from serve_persona_loop failures; no implicit retry / no substitution.

Why split helper from wire-up

The helper is a 3-line composition; the wire-up (slice 13) rewrites the IPC boot loop at ~ipc/mod.rs:1024 to:

  1. After bootstrap_one(&intent) succeeds, build the inference profile via build_profile (slice 5).
  2. Materialize the adapter via LlamaCppPersonaAdapterFactory (slice 9).
  3. Construct HostedPersona (slice 9).
  4. Call spawn_persona_service (this PR) to start hosting.
  5. Track JoinHandles for graceful shutdown.

That's a load-bearing boot-flow rewrite. Splitting keeps each commit reviewable — this PR is the unit-testable composition seam; slice 13 is the consumer.

Reference docs

  • docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md — substrate lifecycle that the spawned task plugs into
  • Per-module docs touched: src/workers/continuum-core/src/persona/host.rs (new), src/workers/continuum-core/src/persona/mod.rs (registers the module)
  • Memory: [[constitutional-design-always-a-next-step]] — this PR ships the helper + names slice 13's consumer in the doc-comment so future authors don't dead-end

Test plan

  • cargo build --bin airc_chat_demo --no-default-features --features livekit-webrtc,accelerate,llama/mac-cpu-only,load-dynamic-ort passes (verified locally before push)
  • cargo test --lib persona:: slice-related modules stay green (verified locally — service_loop, supervisor, spawner, spawner_module all pass)
  • No unit test for spawn_persona_service itself — composition is 3 lines, types check; integration test happens via slice 13's IPC boot path
  • Pre-existing persona::allocator::test_allocate_no_keys failure on canary is tracked separately (task Build(deps-dev): Bump @types/node from 22.14.0 to 24.7.0 #138), unrelated to this PR

🤖 Generated with Claude Code

The composition seam between the substrate's planning surface
(slices 5-11) and the headless boot loop (slice 13).

`spawn_persona_service(hosted, runtime, opts, rt_handle)`:
  1. Up-cast the persona's `Arc<Airc>` to `Arc<dyn
     AircTranscriptReader>` for the RAG layer (zero-cost — same
     pointer, different vtable view; impl already exists at
     `airc_source.rs:74`).
  2. Wrap `Arc<PersonaAircRuntime>` in `AircPersonaConversation`
     (slice 11) — production conversation that knows how to talk
     to the live daemon.
  3. `rt_handle.spawn(serve_persona_loop(hosted, &mut conversation,
     reader, opts))` — slice 10's loop runs on the caller's tokio
     pool.

Returns a `JoinHandle<Result<ServeOutcome, String>>` so the slice-13
boot path can collect handles for graceful shutdown (.abort() on
server stop, or just .await for steady-state ServeOutcome capture).

Net-additive — does NOT touch the existing IPC boot loop. Slice 13
rewires `crate::ipc::start_server` (~line 1024) so that after
`bootstrap_one(&intent)` succeeds, the boot path builds the
inference profile + adapter + HostedPersona and calls
`spawn_persona_service` to start hosting the persona. Splitting the
helper from the wire-up keeps each commit reviewable.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply

Copy link
Copy Markdown
Contributor Author

Adversarial review — slice 12 spawn_persona_service

Verdict: APPROVE with two non-blocking notes.

Reviewed against the eight requested axes. The 3-line composition is correct, the lifetimes are sound, the up-cast is essentially zero-cost, slice 13 is unblocked, and the doctrines hold. Findings below in order of severity.


Soundness ✅

Arc<Airc> → Arc<dyn AircTranscriptReader> up-cast (host.rs:90)

let reader: Arc<dyn AircTranscriptReader> = runtime.airc().clone();
  • runtime.airc() returns &Arc<Airc> (airc_runtime.rs:251).
  • .clone() yields Arc<Airc> — ONE relaxed atomic increment on the strong-count word of the existing ArcInner<Airc>. No heap alloc.
  • The assignment is an unsized coercion Arc<T> → Arc<dyn Trait> where impl AircTranscriptReader for airc_lib::Airc (airc_source.rs:74). The data pointer stays identical; the Arc fat pointer gains a vtable view. Object-safe because async_trait desugars to Pin<Box<dyn Future ...>>-returning methods (no Self, no generics, Send + Sync bounds satisfied).
  • Result: same ArcInner slot, two Arc handles (runtime's airc field + this reader), strong-count = 2 once the task is spawned. No alloc beyond the count bump.

Doc-comment accuracy (host.rs:87-89): The "same heap pointer, different vtable view" claim is correct for the coercion itself. Strictly speaking there's one atomic increment from .clone(), but that's a single uncontended op against a hot cache line, not a "cost" in any architectural sense. I would not block on this; if you want to be pedantic, change "zero-cost" to "near-zero-cost — one atomic refcount bump, no heap alloc, no vtable indirection on the Arc itself". Optional.


Lifetime / leak audit ✅

The spawned task captures by move: hosted (owns Arc<dyn AIProviderAdapter>), runtime (Arc<PersonaAircRuntime>), opts, and the freshly-built conversation (which also holds Arc<PersonaAircRuntime>).

  • Cycle check: Arc<PersonaAircRuntime> is held by both runtime (the local var) AND conversation.runtime (airc_persona_conversation.rs:53). Both are dropped together when the task finishes or is aborted. Strong-count goes 2 → 0 (modulo any other holders, e.g. the registry, which is the intended permanent holder). No cycle — neither side reaches back into the task.
  • Adapter lifetime: hosted.adapter is Arc<dyn AIProviderAdapter>. Per service_loop.rs:174 it's cloned into the RAG path each turn. On task abort, the loop's local adapter Arc and the hosted.adapter Arc both drop; if the adapter is sole-owned at that point, the GGUF unloads via the adapter's own Drop. Clean.
  • .abort() semantics: tokio::task::JoinHandle::abort() schedules cancellation at the next .await point. The loop is fully await-driven (subscribe, RAG, inference, say), so cancellation is responsive within one async step. All owned Arcs in the task's stack frame drop on the cancellation path.

Cancellation safety ⚠️ NOTE (non-blocking)

If .abort() lands mid-say or mid-inference:

  • The inference adapter's generate_text will be dropped mid-future. LlamaCppAdapter is in-process Candle; dropping its future cancels token generation cleanly (no externally-observable state). ✅
  • The airc subscribe stream is owned by AircPersonaConversation.stream (airc_persona_conversation.rs:63). On task drop the stream drops; airc-lib's EventStream is expected to send an unsubscribe / close on its own Drop. I did not verify airc-lib's EventStream::drop behavior in this review — if that close path is missing, the daemon will keep the subscription alive until heartbeat timeout. Worth a one-line check on the airc-lib side before slice 13 starts wiring shutdown.
  • The persona's say is airc_lib::Airc::say — atomic from the daemon's perspective (single publish). Cancellation mid-flight either lands or doesn't; no half-state.

Not blocking. This is the right shape for slice 12; the audit belongs in slice 13's shutdown smoke test.


Slice 13 brick-wall check ✅

Walked the proposed slice-13 path against ipc/mod.rs:1062:

  1. bootstrap_one(&intent) returns PersonaInstanceInfo and INTERNALLY registers the runtime in PersonaAircRuntimeRegistry (persona_instance_manager.rs:217). Slice 13 will need to either (a) call registry.get(info.persona_id) to recover the Arc<PersonaAircRuntime>, or (b) refactor bootstrap_one to return the Arc directly. Option (a) is the smaller diff and keeps the registry as the single owner. No brick wall, but worth naming in the host.rs doc-comment that slice 13 must look the runtime back up via the registry.
  2. The adapter materialization path (LlamaCppPersonaAdapterFactory → materialize_adapters) is already in place from slice 9. Slice 13 will need to plumb MaterializedPersonaPlan through bootstrap_one's return — feasible from existing primitives.
  3. rt_handle is trivially tokio::runtime::Handle::current() inside the boot loop (already inside tokio::spawn).
  4. Tracking JoinHandles for graceful shutdown: caller pushes into a Vec<JoinHandle<Result<ServeOutcome, String>>> in the boot scope and .abort() each on shutdown. The JoinHandle<Result<ServeOutcome, String>> shape supports this directly.

No hidden cyclic ownership. Slice 13 author has the surface they need.


API ergonomics ✅

JoinHandle<Result<ServeOutcome, String>> is the right shape:

  • The Result<ServeOutcome, String> is the inner result of serve_persona_loop. Surfacing it preserves the no-fallbacks doctrine — the supervisor sees structured success (with outcome counters) vs structured error.
  • JoinHandle<ServeOutcome> with errors logged would VIOLATE [[no-fallbacks-ever]] by swallowing failure into logs.
  • A typed error (ServeError enum) would be marginally better than String, but serve_persona_loop itself returns Result<ServeOutcome, String> (service_loop.rs:162), so this PR can't improve typing without changing slice 10's surface. Defer to a future cleanup pass.

Doctrine conformance ✅

  • [[no-stdio-piping-for-process-ipc]]: ✅ — all I/O routes through PersonaAircRuntime → airc_lib typed sockets. No stdin/stdout anywhere.
  • [[no-if-statements-use-llms-for-cognition]]: ✅ — the helper itself contains zero decision gates; it composes and spawns. The substrate's pre-LLM filters (high-water-mark, self-skip, non-text) live inside serve_persona_loop and AircPersonaConversation::next_message, both downstream of this helper. The LLM still decides.
  • [[no-fallbacks-ever]]: ✅ — failures propagate through Result<ServeOutcome, String>; no implicit retry, no substitution.
  • [[substrate-is-a-good-citizen-on-the-host]]: ✅ — rt_handle is supplied by the caller; no tokio::spawn against a global runtime, no std::thread::spawn. Caller controls scheduling.
  • Lifetime = JoinHandle lifetime: ✅ — supervisor abort cleanly cascades through the loop's await points.

Testability ⚠️ NOTE (non-blocking)

The 3-line helper is too thin to unit-test meaningfully without standing up:

  • A live Arc<PersonaAircRuntime> (needs a real airc daemon for Airc::attach_as)
  • A real HostedPersona (needs a real adapter)

The PR body's claim — "no unit test for spawn_persona_service itself — composition is 3 lines, types check; integration test happens via slice 13's IPC boot path" — is correct. Adding a trait abstraction for the spawn surface itself would be over-engineering: the helper IS the abstraction.

The one thing that COULD be unit-tested without a daemon is "does spawn_persona_service return a JoinHandle whose abort actually cancels the inner loop?" — but that requires fabricating a HostedPersona + PersonaAircRuntime outside their constructors, which both crates lock down. Integration test in slice 13 is correct.


Missing pieces ⚠️ NOTE

The doc-comment at host.rs:17-41 correctly names slice 13's consumer + the wire-up points, satisfying [[constitutional-design-always-a-next-step]] — no dead-end. Two small additions would harden it:

  1. Naming the registry lookup: explicitly say "slice 13 recovers the Arc<PersonaAircRuntime> via PersonaAircRuntimeRegistry::get(info.persona_id) after bootstrap_one". The current wording leaves slice 13 to discover this themselves.
  2. Subscribe lazy-init reminder: the conversation's subscribe stream is lazy (airc_persona_conversation.rs:103); the spawn helper itself does NOT cause an airc daemon round-trip. Worth one line so slice 13 knows boot is still cheap even with N personas.

Both are doc-only nits. Optional.


Summary

Axis Finding
Soundness Up-cast correct, near-zero-cost (one atomic increment).
Lifetimes No cycles. .abort() cleanly drops adapter + runtime + conversation.
Cancellation Clean at all await points. Verify EventStream::drop in airc-lib (slice 13 work, not blocking).
Slice 13 path Unblocked. Will need registry.get(persona_id) to recover runtime; doc could name this.
API shape JoinHandle<Result<ServeOutcome, String>> is correct — preserves no-fallbacks.
Doc accuracy "zero-cost" is slightly loose; one atomic op. Optional nit.
Testability Integration-only is correct given the 3-line surface.
Doctrine All five honored.

Verdict: APPROVE. Ship. The two notes (doc-comment additions + airc-lib EventStream::drop audit) belong in slice 13's wire-up commit, not as a blocker on this seam.

@joelteply
joelteply merged commit 980f731 into canary Jun 2, 2026
3 checks passed
@joelteply
joelteply deleted the feat/persona-headless-host-loop branch June 2, 2026 04:57
joelteply added a commit that referenced this pull request Jun 7, 2026
* docs(planning): HEADLESS-PERSONA-HOST-LOOP — slice 13 design

Captures the boot wire-up plan for #133 slice 13 before touching
the load-bearing `ipc::start_server` flow.

Documents:
- The "moment-of-truth" gap: composition pieces from slices 5-12
exist; nothing in continuum-core actually calls them at boot.
- Before/after of the IPC boot loop (~ipc/mod.rs:1024-1089).
- The cleanup model verified during PR #1508's slice-12 review:
.abort() → JoinHandle drop → conversation drop → EventStream drop
→ broadcast::Receiver drop auto-decrements subscriber count. Wire
subscriber is ref-counted across local subscribers; tears down
when runtime Arc reaches 0. No leak; no manual unsubscribe.
- Five open questions with recommendations:
  1. Arc<Registry> for build_profile — add model_registry::global_arc()
  2. HwCapabilityTier source — HostCapabilityProbe::detect_at_boot()
  3. hosted_handles ownership — new PersonaSupervisor module
  4. ResumeOrMintProvider role-mapping — slice 14 territory
  5. BootSummary event for per-slot failures
- Test plan: PersonaBootstrapper trait split for stubbing.
- Explicit non-goals (shared-base / cross-grid / LoRA / role-aware).
- Doctrine memories worth refreshing on implementation.

Net-additive doc — no code changes. Slice 13 implementation lands
as a follow-up PR.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(planning): rev HEADLESS-PERSONA-HOST-LOOP per PR #1510 review

PR #1510's adversarial reviewer caught 9 findings, 3 blocking.
Substantial revision addresses each:

Blockers:
- Finding #1 (cleanup model wrong): rewritten "Cleanup model" section.
  `.abort()` alone is INSUFFICIENT — wire subscriber stays in
  Arc<Airc>.inner.subscribers until registry-remove drops the Arc.
  Supervisor shutdown path MUST: abort → await → registry.remove.
- Finding #2 (position-pairing broken): elevated to hard prereq P2.
  scan_personas_dir sorts alphabetically; boot 2 yields persona
  order != plan order on random-derived names. Slice 13 ships with
  plan.len() <= 1 (Helper only); slice 14 lands role-in-seed.json
  + RoleAwareProvider before re-enabling Coder.
- Finding #3 (after-code reimplements existing fns): "after" rewrite
  uses bootstrap_planned (slice 8) + materialize_adapters (slice 9)
  as composition, not open-coded copies. Net-new code ~25 lines, not
  ~50.

Major:
- Finding #4 (PersonaSupervisor dup with PersonaAircRuntimeRegistry):
  Q3 revised to EXTEND the registry — HostedPersonaRuntime owns both
  airc_runtime + service_loop JoinHandle. registry.remove becomes
  the natural shutdown path. One keyspace, one cleanup chain.
- Finding #5 (no Runtime::shutdown caller): elevated to hard prereq
  P1. Slice 13 wires tokio::signal::ctrl_c -> runtime.shutdown.
- Finding #6 (no broker admission for N adapter spawns): elevated to
  hard prereq P3. ResourceBroker.acquire before each
  factory.build_adapter.

Moderate:
- Finding #7 (detect_host_capability already exists): Q2 restated to
  call the existing free function at host_capability_probe.rs:87.
- Finding #8 (global_arc() cost inverted): Q1 recommendation flipped
  to (B) — refactor bootstrap_planned to take &Registry. Singleton
  storage migration would have touched every callsite of global().

Minor:
- Finding #9 (BootSummary venue): Q5 specifies
  MessageBus::publish("persona:boot:summary", ...) with operator
  scraping via events/recent; no declared subscribers in slice 13.
- Finding #10 (hot-reload undefined): added as Q6, declared
  out-of-scope.
- Finding #11 (wire-subscription failure mid-boot): added as Q7,
  supervisor polls JoinHandle::is_finished every 5s.

Plus added implementation checklist at end so slice 13 PR has a
sign-off surface.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(planning): rev2 HEADLESS-PERSONA-HOST-LOOP — match shipped impl + correct cleanup model

PR #1510 re-review (after the first revision) caught:

1. **Cleanup model still wrong** — claimed `ensure_wire_subscriber`
   / `inner.subscribers` (was the 428f928 worktree I was reading,
   not the pinned f6ed190). Real mechanism in f6ed190 is
   `EventStream::EventStreamInner::Daemon` holding
   `DaemonAttachGuard` (`stream.rs:25-68`). On `EventStream` drop,
   guard drops, per-channel attach `JoinHandle`s abort.
   **`.abort()` ALONE is sufficient** against the pinned rev. The
   `shutdown_slot` registry-remove is for in-substrate Arc state
   hygiene, not for daemon-side teardown. Section rewritten with
   the correct mechanism, file:line cited.

2. **"Hard prerequisites" misrepresented impl scope** — listed
   P1 (ctrl_c→shutdown), P3 (broker), Q5 (BootSummary publish),
   Q7 (5s poller) as "MUST land" but the implementation explicitly
   deferred all four. Restructured to "Slice 13 scope vs deferred
   follow-ups" with honest splits: shipped vs deferred + why each
   deferral is acceptable (single-persona LCD is in-budget;
   `shutdown_slot` available via IPC commands; cleanup model now
   shows `.abort()` is sufficient).

3. **"After" snippet didn't match impl** — used
   `BootSummary::default()` / `bus.publish` / `summary.failed.push`,
   but the impl uses `tracing::info!(hosted=N, failed=N)` counters.
   Rewrote the snippet to match what shipped. Notes Q5
   (BootSummary publish) as deferred.

Plus the implementation status section is now accurate:
- Q1, Q3, P2, Q2-partial: shipped ✅
- P1, P3, Q5, Q7, Q2-full: deferred to slice 13.5+ ❌
- Integration polish in #1511: room-name discovery + LCD model
  registry entry + PersonaContext rename + RagInspectionRequest::
  for_persona derivation site (the `&ctx` doctrine)
- Integration validation: Paige replied in continuum room

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Oct 3, 2026
…airc stop` (#4675)

* fix(boot): start-server starts airc through airc's lifecycle, never `airc stop`

Review of airc #1508 (operator stop intent): continuum's boot handled a stale or
wedged airc daemon with the public `airc stop` and then a raw `airc daemon`. Once
#1508 lands, that `airc stop` records a durable OPERATOR stop intent; the raw
daemon still came up, but every ensure_daemon_running caller (msg, inbox, status,
monitor attach) is then refused against a live daemon, and the next `airc update`
stops it for good. Any continuum boot that met a stale daemon would cut the
node's CLI off the mesh.

- A stale (answering, non-current) daemon is left to airc: its own ensure stops a
  non-current daemon over IPC and starts the installed one. Not reaped here.
- A wedged holder (answers nothing) is reaped by pid as before, without the
  `airc stop` first; it could not take an IPC stop anyway.
- The start is airc's gated autostart (`airc events list --limit 0` from $HOME),
  not a raw `airc daemon`: it honors the maintenance lock and the operator stop
  intent and provisions the daemon's token. Switches to `airc join --ensure` once
  #1508 lands.

Verified: bash -n; no other continuum script or core path calls the public `airc
stop` (the core's raw spawn is replaced in #4672). Not exercised live: the M5's
daemon is current, so boot adopts it without reaching these branches.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(boot): no shell-owned airc reap; airc's refusal reaches the operator

Review of #4675 (BIGGIEDESK): any failed `airc ping` (denied, timed out, protocol
mismatch) entered the wedged branch, which globbed the newest socket and `kill`ed
then `kill -9`ed every lsof holder, clients included. A failed ping does not prove
a wedged owner, and the shell cannot name the canonical endpoint's holder.

- machine_daemon_pids and the reap are removed. Recovery and refusal are airc's:
  its gated autostart replaces a stale daemon over IPC and refuses, with its
  reason, what it cannot recover.
- The autostart's failure is no longer swallowed: boot prints airc's own words
  from the daemon-boot log and fails.

Test (new, folded into the existing launcher step of continuum-rust-tests):
start-server-airc-recovery.test.sh runs the real ensure_airc_daemon against a fake
airc with a machine socket present. A failed ping never calls kill, pkill or
lsof; the start is `airc events list`; no public stop and no raw daemon; and an
operator-stopped refusal is shown and fails boot. It fails against canary's
launcher.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant