Skip to content

feat(session): persist a run receipt with per-group coverage (#2124) - #2132

Open
nitishagar wants to merge 1 commit into
alibaba:mainfrom
nitishagar:feat/issue-2124-session-receipt-groups
Open

nitishagar wants to merge 1 commit into
alibaba:mainfrom
nitishagar:feat/issue-2124-session-receipt-groups

Conversation

@nitishagar

@nitishagar nitishagar commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #2124.

A caller running ocr inside 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. --resume already 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:

  • Run receipts (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 the session_id, a status (running while live; complete/partial/failed/cancelled/skipped at the end; a stale running receipt means the process died), and per-group / per-file coverage (state, failure_code, group_id). The extension is deliberately not .jsonl, so ocr session list enumeration is unaffected. Receipt write failures never propagate — the journal stays the source of truth.
  • Per-group state in the result JSON: groups[] already carried {label, files}; it now also carries state, completed_files, missing_files, and failure_code, joined from the same receipt state, so coverage can be mapped to groups after the fact. label/files keep their historical shape (additive fields only).
  • Group identity: review installs one receipt group per semantic dispatch group (the result's 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.
  • Cancellation: the existing cancellation paths (RunFailureCancelled / deadline on review; ctx cancel or deadline on scan) pin the receipt's terminal status to cancelled, so an interrupted run — on either command — never reads as partial.
  • Lifecycle: runs that never reach dispatch write no receipt (nothing to honestly report); ocr session rm removes 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; --resume reuse 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

  • New feature (non-breaking change that adds functionality)

How Has This Been Tested?

  • New unit tests: 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 to ocr session list via an exact-count assert, write-failure swallow, untracked-path tracking), internal/agent/receipt_test.go (groups[] state join: partial group with missing_files/failure_code, untouched group stays pending), internal/scan/receipt_test.go (two-batch run: batch-0/batch-1 groups land, rollup flips to done, terminal complete; plus a mid-batch cancellation test proving status: cancelled with the undispatched batch pending).
  • Kill-path smoke with the built binary: started ocr scan against a stalled LLM endpoint, kill -9 mid-run → ~/.opencodereview/sessions/<repo>/<session-id>.receipt.json survives, parseable, "status":"running", batch-0 with its files pending — the caller can resume without scraping the journal.
  • Red-team pass applied: scan batches pre-installed so truncation reads partial (not complete), cancelled pinned 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 rm removes the receipt, receipt-lag sentence added to the docs.
  • make check clean; full make test suite (race, coverage gate) green; gofmt clean.
  • Failing-first: the new tests reference APIs that don't exist on main (compile-fail evidence); the groups[] enrichment test asserts state fields absent from today's output.

Checklist

  • My code follows the project's coding style (go fmt, go vet)
  • I have performed a self-review of my code
  • I have added tests that prove my fix is effective or my feature works
  • New and existing unit tests pass locally with my changes
  • I have updated the documentation accordingly (if applicable) — 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 green
  • I have signed the CLA
  • I did not use AI/LLM to create this PR, or I disclosed the tool/model below and reviewed its output; I did not attribute commits to AI and will answer maintainer questions and review comments myself without AI/LLM.

AI disclosure: GLM via ZCode was used to draft the change and tests; I reviewed and tested the output.

Related Issues

Closes #2124.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

🔍 OpenCodeReview found 6 issue(s) in this PR.

  • ✅ Successfully posted inline: 6 comment(s)

Comment thread internal/agent/agent.go
if rg, ok := byGroup[receiptGroupID(i)]; ok {
result[i].State = rg.State
result[i].CompletedFiles = rg.CompletedFiles
result[i].MissingFiles = rg.MissingFiles

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

bug · medium
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
}

Comment thread internal/scan/agent.go
Comment on lines +228 to +237
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
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

maintainability · low
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:

  1. Filtering empty-content items in selectScanItems/whyExcluded so they never reach batches (consistent with binary exclusion), or
  2. Including them in scanBatchPaths to match what dispatchBatch actually processes.

Comment on lines +188 to +193
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 })

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

bug · critical
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.

Comment on lines +223 to +231
switch {
case len(rg.MissingFiles) == 0:
rg.State = "done"
case rg.CompletedFiles == 0:
rg.State = "pending"
rg.FailureCode = ""
default:
rg.State = "partial"
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

maintainability · medium
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.

Comment thread internal/session/receipt.go Outdated
Comment on lines +238 to +239
sort.Slice(files, func(i, j int) bool { return files[i].Path < files[j].Path })
return Receipt{

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

performance · low
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.

Comment on lines +292 to +311
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)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

performance · medium
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.

@nitishagar
nitishagar force-pushed the feat/issue-2124-session-receipt-groups branch from ebc55ed to 79b690d Compare November 28, 2026 10:58
…#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.
@nitishagar
nitishagar force-pushed the feat/issue-2124-session-receipt-groups branch from 79b690d to bcb9fa8 Compare November 28, 2026 11:06

This branch has not been deployed

No deployments
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.

Killed or timed-out reviews should leave a discoverable session id and per-group state

1 participant