Repository navigation
relearn: stop inventing root causes for text-less failures, and four defects around it - #684
Conversation
write_cache and read_cost_proposals round-tripped cost-proposal state through hand-written key lists. Any cost_* key missing from either list was silently dropped on the next relearn-leg recompute -- no error, just a field that read as "never stamped". Live instance: cost_proposals_error and cost_proposals_error_at (a recorded recompute-failure state) were absent from write_cache's preservation loop, so a routine relearn recompute erased evidence of a failed cost refresh. Both functions now copy/project cost_* keys by prefix instead of by a maintained list, so a future cost_* key can't repeat this silently. Co-Authored-By: Claude <[email protected]>
A span with no status_message falls back to its own name (e.g. gen_ai.tool.call) as error_text, in both the OTel and archive extraction lanes. That fallback carries no diagnosis of what actually failed, but it was being treated exactly like real error text: unrelated failures that happened to share the same tool and no message all collapsed into one generic signature, and once that cluster recurred across enough sessions it was handed to the LLM distill pass, which confidently invented a root cause and fix for a cluster made of nothing but a bag of unrelated failures. FailureEpisode now carries error_text_is_name_fallback, set only by the two span-sourced extraction paths (the transcript lane always has real error text). _failure_signature scopes a name-fallback failure's signature to its own session, so it can never merge with an unrelated failure and can never clear the cross-session recurrence gate — the money is still counted, via the existing below-threshold residue path, just never claimed as a named recurring relearn. _evidence_too_thin_for_distill additionally rejects any cluster made entirely of name-fallback failures outright, as a second, independent line of defense against a model call ever being spent naming a failure with nothing to ground a name in. Rewrote the pinned fallback test to assert the new flag instead of just the fallback text, and added coverage for the no-merge and no-distill guarantees at both the extraction layer and the distill-gate layer. Co-Authored-By: Claude <[email protected]>
…ck alone The daemon's scan-cycle interval job re-ran the full analyzer pass — including the relearn distill pass's LLM subprocess calls — on a pure timer, so an idle machine recomputed an answer that could not have changed several times a day. Add a cheap in-process watermark (core/optimize/ingest_watermark.py) bumped at the two DuckDB write paths every ingestion source (live pipeline, backfill, catch-up) funnels through. A SCHEDULED tick now also requires at least `scan_watermark_min_new_spans` new spans since the last pass that actually ran (default 1, preserving today's behaviour for any active machine); a `scan_watermark_max_staleness_hours` ceiling (default 24h) forces a refresh regardless once that long has passed, so a genuinely quiet machine still rescans eventually. `trigger_scan_cycle` grows a `force` parameter reserved for an explicit user rescan (POST /optimize/rescan), which always bypasses the gate. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…/--db core/distill.py's _default_cache_dir() had no config parameter at all and always resolved to the real ~/.tj/distill_cache, unlike the three existing precedents (relearn_store.default_cache_path, report_store.default_report_ path, transcript_cache.default_cache_dir) that already honor storage.path scoping. Worst of the three: api/routes/sessions.py's session-distill route called peek_cached_titles/distill_titles_cached with no cache_dir at all — a served API route writing into the operator's real home regardless of the active config's scope. - _default_cache_dir(config=None) now routes through relearn_apply._storage_base_dir(config) when a config is given, keeping the historical ~/.tj default when it isn't (no import cycle: distill.py has zero tokenjam.* top-level imports and imports relearn_apply lazily). - The session-distill route resolves the active config off request.app.state.config and threads the scoped cache_dir through both calls. - analyzers/relearn.py's apply_distill_to_residual now requires an explicit cache_dir (was Path | None = None, silently falling back to the unscoped resolver) — its one production call site already always supplies one. Added the same "fake, obviously-not-real HOME" scoping test used by test_relearn_apply.py, plus a route-level test asserting the distill calls receive the config-scoped cache_dir. Co-Authored-By: Claude <[email protected]>
core.distill._invoke_claude (shared by relearn-cluster naming and core.rulewrite.presence's rule-presence check) shells out to the same local `claude` CLI a user's own Claude Code sessions do, and that subprocess writes an ordinary transcript to disk like any other invocation. Nothing at the ingest boundary excluded it, so tokenjam's own housekeeping calls were being counted as real user sessions. _invoke_claude now runs from a dedicated marker subdirectory of the system temp root (INVOKE_CWD_DIRNAME) instead of the bare temp root, and is_tokenjam_invoke_cwd() checks a recorded session's cwd against that marker's basename. A bare "cwd resolves under the temp root" check would also catch a user genuinely working out of /tmp; the dedicated marker name lets the ingest boundary positively identify tokenjam's own calls instead of guessing from a heuristic, so a real temp-dir user's session is left alone. Wired in at both on-disk ingest readers: core.backfill.parse_claude_code_ session drops such a file at the earliest point cwd is known (before building any spans), and transcript_sync.scan_disk_sessions (which _header_fields now also reads cwd for) excludes it from the reconciliation scan so it's never reported as a "missing" session and pulled in by a scheduled catch-up. The daemon's scan schedule itself is untouched. Tests cover: the marker is positively identified and a bare /tmp cwd is not; the two halves (what _invoke_claude actually passes as cwd, and what the checker accepts) agree; both ingest readers exclude a marker-cwd session while keeping an unrelated real /tmp session intact. Co-Authored-By: Claude <[email protected]>
|
| Filename | Overview |
|---|---|
| tokenjam/core/distill.py | Adds scoped cache resolution and a marker cwd for internal model calls, but the marker predicate can collide with a genuine user project basename. |
| tokenjam/core/backfill.py | Excludes transcripts identified as internal, including genuine sessions falsely matched by the basename-only predicate. |
| tokenjam/core/transcript_sync.py | Mirrors the internal-session exclusion in catch-up reconciliation, preventing a falsely excluded transcript from being recovered later. |
| tokenjam/core/optimize/scan_cycle.py | Adds scheduled watermark gating but advances the successful-pass baseline before all downstream stores have refreshed. |
| tokenjam/core/optimize/ingest_watermark.py | Introduces a thread-safe process-local ingestion counter used by scheduled scan gating. |
| tokenjam/core/optimize/analyzers/relearn.py | Tracks name-fallback evidence explicitly, session-scopes its signatures, and independently excludes all-fallback clusters from distillation. |
| tokenjam/core/optimize/relearn_store.py | Replaces fragile cost-field whitelists with prefix-based preservation and projection while retaining established defaults. |
| tokenjam/api/routes/sessions.py | Threads the active configuration's scoped distillation-cache directory through both cache read and write paths. |
| tokenjam/core/db.py | Bumps the ingestion watermark after successful per-row and bulk span writes. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
Tick[Scheduled analyzer tick] --> Gate{Watermark permits run?}
Gate -->|No| Skip[Skip cycle]
Gate -->|Yes| Report[Build and store report]
Report --> Mark[Record pass watermark]
Mark --> Relearn[Refresh relearn store]
Relearn --> Cost[Refresh cost proposals]
Cost --> Presence[Refresh rule presence]
Relearn -. downstream failure .-> Stale[Store remains stale]
Stale --> Next[Next idle scheduled tick]
Next --> Gate
Prompt To Fix All With AI
### Issue 1
tokenjam/core/distill.py:184-185
**Basename collision drops real sessions**
When a genuine user project is named `tokenjam-internal-distill-cwd`, this basename-only predicate classifies its recorded cwd as TokenJam's internal directory. Both backfill and transcript synchronization then discard the complete session, causing its tokens, costs, timeline, and analyzer evidence to disappear from downstream surfaces.
### Issue 2
tokenjam/core/optimize/scan_cycle.py:270
**Watermark records partial cycle completion**
When the report write succeeds but a later relearn, cost-proposal, or rule-presence refresh fails, this line records the pass as complete before those operations run. With no subsequent telemetry, scheduled ticks then skip the incomplete cycle, leaving downstream stores stale or degraded until a forced rescan, new span, or the 24-hour staleness ceiling.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.Reviews (1): Last reviewed commit: "Merge remote-tracking branch 'origin/sca..." | Re-trigger Greptile
| try: | ||
| return PurePosixPath(cwd.replace("\\", "/")).name == INVOKE_CWD_DIRNAME |
There was a problem hiding this comment.
Basename collision drops real sessions
When a genuine user project is named tokenjam-internal-distill-cwd, this basename-only predicate classifies its recorded cwd as TokenJam's internal directory. Both backfill and transcript synchronization then discard the complete session, causing its tokens, costs, timeline, and analyzer evidence to disappear from downstream surfaces.
Knowledge Base Used: Session Analysis and Export
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/distill.py
Line: 184-185
Comment:
**Basename collision drops real sessions**
When a genuine user project is named `tokenjam-internal-distill-cwd`, this basename-only predicate classifies its recorded cwd as TokenJam's internal directory. Both backfill and transcript synchronization then discard the complete session, causing its tokens, costs, timeline, and analyzer evidence to disappear from downstream surfaces.
**Knowledge Base Used:** [Session Analysis and Export](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/session-analysis-export.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.| if stored is None: | ||
| # The overlap guard declined between the check above and here. | ||
| return | ||
| _record_pass_watermark(watermark_at_start) |
There was a problem hiding this comment.
Watermark records partial cycle completion
When the report write succeeds but a later relearn, cost-proposal, or rule-presence refresh fails, this line records the pass as complete before those operations run. With no subsequent telemetry, scheduled ticks then skip the incomplete cycle, leaving downstream stores stale or degraded until a forced rescan, new span, or the 24-hour staleness ceiling.
Knowledge Base Used: Relearn / Self-Improve Loop
Prompt To Fix With AI
This is a comment left during a code review.
Path: tokenjam/core/optimize/scan_cycle.py
Line: 270
Comment:
**Watermark records partial cycle completion**
When the report write succeeds but a later relearn, cost-proposal, or rule-presence refresh fails, this line records the pass as complete before those operations run. With no subsequent telemetry, scheduled ticks then skip the incomplete cycle, leaving downstream stores stale or degraded until a forced rescan, new span, or the 24-hour staleness ceiling.
**Knowledge Base Used:** [Relearn / Self-Improve Loop](https://app.greptile.com/metabldr/-/custom-context/knowledge-base/metabuilder-labs/tokenjam/-/docs/relearn-loop.md)
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
Four independent defects in the relearn analyzer and the machinery around it. Each is its own commit; they are grouped because they share the same three modules and were verified together against one live corpus.
1. Text-less error spans no longer reach the model, or merge with each other
An OTEL error span whose
status_messageis empty fell back to the span's own name as its error text, soerror_textbecame the literal stringgen_ai.tool.call. Every unrelated failure carrying that non-error then shared a signature and merged into one cluster.Those merged spans were being handed to the distill pass, which — given no error text at all — still produced a confident diagnosis. On a real 6,584-session corpus this surfaced as three LLM-titled clusters ("Tool Invocation Framework Error", 120 sessions, $23.00; "WebFetch Tool Generic Repeated Error", $4.89; "Tool Call Permission Not Configured", $3.98) whose every recorded example snippet was the string
gen_ai.tool.call. About $32 of a $368 headline was a bag of unrelated failures wearing an invented root cause, and model calls were being spent to invent it.FailureEpisodenow records whether its error text came from the name fallback, set at both extractor sites rather than re-derived downstream by string comparison.2. Three cache paths escaped
--projects-root/--dbscopingThe scoping contract promises a scoped or demo run does not write the operator's real machine state. Three paths ignored it, and the write fires only after a successful model call, so it was invisible in the common path and in tests.
distill._default_cache_dir()hardcoded~/.tj/distill_cachewith no config parameter at all. It now routes through the same storage-base helper the relearn store, report store, and transcript cache already use, keeping the old location as the no-config fallback.apply_distill_to_residual's cache directory is now required rather than defaulting to the unscoped resolver, so the safe path is not something every caller has to remember.Tests mirror the existing fake-HOME isolation precedent; none existed for any of these three.
3. The tool's own model calls are no longer ingested as user sessions
The distill and rule-presence paths invoke the local
claudebinary, which writes a transcript to disk, which ingestion then read back as an ordinary coding session. On the corpus this was verified against, 1,010 of 6,972 sessions — 14.5% — were the tool measuring itself. The dollar contamination was negligible; the session-count contamination was not, since per-session denominators, persona classification and cohort counts all run over that population.Rather than guess at a fingerprint from fields no parser reads, the invocation now runs from a dedicated, explicitly-named marker subdirectory of the temp root, and both on-disk readers exclude sessions recorded against it. A user genuinely working in a temp directory is unaffected — only the exact marker directory is excluded.
4. The shared cost cache stops dropping keys it was never told about
The relearn detector and the cost proposals share one cache file, and a
cost_-prefixed key had to be named in two separate hand-written lists to survive a round trip — one in the write path's preservation branch, one in the read path's projection. A key missing from either was dropped with no error, and read downstream as a legitimate "absent".It had already eaten two keys. A third was live: a recorded cost-proposals error was silently erased by any relearn-leg rewrite, so a failed recompute read back as though nothing had gone wrong. Both lists are replaced by prefix copy-through, with the existing defaulting behaviour preserved for the callers that rely on it. The new test round-trips a key that appears nowhere in the source, so the guard cannot pass by whitelist coincidence.
5. The scheduled analyzer pass no longer re-spends on an idle machine
The daemon ran the full pass — model calls attached — on a plain wall-clock interval with no reference to whether any new telemetry had arrived, so a machine where nothing happened still recomputed an answer that could not have changed. Catch-up ingestion was already a separate, independently-scheduled job with no coupling to it.
A span counter bumped at the two database write choke points now gates the scheduled pass. A staleness ceiling guarantees a quiet machine still refreshes, an explicit user rescan always runs regardless, and the anti-thrash floor is structural: the gate is only ever evaluated on the scheduler's own interval, so two passes cannot land closer together than that.
Verified against the current code and a live corpus before implementation; several details in the original problem reports turned out to be stale and were corrected rather than carried forward. Analyzer thresholds, the finding's field set, the render contract, and the persisted cache schema are all unchanged.