Repository navigation
feat(session): persist a run receipt with per-group coverage (#2124) - #2132
nitishagar wants to merge 1 commit into
Conversation
|
🔍 OpenCodeReview found 6 issue(s) in this PR.
|
| if rg, ok := byGroup[receiptGroupID(i)]; ok { | ||
| result[i].State = rg.State | ||
| result[i].CompletedFiles = rg.CompletedFiles | ||
| result[i].MissingFiles = rg.MissingFiles |
There was a problem hiding this comment.
Bug: buildReceiptLocked() in receipt.go sets MissingFiles to a non-nil empty slice ([]string{}) when there are no missing files (lines 202 and 232-233). That non-nil empty slice is copied here into FileGroupInfo.MissingFiles. Go's encoding/json only omits nil slices for omitempty, so fully-completed groups will still serialize as "missing_files": [] rather than being omitted entirely.
To fix, set MissingFiles to nil instead of []string{} when there are no missing files — either in buildReceiptLocked() or here at the assignment site. For example:
if len(rg.MissingFiles) > 0 {
result[i].MissingFiles = rg.MissingFiles
}| func scanBatchPaths(batch []model.ScanItem) []string { | ||
| paths := make([]string, 0, len(batch)) | ||
| for i := range batch { | ||
| if batch[i].IsBinary || batch[i].Content == "" { | ||
| continue | ||
| } | ||
| paths = append(paths, batch[i].Path) | ||
| } | ||
| return paths | ||
| } |
There was a problem hiding this comment.
Potential mismatch between receipt group files and actually dispatched items: scanBatchPaths skips items where Content == "", but dispatchBatch does not filter them out — it will dispatch and later record them via RecordReviewItemDone/RecordReviewItemFailed. Those items end up in receiptItems (the catch-all in recordReceiptItem handles unknown paths) but won't appear in any group's Files list, so the group rollup will undercount them.
Consider either:
- Filtering empty-content items in
selectScanItems/whyExcludedso they never reach batches (consistent with binary exclusion), or - Including them in
scanBatchPathsto match whatdispatchBatchactually processes.
| for path, item := range sh.receiptItems { | ||
| f := ReceiptFile{Path: path, State: item.state, FailureCode: item.failureCode} | ||
| files = append(files, f) | ||
| byPath[path] = &files[len(files)-1] | ||
| } | ||
| sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path }) |
There was a problem hiding this comment.
Bug: Pointer-to-slice-element invalidated by sort. byPath stores pointers into files slice elements (&files[len(files)-1]). The subsequent sort.Slice on line 193 rearranges elements in place via swaps, so after sorting, the pointer stored in byPath[p] no longer necessarily points to the element with path p — it points to whatever element was swapped into that slot. When lines 209-210 later do f.GroupID = g.GroupID through byPath[p], the GroupID is written to the wrong ReceiptFile entry.
The second sort.Slice on line 238 then re-sorts (redundantly), but the GroupID assignments are already corrupted.
Fix: populate byPath after the first sort, or avoid pointers entirely by building the GroupID assignment in a separate pass over the sorted slice.
| switch { | ||
| case len(rg.MissingFiles) == 0: | ||
| rg.State = "done" | ||
| case rg.CompletedFiles == 0: | ||
| rg.State = "pending" | ||
| rg.FailureCode = "" | ||
| default: | ||
| rg.State = "partial" | ||
| } |
There was a problem hiding this comment.
Inconsistent state vocabulary between group-level and session-level status. Group states use raw strings "done", "pending", "partial" while the top-level Receipt.Status uses the exported constants ReceiptStatusComplete, ReceiptStatusRunning, etc. This inconsistency will confuse consumers parsing the JSON who expect uniform vocabulary. Consider defining group-level constants (e.g., ReceiptGroupDone, ReceiptGroupPending, ReceiptGroupPartial) or reusing the existing ReceiptStatus* constants for consistency.
| sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path }) | ||
| return Receipt{ |
There was a problem hiding this comment.
Redundant sort. files is already sorted on line 193. No mutation of files elements' Path field occurs between the two sorts (only GroupID is assigned via byPath pointers). This duplicate sort wastes CPU on every receipt write, which happens on every item completion. Remove this second sort, or better yet, restructure to fix the pointer bug above and keep only one sort at the end.
| func (sh *SessionHistory) writeReceiptLocked() { | ||
| if sh.persist == nil || sh.SessionID == "" { | ||
| return | ||
| } | ||
| dir, err := SessionsDir(sh.RepoDir) | ||
| if err != nil { | ||
| return | ||
| } | ||
| receipt := sh.buildReceiptLocked() | ||
| data, err := json.MarshalIndent(receipt, "", " ") | ||
| if err != nil { | ||
| return | ||
| } | ||
| final := filepath.Join(dir, sh.SessionID+".receipt.json") | ||
| tmp := final + ".tmp" | ||
| if err := os.WriteFile(tmp, data, 0600); err != nil { | ||
| return | ||
| } | ||
| _ = os.Rename(tmp, final) | ||
| } |
There was a problem hiding this comment.
Holding mutex during disk I/O. writeReceiptLocked performs JSON marshaling, temp file write, and rename while holding sh.mu. Since recordReceiptItem calls this on every file completion, concurrent RecordReviewItemDone/Failed/Reused callers are serialized through the entire I/O cycle. For large reviews with many files completing in parallel, this could become a bottleneck.
Consider building the receipt data under the lock, then releasing the lock before performing the actual file I/O (marshal + write + rename). The receipt is documented as best-effort, so a slightly stale snapshot during the unlocked write window is acceptable.
ebc55ed to
79b690d
Compare
…#2124) Every run that has started dispatching now maintains <session-id>.receipt.json (ocr.session-receipt/v1) atomically beside the journal, rewritten as checkpoints land, so a run killed hard (SIGKILL, supervisor timeout) leaves a parseable snapshot: the session id, a status (running while live; complete/partial/failed/cancelled/skipped at the end), and per-group / per-file coverage with failure codes. The receipt can lag the journal by the most recent checkpoint — the journal record is written first — so resume, which is journal-driven, may reuse slightly more than the receipt shows. The extension is not .jsonl, so ocr session list enumeration is unaffected, receipt write failures never propagate (the journal stays the source of truth), runs that never reach dispatch write no receipt, and ocr session rm removes the receipt with the journal. The result JSON's groups[] gains the same per-group rollup (state, completed_files, missing_files, failure_code) joined from the receipt state, so coverage can be mapped to groups after the fact; label/files keep their historical shape. Review installs one receipt group per semantic dispatch group; scan installs one per dispatch batch, all up front — so a scan truncated by cancellation or the budget gate leaves its undispatched batches visibly pending instead of reading complete. The existing cancellation paths pin the receipt status to cancelled on both commands so an interrupted run never reads as partial. Resume after an unclean kill already reused completed checkpoints and tolerated a torn journal tail; the receipt gives the caller the discoverable, documented surface the issue asks for.
79b690d to
bcb9fa8
Compare
Description
Fixes #2124.
A caller running
ocrinside a hard wall-clock window (CI slice, platform reviewer) whose run is killed or timed out previously had no parseable record of the session id or of which files/groups were covered: the journal's non-checkpoint records sit in an unflushed buffer under a hard kill, and the journal itself is not a documented interface.--resumealready reuses completed checkpoints after an unclean kill (and already tolerates a torn journal tail), so the remaining gap was discoverability and per-group state.Change:
internal/session/receipt.go, new): every run that has started dispatching maintains<session-id>.receipt.json(ocr.session-receipt/v1) atomically beside the journal — rewritten as checkpoints land, so even a SIGKILL leaves the last snapshot. It carries thesession_id, astatus(runningwhile live;complete/partial/failed/cancelled/skippedat the end; a stalerunningreceipt means the process died), and per-group / per-file coverage (state,failure_code,group_id). The extension is deliberately not.jsonl, soocr session listenumeration is unaffected. Receipt write failures never propagate — the journal stays the source of truth.groups[]already carried{label, files}; it now also carriesstate,completed_files,missing_files, andfailure_code, joined from the same receipt state, so coverage can be mapped to groups after the fact.label/fileskeep their historical shape (additive fields only).groups[]joins by dispatch order); scan installs one group per dispatch batch (batch-<idx>), all up front — so a scan truncated by cancellation or the budget gate leaves its undispatched batches visibly pending instead of reading complete.RunFailureCancelled/ deadline on review; ctx cancel or deadline on scan) pin the receipt's terminal status tocancelled, so an interrupted run — on either command — never reads as partial.ocr session rmremoves the receipt with the journal; the receipt can lag the journal by the most recent checkpoint (the journal record is written first), so resume — journal-driven — may reuse slightly more than the receipt shows.Already true on
main(no code needed, verified while implementing): SIGINT/SIGTERM graceful shutdown with second-signal force exit;--resumereuse of completed files without re-issuing model requests; torn-tail tolerance when replaying a killed run's journal. The receipt complements these with a documented, kill-survivable discovery surface.Type of Change
How Has This Been Tested?
internal/session/receipt_test.go(initial pending write, transition rewrites, finalize status matrix incl. cancelled override + no-receipt-for-never-dispatched runs + reuse-preservation across re-install + no tmp residue + receipt invisible toocr session listvia an exact-count assert, write-failure swallow, untracked-path tracking),internal/agent/receipt_test.go(groups[]state join: partial group withmissing_files/failure_code, untouched group stays pending),internal/scan/receipt_test.go(two-batch run:batch-0/batch-1groups land, rollup flips to done, terminalcomplete; plus a mid-batch cancellation test provingstatus: cancelledwith the undispatched batch pending).ocr scanagainst a stalled LLM endpoint,kill -9mid-run →~/.opencodereview/sessions/<repo>/<session-id>.receipt.jsonsurvives, parseable,"status":"running",batch-0with its filespending— the caller can resume without scraping the journal.cancelledpinned on scan's cancellation/deadline paths, empty-content scan items kept in their group (they dispatch), no receipt minted for runs that never dispatched,ocr session rmremoves the receipt, receipt-lag sentence added to the docs.make checkclean; fullmake testsuite (race, coverage gate) green; gofmt clean.main(compile-fail evidence); thegroups[]enrichment test asserts state fields absent from today's output.Checklist
go fmt,go vet)pages/src/content/docs/en/cli-reference.md("Resuming interrupted reviews" gains a "Run receipts" subsection with the schema and status semantics); localized section headings added to all locale docs (zh/ja/ko/ru/tr) so the pages heading-sync test stays greenAI disclosure: GLM via ZCode was used to draft the change and tests; I reviewed and tested the output.
Related Issues
Closes #2124.