GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing github.com — feat(perf): emit prompt-prefix hash fingerprint per turn by anandh8x · Pull Request #704 · Twigpine/zero Conversation
|
| file | change |
|---|---|
internal/trace/trace.go |
new PrefixHash event type; TurnTrace carries []PrefixHash; "event:prefix_hash" added to OptionalEventKeys() |
internal/trace/recorder.go |
new EmitPrefixHash(p PrefixHash) method, nil-safe, sealed-after-Finish |
internal/trace/emit.go |
WriteNDJSON emits one prefix_hash line per fingerprint after counters, sorted by complete_prefix for stable output |
internal/agent/prompt_fingerprint.go |
new file: buildPromptSubstrings, toolSubstrings, canonicalSchemaString (json.Marshal for stable map rendering), ComputePrefixFingerprint |
internal/agent/loop.go |
after partitionToolsCached returns, if options.Trace != nil, compute the fingerprint and emit it |
internal/agent/prompt_fingerprint_test.go |
new file: 7 tests covering stability, name-order independence, schema sensitivity, system-prompt sensitivity, complete-is-aggregate, default-options invariant, canonical-schema-string stability for map parameters |
go test -race ./internal/trace/... ./internal/agent/... — greengofmt -l — cleango vet ./internal/... — cleangolangci-lint run --enable-only unused,ineffassign,staticcheck ./internal/trace/... ./internal/agent/... — 0 issuesgo run golang.org/x/vuln/cmd/[email protected] ./internal/trace/... ./internal/agent/... — no vulnerabilitiesRun an end-to-end with a real provider:
ZERO_TRACE=/tmp/run.ndjson zero exec --prompt "list the files in this repo"
Then inspect the trace:
jq -c 'select(.type == "prefix_hash")' /tmp/run.ndjson
For a multi-turn session, the complete_prefix should be stable across the first turn's hash if no project doc or skill list changed.
These are deliberate scope limits of this PR, not omissions. They are listed so the next PR can pick them up cleanly.
buildSystemPrompt are in the fingerprint. The captured substrings are baseInstructions, confirmationPolicy, projectContext (workspace context), and skills. Sections that fire only for non-default Options (specialist delegation context, response style, session runtime context, model addendum, approved command prefixes, user guidelines, workspace seed) are out of scope. For default Options (the common case), the four captured substrings cover the full prompt and the fingerprint is accurate. A follow-up PR that extends the decomposition to all 10 sections — and a test asserting the full join matches buildSystemPrompt byte-for-byte for any Options — is the natural next step.trace.PrefixHash. A future caller could put a non-SHA-256 string in a BaseInstructionsHash field and the trace would silently accept it. A NewPrefixHash(...) constructor that does the hashing in one place is a small follow-up.complete_prefix in WriteNDJSON. Deterministic but not informative — the order changes as the run progresses and is not a stable turn index. Switching to insertion order (no sort) or attaching a turn field to the event is a small follow-up.cached_input_tokens move when complete_prefix is stable? — requires a real provider run and is the M1-baseline-evidence work, not a code change.Pure observability. No provider call, no model call, no request shape change. If the prefix_hash event proves noisy, the schema bump is TurnTrace.PrefixHashes (omitempty) and the new event type in OptionalEventKeys() — both backward-compatible drops. Rolling back is git revert e503ad29.
New Features
prefix_hash events containing per-component hashes plus the derived complete_prefix hash.Tests
prefix_hash events and preserve insertion order.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (3)
WalkthroughThe agent computes deterministic hashes for prompt-prefix components on traced turns. Trace records store, serialize, and parse these hashes as ChangesPrompt Prefix Fingerprint Tracing
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant AgentRun
participant ComputePrefixFingerprint
participant Recorder
participant WriteNDJSON
participant ReadNDJSON
AgentRun->>ComputePrefixFingerprint: compute prompt-prefix hashes
ComputePrefixFingerprint-->>AgentRun: return component and complete hashes
AgentRun->>Recorder: EmitPrefixHash(PrefixHash)
Recorder->>Recorder: store prefix hash in TurnTrace
WriteNDJSON->>WriteNDJSON: encode prefix_hash records in insertion order
ReadNDJSON->>ReadNDJSON: reconstruct PrefixHashes
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Zero automated PR reviewVerdict: No blockers found Blockers
Validation
ScopeHead: This deterministic review checks validation status and basic diff hygiene. A human reviewer still owns product judgment and design quality. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
|
@coderabbitai full review |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
✅ Action performedFull review finished. |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
internal/agent/prompt_fingerprint.go (1)
114-133: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low valueFallback for
canonicalSchemaStringmay introduce non-determinism.If
json.Marshalfails (e.g., due to unsupported types likeNaN, functions, or cyclic references—which are highly unlikely in valid JSON schemas), the fallback usesfmt.Sprintf("%v", params). Sinceparamsis a map,fmt.Sprintfwill iterate over it in a random order, resulting in a non-deterministic trace hash.While encountering non-JSON-compatible values in
Parametersis extremely rare, you may want to consider a stable stringification method for the fallback or at least note this limitation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/agent/prompt_fingerprint.go` around lines 114 - 133, The fallback in canonicalSchemaString remains non-deterministic because fmt.Sprintf formats the parameter map in random key order. Replace the fmt.Sprintf("%v", params) fallback with a deterministic serialization or stable key-sorted stringification while preserving the "__non_json:" prefix and existing JSON-marshalling behavior.
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/trace/recorder.go`:
- Around line 175-190: Update Recorder.Finish to copy r.tr.PrefixHashes into the
returned trace, matching the existing defensive copies for Spans and Counters.
Ensure the finished result cannot mutate the recorder’s internal PrefixHashes
slice while preserving the current sealing behavior.
---
Nitpick comments:
In `@internal/agent/prompt_fingerprint.go`:
- Around line 114-133: The fallback in canonicalSchemaString remains
non-deterministic because fmt.Sprintf formats the parameter map in random key
order. Replace the fmt.Sprintf("%v", params) fallback with a deterministic
serialization or stable key-sorted stringification while preserving the
"__non_json:" prefix and existing JSON-marshalling behavior.
Fix all unresolved CodeRabbit comments on this PR:
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID: 88867e11-c64b-473b-b872-7bc820a8b847
internal/agent/loop.gointernal/agent/prompt_fingerprint.gointernal/agent/prompt_fingerprint_test.gointernal/trace/emit.gointernal/trace/recorder.gointernal/trace/trace.go
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
internal/trace/recorder.go (1)
175-190: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCopy
PrefixHashesinFinish()to prevent mutation of recorder state.The
Recorder.Finish()method (lines 194-210) defensively copiesSpansandCountersto prevent callers from mutating the recorder's internal slices, but it was not updated to copy the newly addedPrefixHashesslice.Update
Finish()to include a copy ofPrefixHashesto preserve the sealing behavior.💻 Proposed fix
Update
Finish()ininternal/trace/recorder.go(around line 209):snap := r.tr // Copy the slices so callers cannot mutate the recorder's state. snap.Spans = append([]Span(nil), r.tr.Spans...) snap.Counters = append([]Counter(nil), r.tr.Counters...) + snap.PrefixHashes = append([]PrefixHash(nil), r.tr.PrefixHashes...) return &snap🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/trace/recorder.go` around lines 175 - 190, Update Recorder.Finish to defensively copy the PrefixHashes slice alongside Spans and Counters before returning the sealed trace, ensuring callers cannot mutate recorder state through the returned PrefixHashes.
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Duplicate comments:
In `@internal/trace/recorder.go`:
- Around line 175-190: Update Recorder.Finish to defensively copy the
PrefixHashes slice alongside Spans and Counters before returning the sealed
trace, ensuring callers cannot mutate recorder state through the returned
PrefixHashes.
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 3bec2e59-dd5e-474a-b816-a3130b419e4d
internal/agent/loop.gointernal/agent/prompt_fingerprint.gointernal/agent/prompt_fingerprint_test.gointernal/trace/emit.gointernal/trace/recorder.gointernal/trace/trace.go
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Requesting changes — but only on contract-doc accuracy, not the implementation. The code is sound and the agent→trace seam is clean; the issue is that the in-code docs advertise a stronger invariant than the 4-of-11 coverage actually delivers, and for a trace event whose whole purpose is "don't let this be misread," that gap is worth closing before merge.
Decision up front: qualify the complete_prefix invariant in the type/function docs (items 1–2 below). Everything else is a suggestion or a nit. Land 1 and 2 and I'm an approve.
1. (must fix) complete_prefix stable ≠ full prefix byte-identical. buildSystemPrompt is 11 sections; the fingerprint covers 4 (core, confirmationPolicy, workspaceContext, skillsContext). Seven aren't hashed: modelPromptAddendum, sessionRuntimeContext, approvedCommandPrefixContext, workspaceSeedContext, userGuidelines, specialistDelegationContext, responseStyleContext. The PrefixHash doc and ComputePrefixFingerprint doc both say "stable CompletePrefixHash ⇒ cacheable prefix byte-identical" unconditionally. That's false the moment any of the seven changes — and the sharpest case is modelPromptAddendum(options.Model), which moves on a model switch, and model switches are themselves a traced counter. So a consumer could read a stable complete_prefix right through a model switch that actually changed the prefix. You call this out in Known-limitations #1, and I read it — the ask is only that the type/function docs (what a consumer reads, not the PR body) carry the same qualification: complete_prefix reflects the captured sections; a stable value means those are byte-identical, not the full prefix. A test asserting an edit to an uncaptured section (e.g. responseStyle) does NOT move complete_prefix would make the boundary a tested contract, not just a README note.
2. (must fix) "does not read files" is wrong. ComputePrefixFingerprint's doc says it "does not read files." It does: buildPromptSubstrings → workspaceContext runs git (gitBranchForPrompt, FindProjectGitRoot) and reads the AGENTS.md/ZERO.md chain (projectGuidelines) plus the repo map. Side effect: it re-does the workspace-context work buildSystemPrompt does a few lines later, on every traced turn. Fine for an opt-in trace, but the doc should say so. Either correct the doc, or have the request-build path hand the fingerprint the substrings it already computed so we don't read/git twice per turn.
3. (suggest, one line) drop the complete_prefix sort in WriteNDJSON. The PR's reason for existing is correlating a cached_input_tokens move with the turn whose prefix drifted. The prefix_hash event has no turn index and you sort by complete_prefix, so turn order is gone — the correlation is ambiguous. Known-limitations #3 calls the sort cosmetic; I'd argue it breaks the one use case the event is for. Insertion order is turn order and is already deterministic; dropping the sort is one line and makes the event actually usable for the correlation. I'd take it here rather than as a follow-up, but I won't block on it.
4. (nit) toolSubstrings's comment justifies schema stability via a "schema-render cache," but canonicalSchemaString uses json.Marshal directly (sorted keys = stable on its own), so the cache isn't what makes it stable. Also SchemaHash is json.Marshal(def.Parameters), which may not match the bytes a provider actually sends — so it's a stability signal, not a wire-identity signal. A one-line note keeps a consumer from assuming SchemaHash == wire schema.
What's good: nil-safe EmitPrefixHash matching the recorder pattern, sealed-after-Finish, the agent→trace boundary (trace doesn't import agent), options.Trace != nil gating, OptionalEventKeys placement (optional, so a short healthy trace doesn't false-fail), and the test coverage (stability / reorder / schema / system-prompt / aggregate / default-options / canonical-schema). CI green across all 9 checks. The split-plan seam is clean.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Gate: @Vasanthdev2004 has a formal review on this PR.
| Check | Result |
|---|---|
| go test -race ./internal/trace/ ./internal/agent/ | pass |
| gofmt / go vet on touched packages | clean |
| CI | green |
Solid Stream B / Phase-1 instrumentation on the Phase 0 tracer: opt-in, pure observability, stable schema rendering via json.Marshal, good tests. Untraced path is a no-op. Partial buildSystemPrompt coverage is OK if documented loudly.
internal/trace/recorder.go. Without it the snapshot aliases the recorder slice. CodeRabbit flagged the same issue.snap.PrefixHashes = append([]PrefixHash(nil), r.tr.PrefixHashes...)
type: "prefix_hash" into TurnTrace.PrefixHashes in internal/trace/parse.go. Write path emits it; re-parse currently drops the signal (harness / offline analysis).Approve after the Finish copy + NDJSON parse fixes.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
e503ad2 to
c40a25f
Compare
|
All review feedback addressed in the latest push ( From Vasanth (must fix):
From Vasanth (suggest + nit): From gnanam (must fix): From both: All checks green:
Ready for re-review at HEAD |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
Gate: Vasanthdev2004 has formal review activity on this PR.
| Check | Result |
|---|---|
| go test -race ./internal/trace/ ./internal/agent/ | pass |
| TestReadNDJSONRoundTrip / Finish snapshot tests | pass |
| Prior must-fix items | addressed (see below) |
| Item | Status |
|---|---|
| Finish() deep-copy PrefixHashes | Fixed |
| ReadNDJSON parse type:prefix_hash | Fixed (+ round-trip coverage) |
| Item | Status |
|---|---|
| Doc: complete_prefix stable ≠ full prompt | Fixed on PrefixHash + ComputePrefixFingerprint |
| Doc: "does not read files" was wrong | Fixed — I/O side effects documented |
| Drop sort-by-complete_prefix in WriteNDJSON | Fixed — insertion/turn order |
Clean observability PR. My previous CHANGES_REQUESTED items are resolved. Happy to land.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
Compute a seven-field SHA-256 fingerprint of the cacheable prompt prefix (base instructions, confirmation policy, project context, skills, tools, tool schemas, complete) and emit one prefix_hash event per turn through the trace recorder. The complete hash is the SHA-256 of the canonical join of the other six, so any sub-component drift is observable both individually and in aggregate. The decomposition exists so a downstream observer can detect which sub-component of the prefix broke cache stability across turns: a stable complete_prefix hash means the cacheable prefix is byte- identical, and the sub-hash that changed names the culprit. No behavior change for untraced runs. For OpenAI, the existing prompt_cache_key (session ID) is unchanged; the fingerprint is purely additive observability. The Anthropic cache_control breakpoint work already in main is not touched.
c40a25f to
0fa1d99
Compare
|
CodeRabbit review at #pullrequestreview-4715021444 — second finding (the What was wrong: the fallback path for non-JSON-encodable values used What I did:
The first finding in that review (deep-copy All checks green: gofmt, go vet, go test -race, golangci-lint (0 issues). |
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
All four addressed — approving. CI green across the board and gnanam's already approved too.
PrefixHash doc and ComputePrefixFingerprint doc now scope to the 4 captured sections, name the seven uncaptured ones, and call out the model_switches cross-check for modelPromptAddendum. That's exactly the qualification the event needed.workspaceContext runs git and reads the guideline chain, doubled per traced turn, follow-up to pass substrings through. Good.cached_input_tokens correlation. Taking it now rather than as a follow-up, thanks.canonicalSchemaString now notes SchemaHash is a stability signal, not a wire-identity signal. Fine.One non-blocking follow-up I'll leave here rather than hold the PR on: a test asserting an edit to an uncaptured section (e.g. responseStyle) does not move complete_prefix would pin the 4-of-11 boundary as a tested contract, so a future extension — or an accidental change to the captured set — is caught. Not blocking; the docs carry the scope clearly now.
Nice cleanup on the …ReorderChangesToolsHash → …IsNameSetSensitive rename too — the old name asserted the opposite of what it read.
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
The reason will be displayed to describe this comment to others. Learn more.
LGTM
Sorry, something went wrong.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
There was an error while loading. Please reload this page.
Successfully merging this pull request may close these issues.
There was an error while loading. Please reload this page.