Skip to content

fix(session): report active sessions as running instead of aborted in session list - #1589

Open
weiconghe wants to merge 1 commit into
alibaba:mainfrom
weiconghe:fix/session-list-running-status
Open

weiconghe wants to merge 1 commit into
alibaba:mainfrom
weiconghe:fix/session-list-running-status

Conversation

@weiconghe

@weiconghe weiconghe commented Sep 28, 2026 •

Copy link
Copy Markdown

Description

Closes #1588 — full root-cause analysis and reproduction steps there.
Revised per the reviews on a5e7aef and 960891f: liveness is an explicit writer-side heartbeat, and heartbeat capability is now identifiable from a session file's first moments.

The problem. While a review is still running, ocr session list (table and --json) reports the in-progress session as aborted. The status only flips to complete after the run finishes. An agent that polls ocr session list — one of the AI-host-agent workflows this project recommends — sees a healthy running review reported as dead and may start a duplicate review, wasting tokens and duplicating findings.

Root cause. A session JSONL file receives its session_end record only at Finalize() (internal/session/history.go). The listing path (loadSummaryFromFile in internal/session/list.go) initializes Aborted: true and flips it to false only when it reads that record. So a live run — which by design has no session_end yet — is indistinguishable on disk from a crashed one: both are "no session_end". There is no liveness signal in the listing path.

The fix — an explicit heartbeat, not a bigger window.

  • Writer (internal/session/persist.go): the JSONL writer runs a liveness loop that appends a flushed heartbeat record every 60s for the whole life of the run. The loop is a separate goroutine, so the file stays fresh even while the run sits inside one long provider request or retry wait with no completed/request-boundary record — the case a fixed append-activity window cannot cover (the default per-request timeout alone is 5 minutes, and provider-configured timeouts/retry backoffs can be longer). The loop stops at session_end and at the writer's close path via an idempotent stop that waits out any in-flight beat, so nothing writes to a closed file. Readers that don't know the record type ignore it, the same way they ignore resume_lineage.
  • Heartbeat capability from birth: WriteSessionStart appends one synchronous initial heartbeat right after the session_start record, before the periodic loop takes over. With the periodic loop alone, a writer killed during its first interval would leave no heartbeat record at all, and readers could not tell its file from one written by a pre-heartbeat version — it would be held to the wider legacy window for up to 10 minutes instead of the documented ~3-minute residual. The initial beat makes "at least one heartbeat record" a property of every file this version writes, so a session killed at any age selects the heartbeat liveness window.
  • Reader (internal/session/list.go): an unfinished session reports running while its heartbeat evidence is fresh — three missed beats (3 min), which only bounds how long a killed writer can masquerade as running. Session files written by pre-heartbeat versions contain no heartbeat records at all; for those, the walk falls back to the wider 10-minute activity window, so old in-flight sessions are not re-classified mid-upgrade. The markRunning comment states the evidence-vs-lease distinction explicitly: freshness is liveness evidence, not a verified process check — a writer killed inside the window still reports running until the window lapses.
  • Status & JSON contract (cmd/opencodereview/session_cmd.go): describeStatus renders running before aborted. Summary.Running (json:"running,omitempty") documents that running and aborted are not mutually exclusive: aborted keeps its file-based meaning (true until session_end reaches disk, preserving resume semantics and existing consumers), and running takes precedence when both are set. The same rule, the status vocabulary, and the two windows are documented in the ocr session list section of the CLI reference (en/zh/ja/ko/ru), with a pin test keeping the docs present.

A session that stops receiving heartbeats without a session_end still shows aborted once the window lapses — a real interruption. The on-disk format only gains one ignorable record type; backward compatible in both directions.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)

How Has This Been Tested?

New unit tests (following the existing patterns in list_test.go / persist_test.go):

Writer side (persist_test.go):

  • TestJSONLWriterHeartbeatRecordsReachDiskWhileQuiet — beats reach disk at interval with no other records, and stop for good at the writer's close.
  • TestJSONLWriterHeartbeatStopsAtSessionEnd — session_end remains the last physical record; no beat lands after it.

Reader side (list_test.go) — the cases requested in review:

  • Live but quiet request: TestListSessions_QuietLiveHeartbeatWriterStaysRunning — a writer whose heartbeat goroutine is still running while ListSessions reads the file: only session_start plus heartbeat records exist, no progress/request-boundary record ever appears, and the session reports running.
  • Recently terminated writer: TestListSessions_TerminatedHeartbeatWriterNotRunningAfterWindow — still running right after the kill (the documented bounded residual), then aborted/not-running once past livenessWindow, even though heartbeat records exist in the file.
  • Killed before the first periodic beat (the startup-window regression from the latest review): TestListSessions_KilledBeforeFirstPeriodicBeatUsesLivenessWindow — the file's only heartbeat is the synchronous initial beat; aged past livenessWindow but still inside legacyActivityWindow, the session must no longer report running (with the legacy window it wrongly would).
  • Finalized session: TestListSessions_FinalizedFreshFileNeverRunning — a fresh file with session_end never reports running.
  • Plus TestListSessions_MarksFreshUnfinishedSessionRunning / TestListSessions_StaleUnfinishedSessionNotRunning (legacy-window files, simulated with a zero heartbeat interval) and TestSessionDisplayMarksRunningBeforeAborted (precedence).

All new heartbeat/running tests were additionally run with -count=3 to guard against timing flakiness.

  • Full suite locally: go test -count=1 ./... excluding /extensions/ — all ok, 0 failures; total coverage 91.5% (above the 90% CI gate).
  • Every other CI step replayed locally against .github/workflows/ci.yml on this head: generated provider presets, license headers, action pins, english-only check, gofmt -s -l ., line endings (LF in committed blobs), go mod tidy (no diff), go vet ./..., govulncheck (0 vulnerabilities affecting code), Node launcher test, build + smoke test, and the full cross-compile matrix (linux/arm64, darwin/amd64, darwin/arm64, windows/amd64, windows/arm64) — all pass.
  • make test with -race: not run on this machine — Windows without a C compiler, and -race requires CGO. The CI Linux job runs it (verified in ci.yml; the Windows CI job skips -race for the same reason). The new goroutine writes only under the writer's existing mutex, and both close paths stop it before closing the file, outside the lock.
  • Manual testing (Windows 11, Go 1.27.0, real provider), two runs against a 2-file demo repo with the patched binary:
    • Run A — live and quiet: 15s into the run, while the writer sat inside its first provider request, ocr session list showed running, and the session file's record order was session_start, heartbeat, llm_request, … — the initial beat lands immediately after session_start, and the 60s periodic beat landed during the same quiet stretch. Killing the process mid-request froze the heartbeat count (no further records of any type; last record llm_request) and the session stayed running — the documented residual, bounded by 3 missed beats. Aging the file 4 minutes (past the 3-minute liveness window, inside the 10-minute legacy window) flipped it to aborted.
    • Run B — killed before the first periodic beat, the reviewed edge case: the process was killed 18s after startup. The file contained exactly one heartbeat — the synchronous initial beat (session_start, heartbeat, llm_request); on the previous revision it would have contained none and been classed legacy. Right after the kill ocr session list showed running; after aging the file 4 minutes it showed aborted, i.e. the heartbeat liveness window applied from the session's first seconds instead of the 10-minute legacy window.

Screenshots

N/A (pure code; terminal output summarized above).

Checklist

  • My code follows the project's coding style (go fmt, go vet both clean)
  • 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 — ocr session list status semantics and the running/aborted precedence rule added to the CLI reference in all five locales
  • 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 per the project's AI-assisted development policy: developed with the ZCode agent using GLM (glm-5.3-flash). I have reviewed every line of the diff and can explain and defend any part of it.

Related Issues

Closes #1588

@CLAassistant

CLAassistant commented Sep 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

Copy link
Copy Markdown
Contributor

✅ OpenCodeReview: Review complete: 0 finding(s) across 2 selected item(s).

@Qiyuanqiii Qiyuanqiii left a comment

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.

Reviewed a5e7aef. The missing distinction between unfinished and actively running sessions is real, but file modification time is not sufficient to expose a definitive liveness state.

An unfinished session whose writer has just been killed is still reported as running for up to ten minutes. Conversely, a live operation that produces no session record for more than ten minutes is reported as aborted. Longer configured provider requests or retry waits can reach the latter case without the process having died.

One important detail: the writer does not append only when a file finishes. AppendTaskRecord, SetResponse, and tool-result recording also write JSONL entries. Therefore a long overall subtask alone is not the reproduction; the relevant case is a live interval with no completed/request-boundary record long enough to exceed this window.

Please distinguish observed activity from verified liveness. An explicit owner/lease or heartbeat mechanism is one option; a clearly named activity heuristic with an unknown/suspected state is another. Merely increasing the fixed window still cannot establish whether the writer is alive.

Please cover a recently terminated writer, a live but quiet request, and a finalized session. Also document the JSON interpretation: the current design can emit both running: true and aborted: true, so consumers need an explicit precedence rule rather than assuming those flags are mutually exclusive.

@weiconghe
weiconghe force-pushed the fix/session-list-running-status branch from a5e7aef to 960891f Compare September 30, 2026 10:04
@weiconghe

Copy link
Copy Markdown
Author

@Qiyuanqiii addressed in 960891f by replacing the append-activity heuristic with an explicit heartbeat — your first suggested option.

Writer side (internal/session/persist.go): the JSONL writer now runs a liveness loop that appends a flushed heartbeat record every 60s for the whole life of the run, stopping at session_end (and at the writer's close path) via an idempotent stop that waits out any in-flight beat. Because the loop is an independent goroutine, the file keeps receiving records while the run sits inside one long provider request or retry wait with no completed/request-boundary record — exactly the interval you identified as the real reproduction. Readers that don't know the record type ignore it, the same way they ignore resume_lineage.

Reader side (internal/session/list.go): running now means heartbeat evidence is fresh — three missed beats, so a killed writer masquerades as running for at most ~3 minutes instead of ten. The residual is stated in the markRunning comment as evidence, not a lease. Session files written by pre-heartbeat versions contain no heartbeat records; for those, the walk falls back to the previous 10-minute activity window, so this change does not re-classify old in-flight sessions mid-upgrade. No window had to grow: with heartbeats, the window only bounds the kill residual, it never has to cover request duration.

The three requested cases are covered by unit tests and a manual run:

  • Recently terminated writer — TestListSessions_TerminatedHeartbeatWriterNotRunningAfterWindow: still running right after the kill (the documented bounded residual), not-running/aborted once past the window, even though heartbeat records exist in the file.
  • Live but quiet request — TestListSessions_QuietLiveHeartbeatWriterStaysRunning: the file contains only session_start plus heartbeat records; no progress or request-boundary record ever appears, and the session stays running. TestJSONLWriterHeartbeatRecordsReachDiskWhileQuiet pins the writer half.
  • Finalized session — TestListSessions_FinalizedFreshFileNeverRunning: a fresh file with session_end never reports running.

JSON interpretation documented: Summary.Running's doc comment and the ocr session list section of the CLI reference (all five locales, with a pin test) now state that running and aborted are not mutually exclusive — aborted keeps its file-based meaning (true until session_end reaches disk) and running takes precedence when both are set, exactly as the status column does.

Manual check (Windows 11, real provider, 8-file range review): 75s into the run — while the writer was inside an LLM request with no record written in that window beyond the beat — ocr session list showed running and the JSONL contained exactly one heartbeat; killing the process mid-request froze the beat count, and a completed run reported complete.

@Qiyuanqiii Qiyuanqiii left a comment

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.

Reviewed the updated head 960891f.

The heartbeat-based direction addresses the main concern from my previous review much better than the original append-activity heuristic. In particular, a quiet provider request can now keep producing explicit liveness evidence independently of request/progress records, and stopping the heartbeat before session_end avoids a write-after-finalization race.

I found one remaining edge case in the new/legacy distinction.

markRunning selects the shorter livenessWindow only after the reader has already seen at least one heartbeat record. A current-version writer does not emit its first heartbeat until 60 seconds after startup. Therefore, if a new writer is killed before that first heartbeat, its file contains no heartbeat at all and is indistinguishable from a pre-heartbeat session:

new writer starts
→ session file created / session_start written
→ process dies at e.g. 5s
→ no heartbeat record exists
→ sawHeartbeat == false
→ legacyActivityWindow (10m) is used

So a current-version run killed during its first minute can still be reported as running for close to ten minutes, rather than the documented ~3-minute residual for heartbeat-enabled writers.

Please make heartbeat capability identifiable independently of whether the first periodic beat has happened. For example, the current format could mark heartbeat support in session_start, or emit an initial heartbeat synchronously after session_start before starting the periodic loop. The important part is that a new-format session killed before its first periodic tick must still select the heartbeat liveness window.

Please add a regression for:

  1. create a current-version session,
  2. terminate it before the first periodic heartbeat,
  3. age the file past livenessWindow but keep it younger than legacyActivityWindow,
  4. verify it is no longer reported as running.

There is also a test-coverage detail worth correcting while touching this area: TestListSessions_QuietLiveHeartbeatWriterStaysRunning currently calls writeKilledHeartbeatSession, which stops the heartbeat and closes the writer before ListSessions is invoked. It therefore exercises a freshly terminated writer, not an actually live quiet writer. The separate writer test proves heartbeats are emitted while alive, but having the reader test query a writer whose heartbeat goroutine is still running would make the intended integration contract explicit.

Other than this startup-window distinction, I did not find another code-level blocker in the revised heartbeat implementation.

… session list

An unfinished session (no session_end record yet) is indistinguishable
from an interrupted one, so ocr session list showed live reviews as
aborted until they finished. The writer now emits a flushed heartbeat
record every 60s — liveness evidence that keeps the file fresh through
long provider requests and retry waits, which no fixed append-activity
window could cover — and the listing path reports an unfinished session
as running while that evidence is fresh (three missed beats). Files
written by pre-heartbeat versions keep the wider activity window.

Aborted keeps its file-based meaning (true until session_end reaches
disk) so resume logic and existing JSON consumers are unaffected; the
running/aborted precedence rule is documented in the CLI reference.
@weiconghe
weiconghe force-pushed the fix/session-list-running-status branch from 960891f to b96d01f Compare September 30, 2026 17:23
@weiconghe

Copy link
Copy Markdown
Author

Thank you for the careful review — the startup-window gap was real, and it is fixed on the new head b96d01f (amended into the same commit, force-pushed).

Initial heartbeat instead of a format marker. I took your second option: WriteSessionStart now appends one synchronous heartbeat immediately after the session_start record, before the periodic loop starts (internal/session/persist.go). "At least one heartbeat record" is therefore a property of every file this version writes from its first moments, so sawHeartbeat selects livenessWindow no matter when the writer died — including inside the first interval. The loop is now started from WriteSessionStart rather than at file open, which keeps the record order stable (session_start first) and needs no session_start schema change; a guard makes the start idempotent, and the existing stop-before-close paths are unchanged. I kept the degenerate-interval branch as the way tests simulate pre-heartbeat (legacy) writers.

Regression test. TestListSessions_KilledBeforeFirstPeriodicBeatUsesLivenessWindow in internal/session/list_test.go follows your script: with a one-minute interval no periodic tick fires, a session is created and terminated without session_end, and the test first asserts the file holds exactly the one initial beat. Right after the kill the session reports running; after aging the file past livenessWindow while keeping it younger than legacyActivityWindow (-2 * livenessWindow = 6 min), it reports neither running nor a flip of aborted semantics — on the previous revision the legacy window would have kept it running there.

Live-writer test corrected. TestListSessions_QuietLiveHeartbeatWriterStaysRunning no longer uses writeKilledHeartbeatSession. It now creates the writer, lets beats land during a quiet interval, and calls ListSessions while the heartbeat goroutine is still running; flushAndClose is deferred so the goroutine never outlives the test. writeKilledHeartbeatSession remains for the terminated-writer tests.

Verification on this head (all local, real runs): gofmt -s, go vet ./..., full go test -count=1 ./... green with total coverage 91.5%, the heartbeat/list tests additionally with -count=3, plus the other CI-equivalent checks (license/action-pins/english-only/presets/tidy/govulncheck/smoke/launcher/cross-compile matrix). Manually, with the patched binary against a real provider: a run killed 18s after startup left exactly session_start, heartbeat, llm_request in its file — the single initial beat — showed running immediately after the kill, and flipped to aborted once the file was aged 4 minutes (past the 3-minute window, inside the legacy 10). -race is still not runnable on this Windows machine (no CGO); the CI Linux job covers it, and the new write happens on the session-creation path under the writer's existing mutex.

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.

Session list reports running sessions as "aborted" until they finish

3 participants