Skip to content

Fix 35GB memory leak + persona meter reliability - #296

Merged
joelteply merged 3 commits into
mainfrom
feature/rust-live-memory-leaks
Mar 12, 2026
Merged

joelteply merged 3 commits into
mainfrom
feature/rust-live-memory-leaks

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

  • Fix 35GB memory leak: Removed auto-loading LoRA adapters across all 14 personas at startup (~2GB each). Root cause was activateRegisteredAdapters() + cross-persona adapter sharing added in commit 3759837.
  • Persona meters now reliable: Added periodic 10s snapshots, request-on-mount event, replaced useless QUE meter (always 0) with ATN (attention/focus).
  • ORM hardening: SQLite auto-evolves schema on missing columns, Postgres error detection uses format_pg_error() instead of broken e.to_string().

Test plan

  • RSS stays bounded during live calls (was 35GB, now stable ~18-21GB)
  • Users & Agents widget shows real INT/NRG/ATN values on page load
  • Meters update in real-time as personas process messages
  • Genome bars capped at 4 with heatmap maturity colors
  • SQLite handles stale schemas after branch switching
  • Postgres missing tables return empty results instead of errors

…ersonas

ROOT CAUSE (bisected to commit 3759837 "cognition fixes"):
- activateRegisteredAdapters() auto-loaded LoRA weights into GPU memory
  for every persona at startup via genome.activateSkill()
- Cross-persona adapter sharing in LimbicSystem made ALL 14 personas
  discover adapters (even personas with no training of their own)
- Each adapter is ~2GB of weights → 14 personas × 2GB = 28GB+ leaked
- This ONLY manifested during live mode because live mode activates all
  14 personas simultaneously, triggering concurrent adapter loading

THE RULE: Never auto-load LoRA adapters at startup. Adapter activation
must be explicit, pressure-aware, and bounded. Future genome PR should
load adapters on-demand during inference, not eagerly at boot.

Also fixes:
- Postgres ORM: e.to_string() doesn't contain error details on
  tokio-postgres — switched to format_pg_error() so "relation does not
  exist" detection actually works (was returning errors instead of
  empty results for missing tables)
- SQLite ORM: schema evolution — auto ALTER TABLE ADD COLUMN on
  INSERT/UPDATE failure with "has no column named X" (matches Postgres
  behavior, fixes stale DBs from branch switching)
- PersonaState: emit initial snapshot 2s after construction so browser
  widget shows real values on page load instead of hardcoded defaults
- PersonaStateManager emits snapshots every 10s (idle personas no longer invisible)
- PersonaTile requests current state on mount via persona:state:request event
- QUE meter (always empty) replaced with ATN (attention/focus) which varies with fatigue
- dispose() added to PersonaStateManager for cleanup
Copilot AI review requested due to automatic review settings March 12, 2026 02:28
@joelteply
joelteply merged commit 84b90b6 into main Mar 12, 2026
2 of 5 checks passed
@joelteply
joelteply deleted the feature/rust-live-memory-leaks branch March 12, 2026 02:28

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 addresses a major memory leak related to LoRA adapter activation/sharing across personas, improves persona meter reliability in the UI via periodic/requested snapshots, and hardens ORM behavior for schema drift and Postgres error handling.

Changes:

  • Stop auto-loading/adopting cross-persona LoRA adapters on startup to keep memory bounded.
  • Make persona meters reliable on page load by emitting periodic snapshots and adding a request-on-mount flow; replace QUE with ATN.
  • Add SQLite “schema evolution” on missing-column errors and standardize Postgres missing-table detection via format_pg_error().

Reviewed changes

Copilot reviewed 9 out of 10 changed files in this pull request and generated 5 comments.

Show a summary per file
File Description
src/workers/continuum-core/src/orm/sqlite.rs Factor out SQLite type inference and add missing-column schema evolution + retry for create/update.
src/workers/continuum-core/src/orm/postgres.rs Use format_pg_error() consistently for error inspection/messaging.
src/widgets/chat/user-list/PersonaTile.ts Switch meter from QUE→ATN and request a state snapshot on mount.
src/system/user/server/modules/being/LimbicSystem.ts Remove cross-persona adapter fallback/sharing during adapter discovery.
src/system/user/server/modules/PersonaState.ts Add delayed initial snapshot, periodic snapshots, request handler, and a dispose() method.
src/system/user/server/PersonaUser.ts Remove auto-activation of registered adapters after wiring GPU provider.
src/shared/version.ts Bump shared version constant.
src/package.json Bump package version.
src/package-lock.json Sync lockfile version bump.
src/generated-command-schemas.json Update generation timestamp.
Files not reviewed (1)
  • src/package-lock.json: Language not supported

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

Comment on lines +88 to +92
setTimeout(() => this.emitSnapshotNow(), 2000);

// Periodic snapshot every 10s ensures browser always gets fresh state,
// even when persona is idle and no activity/rest events fire.
this._periodicInterval = setInterval(() => this.emitSnapshotNow(), 10_000);

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

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

The constructor adds a setTimeout + setInterval + global Events.subscribe per persona, but dispose() is never called anywhere in the repo (no call sites found). This can leak timers/subscriptions if personas are ever shut down/recreated; also the initial setTimeout handle isn’t tracked so it can’t be cancelled on dispose. Suggest storing the timeout ID and ensuring the owning lifecycle (e.g. PrefrontalCortex shutdown) calls personaState.dispose().

Copilot uses AI. Check for mistakes.
Comment thread src/shared/version.ts
*/

export const VERSION = '1.0.8895';
export const VERSION = '1.0.8899';

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

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

src/shared/version.ts is marked auto-generated from package.json, but after this change it no longer matches (VERSION is 1.0.8899 vs package.json 1.0.8900). This will cause inconsistent version reporting; please rerun the version generator or update this constant to match package.json.

Suggested change
export const VERSION = '1.0.8899';
export const VERSION = '1.0.8900';

Copilot uses AI. Check for mistakes.
match value {
Value::Bool(_) => "INTEGER",
Value::Number(n) => {
if n.is_i64() { "INTEGER" } else { "REAL" }

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

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

infer_sqlite_type() treats any non-i64 JSON number as REAL. serde_json::Number can be u64, so large positive integers will get stored as REAL and may lose precision. Consider treating is_u64() as INTEGER too (or using as_i64()/as_u64() checks) so integer semantics are preserved.

Suggested change
if n.is_i64() { "INTEGER" } else { "REAL" }
if n.is_i64() || n.is_u64() { "INTEGER" } else { "REAL" }

Copilot uses AI. Check for mistakes.
Comment on lines +355 to +356
let alter = format!("ALTER TABLE {} ADD COLUMN {} {}", table, col_name, col_type);
match conn.execute(&alter, []) {

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

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

evolve_table_schema() builds PRAGMA/ALTER statements via string interpolation of table and col_name. naming::to_table_name() / to_snake_case() only change casing and don’t validate/escape identifiers, so unexpected collection/field names could break SQL parsing or allow SQL injection if any of these values are ever influenced by untrusted input. Recommend validating identifiers against a strict allowlist (e.g. [a-z0-9_]+) and/or quoting/escaping identifiers consistently.

Copilot uses AI. Check for mistakes.
Comment on lines +425 to +429
if err_msg.contains("has no column named") {
// Schema evolution: add missing columns and retry
if evolve_table_schema(conn, &table, &record.data) {
match conn.execute(&sql, params.as_slice()) {
Ok(_) => return StorageResult::ok(DataRecord {

Copilot AI Mar 12, 2026

Copy link

Choose a reason for hiding this comment

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

The new schema-evolution retry path in do_create() (detecting "has no column named", ALTER TABLE, then retry) isn’t covered by the existing SQLite adapter tests in this file. Please add a test that creates a table with an initial schema, then inserts/updates a record containing a new field and asserts the column is added and the operation succeeds on retry.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Aug 2, 2026
… is a supported event (#296) (#2104)

2026-08-01 incident, glass-boxed: disk eviction swept the shared cargo
cache's debug/ dir (build/ + deps/ survived). `continuum reboot` ran an
incremental cargo build that printed "Finished" WITHOUT restoring
debug/continuum-core-server, then start-server.sh's `exec "$CORE_BIN"`
died with "No such file or directory" and serving stayed down.
Fail-loud worked; self-heal didn't. Cache eviction is a SUPPORTED event
(CLAUDE.md disk doctrine) — every deploy path must tolerate a swept
artifact.

The self-heal: one shared guard, `ensure_unswept_bin` — if the expected
artifact file is missing, print a loud "missing from cargo cache
(swept?) — rebuilding" line and re-run the SAME cargo build invocation
the script already uses for that bin (a missing output forces cargo to
re-link); if the artifact STILL doesn't exist, return non-zero so the
caller decides fatality. No new build shape, no fallback.

Applied to every artifact this script builds and later exec's/copies:
- continuum-core-server (FATAL): guarded between its build and the #194
  freshness check, so #194 asserts against a real file and a missing
  binary aborts the deploy loudly instead of at exec — leaving any
  running core untouched.
- continuum CLI (non-fatal, matches its build's own warn): restored
  before the ~/.local/bin copy so the install gets real bytes.
- forge-custodian (non-fatal): restored at build time instead of
  failing loud at first gene conversion.
- livekit-bridge (non-fatal): the rail already rebuilt on missing; now
  it verifies the rebuild actually produced the binary before nohup'ing
  a nonexistent path.

Validation: `bash -n` clean; the guard function was exercised in
isolation (sed-extracted from the script, stubbed `cargo`) across
present / restored / still-missing / build-failed cases — all behave as
designed under `set -e`. The live shared cargo cache was deliberately
NOT touched to simulate the sweep (the running core depends on it).


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
joelteply added a commit that referenced this pull request Aug 5, 2026
…-tier engine was never built

The fork gained `quantize --resident-only` + tier manifest three days ago
(1da3a0e, fork #40). The build never emitted the tool that exposes it. So for
three days the capability was vendored in, the plan-file wire carried
`resident_tier`, DivisionPolicy learned a residency curve from the measured
V4-Flash data — and the one thing that can actually PRODUCE a resident tier did
not exist on disk. MoE tiering had a brain, a seam, an actuator, and no engine.

`cmake --build --target llama-server` was the whole target list, on both the
POSIX and Windows branches. One word missing, invisible because everything that
depended on it fails LATER: the forge custodian would have discovered it at run
time, mid-way through a 91GB job, as a missing binary.

Both targets now build, and llama-quantize is verified with the same FATAL check
llama-server already had. Deliberately fatal, not a warning: a soft skip here
recreates exactly the gap being closed — a build that reports success while
omitting the thing the next stage needs. If a platform truly cannot build it we
want that at build time, in one second, named.

Verified: target builds clean into bin/llama-quantize, and the BINARY carries the
fork flag (`--resident-only  emit ONLY non-expert (resident) tensors, skipping
*_exps.*`) — checked with --help, not inferred from the source.

Same built-≠-shipped family as #296 (reboot reported success without restoring a
swept binary) and today's plugin hook that was installed but never deployed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 14, 2026
…able (#422) (#2293)

`continuum reboot` sets CONTINUUM_SKIP_SELF_BUILD=1 unconditionally, so
start-server.sh skips the CLI build on every platform. That guard exists for
exactly ONE constraint, stated in its own comment: Windows LOCKS a running
image, so `cargo build --bin continuum` from inside the running `continuum`
fails with `failed to remove file ...\continuum.exe`, cargo returns non-zero for
the WHOLE invocation, every later build is skipped — the CORE included — and
reboot dies after its full timeout having rebuilt nothing (772s on BIGMAMA,
2026-08-05). Real, and worth guarding.

The same comment also records that on Unix it "silently works: unlink leaves the
running inode" — and the guard was applied there anyway. That is the whole of
#422: a Windows accommodation charged to every operator, making the documented
deploy path (`edit → reboot → exercise`) structurally unable to ship a fix
living in the CLI. Proven on this Mac 2026-08-14: `stop`'s split-brain reap
(#2287) had merged and had NOT reached the installed CLI, leaving a core alive
and silent — while deploy-verify printed its green checkmark, because it only
looked at the core.

Nothing else was missing. start-server.sh already installs the built CLI into
~/.local/bin with a temp+mv atomic swap, and does it OUTSIDE the guard — so on a
Rebuild platform the loop closes with no new verb and no new swap machinery.
The running image is normally the ~/.local/bin COPY, not the target-dir binary
cargo replaces, so the Unix inode behaviour is a second line of defence rather
than the first.

deploy_provenance::cli_self_build(target_os) now owns the decision and names the
one platform it is for. It takes the OS as a parameter rather than reading
cfg!, so BOTH rows are unit-tested from any host — the Windows row is the one no
Mac CI job would otherwise cover. On Skip the CLI states out loud that a
CLI-side fix is NOT deployed; a silent skip that reads as a completed deploy is
how the stale CLI survived a green deploy-verify in the first place.

SECOND DEFECT, found while validating this and fixed here because enabling the
build walks straight into it: the CLI's GPU-free flag was a bare
`--no-default-features`, which on macOS ALWAYS fails — `metal` is not a default
feature and `llama` is an unconditional path dependency, so the llama crate's
`compile_error!("built on macOS WITHOUT --features metal")` fires. The GPU-free
CLI build has therefore never once succeeded on a Mac; every `npm start` since
it landed hit the loud "⚠ GPU-free continuum build failed … Please report this"
fallback and shipped a GPU-linked CLI while reporting an anomaly nobody
reported. CONTINUUM_CLI_FEATURES is now platform-shaped like the core's set
already was, using `llama/mac-cpu-only` — that guard's OWN declared opt-in for a
deliberately CPU-only build, which is exactly what a socket client wants.
Verified: `cargo check --bin continuum --no-default-features --features
llama/mac-cpu-only` compiles clean in 1m45s.

Also repointed the swept-cache CLI restore (#296 path) from CONTINUUM_FEATURES
to CONTINUUM_CLI_FEATURES — it was rebuilding the CLI WITH GPU deps, re-creating
the exact Windows-unlaunchable bug (0-byte exit 127 on a CUDA-version mismatch)
that the GPU-free build exists to prevent.

Tests: 5/5 in runtime::deploy_provenance, under the `cargo test --lib` gate CI
actually runs.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Aug 19, 2026
…curriculum — one exclude list, not two

LIVE FINDING 2026-08-18: sympy-22714's staged workspace held `.airc/identity.key` at git
status `A` — ALREADY intent-added. airc creates its scope at the enclosing git root
("in a git repo → <repo-root>/.airc/"), so a citizen working inside a cloned bench repo
gets `events.sqlite`, a work-board cache, and a PRIVATE KEYPAIR written under the very
repo she is being graded on.

TWO READINGS OF "HER WORK" HAD DRIFTED APART, which is exactly what one of them warned
about in its own doc — `workspace_candidate_diff`: "a second inline `git diff` would
drift on the exclude rules":

  - `benchmark::workspace_candidate_diff` — excluded `.airc` inline. SAFE. This is why
    the sympy-22714 grade came out at a clean 2,021 bytes rather than the 92KB the raw
    tree carries.
  - `agent::solve::workspace_patch` — its own near-copy of the exclude list, WITHOUT
    `.airc`. Not safe. And it is the reading that feeds `files_changed`, which feeds
    `format_solve_lesson` → the curriculum. An unexcluded key becomes the training
    sentence "I changed: .airc/identity.key". It also runs `git add -A -N`, which is
    what intent-added the key in the first place.

This is the second time the same hole has cost something: card b34f7eb5 records 91KB of
staged `.airc` blobs voiding a REAL fix, because the fresh clone refused the whole
candidate.

FIX (compression, not a patch): ONE list —
`benchmark::SOLUTION_PATH_EXCLUDES` — consumed by BOTH readings. `.airc` and
`.continuum` join the build/cache byproducts, with the doc stating plainly that the
first group is tidiness and the second is a SECURITY boundary. solve.rs's duplicate is
deleted and re-exported from the shared constant, so a future exclude can only be added
in one place.

POSITIVE CONTROL (the guard is real, not vacuous): with the `.airc` entries temporarily
removed, `workspace_patch_never_carries_agent_scope_state_or_credentials` FAILS on
"KEY MATERIAL must never reach a patch" — the literal `SUPERSECRETKEYMATERIAL` lands in
the diff. Restored, it passes. The test asserts three things a leak would break: the key
bytes are absent, no `.airc` path appears, and `files_changed` names ONLY her source
file (because that vector is what the curriculum reads).

31 tests green across workspace_patch / swe_bench / swe_setup.

NOTE, unrelated and not chased here: a cache sweep removed the cargo target's
`debug/deps` mid-command (~27GB freed, 141→168GB). No data loss, forces a rebuild;
belongs to the #155/#296 cache-governance lane.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Sep 20, 2026
…rgo line, one feature set (card 9174fc83) (#4276)

Measured on the IntelMac deploy of 2026-09-20: start-server.sh ran FOUR
separate `cargo build` invocations, one per bin (continuum-mcp, continuum,
forge-custodian, continuum-core-server), and "Compiling continuum-core"
appeared four times per deploy — 18m16s + 5m41s + 5m14s + 7m46s = 37 minutes.
25 minutes on the M5. Under the stop-first reboot path (the CLI's memory bar)
the serving core is dark for all of it.

Cause: each invocation resolves features, reruns the build scripts and
fingerprints the library for itself. The CLI carried its own feature variable
(CONTINUUM_CLI_FEATURES) on the Linux/Windows arm — `--no-default-features`,
unconditionally — so its fingerprint differed from the other three bins' and
the whole library recompiled for it; per-bin invocations then paid the
build-script re-run and the per-invocation resolution on every bin.

THE LAW: a deploy compiles the library once.

- build_core_bins() is the single place the crate's bins are built: ONE
  `cargo build --manifest-path "$CORE_MANIFEST" --bin … --bin … --bin … --bin …`
  so the lib compiles once and the four links run in parallel. The deploy
  build, the #296 swept-cache restore, the #194 forced rebuild and the
  GPU-free CLI arm all call it; the six literal invocations become one.
- One feature set by default. The CLI shares the core's set everywhere the
  set links no GPU runtime. The only sanctioned separation is the measured
  one — a set carrying cuda/rocm/vulkan makes a socket-client CLI unlaunchable
  on Windows (load-time cublas import, exit 127 with zero bytes, #6) — and
  there the CLI is one extra line, `--bin continuum` alone, with its own set.
  A CPU-only or DirectML-only Linux/Windows box no longer pays a second lib
  compile for a CLI that merely dropped `livekit-webrtc`.
- Every existing behaviour around the builds is kept: the core's failure is
  FATAL and a sidecar's is a warning (on a combined failure the core is built
  alone, warm, and ITS exit code decides), the self-build guard, the loud
  GPU-free→featured CLI fallback, the CLI install, the #296 restores (now for
  continuum-mcp too), the #194 freshness guard, the build-only receipt. The
  prebuilt-core `cargo()` shim — which would have skipped the whole combined
  invocation, sidecars included (the hole Cormac's review of #4107 closed) —
  is replaced by leaving continuum-core-server out of the bin list.
- The memory bar (warm_build_allowed in the CLI) is untouched: with one
  invocation there is no cheap-bins-before-the-big-link ordering to exploit;
  the lib compile IS the memory cost and every bin needs it. Stop-first now
  holds the core for one build instead of four.

Self-running check (tools/scripts/tests/start-server-build-only.test.sh,
already in both CI jobs): the script text carries exactly ONE literal
`cargo build --manifest-path "$CORE_MANIFEST"` (canary had 6); a fixture run
traces one cargo line naming all four bins with one feature set; a cuda set
separates only the CLI, on exactly one extra line; the fixture cargo now
understands a multi-`--bin` command line like real cargo.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5.1 <[email protected]>
joelteply pushed a commit that referenced this pull request Nov 19, 2026
Card 068a8a31 identified that deploy time includes four serial recompiles
of continuum-core because the start script built core-server, mcp,
forge-custodian, and the CLI each with potentially different features.

Changes:
- core-features.sh: CONTINUUM_CLI_FEATURES now always equals
  CONTINUUM_FEATURES (removed the case statement that set it empty on
  CUDA/ROCm/Vulkan). The CLI no longer gets a GPU-free separate build.
- start-server.sh: Removed the entire cli_build_separately /
  cli_is_running_image block. The `continuum` bin is now always added to
  core_build_bins, building alongside the other bins in one cargo
  invocation with the same feature set.

On Macs this eliminates the second library compile entirely (the sets were
already equal). On CUDA/ROCm/Vulkan boxes the CLI carries GPU link deps —
it's a socket client that doesn't use them at runtime, but it builds and
runs correctly. The tradeoff: one deploy = one lib compile instead of two.

The Windows self-build guard (cli_is_running_image) was removed because
the running-image constraint is unique to overwriting the CLI binary itself;
with a unified build the CLI is just another bin in the same invocation,
and the #296 swept-cache ensure_unswept_bin path handles restoration.
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