Skip to content

fix(llm): report a request's total wall clock, not just per-attempt timings - #1788

Open
ydflow wants to merge 3 commits into
alibaba:mainfrom
ydflow:fix/retry-total-elapsed
Open

ydflow wants to merge 3 commits into
alibaba:mainfrom
ydflow:fix/retry-total-elapsed

Conversation

@ydflow

@ydflow ydflow commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

AI disclosure

I used an AI coding assistant (Claude, via the WorkBuddy agent) to help audit the retry-report code, draft the change and write the tests. I read through the original diff myself and can explain any part of it. The follow-up changes and regression tests were developed with OpenAI Codex (GPT-6).

Problem

The retry report cannot answer the question an operator actually asks when a review feels slow: how long did one logical request hold the run?

Two numbers exist today, and neither is that one:

  • duration_to_headers_ms stops when the response headers arrive — it excludes body read, decode and the whole stream.
  • observed_backoff_ms only covers the gap between two attempts.

Because the clients are built with WithMaxRetries(5), one logical request can make six real HTTP attempts, each allowed a full OCR_LLM_TIMEOUT (300s by default). Add the backoff between them and a single request can wait roughly 25 minutes while every single number in the report looks reasonable. The thing that bounds the run is the group deadline (--timeout), and that deadline is charged for the whole request — so the report and the run disagree about what a request cost.

There is also no reference point: a total of "18 minutes" means nothing without the per-attempt budget it was supposed to fit inside.

The gap is worst for streamed requests. The retry observer is an SDK middleware, so it sees the response headers and nothing afterwards. A stream that runs for four minutes currently measures as the few milliseconds it took to open it — the report excludes exactly the requests that wait longest.

This is the reporting half of the envelope described in #1717 (a stalled request that looks like 0% CPU for many minutes with no visible retry). I am not claiming to fix that hang here; this PR makes the wait measurable and attributable so the next report can show where the time went.

Change

Per request — RequestReport.TotalElapsedMS

Spans the first attempt's start through completion of the logical request, including backoff and body reads. A pointer, so a sub-millisecond wait serializes as 0 instead of disappearing behind omitempty.

Per run — RetryReport.TotalElapsedMS and AttemptTimeoutMS

The same total across the listed requests, next to the per-attempt budget those requests were each meant to fit inside. The budget is passed at construction (NewRetryCollectorWithAttemptTimeout) rather than read at freeze time, because the endpoint config is gone by then. NewRetryCollector still exists and builds a timing-only collector.

Request completion

The shared client boundary supplies the completion timestamp when it finalizes a Chat Completions, Responses or Anthropic request. This covers streaming, non-streaming body reads and cancellation during SDK backoff. The observer continues to record per-attempt time to headers.

Terminal summary

LLM wait across listed requests: 24.0m (per-attempt budget 5.0m)

The suffix is dropped when no budget was set, and the line is absent when nothing was measured.

Design notes

  • The collector stays a pure aggregator: it still reads no clock. Every timestamp comes from the caller.
  • The final timestamp can only advance the observed end. Finalization skips requests with no observed attempt.
  • Concurrent requests each contribute their own elapsed time to the sum across listed requests.
  • The run total saturates at MaxInt64 instead of wrapping, so an overflow cannot turn a very long wait into a short one.
  • No new plain-string field was added, so TestRetryReportHasNoUnexpectedTextFields (the structural redaction guarantee) is unchanged.

Tests

Test What it proves
TestFreezeReportsTotalElapsedAcrossAttemptsAndBackoff 10s + 15s attempts with 20s backoff report 45000, not 25000
TestFreezeOmitsAttemptTimeoutWhenUnset a timing-only collector measures the total and invents no budget
TestBoundaryMeasuresFinalBodyAndBackoff exercises a recovered non-streaming response, an invalid delayed body and cancellation during SDK backoff with a fake clock; all three preserve the per-attempt header duration
TestFinalizeAtKeepsObservedEnd an earlier completion timestamp cannot shorten the observed elapsed time
TestStreamedRequestElapsedCoversTheStream a real client against a real SSE server that flushes a chunk, sleeps 250ms, then sends [DONE]: the request's elapsed is ≥250ms while duration_to_headers_ms stays far below it
TestAddMillisSaturatesInsteadOfWrapping the run total cannot wrap negative
TestTotalElapsedSerializesAsZeroNotOmitted the JSON wire names and the zero-not-omitted rule
TestOutputRetryReportText_ShowsTotalWait the summary line, its budget suffix, and its absence cases
TestFormatElapsedMS one decimal, s → m → h, including the boundaries

On the previous PR head, the two delayed-body cases reported 1000 ms instead of 1250 ms and cancellation reported 0 ms instead of 100 ms. The new regression exercises the real Chat Completions client and SDK retry loop using an in-process transport.

Verification

At 6ab9996, make check and the full make test (25 packages, race detector enabled) passed on Windows with Git 2.56. The focused timing tests passed ten consecutive runs; internal/llm statement coverage was 95.3%. The pre-commit ocr review (GPT-6.2 Sol) selected four items and reported zero findings.

Original checks:

go build ./...                       ok
go vet ./...                         ok
go test ./... -count=1               ok (all 25 packages)
scripts/verify-license.sh            All source files have valid license headers.
scripts/verify-english-only.go       No unapproved non-English text in 794 files.
coverage ./internal/llm              95.3% (threshold 90%)

-race could not be run locally: this machine is Windows without a C compiler, and -race requires cgo. CI will cover it. TestLazyFileWriter_PreservesSymlinkTarget is skipped locally because it is Windows-only-hostile; it is untouched by this change.

Duplicate check

I searched open PRs and issues for retry, elapsed, timeout, wall clock and duration:

No existing PR adds a wall-clock total to the retry report.

Scope

Purely additive to the JSON contract: both new run-level fields use omitempty-with-pointer semantics and every existing field keeps its name and meaning. The text summary gains one line.

…imings

A request whose six attempts each timed out at OCR_LLM_TIMEOUT added up to
roughly 25 minutes of waiting that appeared nowhere in the retry report: the
per-attempt duration stops at the response headers and the backoff only covers
the gap between attempts. The group deadline is charged for the whole request,
so add that missing measurement per request and per run, alongside the
per-attempt budget it was meant to fit inside, and advance a streamed request's
clock to the end of the stream instead of leaving it at the headers.
The new summary line is only useful if it renders the wait in a unit an
operator can read, and only if it stays absent when nothing was measured.
Cover both, plus the hour boundary the formatter switches on.
@github-actions

github-actions Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

  • ✅ Successfully posted inline: 1 comment(s)
  • ❌ Failed to post inline: 1 comment(s)

bug · medium

📄 internal/llm/retry_report.go (L790-L793)

⚠️ GitHub could not post this as an inline comment: Lines 790-793 could not be resolved (outside PR diff hunks)

The new TotalElapsedMS aggregate is accumulated in Freeze but never cross-checked in validateReport. The function's own doc comment states: "Every aggregate except TotalRequests is recomputed from the listed requests and compared with the value accumulated over all entries." All other aggregates (TotalRetries, RetriedRequests, RecoveredRequests, FailedRequests, CancelledRequests) have corresponding validation, but TotalElapsedMS does not.

This means a bug in the elapsed-time accumulation (e.g., double-counting, missed entries, or an addMillis regression) would silently produce incorrect totals without the invariant check catching it. Consider adding a totalElapsed accumulator in the validation loop that sums *r.TotalElapsedMS for each listed request and compares it against *rep.TotalElapsedMS.

Comment on lines +532 to +533
func formatElapsedMS(ms int64) string {
d := time.Duration(ms) * time.Millisecond

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 · low
Potential integer overflow: addMillis saturates at math.MaxInt64, but time.Duration(ms) * time.Millisecond multiplies by 1e6 internally (converting ms → ns). If ms exceeds ~9.2e12 (≈292 years in ms), this multiplication overflows int64, producing a negative duration and output like -0.1s.

While practically unreachable, the explicit saturation in addMillis suggests defensive intent at this boundary. Consider capping ms before the conversion, e.g.:

if ms > int64(time.Duration(math.MaxInt64)/time.Millisecond) {
    d = time.Duration(math.MaxInt64)
} else {
    d = time.Duration(ms) * time.Millisecond
}

Or saturate addMillis at math.MaxInt64 / 1e6 so the conversion is always safe.

@NanaseInori NanaseInori left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed the complete ten-file diff, the common finalization path, #1717 and the existing discussion. The TotalElapsedMS search returned only this PR. Measuring logical-request wait is distinct from limiting retries or tracing individual HTTP attempts.

[P2] Advance the request end at the common client boundary, not only in the two streaming wrappers. The new elapsed() uses lastAttemptEnd, which RecordAttempt sets when headers arrive. Only completionsStreaming and responsesStreaming now extend it. For non-streaming Chat, Responses and Anthropic calls, finalizeRequest still invokes ReviseLastAttempt with a zero timestamp and then Finalize without updating the clock.

Consequently, a listed request that receives 200 headers promptly and then spends its timeout waiting for a non-streaming body is still reported as taking only the header latency—the exact blind spot this feature intends to explain. Cancellation during SDK backoff after the last observed attempt has the same missing-tail problem. A recovered non-streaming request also omits the final successful body's wait.

Please supply the logical completion timestamp to the shared finalization boundary before freezing the request, keeping the collector clock-free and duration_to_headers_ms unchanged. Add delayed non-streaming success/failure coverage and a cancellation-during-backoff case; the current SSE test only proves the specially instrumented path. Preserve the no-attempt/no-entry behavior.

References: finalizeRequest still carries no end timestamp, SDK body reading after the observer/retry loop.

The run-level sum is also cumulative wait across listed requests, not elapsed wall time of a concurrent run; the terminal label correctly says 'across listed requests' and should retain that distinction. I am not elevating the existing practically unreachable formatting-overflow observation into another blocker.

Validation was source/test inspection. The delayed-body outcome above follows from the timestamp call graph; I did not independently execute a delayed-body client reproduction, the SSE test, or the full repository suite.

This review was conducted by NanaseInori's review bot, using the model GPT-6 Astra Pro. If you need a human review, please manually @NanaseInori.

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.

2 participants