Skip to content

Fix persona DB isolation: no more main DB pollution - #275

Closed
joelteply wants to merge 10 commits into
mainfrom
fix/persona-db-handle-isolation
Closed

joelteply wants to merge 10 commits into
mainfrom
fix/persona-db-handle-isolation

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • 14 personas were writing cognition logs, RAG contexts, and memories to the shared main DB (3.4GB) instead of their personal longterm.db
  • Root cause: startAutonomousServicing() ran before propagateDbHandle(), and DataCreateServerCommand silently fell back to 'default' when handle was undefined
  • BaseUser.personalDbHandle — every citizen (human or AI) gets personal storage as a base feature
  • Hippocampus sets the handle on the parent directly; PersonaMemory reads it via live getter reference — no propagation step needed
  • Hippocampus throws on DB failure instead of silently degrading to STM-only mode

Changes

File What
BaseUser.ts Added personalDbHandle: DbHandle | null — base infrastructure for all users
PersonaUser.ts Init order: hippocampus → ensureDbReady → genome → logger → autonomous loop (last)
LimbicSystem.ts ensureDbReady() replaces propagateDbHandle()/setDbHandle(), throws on null
PersonaMemory.ts Constructor takes () => DbHandle | null getter, requireHandle() guard on all ORM ops
Hippocampus.ts Sets persona.personalDbHandle directly, throws on DB open failure
CognitionLogger.ts Cleaned unused imports; init order guarantees handles populated before use

Test plan

  • npm run build:ts — clean compilation
  • npm start — deployed and running
  • All 14 personas initialized with cognition logs present
  • No DB handle errors in any persona logs
  • AI personas responding to chat messages
  • IPC timeouts observed are pre-existing (not related to this change)

🤖 Generated with Claude Code

…n fix

Phase 1 — Stabilize:
- AVATAR_FPS 24→15 (~40% GPU/CPU reduction for 16 concurrent avatars)
- Wrap spawn_renderer_loop in spawn_blocking (std::sync::Mutex was starving tokio)
- Accumulate 160-sample LiveKit frames to 480-sample chunks for earshot VAD
  (VAD requires ≥240 samples; was always returning silence)
- VideoPublishState struct, max_bitrate 1.2M→800k, max_framerate 24→15

Phase 2 — FramePublisher abstraction:
- FramePublisher trait: try_publish() decouples video loop from format conversion
- CpuI420Publisher: RGBA→I420 (BT.601), works on all platforms (default)
- create_publisher() factory selects best publisher per platform
- rgba_to_i420_into() moved to frame_publisher.rs (single source of truth)
- Unit tests for BT.601 conversion correctness

Phase 3 — NativeBufferPublisher (macOS, disabled by default):
- CVPixelBuffer BGRA path via CoreVideo FFI (skips I420 conversion)
- Enabled via CONTINUUM_NATIVE_VIDEO=1 for testing
- Dark frames issue: WebRTC encoder doesn't handle BGRA CVPixelBuffers correctly
- Falls back to CpuI420Publisher on failure or non-macOS
Pre-allocate double-buffered IOSurface-backed NV12 CVPixelBuffers per slot.
Bevy ReadbackComplete observer writes RGBA→NV12 directly to IOSurface via
atomic frame counter — eliminates pixel_bytes.to_vec() (1.2MB) and per-frame
CVPixelBufferCreate (460KB). Publisher wraps IOSurface in lightweight
CVPixelBuffer metadata (~40 bytes) via CVPixelBufferCreateWithIOSurface.

At 195 frames/sec (13 agents × 15fps): ~324 MB/s alloc → ~7.6 KB/s.

Three-tier macOS cascade: GpuBridge → NativeBuffer → CpuI420.
CONTINUUM_CPU_VIDEO=1 escape hatch preserved.
Align Rust module naming with TypeScript's existing live/ convention.
The voice/ module contained audio, video, avatars, transport — the entire
live experience, not just voice. Now properly organized:

  live/
  ├── audio/     (buffer, router, mixer, stt/, tts/, vad/)
  ├── avatar/    (catalog, selection, publishers, render_loop)
  ├── video/     (bevy_renderer, generator, source)
  ├── transport/ (livekit_agent, call_server, media)
  └── session/   (orchestrator, voice_service, tests)

Module declaration order in live/mod.rs is load-bearing: webrtc-dependent
modules (avatar, video, transport) must be declared before ort-dependent
modules (audio) to avoid protobuf symbol conflicts between libwebrtc.a
and libonnxruntime.a which bundle different protobuf C++ versions.

Also fixes executable permissions on all scripts/*.sh files.
… strip and controls

Captions were absolute-positioned at a fixed offset (bottom: 56px) which overlapped
the participant strip in spotlight mode and bottom grid rows in grid mode. Then the
flex-flow fix put them as a separate bar between strip and controls — wrong place.

Now: wrap main content (grid or spotlight-main) in .content-area with position:relative.
Captions are position:absolute at bottom of that area, overlaying the video content
like Zoom/Teams/Meet do it. Strip and controls are outside the overlay zone.
- Add captionsEnabled to CallState type and default (UserStateEntity)
- Load/save captionsEnabled in LiveWidget state persistence
- Replace abstract SVG caption icon with universal "CC" text in box
  (matches Zoom, Meet, Teams standard)
- LiveParticipantTile: isPinned prop, hover overlay bar with name + pushpin
  SVG icon, pin-participant custom event, pinned CSS class with cyan border
- LiveWidget: pin-participant event wiring, _onPinParticipant toggle handler,
  isPinned passed to all tiles in grid and spotlight views
- Tile click = temporary spotlight (auto-speaker can override),
  pin icon click = locked pin (only way to pin)
- LiveCaptions: always render DOM, toggle display via CSS (no conditional
  DOM insertion/removal)
- toggleCaptions now calls saveCallState() (CC preference persists)
- _stateLoaded guard prevents controls rendering with wrong defaults
- SCSS: z-index layering (video:1, name:3, overlay:5), prominent hover
  overlay with gradient bg, 32px pin button
- BaseUser.personalDbHandle: every citizen gets personal storage
- Hippocampus sets handle on parent directly (no propagation step)
- PersonaMemory reads handle via live getter reference, requireHandle() throws if null
- LimbicSystem.ensureDbReady() replaces propagateDbHandle(), throws on failure
- PersonaUser init order: hippocampus → ensureDbReady → genome → logger → autonomous loop (last)
- Hippocampus throws on DB open failure (no silent STM-only fallback)
- CognitionLogger: cleaned unused imports, init order guarantees handle populated
Copilot AI review requested due to automatic review settings February 27, 2026 23:31
@joelteply joelteply closed this Feb 27, 2026
@joelteply
joelteply deleted the fix/persona-db-handle-isolation branch February 27, 2026 23:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes a critical DB isolation bug where 14 AI personas were writing cognition logs, RAG contexts, and memories to the shared main database instead of their individual longterm.db. The root cause was a race condition: startAutonomousServicing() ran before propagateDbHandle() completed. Concurrently, the voice Rust module is reorganized into a more structured live module hierarchy (live/audio, live/session, live/transport, live/video, live/avatar).

Changes:

  • DB isolation fix (TypeScript): Corrected init order in PersonaUser, replaced the two-step propagation pattern with a live getter reference in PersonaMemory, added personalDbHandle to BaseUser, made Hippocampus throw on DB failure instead of silently degrading.
  • Module rename (Rust): The voice module is restructured into a live module with explicit submodule hierarchy and linker-ordering comments for protobuf symbol conflict mitigation.
  • UI improvements: Added pin-participant feature, captions state persistence, _stateLoaded guard to prevent rendering with stale defaults, and repositioned captions overlay into a content-area container.

Reviewed changes

Copilot reviewed 67 out of 115 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
BaseUser.ts Adds personalDbHandle: DbHandle | null as base infrastructure for all users
PersonaUser.ts Fixes init order (hippocampus → ensureDbReady → genome → logger → autonomous loop)
LimbicSystem.ts Replaces propagateDbHandle()/setDbHandle() with ensureDbReady() that throws on null
PersonaMemory.ts Uses live getter () => DbHandle | null instead of stored handle; adds requireHandle() guard
Hippocampus.ts Sets persona.personalDbHandle directly; throws on DB failure instead of STM-only fallback
CognitionLogger.ts Removes unused imports; adds init order documentation
src/workers/continuum-core/src/lib.rs Top-level voice → live rename
src/workers/continuum-core/src/live/mod.rs New module hierarchy with linker-ordering comments
src/workers/continuum-core/src/live/audio/* Audio submodules relocated from voice
src/workers/continuum-core/src/live/video/* Video submodules with new bevy_renderer resize implementation
src/workers/continuum-core/src/live/transport/* Transport submodules (call_server, livekit_agent, media)
src/workers/continuum-core/src/live/session/* Session/orchestrator submodules
src/workers/continuum-core/src/live/handle.rs Handle type moved from voice
src/workers/continuum-core/src/live/avatar/* Avatar rendering subsystem expanded with registry, backends
LiveWidget.ts Adds pin participant, _stateLoaded guard, captions persistence, content-area wrapper
LiveParticipantTile.ts Adds pin icon and isPinned property
LiveCaptions.ts Changes from returning empty template to display: none for hidden state
LiveControls.ts Updates CC icon to use text-based SVG
live-widget.scss / live-participant-tile.scss Adds content-area wrapper, hover overlay, pin button styles
UserStateEntity.ts Adds captionsEnabled to call state persistence
src/workers/Cargo.toml Adds codegen-units = 1 for release builds
src/output.md ⚠️ Accidentally committed chat export file
Files not reviewed (1)
  • src/package-lock.json: Language not supported
Comments suppressed due to low confidence (1)

src/workers/continuum-core/src/modules/live.rs:60

  • The VoiceModule struct name (and VoiceState) no longer matches the module it lives in (modules/live.rs) or its registered name ("live"). The type should be renamed to LiveModule and LiveState to be consistent with the new naming convention, since other modules follow the pattern where the struct name matches the module name (e.g., MemoryModule, CognitionModule).

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

await this.limbic!.propagateDbHandle();
// CRITICAL: Ensure Hippocampus has opened longterm.db before any work begins.
// Throws if the handle is null — persona cannot start without longterm.db.
// Hippocampus sets PersonaUser.personaDbHandle directly; PersonaMemory reads it

Copilot AI Feb 27, 2026

Copy link

Choose a reason for hiding this comment

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

The personaDbHandle field comment in PersonaUser.ts (line 847) refers to PersonaUser.personaDbHandle but the actual field is named personalDbHandle (defined in BaseUser.ts). This is a typo in the inline code comment.

Suggested change
// Hippocampus sets PersonaUser.personaDbHandle directly; PersonaMemory reads it
// Hippocampus sets PersonaUser.personalDbHandle directly; PersonaMemory reads it

Copilot uses AI. Check for mistakes.
Comment thread src/output.md
Comment on lines +217 to +222
## #2dcd72 - DeepSeek Assistant (reply to #338771)
*2/26/2026, 8:37:49 PM*

I see you're both encountering file access issues. Fireworks AI is hitting security restrictions on native_buffer.rs, and Groq Lightning seems to be having trouble with something else. What specific files or operations are you trying to access?

---

Copilot AI Feb 27, 2026

Copy link

Choose a reason for hiding this comment

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

The output.md file appears to be a raw chat export accidentally committed to the repository. This file contains AI conversation logs and should not be part of the source code history. It should be removed from the PR and added to .gitignore if needed.

Suggested change
## #2dcd72 - DeepSeek Assistant (reply to #338771)
*2/26/2026, 8:37:49 PM*
I see you're both encountering file access issues. Fireworks AI is hitting security restrictions on native_buffer.rs, and Groq Lightning seems to be having trouble with something else. What specific files or operations are you trying to access?
---
## Note
This file previously contained raw AI chat export logs. That content has been removed because such logs should not be committed to the repository.
If you need to inspect chat outputs locally, store them outside the tracked source tree or add the corresponding paths to .gitignore.

Copilot uses AI. Check for mistakes.
Comment on lines +224 to 226
// No fallback — persona cannot operate without longterm.db
throw error;
}

Copilot AI Feb 27, 2026

Copy link

Choose a reason for hiding this comment

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

The Hippocampus now throws on DB open failure instead of degrading to STM-only mode. This is a significant behavioral change with operational impact: if longterm.db cannot be opened (e.g., disk full, permissions issue, corruption), the entire persona fails to start rather than operating with reduced functionality. While the PR description mentions this as intentional, this means a transient storage issue (e.g., temporary disk full) permanently breaks a persona until the system is manually restarted. Consider whether there should be a retry mechanism with backoff before throwing, rather than a single hard failure.

Copilot uses AI. Check for mistakes.
@@ -0,0 +1 @@
mod call_server_orchestrator_test;

Copilot AI Feb 27, 2026

Copy link

Choose a reason for hiding this comment

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

The tests/mod.rs file declares mod call_server_orchestrator_test;, but the orchestrator_tests.rs file in the same directory is referenced from orchestrator.rs via #[path = "tests/orchestrator_tests.rs"]. The orchestrator_tests.rs file is not declared in tests/mod.rs, which means the mod tests module in session/mod.rs will compile call_server_orchestrator_test but NOT orchestrator_tests — the latter is only compiled as a submodule of orchestrator.rs itself. This inconsistency in how the two test files are structured may cause confusion and could lead to orchestrator_tests.rs being unexpectedly excluded if the path attribute is removed in a future refactor.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Aug 15, 2026
…30x the lease's heartbeats (Joel: heartbeat needs fix)

A 30-minute claim lease was renewed on EVERY 60s presence tick — ~30x the
events one lease needs, crossing the wire to every subscriber on every
node (the churn that burned this week's session tokens through an
unfiltered feed). Presence keeps its 60s pulse (roster liveness IS a fast
question); renewal now runs at TTL/3, derived from the one lease constant.
A citizen still gets three renewal opportunities per lease, and any
roster-read or per-card failure falls back to retrying on the next 60s
tick until clean — degraded mode is exactly the old cadence, never a
wider gap.

Context: the render half (#275, airc ac4936c) and the store half (#323,
Durable-only DurableSink) are ALREADY FIXED in airc HEAD — but the box
runs airc daemons started Aug 5, two days BEFORE that fix merged (#272
deploy gap). This commit is the source-reduction half that no repo had;
the daemon refresh rides the next reboot window.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 15, 2026
…code-rate floor (#441) (#2311)

* feat(serving): throughput sentinel — placement-contract readback + decode-rate floor (#441)

Joel 2026-08-15: "we need very good tok/sec or it's a failure. We need
warnings when shit hits the fan. You ignore and miss major throughput
issues including models that got fucked by serving and are on cpu. You
never catch it and we are waiting an eternity."

Two seams, both riding EXISTING machinery — no new monitor task, no new
tick, no second connection to the engine:

1. PLACEMENT CONTRACT READBACK (inference/placement_watch.rs, new file).
   The governor plans a placement; llama.cpp decides the real allocation
   at load and can land somewhere else (Metal init failure, VRAM
   exhaustion at map time). The stderr pump already reads every engine
   line for the log cap + wedge watch — an OffloadWatch on the same pump
   now records the engine's own `offloaded X/Y layers to GPU` banner
   into a shared cell, and serve() compares it against the PLANNED
   placement after readiness: a GPU-intent lane at 0/N layers probes
   serving.placement.cpu_fallback as a PLACEMENT VIOLATION. A lease
   nobody reads back is a suggestion; this is the readback half of the
   contract. Partial offload stays silent (MoE cold-expert -ot splits
   offload a subset by design); no banner observed is reported as its
   own fact, never conflated with healthy. The watcher only REPORTS —
   lifecycle stays with the serving daemon, same doctrine as the wedge
   flag.

2. DECODE-RATE FLOOR (ai/openai_adapter.rs). Every streamed call already
   parses the lane's own timings; measured decode t/s (predicted-only,
   undiluted by prefill so long prompts can't false-positive) is now
   compared against the catalog row's tokens_per_second. Below a quarter
   of expectation on a real sample (≥16 decoded tokens) probes
   serving.throughput.degraded naming the measured vs expected rates and
   the suspect causes. Coarse by design: an order-of-magnitude-collapse
   alarm, not a perf tracker — a 2×-optimistic catalog row stays silent.
   Rows without a registry expectation (cloud adapters) have no lease to
   breach and stay silent.

Regression test pins the banner parse (both prefix spellings, lookalike
rejection, no-banner ≠ reported-zero) — a silent parse miss here means a
CPU-fallback lane reads healthy forever, the exact class this kills.

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

* fix(persona): claim renewal on its own TTL/3 cadence — stop emitting 30x the lease's heartbeats (Joel: heartbeat needs fix)

A 30-minute claim lease was renewed on EVERY 60s presence tick — ~30x the
events one lease needs, crossing the wire to every subscriber on every
node (the churn that burned this week's session tokens through an
unfiltered feed). Presence keeps its 60s pulse (roster liveness IS a fast
question); renewal now runs at TTL/3, derived from the one lease constant.
A citizen still gets three renewal opportunities per lease, and any
roster-read or per-card failure falls back to retrying on the next 60s
tick until clean — degraded mode is exactly the old cadence, never a
wider gap.

Context: the render half (#275, airc ac4936c) and the store half (#323,
Durable-only DurableSink) are ALREADY FIXED in airc HEAD — but the box
runs airc daemons started Aug 5, two days BEFORE that fix merged (#272
deploy gap). This commit is the source-reduction half that no repo had;
the daemon refresh rides the next reboot window.

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

* fix(#2311): throughput floor delegates to throughput_expectation — kills the guard-tripping consts

The de-hardcode guard (context_budget) correctly flagged MIN_SAMPLE_TOKENS/
FLOOR_FRACTION as new bare-literal consts. Rather than dressing them up, this
converges the two parallel implementations: warn_if_decode_collapsed is now the
first production consumer of inference::throughput_expectation::classify_throughput
(which was built on canary but had zero callers). Thresholds are call-site policy
arguments — sample gate 16 tokens, collapse floor 0.25, no above-par ceiling —
and the classification itself lives in ONE place per the compression law.

Guard test + placement_watch + throughput_expectation tests green.

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

---------

Co-authored-by: Claude Fable 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.

2 participants