Skip to content

fix(memory): distil only what is new, off the first turn - #4033

Merged
kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/synthesis-watermark
Sep 26, 2026
Merged

kovtcharov-amd merged 5 commits into
amd:mainfrom
kovtcharov:claude/synthesis-watermark

Conversation

@kovtcharov

Copy link
Copy Markdown
Contributor

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 green
  • On a machine with existing memory, gaia chat twice: the first start distils at most two clusters and the answer arrives while it runs; the second start logs nothing new to distil and makes no model call
  • gaia memory status opens an existing (pre-v5) store without error — the migration is additive
  • gaia eval agent --category context_retention shows no regression against the baseline
🔍 Technical details

Where the progress lives. meta.skill_synthesis_watermark is the newest tool_history timestamp a pass consumed, passed straight to iter_sessions(since=…). A single timestamp cannot express a handled session sitting above an unhandled older one, so a new synthesis_marks table (schema v5, additive CREATE 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 SKIP sentinel, an unparseable document, or a response truncated at the model's output cap all arrive as candidate is None; those episodes are marked unusable with the reason and logged with their goal, both when they are marked and on every later pass that skips them. _synthesize_skills(force=True) or MemoryStore.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 in memory_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_count is 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_supersedes was updated accordingly.

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.
@github-actions github-actions Bot added documentation Documentation changes tests Test changes agents labels Sep 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Request changes

This 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 evidence

N/A — no evidence bundle was produced for this run, and the PR's test plan is present but entirely unchecked, including the gaia chat cold/warm start comparison, the gaia memory status check against a pre-v5 store, and the context_retention eval. The behaviour this PR claims (first start distils at most two clusters, second start makes no model call, answer arrives while the pass runs) is exactly the kind of thing that only shows up on a machine with real history, so please attach that CLI output. pytest was unavailable in this environment, so the unit suite was not executed here either — the verdict rests on static review alone.

🔍 Technical details

🟡 Important

1. Windowed success_count makes RECONCILE a permanent NOOP after the first pass (src/gaia/agents/base/procedural_memory.py:768, skill_synthesis.py:724)

_drop_consumed_episodes removes marked sessions before cluster_by_goal, so GoalCluster.success_count is the sum over the new window only. reconcile_and_store supersedes only when cluster.success_count > prior["success_count"], and prior was written by a pass whose window was the whole history.

Steady state: a cluster is distilled as soon as it reaches min_occurrences=3, its episodes are marked, and the next window for that goal is again ~3 sessions → the same ~9 successful calls → 9 > 9 is false → NOOP, forever. The updated test_name_drift_across_passes_supersedes shows this directly: it had to go from 2 extra sessions to 4 to make the update fire.

Two consequences beyond "no update": the stored success_count now understates the procedure's real track record (it is one window's, not the lineage's), and that field is documented as the dominance signal. Suggested direction — when reconcile_and_store matches an existing row, compare against / carry forward prior["success_count"] + cluster.success_count rather than the window alone, so the lineage's cumulative record is what dominates.

2. The watermark can be pinned indefinitely by a never-qualifying episode (procedural_memory.py:828)

_advance_synthesis_watermark stops just below the oldest unconsumed episode in the window. An episode only becomes consumed by being handed to the distiller, which requires it to land in a qualifying cluster. Two classes never can:

  • a one-off goal that never reaches min_occurrences;
  • a session with no role='user' turn — iter_sessions returns goal=None and cluster_by_goal skips it unconditionally (skill_synthesis.py:494).

The new test TestUnusableEpisodes._seed_blocked_history builds exactly that shape and asserts store.get_synthesis_watermark() is None, so the state is known and accepted. The cost it leaves behind: every pass runs extract_sequences over all history from that floor, and cluster_by_goal issues one embedder round-trip per distinct unconsumed goal (it memoizes by goal text, skill_synthesis.py:492) — a set that only grows. The distill cap bounds the expensive half; this half is unbounded.

Worth bounding — e.g. mark episodes older than the prune horizon as stale (a third SYNTHESIS_OUTCOMES value) so they drop out of the window, or cap the pending window size.

3. The background pass shares the live turn's chat client and clobbers its per-call metrics (procedural_memory.py:503)

_synthesize_skills calls self.chat.send_messages, and self.chat is the agent's SDK instance, now used from the synthesis thread while the foreground turn is using it. Two single-valued slots are involved:

  • TurnRecorder._open_call (turn_metrics.py:193) — one open call at a time. _recorder_begin / _recorder_end in sdk.py:403 are called by both threads, so a background distillation opens over the foreground turn's open call and end_llm_call closes the wrong one. Also corrupts _prev_rendered, which drives the cache-prefix ratio. Dev-gated (GAIA_TURN_LOG), so not user-visible — but it is the instrument that produced this PR's numbers.
  • LemonadeProvider._last_usage (providers/lemonade.py:542) and get_stats() (Lemonade /stats is server-global) — both read in sdk.py:415-420 after the foreground chat() returns. A background call completing in that window makes the turn report the distillation call's tokens/tok-s. This is the same class of mis-attribution b46327f just fixed.

Related, lower confidence but worth a thought: the background pass also issues embedder calls concurrently with the user's turn. CLAUDE.md records the embedder warm-up evicting the resident chat model (#1030); _ensure_model_loaded would recover it, so the failure mode is a mid-turn stall rather than a wrong answer — but it is a new interleaving that inline synthesis did not have.

🟢 Minor

4. start_skill_synthesis has a TOCTOU on the thread guard (procedural_memory.py:528) — the is_alive() check and the assignment to _skill_synthesis_thread are not atomic, so two concurrent callers can both start a pass. Only one caller exists today, so this is cheap insurance rather than a live bug; a module-level threading.Lock around the check-and-set closes it.

5. The documented retry lever is not reachable from the CLI — both docs/sdk/sdks/memory.mdx:105 and the off-state table point users at _synthesize_skills(force=True) (private) or MemoryStore.reset_synthesis_progress(). Neither is exposed through gaia memory. Since marking a cluster unusable is now permanent until someone resets, a gaia memory subflag would make the documented escape hatch real.

6. _proc_faiss_search reads the index outside the lock it then searches under (procedural_memory.py:182-195) — index, index.ntotal and _validated_faiss_query run before with _PROC_INDEX_LOCK. Today the only concurrent writer is _proc_faiss_add, so a stale ntotal just shrinks k harmlessly, but capturing the index inside the lock would make the invariant obvious and survive a future _rebuild_faiss_index from another thread.

Strengths

  • The v4→v5 migration is genuinely additive and tested from the cold state — TestOldStore.test_v4_store_migrates_and_synthesizes drops the table, rewinds the version marker, reopens, and asserts both the migration and that history survived. That is the pattern CLAUDE.md asks for and it is often skipped.
  • The distinction between "the model could not distil this" (marked unusable, not retried) and "Lemonade was down" (left unmarked, retried next pass) is the right line, and test_infra_failure_leaves_the_cluster_unmarked locks it in. Excluding the live session from the window is a subtle case caught before it bit.
  • Docs were updated in all three places the change touches — the plan, the SDK page, and the architecture spec, including the schema block and the migration ladder. That is the "update EVERY doc that describes it" rule actually followed.
  • test_first_query_does_not_wait_for_distillation asserts the user-visible property (the answer returns while the model call is still blocked) rather than just that a thread was spawned.

@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

Merged current main into this branch to clear the drift. Nothing in the PR's own change had to move — the only overlap with main was in the memory docs and memory.py, and both auto-merged.

🔍 Technical details

Merge commit 31a00f01a (git merge origin/main, no rebase/force-push). Auto-merged: docs/sdk/sdks/memory.mdx, src/gaia/agents/base/memory.py. PR content vs main: 12 files, +1141/-84.

Tests: 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_adaptive_skills.py tests/unit/test_starter_skills.py -q → 935 passed, 15 skipped.

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.
@kovtcharov-amd

Copy link
Copy Markdown
Collaborator

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. NOOP stays reachable and now means what it says: no new evidence. The stored track record is the lineage's again, not one window's.

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 details

Fix 1 — reconcile_and_store (skill_synthesis.py). New _lineage_record(prior, cluster) folds the cluster into the matched row keyed on provenance.from_sessions, not on the numbers, so double-counting is impossible in any path — including force=True and the first pass after reset_synthesis_progress, where the window legitimately re-reads consumed episodes. provenance.from_sessions now carries the lineage's session set forward rather than one window's.

Three tests replaced or added in test_skill_synthesis.py: test_a_small_window_of_new_episodes_still_supersedes (the regression), test_noop_when_the_cluster_brings_nothing_new and test_a_drifted_name_over_already_seen_episodes_noops (NOOP re-expressed — the old pair asserted "weak cluster loses to strong prior", which was only ever reachable because the window was the whole history), and test_re_reading_consumed_episodes_never_double_counts.

test_name_drift_across_passes_supersedes goes back to a realistic 3-session second window — it had been widened to 4 specifically to make the update fire, which is the review's own evidence — and now also asserts the lineage count and provenance.

Fix 2 — _mark_unclusterable_episodes (procedural_memory.py). Runs after _drop_consumed_episodes, marks goalless episodes unusable with a detail naming the reason, and removes them from pending. Two tests: one asserts the mark and that the watermark advances; the other asserts extract_sequences(store, since=watermark) == [], which is the cost the pin actually leaves behind.

Fail-without-the-fix checks, both reverted in place and restored:

windowed comparison  → test_a_small_window_of_new_episodes_still_supersedes FAILED
                       test_name_drift_across_passes_supersedes            FAILED
goalless fix removed → both new watermark tests                            FAILED
test_skill_synthesis_incremental  test_memory_mixin  test_memory_store
test_skill_synthesis  test_adaptive_skills  test_starter_skills
→ 1023 passed, 15 skipped
black + isort clean

tests/integration/test_memory_integration.py not run — no local Lemonade on this host. No eval run for the same reason; the change touches reconciliation arithmetic and watermark bookkeeping, not prompts or tool schemas, but context_retention is still the right gate before merge.

Docs updated where the rule is stated: docs/plans/skill-synthesis.mdx step 4 and docs/sdk/sdks/memory.mdx. Note the PR description still says "a cluster's success_count is now the new window's, not the whole history's" — that sentence is now out of date and worth editing before merge.

Merged origin/main cleanly on top.

@kovtcharov-amd
kovtcharov-amd added this pull request to the merge queue Sep 26, 2026
Merged via the queue into amd:main with commit 6a07c23 Sep 26, 2026
39 of 41 checks passed
@kovtcharov-amd
kovtcharov-amd deleted the claude/synthesis-watermark branch September 26, 2026 03:45
kovtcharov-amd added a commit to kovtcharov/gaia that referenced this pull request Sep 26, 2026
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents documentation Documentation changes tests Test changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants