Repository navigation
feat(recall): SQLite recall system - #3278
Conversation
4dba399 to
b286145
Compare
b286145 to
7f7b640
Compare
6137889 to
f8c2b81
Compare
KuSh
left a comment
There was a problem hiding this comment.
Automated review of the retriever/recall subsystem (high effort). 8 findings below are anchored inline. Two additional findings reference code outside this PR's diff (so GitHub won't let me anchor them to a line):
-
src/main.rs:1398(correctness) — The generic TOML-filter fallback path (pre-existing, unmodified by this PR) passes the full raw shell command line as the recall slug instead of a filter-family name:core::tee::tee_and_hint(&combined_raw, &raw_command, exit_code). Sincerecall_statsnow aggregates by slug family, every one of the 63 TOML-DSL-filtered commands (npm, docker, kubectl, ruff, etc.) gets a new stats row per unique invocation instead of aggregating per filter — e.g.npm run test -- --coverageandnpm run test -- --watchbecome two permanently separate rows. This is the default sqlite mode, sortk gain --recallsis effectively broken for the majority of RTK's filters. -
src/cmds/cloud/aws_cmd.rs:367(dead code, file untouched by this PR) — The successful, non-truncated branch callstee::tee_and_hint(&raw, &slug, 0), but the newtee_and_hint()in this PR (src/core/tee.rs) unconditionally returnsNonewhenexit_code == 0. That call site is now permanently dead — previously it could tee under the oldmode = "always"behavior, but that mode no longer exists (correctly documented in README.md), so this call can never produce a hint. Not a regression this PR needs to fix, but worth a follow-up cleanup since it's misleading dead code.
5ebaa63 to
1c79688
Compare
KuSh
left a comment
There was a problem hiding this comment.
Round 2 on 1c796881. Thanks for the quick turnaround — I verified each of the previous findings against the new head and resolved 9 threads, with the fixing commit named on each. 3c0a372b's explicit-key handling is a better resolution than what I originally suggested.
One resolution I got wrong and have reopened: the evict() thread. 669e6255 fixes the same-second tie but leaves a sharper bug behind — details on that thread.
A theme worth calling out across this round: several fixes are correct on the path they were applied to, but not on every path that makes the same promise. record_tee_recall now honors the kill switches, but stats_snapshot and the rtk recall CLI still create the DB when mode = "disabled". The legacy [tee] merge now keeps the user's values, but the notice that would tell them so never fires in that case. Those are called out inline.
cargo check --all-targets is clean at this head.
|
@KuSh round 2 addressed, all findings fixed (05e5d65..a3dbeb6). Three direction calls made along the way:
Also per review: eviction keeps the just-stored hash by construction (your invariant is now a test: a hash returned by |
KuSh
left a comment
There was a problem hiding this comment.
Round 3 on a3dbeb6a. Strong push — I verified each previous finding by running its repro against this head rather than reading the diff, and 7 are genuinely fixed with clean before/after measurements:
| finding | measured |
|---|---|
grep_bytes byte-faithfulness |
prev 14185 B vs new 14184 B; --grep '^' now byte-identical to --full |
evict ordering |
refreshed row survives, correct oldest evicted |
evict self-eviction |
returned hash resolves, cap respected |
| read paths creating the DB | prev created recall.db under disabled, new creates nothing |
| test flakiness | 0 failures in 32 runs (was 2/32) |
| hook counting denied reads | track_tee_read now runs after the Deny return |
tee_on_success mechanism |
true+exit 0 → Some(hint), false → None |
The keep_hash guard in evict is a better fix than what I suggested, and factoring recovery_disabled_by_env / open_existing / with_open is exactly the right answer to the "fixed on one path but not all paths" theme from round 2 — those stayed fixed.
Two corrections I owe you. My round-2 privacy finding on recall_slug_is_public was wrong and I'm retracting it: go routes through a native module with a fixed go_build slug, so the raw command line never reaches the ping by that route. I also retract most of the tee_reads dedup finding — tee filenames embed an epoch second, so paths are effectively never reused. Details on those threads.
Requesting changes on four items, two of which are regressions introduced by this push. The severe one is retriever.rs:525: the hint promises 96 hidden lines where rtk recall can return 1, and an over-cap truncation that cuts before shown_upto makes recall print nothing and exit 0 — an empty success reads as "there was nothing more."
One recurring class, worth factoring rather than patching. Across three rounds the same shape keeps returning: the invariant holds on one path or one config shape, not all of them. Where you factored it, it stayed fixed. The remaining un-factored case is the config migration — migrate_legacy_tee and apply_recall_mode are two independent implementations of the same mapping and they now disagree on the same input. A shared helper is genuinely right here (unlike the call-site cases): both callers take a legacy [tee] table and must produce the same RetrieverConfig. The test that closes the class is a differential one — for every combination of {legacy mode, enabled, [retriever] present, explicit tee_* keys}, both paths must agree.
Mechanical state: CLA signed, tests/clippy/fmt green on CI and locally (3216 pass, 0 clippy warnings). The red benchmark check is not yours — develop and this head produce identical results locally (displayed=10, total=414, i.e. passing) and the PR never touches find_cmd.rs; it looks CI-environment-specific, but it is what's holding the merge.
|
@KuSh round 3 addressed (e4f6447..c26794a). Thanks for the reproductions with numbers, they made every one of these direct to confirm and fix. The Fixed:
Validation before pushing, since the last round introduced regressions: 3219 unit tests, clippy clean, plus three independent fuzz passes. Byte robustness 48/48 (bidi, Zalgo, NUL, invalid UTF-8, 11MB over cap, and the hint invariant at 7 caps). Config migration 305 cases, 234 of them the combinatorial agreement matrix, no panic and no data loss. And a differential run against the true rebase base (84f629d): 61 commands, filter payloads and exit codes byte-identical once the hint line is normalized, store creation 1:1 with baseline tee-file creation across 32 probes, startup +0.2 ms. One finding from the config fuzz I am deliberately leaving alone: a single wrong-typed value anywhere in config.toml makes Your two retractions noted, and the perf note stays open on my side: sqlite mode is still above the disabled baseline because |
KuSh
left a comment
There was a problem hiding this comment.
Round 4 on c26794ae. All four blocking items from round 3 are fixed, and I verified each by the mechanism rather than the symptom — a disappearing warning can mean the correct path or a new suppression, so I checked which:
| round-3 blocker | verified how |
|---|---|
hidden_lines promised what recall couldn't return |
probed across 3 storage caps: at 20 000 B and the 10 MiB default the hint is accurate (promised 175 = actual 175); only the pathological cap now emits no hint. Hints are not broken generally. |
legacy always dropped / two migration paths disagreeing |
map_legacy_tee is now the single source of truth, and test_migration_paths_agree_on_every_legacy_shape exercises 36 combinations |
tee_on_success inflating elisions |
reverted in c26794ae; grep -r tee_on_success src/ is empty |
| the test reading the developer's real config | tee_and_hint returns on exit_code == 0 before active(), so Config::load() is never reached on the success path |
The empty-recall case is properly closed too — rtk recall <hash> --from 999 on a truncated entry now exits 1 with "the requested lines were lost to the 2000-byte storage cap" instead of an empty exit 0. And the differential test is exactly the class-closing test I asked for rather than a test of the instance; that's the right response to a recurring bug class.
Still requesting changes on one item, because the hidden_lines fix moved a failure rather than removing it: the new hidden_lines > 0 gate returns None where a hint used to be produced, and main.rs:1587 turns any None on a lossy filter into the full raw output. Details inline. The remaining four are notes.
Open threads the author hasn't responded to yet. None of these have had a reply across rounds 1-4, so listing them so they don't get lost — I've resolved everything this round settled, so what follows is the live set:
src/core/retriever.rs:82—content_hashtruncates SHA-256 to 48 bits andON CONFLICTsilently overwrites on collision. Low severity (birthday bound is ~1e-10 at the default 200-entry cap) — I'd accept "won't fix" as an answer, but it has never been answered.src/core/retriever.rs:203—with_openreuse guard checkspath.exists()but not dev/ino, so a replaced DB keeps a stale handle and a printed hint resolves to nothing.src/cmds/system/ctest_cmd.rs:1778— the suite still writes the developer's real recall store. Now quantified: a sandboxedcargo test --bin rtkproduces 31 recall rows and 14 stats rows (curl,pnpm-prod,pytest-xfail,uv-run-stdout,ruff-check,uv-traceback), andtelemetry.rsfeedsstats_snapshot()into the daily ping, so those fabricated counts ship as real usage. The.logfiles are gone, the DB rows are not.src/core/retriever.rs:180— sqlite overhead. Re-measured this round: disabled 14.1 ms, sqlite 22.1 ms (was 22.7 ms) — still 1.57× the baseline against the <10 ms target.src/hooks/rewrite_cmd.rs:74—Askstill records a read for a command the user may reject; onlyDenyis excluded.src/core/tee.rs:49—force_tee_hintpassesNonefrom ~20 call sites that know the real exit code.src/analytics/gain.rs:34,docs/contributing/TECHNICAL.md:283,docs/usage/FEATURES.md:1369— your own three from round 1 (the boolean-flag proliferation, the gzip question, the French section naming).run()still takesrecalls: boolandshow_recall_statsis still private.
Mechanical state: CLA signed, fmt/clippy/tests green locally (3135 pass, 0 clippy warnings) and on CI. benchmark is still red with the same two find --max cap violations — unchanged from round 3, and still not yours: develop and this head are identical locally (displayed=10, total=414, passing), and the PR never touches find_cmd.rs.
|
On the three pre-existing findings you surfaced — all three tracked, none of them belong in this PR: Config falling back to defaults silently. Agreed it's out of scope here, and it turns out to be the same defect as #1482 (missing $ printf '[retriever]\nmode = "tee"\n' > config.toml && rtk config recall
recall mode: tee
$ printf '[retriever]\nmode = "tee"\n\n[limits]\nmax_width = "not-a-number"\n' > config.toml && rtk config recall
recall mode: sqliteWorth flagging for whoever takes #1482:
The stale On the perf note staying open: agreed, batching |
…er] mode sqlite (default) queried by 'rtk recall'; tee (legacy files) and disabled modes retained.
…paths Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
… gain --reset Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
c26794a to
ddc2182
Compare
The usage guard returns early when no hash and no --list is given, and --list returns before this match, so the arm could never run. Removing it keeps the usage string in one place. Co-Authored-By: Claude Opus 5 <[email protected]>
KuSh
left a comment
There was a problem hiding this comment.
Round 5 — APPROVED, follow-ups filed
Claim: give RTK a content-addressed recall store with a selectable [retriever] mode, so output elided by a filter can be recovered by hash instead of lost.
Scope: accept (round 1, frozen).
Ran: rtk grep over a 300-line producer at 4 storage caps x hint/recall round-trip; rtk recall usage, bad-hash and --from paths; full suite on the head and on the merge with latest develop; hyperfine across all three modes; gain --reset scoping. Savings 97.4% (grep) and 37.2% (git log) against the 20% floor (CONTRIBUTING.md).
Blocks merge (0)
Empty. The one item carried into this round is fixed.
src/core/tee.rs — the round-4 blocker was that suppressing the hint when hidden_lines == 0 made main.rs fall back to the entire raw output. 2b13d80c fixes it at the root instead of the symptom: over the cap the store now keeps the hidden tail rather than the prefix the agent already saw, so there is always something to promise and the promise always matches. Verified across the cap range:
cap=400 promised=5 actual=5 OK (round 4: no hint -> full raw)
cap=2000 promised=27 actual=27 OK
cap=20000 promised=272 actual=272 OK
cap=10485760 promised=275 actual=275 OK LINES=300 HIDDEN=275
Also fixed this push, both carried from earlier rounds:
- Test isolation (
ctest_cmd.rs:1778, open since round 2).db_path()now resolves to a per-process temp dir under#[cfg(test)]. A sandboxedcargo test --bin rtkcreates no ambientrecall.db; at round 4 it wrote 31 recall rows and 14 stats rows that would have shipped through the telemetry ping. - Stale cap number (round 4). The message no longer interpolates the current cap: the same entry now reads
stored truncated (output exceeded the cap in force at the time)both before and after the cap is changed, instead of2000-bytethen10485760-byte.
The reinstated tee_on_success in a882419b is correctly scoped: legacy always semantics stay in tee mode, sqlite returns early on success, elisions are recorded only on failure, and tee_and_hint_with takes a resolved mode and config so tests never reach Config::load().
Optional — will not hold merge; threads resolved by me
ab09904e (pushed with this review) removes the unreachable no-hash arm in run_recall, which duplicated the usage string in two places. Behaviour identical: bare recall exits 2, --list exits 0, unknown hash exits 1.
Filed as follow-ups
Each is pre-existing or an optional note that never blocked merge:
- #3945
with_openreuse guard misses store replacement (dev/ino, not just existence) - #3946 sqlite recall mode ~1.7x the disabled baseline; batch
search.rsinto one store per run - #3947 recall accounting:
--listLINES hides the dropped magnitude;elisionscounts stores in sqlite but emitted hints in tee - #3948
content_hashtruncates SHA-256 to 48 bits andON CONFLICToverwrites - #3953
track_tee_readrecords a read forAskoutcomes the user may reject
Checked and correct — no need to re-verify
Merges cleanly into latest develop (f7495466) and the merged tree is green: 3395 tests pass. cargo fmt, cargo clippy --all-targets (0 warnings) clean. All CI checks pass — benchmark included, now that 7c10f779 stops the recall hints being counted as find entries (that failure was #3860, never this PR's). gain --reset clears counters without touching stored entries.
Your questions
"Is gzip still the best choice here, or might it be somewhat outdated?" (open since round 1, never answered) - measured on representative recall payloads, and the answer is that gzip is fine:
raw gzip zstd -3 gzip zstd
grep output 996 KB 171.6 KB 176.1 KB 5.80x 5.66x
dep tree 11.9 KB 2.1 KB 2.5 KB 5.52x 4.79x
git log 324 KB 116.5 KB 114.7 KB 2.78x 2.83x
compress 1 MB 13.1 ms 4.3 ms
Ratio is a wash - gzip is slightly ahead on two of the three. The only real argument for zstd is CPU (~3x faster), which becomes interesting only once #3946 batches the per-file stores into one per run; today the compression cost is spread thin and a C-backed dependency would work against the binary-size target. The codec column already stored per entry means a later switch is cheap and does not need a migration. Resolving on that basis - reopen if the batching work changes the calculus.
No new questions since round 4; the three pre-existing findings you raised were answered in my 2026-09-07 comment (config fallback folded into #1482, find histogram filed as #3914, stale develop ref not a repo defect). The perf note you asked to keep open is follow-up 2 above, with current numbers.
Next
Nothing — approving. Five follow-ups filed and linked above; ab09904e is the only change I made and it is cosmetic.
Threads: 0 open, 14 resolved this round (3 fixed by this push, 1 by the fixup, 10 converted to the follow-ups above).
pszymkowiak
left a comment
There was a problem hiding this comment.
This is careful work. Taken line by line it's more thorough than most: failure paths are handled before happy paths, store() goes silent on any error so no extra token ever enters the agent session and neither output nor exit code is touched, and on truncation the store keeps the hidden tail rather than the prefix the agent already saw - so the hint can never promise more than recall returns. The byte-fidelity tests (NUL, ANSI, CRLF, 15MB truncation, concurrent writes, corrupted DB) lock down the one property a recovery store lives or dies on, and they come first, which is the right order.
The part I think outlives the feature is rtk gain --recalls. Counting recalls turns "is this filter too aggressive" from an opinion into a number, and since a recall costs an extra API turn plus the full output, it cancels that command's savings outright. Any heuristic that hides information should ship its own regret counter. The telemetry is allowlisted with unknown slugs folded into other, and there's a test asserting the payload has exactly four keys - that's how a privacy guarantee should be written, as an assertion rather than a comment.
Approving. One thing I'd like fixed, ideally before this lands rather than after:
No total size cap. The limits are per entry (10MB) and per count (200), never on the sum. Nominal worst case is 200 x 10MB before compression. Gzip makes the realistic case far smaller, but a user filtering already-compressed or binary output has no guard at all. A SUM(length(blob)) check in evict(), evicting until it drops back under a global ceiling, is a few lines.
Two smaller ones, your call:
grep_bytes()returns the entire input when the pattern fails to compile both as a regex and as an escaped literal. Asking for a filter and getting 10MB back is the opposite of the intent, and in an agent context it burns exactly the tokens the command was meant to save. An error and a non-zero exit would be truer.total_linesis computed on the (possibly truncated) payload whilebyte_sizegetscontent.len()from the original, so on a truncated entryrtk recall --listshows a line count and a byte count describing two different objects. Each is correct for what it measures - the column header just needs to say which.
On process: 23 commits including "evict by rowid", "read paths never create the database", "preserve recalled flag", "store NULL exit code on truncation paths". Each one fixes a case found after the fact, which says the review was serious and also that a surface this size generates blind spots at a steady rate. A new default recovery mechanism, a new on-disk database, a new CLI command and a telemetry extension in one merge is a lot. I'd rather this went out behind its own minor release than folded into a mixed one - and the docs should state plainly what gets stored and for how long, with a rtk recall --purge to go with it.
Sqlite recall store replaces tee files as the default recovery mechanism.
What changed
[full output: rtk recall <hash>]/[+N hidden: rtk recall <hash>]— the default recall returns only what the agent didn't see.rtk recall <hash>(prefix ok) with--full,--from N,--lines N,--grep,--list(human inspection; the hint is the whole agent interface). Byte-faithful store (gzip BLOB; input is the captured command text, as with tee files), 10MB cap, FIFO 200 entries / 30 days, content-hash dedup.rtk gain --recalls— per-filter rate of elided output the agent goes back for, with aVerdictcolumn naming an over-recalled filter (too aggressiveabove 30%,-under 5 elisions) and pointing at the issue tracker. A recall costs an extra API turn plus the full output, so it cancels the savings on that command. Exact in sqlite, lower bound in tee mode.rtk gain --resetnow clears the recall counters too (stored outputs are kept).rtk config recall <sqlite|tee|disabled>— switch modes without editing files (preserves comments, migrates[tee]keys).recall_stats,recall_mode) — filter names from a fixed allowlist, anything else folded intoother; no hashes, paths, arguments or content.recall.dbcreated owner-only (0600/0700, WAL/SHM included), corrupted/unavailable DB or disabled mode stays silent — no extra token is ever emitted into the agent session, and command output/exit code are never affected.Migration
.logfiles untouched.[tee]section → auto-mapped tomode = "tee"(behavior preserved) ordisabledifenabled = false.rtk init/rtk gainfor legacy users, pointing tortk config recall.[tee] mode = "always"keeps its behavior, mapped totee_on_success = true. Kill switches:RTK_RECALL=0(legacyRTK_TEE=0),RTK_RECALL_DB.Validation
3395 unit tests + e2e suites (byte fidelity incl. NUL/ANSI/CRLF, 15MB truncation, concurrent writes, corrupted DB, migration scenarios) + real-agent fuzz. CI green on ubuntu/macos/windows (rusqlite bundled).