Repository navigation
fix(memory): distil only what is new, off the first turn - #4033
Conversation
Starting a session on a machine with real memory history cost 83 s before the agent answered anything, 65 s of it five distillation calls the agent had already made in earlier sessions. Nothing recorded what had been distilled, so every start re-read the whole history: 28 procedures for about five distinct goals, re-created week after week, and the calls that produced nothing usable were retried forever. A pass now reads only what no earlier pass consumed. A watermark in `meta` is the DETECT `since`, and a new `synthesis_marks` table records the episodes a pass handed to the distiller — including ones it could not turn into a procedure, which is what stops the same failing call from repeating on every start. `_synthesize_skills(force=True)` and the store's `reset_synthesis_progress()` re-open them deliberately; the skip is logged with the goal and the reason either way. The pass also moved off the first turn. `start_skill_synthesis()` runs it on a background thread that logs its start, its outcome (episodes consumed, procedures written, seconds taken) and any failure, with `wait_for_skill_synthesis()` for a caller or a test that needs to join it. It spends at most two distillation calls — each one holds the single local model slot the user's own turn needs — and then leaves the watermark at the last fully consumed episode, so the remainder is picked up next session instead of being skipped. Schema goes to v5. A store written by an older build has no marks and no watermark, which reads as "nothing consumed yet": it distils its history once, records both, and is incremental from then on.
Request changesThis makes session start stop re-distilling history it already processed, and moves the distillation off the user's first turn — a genuinely good fix for the 83 s start, with a clean additive migration and thorough tests. Two things should be settled before merge. Learned procedures will now almost never be updated. Because each pass only sees the episodes since the last one, the "how well did this workflow do" score a new candidate is judged on is the score of that small new batch, not of the whole history. It is compared against the score the original (whole-history) pass recorded, so in normal use the new batch never wins and the stored procedure is kept unchanged forever. The PR body notes the change, but the practical effect is that a workflow which has since drifted or improved can no longer replace the stale version. Either carry the earlier score forward when the match is the same procedure, or say explicitly that this is accepted and track it. A single unrepeatable session pins the "already read" marker permanently. Any episode that never forms a cluster — a one-off task, or a session with no user turn so there is no goal to cluster on — is never recorded as handled, and the marker cannot move past it. The PR's own test asserts exactly this state. Distillation calls stay capped, so the headline fix holds, but the database scan and the per-goal embedding calls still cover the whole history on every start, growing forever. Worth a bound (an age cutoff, or marking stale episodes) in this PR or a tracked follow-up. Also worth a look: the background pass shares the agent's chat client with the live turn, and a few per-call measurement slots on that client hold only one value at a time — so a distillation call landing mid-turn overwrites the user turn's own timing and token numbers. Nothing breaks, but the instrumentation this PR was measured with becomes unreliable once the feature ships. Real-world evidenceN/A — no evidence bundle was produced for this run, and the PR's test plan is present but entirely unchecked, including the 🔍 Technical details🟡 Important1. Windowed
Steady state: a cluster is distilled as soon as it reaches Two consequences beyond "no update": the stored 2. The watermark can be pinned indefinitely by a never-qualifying episode (
The new test Worth bounding — e.g. mark episodes older than the prune horizon as 3. The background pass shares the live turn's chat client and clobbers its per-call metrics (
Related, lower confidence but worth a thought: the background pass also issues embedder calls concurrently with the user's turn. 🟢 Minor4. 5. The documented retry lever is not reachable from the CLI — both 6. Strengths
|
|
Merged current 🔍 Technical detailsMerge commit Tests: |
Two consequences of making synthesis incremental, both of which only show up after the first pass: RECONCILE became unreachable. A cluster now carries only the episodes no earlier pass consumed — a steady min_occurrences-sized batch — and it was compared against a row that a whole-history pass wrote. ~9 > ~9 is false, so a workflow that had since drifted could never replace the stale procedure, and the stored success_count understated the real track record because it was one window's rather than the lineage's. The comparison is now against the matched row's record plus the episodes it was NOT built from, keyed on provenance.from_sessions so a force pass or one following reset_synthesis_progress counts each session once. NOOP stays reachable and now means what it says: no new evidence. The watermark could be pinned forever. A session with no user turn has no goal, cluster_by_goal skips it unconditionally, and nothing else ever marks it — so it held the floor and every later pass re-scanned all history above it, a cost that only grows. Those are now marked on sight: no future session can give a past session a user turn, so recording it is a fact, not a policy. A one-off GOAL that has not yet recurred is left pending, because it still might. test_name_drift_across_passes_supersedes goes back to a realistic 3-session second window (it had been widened to 4 to make the update fire) and now also asserts the lineage count and provenance.
|
Both findings confirmed and fixed. The second one I fixed only for the half that is a fact rather than a policy call — the rest is a decision I would rather not make silently, so it is spelled out below. Learned procedures really were frozen after the first pass. A cluster now holds only the episodes no earlier pass consumed — the same small batch each time — and it was scored against a row a whole-history pass wrote, so it could never win. The comparison is now against the matched row's record plus the episodes it was not built from, keyed on which sessions it came from so a forced pass or one after a reset counts each session once. A session with no user turn no longer pins the "already read" marker. It has no goal, clustering skips it unconditionally, so nothing would ever mark it — and the marker stops below the oldest unread episode, so one of them held the floor and every later start re-scanned all history above it. Those are now marked on sight. No future session can give a past session a user turn, so recording that is a fact, not a policy. What I deliberately did not decide: the other class the review named is a one-off goal that has not recurred yet. Unlike the goalless case it may still qualify later, so dropping it needs a rule about how long to keep hoping — an age cutoff, a pending-window cap, or caching goal embeddings across passes so the re-scan stops costing model time instead of disappearing. Each trades a different thing, and picking one here would bake a retention policy into a bug fix. Worth its own issue. Also unaddressed and worth a maintainer's call: the background pass shares the agent's chat client with the live turn, so a distillation landing mid-turn overwrites that turn's timing and token numbers. Dev-gated, but it is the instrument this PR was measured with. 🔍 Technical detailsFix 1 — Three tests replaced or added in
Fix 2 — Fail-without-the-fix checks, both reverted in place and restored:
Docs updated where the rule is stated: Merged |
Nine test files that no CI lane runs had been failing for weeks without anyone seeing it. `tests/test_sdk.py` alone had 17 failures against APIs that were renamed or removed. This PR gets every one of them passing against current main, so amd#4205's follow-up can put them in a lane. Where a test covered something that no longer exists, it's deleted and the commit says why, rather than rebuilt. Overlaps (small, easy to resolve, all by the same author): - amd#4033 bumps the same schema-version assertion from 4 to 5. Whichever lands second takes its own number. - amd#4290 and amd#3122 edit `tests/test_vlm_integration.py`, which this PR deletes. That file returned booleans instead of asserting, so it could never fail, and it passed a constructor argument that no longer exists. ## Test plan - [x] Before, on `origin/main`: the repaired files fail offline (`test_sdk.py` 17, `test_multi_caller_equivalence.py` 2, `test_memory_integration.py` 1, `test_memory_api_integration.py` 1, `test_documents_router.py` 3, `test_tui_control_e2e.py` 6, `test_ui_email_scope_consent.py` 5, `test_lemonade_embedded_lifecycle.py` 1 on macOS) - [x] After, with homes isolated and Lemonade pointed at a dead port: the offline set passes. That's 534 passed and 12 skipped across the 23 files amd#4205 wires in, in a clean py3.12 venv with `-e ".[api,mcp]"` plus the unit job's test deps, with Go on PATH - [x] `tests/test_ui_email_scope_consent.py` passes inside the email unit lane's full pytest command (4971 passed), in a clean venv with `.[dev,api,publish,mcp]` and the email package installed - [x] `black --check`, `isort --check-only`, `flake8`, and `pylint --errors-only` are clean on every changed file <details> <summary>🔍 Technical details</summary> - `test_sdk.py`: `Agent.execute_tool` was never public; the replacement follows `docs/sdk/testing.mdx` (registry lookup). `openai_server` exposes a module-level `app`, not `create_app()`. `STATE_*` constants live on `Agent`. `_register_tools` is now the only abstract method. Removed the xfail `DatabaseMixin` block, since it ships as `gaia.database.mixin` and has its own wired tests. The MCP tests in this file need the `[mcp]` extra, which the lane installs. - `test_multi_caller_equivalence.py`: mutating `/api/*` calls need `X-Gaia-UI: 1` (`gaia.ui.security`), and `/api/connectors` returns `{"connectors": [...]}` keyed by `id`. - `test_memory_api_integration.py`: consolidation returns 503 until a chat session registers `_consolidate_fn`. That is intended behavior, not a side effect of the environment. Both branches are now pinned. - `test_documents_router.py`: the `failed_doc` fixture and one test uploaded without `mock_index_document`, so they indexed for real and needed Lemonade. - `test_tui_control_e2e.py`: a fresh pty is 0x0, so `resize` refused; runners leave `TERM` unset, so the ANSI screen had no escapes. - `test_ui_email_scope_consent.py`: `EmailTriageAgent` also declares `microsoft_work` now. The three deleted tests hit an in-process `/v1/email` mount that the UI dropped in the amd#1767 sidecar cutover; `tests/unit/test_email_sidecar_*` cover the forwarder. </details> Refs amd#4205 --------- Co-authored-by: Kalin Ovtcharov <[email protected]> Co-authored-by: Kalin Ovtcharov <[email protected]>
On a machine with real memory history, starting a session cost 83 s before the agent answered anything — 65 s of it five procedure-distillation calls it had already made in earlier sessions. Nothing recorded what had been distilled, so every start re-read the whole history: the store held 28 procedures for about five distinct goals, re-created week after week, and the two calls that produced nothing usable were retried forever. A pass now reads only what no earlier pass consumed, spends at most two model calls, and runs in the background instead of in front of the first answer.
Test plan
python -m pytest tests/unit/test_skill_synthesis_incremental.py tests/unit/test_memory_mixin.py tests/unit/test_memory_store.py tests/unit/test_skill_synthesis.py tests/unit/test_adaptive_skills.py tests/integration/test_memory_integration.py -q— all greengaia chattwice: the first start distils at most two clusters and the answer arrives while it runs; the second start logsnothing new to distiland makes no model callgaia memory statusopens an existing (pre-v5) store without error — the migration is additivegaia eval agent --category context_retentionshows no regression against the baseline🔍 Technical details
Where the progress lives.
meta.skill_synthesis_watermarkis the newesttool_historytimestamp a pass consumed, passed straight toiter_sessions(since=…). A single timestamp cannot express a handled session sitting above an unhandled older one, so a newsynthesis_markstable (schema v5, additiveCREATE TABLE IF NOT EXISTS+ version bump, same shape as v2→v3 and v3→v4) records one row per session handed to the distiller with its outcome. A store written by an older build has neither, which reads as "nothing consumed yet".Not retrying what cannot be distilled. A
SKIPsentinel, an unparseable document, or a response truncated at the model's output cap all arrive ascandidate is None; those episodes are markedunusablewith the reason and logged with their goal, both when they are marked and on every later pass that skips them._synthesize_skills(force=True)orMemoryStore.reset_synthesis_progress()re-opens them. An LLM call that raises (Lemonade down) is not the same thing — those episodes stay unmarked so the next pass retries them.The cap: 2 calls (
max_distill_calls_per_pass, overridable inmemory_settings.json). Now that the pass is off the first turn the cost that matters is not latency but the single local model slot — every distillation call queues in front of the user's own tokens. Two calls is one small bite (≈26 s of background model time at the measured ~13 s/call); a backlog like the 28-procedure one above drains over a few sessions. When the cap is hit the pass stops cleanly and the watermark is left at the last fully consumed episode — the maximum consumed timestamp strictly below the oldest episode left behind — so nothing above it is skipped. It never moves backwards.Off the first turn. The maintenance pass calls
start_skill_synthesis(), which runs one pass on a daemon thread and logs start, outcome (episodes consumed, procedures written, clusters not usable, seconds) and failures at ERROR with a traceback, keeping the exception on_skill_synthesis_error.wait_for_skill_synthesis(timeout)joins it. The procedures FAISS index is now touched under a lock, because a background add can otherwise race a foreground recall search. The live session is excluded from the window so it is never marked done while it is still producing tool calls.Behaviour change worth knowing: a cluster's
success_countis now the new window's, not the whole history's, so a stored procedure is superseded only by a later window with more successful runs than the one that wrote it.test_name_drift_across_passes_supersedeswas updated accordingly.