Skip to content

Recall store: review fixes on top of #3278 - #3900

Closed
pr0d1r2 wants to merge 33 commits into
rtk-ai:developfrom
pr0d1r2:feat/retriever-recall-hardened
Closed

pr0d1r2 wants to merge 33 commits into
rtk-ai:developfrom
pr0d1r2:feat/retriever-recall-hardened

Conversation

@pr0d1r2

@pr0d1r2 pr0d1r2 commented Sep 6, 2026

Copy link
Copy Markdown

Recall store: review fixes on top of #3278

This continues #3278 by @aeppling. His ten commits are here with their
original authorship, rebased onto develop; everything after them is review
work on top. Base for comparison: rtk-ai/rtk@1c79688, the head of
feat/retriever-recall at the time of review.

  • 33 commits: 10 by @aeppling, 23 review fixes.
  • develop moved on. feat(recall): SQLite recall system #3278 is 18 commits behind it; this branch is rebased and
    0 behind, which is why the diff against feat/retriever-recall is larger than
    the review work alone.
  • Green: 3294 tests in the bin suite, 3396 across all suites, clippy clean at
    upstream defaults.

Why a second PR rather than commits on #3278

The head branch of #3278 lives in rtk-ai/rtk and I have no write access to it,
so I could not push there. If it is easier to review as commits on the original
branch, say so and I will hand the branch over for @aeppling to pull in — the
work is his feature plus fixes, and the history is arranged so each fix is one
revertable commit.

Merge blockers cleared

Both were open on #3278 at review time.

Eviction ordered by two different clocks. The retention rule deleted by
created_at, which the upsert refreshes, while the count cap deleted by rowid,
which it does not. An entry re-stored daily was fresh to one rule and
first-to-die under the other. Both rules order by created_at now, rowid
breaking ties only. This was the defect the second review round reopened.

benchmark CI red. The counter in benchmark.sh skipped only the legacy
[see remaining: …] hint. The two new sqlite hint forms are five fields each,
so they were counted as filenames and the job overshot by five.

Correctness and privacy fixes

Byte fidelity through --grep. grep_bytes split on \n and re-emitted
every match with an unconditional trailing newline, so rtk recall <hash> --grep '^' returned the stored bytes plus one. The store advertises
byte-faithfulness; it now holds through that path too.

mode = "disabled" created the database. stats_snapshot() opened
unconditionally, reached from rtk gain --recalls and from the daily telemetry
ping, so a user who turned recovery off still got a recall.db.

Telemetry shipped command arguments. The allowlist checked only the first
_/- token of a stats key, so a short command whose head matched a family was
transmitted whole — go_build___cmd_acmepay carried a project path. The
allowlist is tightened, and the slug type below now bounds what can reach a
stats key at all.

Tee reads counted before the permission verdict. track_tee_read() fired
ahead of the Allow/Deny decision, and tee_reads dedups with
INSERT OR IGNORE, so a denied read permanently blocked the later legitimate
read of that file from ever counting.

rtk gain --recalls was broken for 63 filters. The TOML runner passed the
raw shell command line as the slug, opening a row per invocation.

Bounds, races and platforms

The stats table had no cap and no eviction. recall is capped at
max_entries and tee_reads at 500; recall_stats had neither. What kept it
small was a coincidence — stat_family truncates at the first digit preceded by
an underscore, and the one slug carrying a file path happens to have an index
digit in front of it. Three call sites already defeated that:
cargo_{subcommand}, bun_{subcmd} and deno_{subcmd} carry user-typed text
with no digit at all. Capped at 500, least-used evicted first.

Slugs are typed now, not conventional. A Slug says where its name came
from: a literal, a family plus &'static str parts, a value from the user's own
config, or a family plus an unbounded detail that reaches the tee filename and
never the stats key. There is no conversion from String or &str, so a caller
holding a runtime value has to say which it means and the compiler asks. Two AWS
arms changed shape rather than gaining a conversion: they matched
args[0] == "sync" in a guard and then forwarded the user's string anyway.

Eviction could cut below the cap. evict_by_count read SELECT COUNT(*)
into Rust and passed the difference to DELETE … LIMIT excess, so two processes
against the same 203 rows both deleted 3 and left 197. Measured with eight
threads on a barrier: 179 rows, 15 runs out of 15. The count moves inside the
statement, where SQLite evaluates it under the write lock it already holds.

Owner-only was false on Windows. set_owner_only was
#[cfg(not(unix))] fn(..) {} — an empty body — while the code's own comments and
tests described the store as owner-only. The store holds unredacted stdout, full
command lines and absolute working directories, so on Windows its only stated
mitigation did not exist, and every permission test was #[cfg(unix)] so CI
proved nothing about it. It now writes a single-entry DACL with
PROTECTED_DACL_SECURITY_INFORMATION; directories inherit, files do not.

Performance

The sqlite store breached the <10ms startup target on per-file paths: 25.9ms
against 15.6ms disabled on rtk grep -rn "let" src/cmds. The review had
attributed the whole gap to open() running per store(). Measured per
component, open() was 1.80ms of it — about 18% — and the dominant term was the
gzip codec: 6.20ms to compress 889KB against 0.81ms for lz4. Fixed with a
connection cache, a cached config read and lz4; the gap is 2.7ms.

The compression = false path was removed rather than kept: it was slower than
lz4 at every size above 1KB and 2-9x larger on disk, so it never won on either
axis it existed for.

Testing

Every fix here has a test that was shown to fail against the defect it guards,
which caught three of my own that did not. The eviction race needed a barrier —
the sequential version passed against the broken code, because sequential
callers never interleave one caller's count with another's delete.

The Windows work is compiled and run, not just written: the tree builds and
links for x86_64-pc-windows-gnu against the real windows-sys, and the suite
runs under wine at 3229 passing. Wine answers SetNamedSecurityInfoW with
ERROR_SUCCESS and then synthesises a descriptor from Unix mode bits, so the
DACL read-back cannot be observed there; those tests detect wine through
ntdll!wine_get_version and assert the write path, keeping the full assertions
for the windows-latest job in CI.

Found while reviewing, deliberately not fixed here

These are pre-existing and outside this branch's scope. Filed here so they are
not lost.

  • Tee files never expire. retention_days is consumed only by the sqlite
    path. The tee path's only limit is a file count, so rtk config recall sqlite
    orphans every existing .log forever — raw stdout at 0600, no age bound.
  • tee_max_file_size is not a cap. The --- truncated at N bytes ---
    marker is appended after the cut, so files land 33-36 bytes over the number
    the docs call a maximum.
  • max_files is global, not per-slug. One noisy filter evicts every other
    filter's recovery files.
  • A failed tee write can leave an orphan that still counts toward that cap.
  • Telemetry can transmit an invoked path. low_savings_commands
    (tracking.rs) sends the first three whitespace tokens of rtk_cmd, and
    passthroughs are recorded as rtk fallback: {raw_command} (main.rs).
    Together those three tokens are rtk, fallback: and the program that ran —
    a repo-local path when that is what was invoked. Verified with bin/packwerk.
    This is a different path from the allowlist fix above and is not covered by it.

Not addressed, and why

force_tee_hint and force_tee_tail_hint store exit_code = None, so
recall --list shows - for entries that came from an elision rather than a
failure. The exit code exists one frame above, in the runner's closure, but the
hints are emitted from inside filter functions that receive text only. Threading
it means changing filter signatures across 69 call sites in 19 modules this
branch does not otherwise touch, for one column in one listing. It previously
passed a fake 0, which was worse: that is a lie the column cannot distinguish
from a real success.

aeppling and others added 30 commits July 6, 2026 16:10
…er] mode

sqlite (default) queried by 'rtk recall'; tee (legacy files) and disabled modes retained.
Three review findings from rtk-ai#3278, all in the metrics/privacy
path.

--- track_tee_read() fired before the permission verdict

tee read tracking now happens only after an Allow verdict.

- rewrite_cmd.rs run(): moved from before evaluate() into the
  RewriteOutcome::Allow arm — Deny/Ask/Passthrough no longer track.
- hook_cmd.rs decide_from_verdict(): moved from the function head into
  the AllowRewrite arm — Deny/Defer/AskRewrite no longer track.

Why the ordering is load-bearing: tee_reads uses INSERT OR IGNORE with no
upgrade path, so the first record of a path is permanent. Counting a
denied read permanently blocked the later legitimate read of the same
file from ever being counted, inflating the elision rate and corrupting
recall stats.

Tests: 3 in rewrite_cmd (Deny/Passthrough/Ask never reach the Allow
branch), 5 in hook_cmd (Deny, unattestable construct, Ask, unrewritable
defer, and the Allow arm that does reach tracking).

--- telemetry allowlist leaked command arguments

recall_slug_is_public() checked only the first `_`/`-` token of the stat
key, so a short command whose head matched a family shipped verbatim —
"go_build___cmd_acmepay" (head "go", in the allowlist) transmitted the
user's project path to the telemetry endpoint.

Now also rejects slugs containing triple underscores (encoded path
separators) and slugs with more than 4 segments. Such slugs fold into the
"other" bucket instead.

Tests: 15 covering the allowlist, including the leak case above now being
rejected, segment/length/charset boundaries, and every RECALL_FAMILIES
member accepted standalone and with a suffix. Also 14 tests asserting the
payload carries no path or content fields.

--- TOML-filter runner passed the raw command line as recall slug

main.rs now passes filter.name ("jq", "helm", "brew-install") for all
three hint paths instead of the raw shell command line.

Mechanism: sanitize_slug only folds slugs longer than 24 chars into a
prefix+hash form, so raw command lines shorter than that reached
recall_stats verbatim — "jq .items" and "jq .metadata.name" opened
separate rows. Across the 63 TOML-DSL filters that gave one row per
unique invocation, making `rtk gain --recalls` useless for the majority
of filters. Passing the family name also stops arguments entering the
ledger: the raw line persisted user paths and flag values.

Tests: all 63 built-in filter names verified slug-clean, bounded and
argument-free.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two review findings from rtk-ai#3278 in the legacy `[tee]` migration
path, plus the migration coverage that found them.

--- mode = "always" was silently downgraded

Legacy `mode = "always"` teed on success as well as failure. The new model
has no equivalent — tee_and_hint() hard-returns None on exit 0 — so
migrating to RecoveryMode::Tee drops capture of successful output. That was
silent, and apply_recall_mode() removes the [tee] section, so the user's
original intent became unrecoverable.

Surfaced at all three points the user can observe it:
- Config gains migrated_from_legacy_tee_always, set during migration only
  when `[tee] mode = "always"` actually maps to Tee.
- LEGACY_TEE_ALWAYS_NOTICE names the behavior change and points at
  `rtk config recall sqlite`, which does capture successful output.
- Emitted from `rtk init`, `rtk config recall` (show), and from
  set_recall_mode() before the rewrite that drops the [tee] section.

The flag is deliberately narrow: `enabled = false` wins over mode, and an
explicit [retriever] section means the user already migrated — neither
raises the notice.

--- the migration notice gate was wrong in both directions

False positive: legacy_tee_config_in_use() returned migrated_from_legacy_tee
alone, so a user whose [tee] section resolved to Disabled (`enabled = false`
/ `mode = "never"`) was shown LEGACY_TEE_CONFIG_NOTICE — "file mode kept" —
after explicitly turning recovery off. The notice makes a claim about the
mode, so the gate now checks it: migrated AND mode == Tee.

False negative: migrated_from_legacy_tee was only set inside the
!has_retriever branch, but legacy field values (max_files, max_file_size,
directory) merge regardless. A coexisting [retriever] + [tee] config
therefore had legacy values in effect while the flag stayed false and no
notice ever fired. The merge now raises the flag — but only when a value is
actually applied, so an explicit [retriever] key winning, or an empty [tee],
stays silent.

Extracted is_legacy_tee_in_use(&Config) so the gate is testable without
reading the developer's ambient config.

Tests: 11 covering the migration matrix (enabled/mode/field-only/unknown
mode/precedence, and apply_recall_mode remove-carry-idempotent); 8 on the
always-downgrade flag; 10 on the notice gate — 4 on the mode check, 4 on the
coexist flag, plus pre-rewrite intent detection accepting the always shape
and rejecting six others including malformed TOML. One pre-existing test
asserted the false negative as expected behavior; it is flipped here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…z4 codec

The recall store itself: two correctness fixes, the verification coverage
that proves the store's claims, and the performance work needed to meet the
<10ms startup target.

--- grep_bytes() broke byte-faithfulness

`input.split(b'\n')` yields a trailing empty slice when content ends in a
newline, and every match was re-emitted with an unconditional push(b'\n').
`rtk recall <hash> --grep '^'` therefore returned the stored bytes plus one
extra newline, violating the byte-faithfulness the store advertises.

Now drops the trailing empty slice and re-emits the original terminator only
when the input had one — input ending in \n gets it back, input without does
not gain one.

--- Disabled mode still created recall.db

stats_snapshot() and record_tee_elision() called open() unconditionally, so
`mode = "disabled"` still produced the database — reached from
`rtk gain --recalls` and from the daily telemetry ping. Both now return early
on RecoveryMode::Disabled. run_recall() stays unconditional: the user ran the
CLI explicitly — intentional, and now documented as such.

--- <10ms target, and the cause was misattributed

The review attributed the whole ~10ms sqlite-vs-disabled gap to open() running per
store(). Measured, open() is 1.80ms per 9 calls (15.2us once cached) — about
18% of it. The dominant term was the gzip codec.

Two changes, measured end-to-end on `rtk grep -rn "let" src/cmds`:

  stage                          sqlite   disabled   gap
  as the review measured          25.9ms    15.6ms   10.3ms
  + conn cache + cached_config   27.2ms    18.9ms    8.4ms
  + lz4_flex codec               22.6ms    19.9ms    2.7ms

1. Path-keyed thread-local connection cache in open(). rtk is single-threaded
   and short-lived, so one handle per thread needs no pool. Keyed by resolved
   path, since RTK_RECALL_DB and cfg.database_path can select a different DB
   within one process. tee::active() also switched to config::cached_config(),
   because the search.rs hint paths call it once per file.

2. Codec gzip -> lz4_flex. Measured on real captured command output (grep
   results, git log --stat, ls -R, cargo tree) across 1KB-889KB, timing the
   full store path — compress plus the sqlite blob write, since a worse ratio
   is paid back as a larger blob to insert:

   payload        gzip    zstd-1  zstd-3  zstd-6  lz4_flex  none
   1 KB           59us     54us    60us    73us     53us     54us
   10 KB          91us     63us    79us   109us     66us    141us
   15 KB ls -R   141us     71us    75us   118us     64us    116us
   100 KB        573us    122us   136us   350us    103us    176us
   215 KB git    3.75ms   490us   607us  1.61ms    454us    577us
   685 KB grep   5.02ms   778us   972us  2.47ms    635us   1.42ms
   889 KB grep   6.20ms   817us   935us  3.13ms    813us   2.01ms

   Measured on Apple M4 (Mac16,12), 10 cores (4 performance + 6 efficiency),
   16 GB RAM, macOS 26.5.2, rustc 1.97.1, release profile (opt-level 3, LTO).
   20 reps at >=50KB, 200 below; +-10-20% run-to-run at the large sizes, so
   lz4_flex vs zstd-1 at the top end is a tie. The margin over gzip is far
   outside that noise. Decompress at 889KB: gzip 850us, zstd-1 235us,
   lz4 107us.

   lz4_flex over zstd-1 on a tie: pure-Rust MIT, no C toolchain and no
   vendored libzstd, which matters for the DEB/RPM and cross-platform builds.
   Rejected xz/LZMA (compress far too slow) and brotli (no advantage over
   zstd). Parallel compression rejected: payloads are 50-100KB where thread
   spawn/join is ~50-100us against ~250us of work, and the store path
   stays single-threaded.

--- the uncompressed path never won, so it is gone

`compression = false` selected a raw-blob path that is slower than lz4 at
every size above 1KB (the sqlite write dominates — see the `none` column
above) and 2-9x larger on disk. It lost on both axes at once, so the config
knob and the raw codec are removed rather than kept as a choice.

Safe to delete outright: the field, the codec arm and the doc lines all
landed in 37c2905 on this branch, and base 84f629d has no
RetrieverConfig and no `compression` key anywhere in src/. A stale
`compression = false` in a user config is ignored, since RetrieverConfig is
#[serde(default)] with no deny_unknown_fields.

decode() now closes the codec set: an unrecognized codec errors instead of
falling through to `_ => raw`. Returning compressed bytes as if they were
the payload is silent corruption that `rtk recall` would print as garbage.

--- test isolation

test_record_tee_recall_respects_kill_switch set RTK_RECALL_DB with no lock.
db_path() gives that env var precedence over cfg.database_path, so every
concurrently running test's store was redirected to its tempdir, then the
tempdir dropped. The kill-switch state is now a parameter —
record_tee_recall_with() takes it, record_tee_recall() supplies it from
recall_disabled_by_env() — so the test sets no env var at all and the race
is eliminated rather than scheduled around. No serial_test dependency.

--- Verification coverage

Byte fidelity: NUL/ANSI/CRLF/UTF-8/no-trailing-newline round-trips through
the full store-and-recall pipeline, plus lz4 round-trip over all 256 byte
values.
Corrupt store: a corrupt, truncated or read-only DB returns
Stored::Unavailable, emits no hint and never panics — no extra token reaches
the agent session.
Permissions: DB, -wal and -shm are all owner-only while the connection is
open (R7 had this unverified).
Eviction: a #[should_panic] test proving the defect — the count rule orders by
rowid ASC while retention orders by created_at, and ON CONFLICT DO UPDATE
never bumps rowid, so the most-refreshed entry is evicted first. The test
asserts the correct behavior and fails once the ordering is fixed, which is the signal
to update it.
Concurrency: N threads storing simultaneously produce no corruption and no
lock error.

Two corrupt-store tests assumed every store() closes its connection, which the cache
deliberately removes. Both mutate the DB behind a path they seeded, so they
now drop the cached handle first: closing checkpoints the WAL into the main
DB, which would otherwise undo the truncation, and an already-open handle
keeps writing regardless of a later chmod.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The suite wrote its fixture output into the developer's own
~/.local/share/rtk/recall.db. Observed before this change: 15 stat rows,
every one a test fixture slug — ctest-failed, uv-traceback, pytest-xfail,
ruff-check, find-hidden, pnpm-prod — with recalls=0 and elision counts in
exact multiples of the number of suite runs. stats_snapshot() feeds those
rows into the daily telemetry ping.

Two distinct vectors. The review named only the first.

--- unit tests

Filter tests across 20+ modules call force_tee_* with whatever config the
developer has. Fixed at the single point they all pass through:
tee::active() takes its config from recall_cfg(), which under cfg(test)
returns Disabled unless a test installs its own. Production is untouched —
the cfg(not(test)) arm is the previous cached_config() read. A test that
needs the real path wraps it in with_test_recall (explicit config) or
with_temp_recall (throwaway store).

--- integration tests

tests/*.rs spawn the real binary via CARGO_BIN_EXE_rtk. That binary is built
without cfg(test), so the guard above is compiled out of the very thing
under test — it read ambient config and wrote 5 grep_0_<tmpfile> rows per
`cargo test --all`. tests/common/mod.rs::isolate_recall() points
RTK_RECALL_DB at a throwaway path on the test process itself; children
inherit it at spawn, so a helper returning an owned Command still works.
Wired into all 12 spawn sites across 9 files.

Seven tests failed once recall went inert, all for the same reason: they
asserted on a truncation or recovery hint and had been silently relying on
the developer's ambient store being enabled. That reliance is the pollution.
Three curl and four ctest tests now wrap their call in with_temp_recall, so
they exercise the truncation path against a throwaway store. Added a
companion asserting curl passes the body through when recall is unavailable
— the documented fallback, previously unexercised because recall was always
on.

Also removes the last process-wide env mutation in the crate. tee.rs's
env-kill test set RTK_RECALL globally, the same defect as above; it now
runs inside with_test_recall, whose RECALL_TEST_LOCK serializes it against
every other config-installing test, and restores the var via a Drop guard.

Verified: the real recall.db is md5 byte-identical across 3 consecutive full
suite runs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The three modules this branch owns hold themselves to a complexity
ceiling: 15 lines per function, 4 arguments, and clippy's cognitive
complexity, nesting, bool-parameter and type-complexity lints, denied at
each module head. The rest of the crate predates this and is not held to
it — the longest function measured elsewhere is 1077 lines.

The numbers arrived in steps, each landing only after the refactor that
made it reachable, so no commit both moved code and moved the line: 60,
where it installed at the measured maximum with nothing to fix, then 40,
25, 4 arguments, and 15. They are ceilings and may only fall.

Two of the splits earn their place independently of any number.

evict became evict_by_age and evict_by_count, which exposes a real
defect rather than tidying code: the two rules disagree about what
"oldest" means. Retention orders by created_at, which the upsert
refreshes, and the count cap ordered by rowid, which it does not, so an
entry re-stored daily was fresh to one rule and first to die under the
other. Inline they read as one policy; named separately, the
disagreement is visible at the call site. The fix follows in its own
commit.

write_tee_file gave up tee_body, which names the `--- truncated at N
bytes ---` marker appended into the payload. That marker is why tee mode
is not byte-faithful while the sqlite store, which truncates at a line
boundary and adds nothing, is.

The argument groupings are the same kind of change. Capture carries the
command, exit code and lines-already-seen that three functions passed
around together; TeeTarget carries the directory, per-file cap and
rotation limit that are never meaningful apart. Two store call sites
previously ended in a bare integer in the same position, where 1 asserts
the agent saw nothing and a line offset carries a real position into
partly-seen output; Capture::full and Capture::tail say which is meant.

Two places opt out, each for a stated reason. upsert_entry keeps its
eleven-parameter list: that is the width of the recall table feeding one
statement, not complexity, and splitting it would separate the values
from the statement whose parameter order they must match. Test bodies
are exempt, because a concurrency or round-trip test is a linear
setup-act-assert script that splitting makes harder to read.

needs_shell_quoting is the case the ceiling must not be allowed to
mangle: a single `matches!` over twenty characters that rustfmt had
exploded one per line. The line count was measuring formatting, not
complexity, so the characters became a named constant instead of the
function being cut into pieces.

The thresholds themselves are not in this tree. They live in the review
repository that produced this branch, where clippy reads them through
CLIPPY_CONF_DIR; a clippy.toml here would take precedence over that and
bind upstream to numbers it never agreed to. Without one in scope the
module attributes resolve at clippy's own defaults and cost a tree
nothing.

Behavior is unchanged throughout: every extraction is a move.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The merge blocker. The count cap ordered by `rowid` while retention ordered by
`created_at`, and `ON CONFLICT DO UPDATE` refreshes the timestamp but never the
rowid. An entry re-stored daily was therefore *fresh* to retention and
*first-to-die* to the count cap: the hottest entry in the store was the first
one evicted. That is data loss, and the reviewer reopened the previous attempt
at it.

Any fix has to address both orderings with a single consistent rule
rather than patching one side, which is what the reopened attempt did. So both
rules now order on `created_at` — the clock the upsert actually maintains.
Retention drops what is older than the cutoff; the count cap drops the oldest
surplus; a refreshed entry is fresh to both. `rowid` survives only as a
tie-break so that entries sharing a timestamp still evict deterministically.

Two existing tests asserted the bug and have been inverted:

test_b2_hot_entry_should_survive_eviction was #[should_panic] — it asserted the
correct behaviour and passed *because* the code was wrong. It is now
test_b2_hot_entry_survives_eviction and passes on its merits. It also had to
age its rows a day first: `created_at` is whole seconds, and four stores in one
test tick share a timestamp, so the original version was measuring the
tie-break rather than recency. The finding describes an entry re-stored
daily, and the test now says so.

test_b2_eviction_rules_use_different_ordering asserted that the low-rowid row
was deleted despite a fresh timestamp. Renamed to
test_b2_eviction_rules_agree_on_created_at, and rebuilt so the two orderings
genuinely disagree — the high-rowid row is given the oldest created_at, and the
assertions now pin both halves: lowest rowid survives when freshest, oldest
created_at is evicted whatever its rowid. As written before, all three rows
shared a timestamp and it would have passed either way.

Added test_b2_same_second_entries_fall_back_to_insertion_order, which states
the limit of this fix instead of leaving it to be found: at second granularity
there is nothing to order on, so same-second entries evict by insertion order
and a refresh landing in the same second as its neighbours does not protect the
entry. Acceptable, because the finding is about days — but it should be
written down.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The benchmark's two awk counters skipped the legacy `[see remaining: …]` hint
but not the two forms this branch introduced:

  [full output: rtk recall <hash>]
  [+<n> hidden: rtk recall <hash>]

Both are five whitespace-separated fields, so each was counted as five
filenames and every `rtk find --max N` assertion overshot by five. That is the
red `benchmark` job — one failure against sixteen passing, and a merge blocker
on CI alone.

Fixed in count_find_names and count_find_total alike; they share the skip list
and only one of them had been kept in step with the hints.

The comment records why this list exists rather than being derived: the hint
has no single constructor. Three shapes are emitted from three call
sites, so anything that consumes hint output has to know all three, and a
fourth shape will need adding here too. That is the underlying design problem —
this commit fixes the symptom the CI job trips over, not the cause.

Verified against all three forms plus a real filename line: two names counted,
two expected.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`rtk recall <hash> --from N` returned empty output when N exceeded the stored
line count, with nothing on stderr and exit 0. That is indistinguishable from
"the entry genuinely has nothing after line N", which breaks the loop the flag
exists to serve: an agent paging through a long entry gets silence and no way
to tell whether it finished or overshot.

A resumable read has to carry a resume selector,
and silently returning nothing is not one.

The note goes to stderr, matching the existing truncation note, so the bytes on
stdout remain exactly what was stored. The constraint is that no extra token
reaches the *agent session*; stderr diagnostics are already how this path
reports, and staying on stdout would have broken byte fidelity to fix a
usability gap.

Deliberately a warning rather than a non-zero exit: overshooting the end of a
paged read is a normal way to discover you have reached it, and failing the
command would make callers special-case the last page.

Three tests: overshoot detected, in-range output leaves it silent, and no
warning at all when --from was never passed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three places claimed more than the code delivers.

"Byte-faithful" was stated without qualification in configuration.md,
src/core/README.md and TECHNICAL.md, while output over `max_entry_bytes` is
stored truncated. Now qualified — byte-faithful *up to* the cap, with
the truncation and its stderr note described.

The tee-mode asymmetry is stated for the first time: legacy tee
truncation appends a `--- truncated at N bytes ---` marker into the file, so a
truncated tee payload is annotated rather than raw, where the sqlite store cuts
at a line boundary and adds nothing. Both are called "byte-faithful" in the
same breath elsewhere; they are not the same guarantee.

`RTK_RECALL=0` was documented as "disable the recall store", which is not what
it does. It gates writes — the store path and tee-read tracking — but
not `run_recall` or `stats_snapshot`, so `rtk recall <hash>` and
`rtk gain --recalls` still read an existing store with it set. That asymmetry
is deliberate, since the variable targets the hook path rather than a command
the user runs on purpose, but it was nowhere written down and the table entry
implied the opposite.

Documentation only. No behavior changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The argument leak was recorded and fixed against the TOML-filter path in
main.rs. A second call site builds a slug from user arguments the same way and was never in
scope:

    let slug = format!("aws {}", sub_args.join(" ")).replace(' ', "_");

That slug reaches tee_and_hint and force_tee_hint, so it lands in recall_stats,
which the daily telemetry ping reads.

The tightened allowlist catches most of it but not all. A slug survives
intact when it is ≤32 chars, contains no digit, has ≤4 segments and starts with
an allowlisted family — and `aws` is one. So:

    aws ecr describe myrepo  ->  aws_ecr_describe_myrepo

is 23 characters over four segments with no digits, passes every check, and
transmits a private repository name. `aws s3 ls prod-bucket` happens to be
truncated to `aws` because `s3` contains a digit — safe by accident, which is
why the fix looked complete when it was not.

Fixed at the source rather than by tightening the allowlist further. The
allowlist cannot distinguish a leaked resource name from a legitimate
four-segment family, and a predicate that tries would eventually reject real
filter names. `aws_recall_slug` emits `aws_<service>`: the service is a fixed
AWS vocabulary, carries no user data, and is all the per-filter breakdown in
`rtk gain --recalls` actually needs.

The neighbouring `aws_s3_{operation}` site was already bounded and is untouched.

Two tests: the slug is service-only for realistic argument lists, and the shape
the old code produced is shown to satisfy every allowlist condition — so the
test states the leak rather than just asserting the fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…ot resolve

87 references to `B2`, `V17/B6`, `B8/§X5` and similar across nine files,
every one added by this branch — upstream's own commits contain none. They
resolve only in a SPEC.md that lives in a separate review repository. A
reviewer of this PR sees authoritative-looking citations pointing nowhere,
which is worse than no citation: it implies a rationale exists somewhere and
withholds it.

This is the identical defect already fixed in the review repo's clippy.toml,
where the numbers arrived carrying citations into a namespace that repo could
not reach. I fixed it in one file and left it replicated through the code.

Every reference is rewritten as prose that carries the reasoning locally. The
substance is unchanged and in several places clearer for not leaning on an ID:

  "the B4 byte-fidelity defect"
    -> "the byte-fidelity defect this function was fixed for"
  "They disagreed until B2 was fixed — the count cap ordered by rowid"
    -> "They used to disagree: the count cap ordered by rowid"
  "B2 describes an entry re-stored *daily*"
    -> "The defect is about an entry re-stored *daily*"

Test function names keep their `b2_`/`v17_` prefixes. Those are identifiers
rather than claims — they group related cases and read as arbitrary labels, not
as pointers to a document the reader is expected to find.

One reference is left untouched: `src/discover/report.rs` mentions "B6
regression" in upstream's own commit c4b25d2, which is not this branch's to
rewrite.

Comments and test messages only. 3278 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The tee hint is meant to be pasted and run. On Windows it was neither
runnable nor correct, and the defect is in code this branch wrote.

`escape_double_quoted_path` applied POSIX double-quote rules unconditionally,
escaping `\` — which on Windows is the path separator, not an escape. Every
`C:\Users\me\file.log` became `C:\\Users\\me\\file.log`. Worse, `\` is in
SHELL_METACHARS, so *every* Windows path triggered quoting and therefore hit
that escaping. The set was extracted and named earlier in this branch without
noticing it was POSIX-only.

`display_shell_path` also emitted `"$HOME/…"`, which cmd and PowerShell expand
to nothing, and `display_path`'s `~/` prefix, which they take literally. Both
silently produce a path that does not exist.

Now split by target:
  windows       only `"` is escaped; absolute path, no `~` and no `$HOME`
  non-windows   unchanged

Tests: the Windows escaper is pinned under #[cfg(windows)], and the POSIX one
under #[cfg(not(windows))] so the split cannot drift on either side. The
existing backslash test is now correctly scoped to non-Windows, where its
expectation belongs.

Found by reading, not by CI — there is no Windows runner here, which is exactly
why the platform-specific half needs its contract written down.

Not fixed here: `set_owner_only` is a no-op on Windows (utils.rs), so the
0600/0700 guarantee does not hold there at all. That is upstream
code and a much larger change — ACLs rather than a mode bit — and it is
recorded rather than half-attempted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…guarantees

`select_slice` returned an owned Vec for every branch, including `--full`
where it copied the whole entry to hand back what it was given. With
`decode`'s allocation and `apply_grep`'s result that made three live
copies of an entry that can be `max_entry_bytes` — 10 MiB by default, and
user-raisable with no upper bound. It now borrows; `apply_grep` takes a
slice and allocates only when it must, which for the no-pattern case is
the single copy needed for output.

Three guarantees the suite asserted nowhere:

Ambiguous hash prefixes. An ambiguous prefix must be an error rather than
one of the candidates, and the `many =>` arm had no test at all — it
could have been changed to take the first match with everything still
green. That one matters because the failure is silent and plausible: the
agent asks for a prefix and receives the wrong entry's output. Both
halves are now pinned, ambiguous and unambiguous.

Corrupt blob under a valid codec. The unknown-codec arm was tested;
garbage bytes with `codec = "lz4"` were not. That is the likelier
corruption in practice — the column says lz4 and the payload is damaged.

The truncation fallback. The guarantee is "cut at a line boundary", but
when the first `cap` bytes contain no newline it hard-cuts instead. That
fallback is precisely where the stated guarantee does not hold, so both
paths are now asserted.

Also drops `bench_open_cached_vs_uncached`, an `#[ignore]` test that
printed two durations and asserted nothing. It existed to answer one
question during the connection-cache work — is `open()` actually the cost
it was blamed for — and it answered it: 1.80ms uncached against 15.2us
cached, recorded in that commit's message. A test that cannot fail
teaches a reader nothing and invites the assumption that timings are
covered when they are not. `open_uncached` stays; it is the real open
path the cache wraps, not test-only scaffolding.

3283 tests pass.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The earlier sweep across nine source files missed tests/common/mod.rs, which
still pointed at spec IDs a reader outside this review cannot resolve. The
surrounding prose already explains the mechanism — integration tests spawn the
real binary, built without cfg(test), so the unit-test guard is compiled out of
the very thing under test — so the IDs were carrying no information the comment
did not already state.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An adversarial review of my own post-audit commits found four defects. Three
are real breakage; the fourth is a claim that was not true.

WINDOWS BUILD FAILURE. `display_path` is referenced only from the
`#[cfg(not(windows))]` branch of `display_shell_path`, so on Windows it is
unreferenced — `dead_code`, which `[lints.rust] warnings = "deny"` turns into a
hard build error. The commit that fixed Windows path mangling would not have
compiled on Windows. Now gated to match its only caller.

WINDOWS TEST FAILURE. `test_display_shell_path_uses_home_var_for_home_paths_with_spaces`
asserts the `"$HOME/…"` output that the same commit compiled out on Windows.
Its sibling backslash test was scoped; this one was missed. Now gated.

WITHDRAWN: the AWS slug change. The commit claimed the runner "transmits a
private repository name". It does not, and cannot. Every `run_aws_filtered`
caller passes a hardcoded literal array behind an exact-match guard, and there
is no `ecr` arm at all — `"ecr"` appeared only in the tests I wrote to
demonstrate the leak. The slug was always a fixed string.

So the fix corrected nothing and cost something: `aws_ec2_describe-instances`
collapsed to `aws_ec2`, losing per-operation granularity in
`rtk gain --recalls` for a leak that could not occur. Reverted.

What survives is the part that was true: the slug is built by joining
`sub_args`, so its safety rests on a calling convention rather than on
anything in the function. That invariant is now stated where the next
contributor will see it, which is the durable half of the finding.

A weak test was written and then dropped rather than shipped — it counted call
sites without checking they were literal, which is false confidence.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The crate root carried an `#![allow]` for seven complexity lints, with a
comment pointing at `clippy.toml` — a file that is not in this tree and
never was. Four separate audits flagged it: a suppression that wide,
citing a file a reviewer cannot open, reads as scaffolding that escaped
into the diff.

An earlier attempt to remove it was reverted after roughly 190 errors
appeared in `analytics/` and `cmds/`, code this branch does not own, and
`[lints.rust] warnings = "deny"` turns those into hard errors. That
reading was wrong about the cause. The errors do not come from anything
on this branch: clippy walks ancestor directories looking for a
clippy.toml, and this checkout sits inside a review repository that has
one, with `too-many-arguments-threshold = 4` and friends. Unsetting
CLIPPY_CONF_DIR does not escape it — only pointing the variable at a
directory without a clippy.toml does. Measured under those conditions,
which are upstream's conditions: `cargo clippy --all-targets` with the
allow removed reports zero diagnostics. The attribute suppressed nothing
upstream and never would have.

The local ratchet still needs the crate-wide suppression, so it moves to
where the thresholds already live: the pre-commit hook passes the seven
lints as `-A` flags. Source-level attributes outrank command-line lint
flags, so the `#![deny]` at the head of each recall module still fires —
verified by planting a five-argument function in retriever.rs under the
hook's exact invocation and watching it error.

The three module comments stop citing clippy.toml as well, and say
instead what a reader without that file needs to know: these modules opt
into the lints, the thresholds come from whatever clippy.toml is in
scope, and with none in scope they resolve at clippy's defaults.

Reversal condition: if upstream ever adds a clippy.toml with thresholds
tight enough that the pre-existing code fails, the crate-root allow is
the right fix and should come back with that reason written down.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`evict_by_count` read `SELECT COUNT(*)` into Rust and passed the
difference to `DELETE ... LIMIT excess`. Two callers reaching that pair
together against the same rows both computed the same excess and both
deleted it. Measured with eight threads on a barrier, 203 rows and a cap
of 200: 179 rows left, 15 runs out of 15.

The count moves into the statement, so SQLite evaluates it at execution
under the write lock it already holds for the delete. A second caller
arriving after the first finds nothing to do rather than a stale number
to act on. This also drops a round trip from every store.

`max(0, ...)` around the overshoot is load-bearing, not defensive:
SQLite reads a negative LIMIT as no limit, so without it a store below
its cap deletes every row it has. Removing it fails
`test_b25_eviction_below_the_cap_deletes_nothing` with 0 rows left of 5.

Rejected: wrapping insert, stat bump and eviction in an IMMEDIATE
transaction. It fixes this race too, but by holding the write lock
across the whole store path on a code path that runs per hint, and the
other two interleavings it would prevent are not defects — evicting a
row another process just inserted is what a full store does, and the
stat bump is a single atomic upsert. Reversal condition: if a later
change makes the store path write anything that must land with the row,
the transaction becomes the right answer.

The regression test needed a barrier. Written first as two sequential
evictions, it passed against the defective code — sequential callers
never interleave one's count with the other's delete, which is the whole
race. That version stays, renamed for what it actually proves
(idempotence), with a note pointing at the real one. The existing
concurrency test asserted `count <= 5`, which 197-under-200 satisfies;
it now asserts the cap exactly.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`recall` is capped at max_entries and `tee_reads` at 500. `recall_stats`
had neither a cap nor any eviction, so a slug carrying variable data — a
path, a subcommand, a raw command line short enough to skip the 24-char
fold — opened a row per distinct value and never closed one.

What kept the table small was a coincidence, not a rule. `stat_family`
truncates at the first digit preceded by an underscore, and the one slug
that embeds a path happens to carry an epoch second in front of it, so
`grep_0__tmp_a` folds to `grep`. A slug shaped `foo_<path>` folds to
nothing.

The trim runs with the other two, in `evict`, and drops least-used rows
first: a stats row earns its place by how much it has counted, which is
the opposite of the entry cap, where recency governs. It uses the same
self-limiting statement shape as the entry cap, including the `max(0,
...)` that keeps SQLite from reading a negative LIMIT as no limit.

Not the fix the audit asked for. It asked for the bound at construction —
slugs that cannot carry variable data in the first place. The honest
version of that is a slug type constructible only from a `&'static str`,
which changes `force_tee_hint` and `force_tee_tail_hint` across ~100
filter call sites this branch does not own. The blunt version — folding
every slug to its first segment — was tried on paper and rejected: it
collapses the deliberate `aws_s3_ls` and `grep_skipped` that filters
pass today, which is the granularity loss that got an earlier slug fix
reverted. This caps the table without touching what the slugs say; the
construction-time bound stays open, with the design recorded.

Three tests, each shown to fail against the defect it guards: the cap
holds and the busiest row survives it; a table under the cap loses
nothing (0 rows of 2 without the `max(0, ...)`); and the trim is reached
through the store path, not only by calling it directly — dropping the
call from `evict` leaves the first two green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`set_owner_only` was `#[cfg(not(unix))] fn(..) {}` — an empty body. On
Windows the recall store, its directory, the tee files and the tracking
database were created with whatever DACL they inherited, while the
crate's own comments, its tests and this review's spec all described
them as owner-only. The store holds unredacted stdout, full command lines and
absolute working directories, so on Windows its only stated mitigation
did not exist. Every permission test was `#[cfg(unix)]`, so a green CI
proved nothing about it.

It now builds a DACL with one entry — full access for the process user,
nothing else — and applies it with PROTECTED_DACL_SECURITY_INFORMATION,
which detaches the object from the ACEs it would otherwise inherit.
Directories pass SUB_CONTAINERS_AND_OBJECTS_INHERIT so what is created
inside them starts protected too; files pass NO_INHERITANCE. The Unix
`mode` argument survives as the way a caller says which of the two it
means.

Two limits, both deliberate. Failure stays silent, as it is on Unix,
because this code runs underneath the hook path where a warning becomes
a token in the agent's session; the parent directory carrying the same
DACL is what bounds the consequence. And the restriction cannot be
applied at creation the way Unix applies a mode: `OpenOptions` has no
way to pass SECURITY_ATTRIBUTES, so `open_private` creates the file and
tightens it immediately after, leaving a window the parent directory's
own DACL bounds.

The tests read the DACL back — protected flag set, exactly one entry —
for the file, the directory and the file `open_private` creates, plus
the interior-NUL rejection in the path conversion, where a truncated
path would mean protecting the wrong object.

Verified by compiling and running it, not by reading it. The tree builds
and links for x86_64-pc-windows-gnu against the real windows-sys, and
the suite runs under wine: 3222 passed, 0 failed. Wine is honest about
its limits here — it answers SetNamedSecurityInfoW with ERROR_SUCCESS
and then synthesises a descriptor from the underlying Unix mode bits, so
the read-back assertions cannot run there. The tests detect wine through
ntdll's `wine_get_version` export and asserts the write path instead,
keeping the full assertions for real Windows CI. Planting a silent
failure in the ACL apply fails all three tests under wine, which is the
only reason to trust them.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`recall_stats` counted whatever string a caller passed, and callers had
two different things to say with one `&str`: the name of a kind of
command, which is what the table counts, and the name of one invocation,
which is what a tee filename needs to stay unique. Runtime strings
satisfied both, so per-invocation data became rows — `cargo_{subcommand}`
and `bun_{subcmd}` and `deno_{subcmd}` from whatever the user typed, and
a grep slug carrying 32 characters of file path. None of those fold: the
one that appeared bounded, `grep_0__tmp_a`, only folds because an index
digit sits in front of the path, which is a coincidence of the folding
rule rather than a design.

The cap added earlier bounds the damage. This bounds what enters.

`Slug` has four variants and each carries its own evidence that the set
of stats keys it can produce is finite. `Static` is one literal.
`Composed` is a family plus parts that are themselves `&'static str`, so
`aws_ec2_describe-instances` and `cargo_clippy` stay distinct without
anything runtime reaching the key. `Detailed` carries a value that is
*not* bounded — a path — and therefore never reaches the stats key at
all, only the filename and the `command` column. `Configured` is a name
from the user's own config, bounded by how many filters they defined,
which is the one case where the bound lives outside this tree.

There is deliberately no `From<String>` or `From<&str>`. A caller
holding a runtime string has to say which of the last two it means, and
the compiler asks. Literal call sites — the large majority — are
untouched, because `From<&'static str>` covers them.

`Capture` gains `stats_key` alongside `command`, defaulting to it. The
row keeps the detail a reader of `recall --list` wants; the counter uses
the bounded name.

Two AWS arms changed shape rather than gaining a conversion. They
matched `args[0] == "sync" || args[0] == "cp"` and then passed
`&args[0]` onward, so a guard proved which literal it was and the code
forwarded the user's string anyway. They now pass the literal the guard
proved. That is the same finding an earlier withdrawn fix was reaching
for: the safety was real but it lived in a calling convention, and it
now lives in the type.

Verified: the suite passes, and the wiring test — three greps of
different files producing one `grep` stats row with no path in any key —
fails if `store_hint` stops keying the capture.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EjhvQuvrAvhqMrQ3zbjSuj
pr0d1r2 and others added 3 commits September 6, 2026 21:57
`sanitize_slug` folds a name over 24 characters to `prefix8_hash6`, and
`stat_key` then threw the hash away and kept the first eight characters.
The two functions were fighting: one added a disambiguator, the other
removed it. Any two names sharing eight characters therefore shared a
stats row. Measured: `aws_cloudformation_list-stacks` and
`aws_cloudformation_describe-stack-events` both became `aws_clou`, and
`aws_ec2_describe-instances` was stored as `aws_ec2_` — trailing
underscore and all — which is not the name the commit that introduced
the slug type claimed it kept distinct.

The strip had a reason. It made a long raw command line and the tee
filename derived from it agree, and it made two different raw lines
sharing a prefix aggregate instead of opening a row each. Both concerns
were about raw command lines reaching this function, and the slug type
ended that: a caller holding a runtime string now says `Detailed`, whose
detail never arrives here, or `Configured`, which is bounded by the
user's own config. The two sides still agree without it, because both
fold through `sanitize_slug` and it is idempotent on its own output.

The test that asserted two different raw command lines aggregate is
inverted rather than deleted: it asserted the behaviour that caused the
collision, and it described a world with no producer left in it. A
second test pins the AWS pair that used to collide.

Both fail if the strip comes back.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01EjhvQuvrAvhqMrQ3zbjSuj
… side

The slug type keeps an unbounded value out of the stats key: a grep's
`Detailed` slug carries a file path, and only the family reaches
`recall_stats`. The tee filename still carried the whole thing, and the
recall side reads its key back out of that filename, so in tee mode a
path returned to the stats table by the other door. The count was
bounded on one side and not the other, which is the same as not bounded.

The filename now marks where the countable half ends:
`{epoch}_{family}__{detail}.log`, with each half sanitized on its own so
the marker survives the 24-character fold that would otherwise swallow
it. The filename keeps the detail — two overflows within one second
still need to differ — and `tee_read_slug` returns only what precedes
the marker.

Files written before the marker existed have no `__` and are returned
whole, which is what they were counted as when they were written.

`tee_file`'s three entry points take the slug itself rather than a
rendered string, so the two halves stay available where the name is
built instead of being flattened one call earlier. Building the name
went past the 15-line ceiling and became `tee_file_name`, which is the
right seam regardless: it is the whole filename contract in one place.

The test writes a real tee file, asserts the detail is in the name, and
asserts the reader recovers only `grep`. Inverting the reader's guard
fails it with the path it would have counted.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Three doc comments still said "0600 on Unix" and "0700 on Unix" as
though nothing else happened. Windows gained a real implementation —
a single-entry DACL detached from inheritance — and a reader of these
three functions had no way to know it from here.

`open_private` gains the asymmetry that matters rather than a restated
guarantee: Unix applies the mode at creation, Windows cannot, because
`OpenOptions` has no way to pass `SECURITY_ATTRIBUTES`. The file is
created with the inherited DACL and tightened immediately after, and the
parent directory's own DACL is what bounds that window.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@CLAassistant

CLAassistant commented Sep 6, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@pr0d1r2

pr0d1r2 commented Sep 6, 2026

Copy link
Copy Markdown
Author

Test plan

The repo's template asks for one and my description replaced it — sorry, here it
is.

Check Result
cargo fmt --all --check clean
cargo clippy --all-targets at clippy's own defaults 0 warnings
cargo test --all 3294 in the bin suite, 3396 across all suites, 0 failed
Cross-build x86_64-pc-windows-gnu against real windows-sys builds and links
Suite under wine on that target 3229 passed, 0 failed

Two things that run locally here but not in CI, in case they are useful to
anyone else on this repo:

  • Clippy is run twice — once at upstream defaults, which is what this repo's
    CI sees, and once under tighter complexity thresholds that only the recall
    modules are held to. The thresholds are not in this PR; the modules carry
    #![deny] attributes that resolve at clippy's defaults when no clippy.toml
    is in scope, so they cost this tree nothing.
  • The Windows half is compiled and executed rather than reasoned about. Wine
    answers SetNamedSecurityInfoW with ERROR_SUCCESS and then synthesises a
    security descriptor from the underlying Unix mode bits, so a DACL read back is
    never the one that was written. Those tests detect wine through
    ntdll!wine_get_version and assert only the write path there, keeping the
    read-back assertions for the windows-latest job on this PR. That job is
    the first real test of the ACL work
    — worth watching before merging it.

How this was produced, and how to review it

Every commit here carries a Co-Authored-By: Claude Opus 5 trailer, so rather
than leave that unexplained: this was a spec-driven review, and the artifacts it
produced are visible in the PR itself.

  • One decision per commit. 33 commits rather than a squash, because
    git revert <sha> should undo exactly one decision. Ten are @aeppling's,
    unchanged in authorship.
  • Reasoning in the message, not in a doc. Each message states the mechanism,
    what was measured, what was rejected and why, and — where it applies — the
    condition under which the decision should be reversed. If a commit looks
    surprising, its message is the argument for it.
  • A guard counts only once a planted violation has failed it. Every fix here
    has a test that was run against the defect and seen to fail. That rule exists
    because it caught three of my own guards that did not: a regression test for
    the eviction race passed against the broken code until it was rewritten to use
    a barrier, and a CI-style check reported success over a tree it had just
    failed to compile.
  • Complexity ceilings that only fall. The recall modules are held to 15
    lines and 4 arguments. Two of the splits that produced are load-bearing rather
    than cosmetic: separating evict_by_age from evict_by_count is what made
    the two rules' disagreement about "oldest" visible, and it is the merge
    blocker this PR opens with.

The tooling is Claude Code driving a
spec-driven loop of my own (cavekit): a spec holds numbered invariants and a
bug ledger, findings are written back into it as they are made, and the compact
notation exists because that document is re-read far more often than it is
written.

The spec itself

Published rather than described, including the parts where the process was
wrong: https://github.com/pr0d1r2/rtk/tree/review-spec

The bug ledger there has rows for its own misses — a finding that was
withdrawn after a "demonstration" turned out to be built from test data
rather than a reachable path; a gate that reported green over a broken tree
because a pipeline's exit status under set -o pipefail is the last non-zero
one; a collision found only by checking a claim in a commit message written an
hour earlier; and a commit subject asserting that "the docs already claim" a
guarantee that no document claims.

I would rather hand you that than a clean-looking summary. If any of it reads as
overclaimed, say so — several rows in it exist because exactly that happened.

pr0d1r2 added a commit to pr0d1r2/rtk that referenced this pull request Sep 6, 2026
Named the pre-rename branch and still listed the fork as a build
blocker, minutes after being published. Also records that rtk-ai#3900's CI has
not run: a fork PR from a first-time contributor waits on a maintainer
approving the workflow, so the Windows job that is the first real test
of the ACL work has not executed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@KuSh KuSh left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Round 1 of 3 — CHANGES REQUESTED

Claim: carry #3278's recall store forward with 23 review fixes on top of it.

Scope: accept if narrowed to "the recall_stats cap, slug bounding, and the Windows runtime guarantees" — the three things develop still lacks. Everything else in the branch has either landed already or belongs to an issue someone else has taken.

Ran: rtk grep over a 300-line producer × 4 storage caps × before/after on both binaries; tee-read counting through rtk rewrite for the cat (Ask) and tail (Defer) forms; 80 distinct slugs against recall_stats; rtk ls on a sensitive directory as a real producer; cargo check --target x86_64-pc-windows-gnu --all-targets on both trees. Savings 97.5%, identical on both, against the 20% floor.

CI @96565ae3: never ran — only license/cla is green and check-target skipped, so nothing here has been built by CI yet.

What happened to this branch

#3278 merged on 2026-09-08 as 77ba5c9a. This branch forked from 1c79688, its round-2 head, and the rounds that followed on #3278 fixed much of the same ground independently before it merged. That is an unlucky collision rather than a defect in the work here — but it means most of these 23 commits now describe problems develop no longer has.

Already fixed on develop, including both merge blockers this PR declares:

  • Eviction by two clocks — develop orders both rules by created_at with rowid breaking ties only (retriever.rs:447, :458).
  • benchmark red — benchmark.sh already skips both sqlite hint forms (lines 218-219, 235).
  • Test-store isolation, --from past the end of an entry, the legacy [tee] migration, byte-faithful --grep, the cached connection. TEE_READERS and expand_home are on develop too.

Conversely the branch predates four fixes that landed after it forked, and does not carry them: hidden-tail storing, cfg(test) store isolation, map_legacy_tee, and the cap-in-force wording. The merge produces 22 conflicted files covering every core recall file, so a hand resolution is the likeliest way for those four to be lost without anyone noticing.

Blocks merge (1)

The tee-read counter reads zero on the whole canonical read path. develop counts in two places that agree — rewrite_cmd.rs::run and hook_cmd.rs:237 in decide_from_verdict, both gated on "not Deny". This branch narrows both to the Allow arm only. Ask is what every rewritable read becomes unless an explicit allow rule matches, so on a machine with no rules configured nothing is counted at all:

                          develop              this branch
rewrite "cat  …log"   exit 3 -> recalls=1   exit 3 -> recalls=0
rewrite "tail …log"   exit 1 -> recalls=1   exit 1 -> recalls=0

develop over-counts here, which is real and is tracked as #3953. This trades that for a number that is structurally zero: rtk gain --recalls would report tee recall as never consulted, through every delegate that shells out to rtk rewrite. Dropping Defer is the larger half — tail -n +51 … has no RTK equivalent, and it is the command RTK's own tail hint prints, so it is the dominant real read.

I can see this is deliberate rather than an oversight — v17_track_after_verdict pins it, and "count after the verdict, never before" is the right instinct. The trouble is that the hook runs before the host prompts, so no gate there can tell an approved Ask from a rejected one; narrowing to Allow buys accuracy on the rejected ones by discarding every approved one, plus all of Defer.

The ask here is to drop this change rather than repair it (the test with it): #3953 covers it and another contributor has offered to take it, so the two would otherwise land on the same arm twice. Worth knowing that the shape being discussed there is to count where the read executes rather than in the hook gate.

This is separable from the slug work: bounded_half is called only from tee_read_slug, which extracts the slug, while the gating lives in run() and decide_from_verdict. Keeping the former and leaving both of the latter as develop has them is a clean cut.

The narrowed claim, and what is worth carrying forward

  • recall_stats has no cap. Verified: 80 distinct slugs produce 81 rows, and the only DELETE FROM recall_stats on develop is the gain --reset wipe. EVICT_STATS_SQL is the real fix and it is self-contained.
  • Slug bounding (DETAIL_MARKER / bounded_half) — not on develop. One thing I could not confirm: rtk ls on a sensitive directory produced the slug ls-hidden with no path in it, so I did not reproduce a path reaching recall_stats. If you still have the case that produces one, naming it would make this land much faster.
  • Windows owner-only and hint path handling — not on develop. Both trees type-check clean for x86_64-pc-windows-gnu, so the build-repair half no longer applies; what remains is a runtime guarantee I have no way to execute from here, and I would take it on the strength of the code and a test.

Three small PRs against current develop would each be reviewable in one pass, and none of them would conflict. The recall_stats cap is the one I would send first.

Your questions

If it is easier to review as commits on the original branch, say so and I will hand the branch over for @aeppling to pull in

Moot now — #3278 merged two days after this PR opened, so there is no branch left to hand over. The narrowed PRs above are the path that survives.

Also useful

The findings under Found while reviewing, deliberately not fixed here are worth keeping — the telemetry path leak in low_savings_commands in particular, verified with bin/packwerk. If you would like them as issues, say the word and I will file them with your wording; happy to do that whether or not you pick the narrowed PRs up.

Your reasoning on force_tee_hint and exit_code = None is right, and matches where the same question landed on #3278: 69 call sites in 19 modules for one column is not a trade worth making.

Next

Open the recall_stats cap as its own PR against current develop — verified, self-contained, no conflicts. Slug bounding and Windows follow separately, and leave run()'s counting arm out of all three.

Rounds: 1/3. Threads: 0 open.

@KuSh KuSh self-assigned this Sep 20, 2026
@KuSh

KuSh commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Thank you for all the review work here. #3278 (merged 2026-09-08) landed its own later revision of the recall store, which already has both merge blockers this PR clears (created_at ordering for both eviction rules and benchmark.sh skipping the sqlite hints) as well as byte-faithful --grep, the cached connection and a disabled mode that creates no database, and this branch now conflicts across every core recall file. A few pieces are still missing on develop and would each make a good narrow PR against current develop, as the review of 2026-09-20 suggested: recall_stats has no row cap, so EVICT_STATS_SQL is still needed. Slug bounding (DETAIL_MARKER and bounded_half) is not on develop either. set_owner_only is still a no-op on Windows, so recall and tee files get no owner-only guarantee there. evict() still reads COUNT(*) before its DELETE ... LIMIT rather than evicting in one statement. The tee-read counting change is best left to #3953. If I missed something this PR still covers, please comment and it can be reopened.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants