Skip to content

fix(llmloop): stop retrying a failed compression snapshot - #2028

Open
cosolar wants to merge 2 commits into
alibaba:mainfrom
cosolar:fix/compression-failed-snapshot-retry
Open

cosolar wants to merge 2 commits into
alibaba:mainfrom
cosolar:fix/compression-failed-snapshot-retry

Conversation

@cosolar

@cosolar cosolar commented Nov 21, 2026 •

Copy link
Copy Markdown

Description

Background memory compression has no failure memory. When a compression request fails, triggerAsyncCompression clears pendingJob and logs the error; the next addNextMessage sees the history still above the soft limit and starts the same request again. The synchronous path had the same gap: it logged the failure but did not record it. With a deterministic rejection such as a context-window overflow, the unchanged oversized snapshot is resubmitted every round, so the run never makes progress and never records an incomplete outcome.

This change records the failed snapshot and applies a finite policy to both compression paths:

  • compressionSnapshotID fingerprints the visible content sent to the compressor (Role, ExtractText, ToolCallID, tool calls). Native replay state is excluded because compression does not send it.
  • On failure, the snapshot ID and attempt count are stored in compressionState. Both asynchronous jobs and synchronous compress() calls use the same recordCompressionFailure / recordCompressionSuccess helpers.
  • Deterministic failures (token budget, HTTP 400/401/403/404/413/422) block the snapshot immediately.
  • Transient failures get one retry; a second failure blocks the snapshot.
  • A genuinely changed history produces a new fingerprint and is allowed to try again.
  • addNextMessage stops with StopCompression when the current snapshot is blocked, but appends the assistant message and tool results first, so the latest turn is not dropped from the conversation. The original failed request and its error remain in the session record.

Classification uses llm.ErrTokenBudget and llm.ProviderHTTPStatus only, consistent with the internal/llm rule that retry classification never reads message text. compressionBlocked also short-circuits while no failure is recorded, so the happy path does not hash the snapshot.

Related Issue: Fixes #1877

AI Assistance

This change was prepared with AI assistance from TraeCode (DeepSeek-V4.1-Flash). I reviewed and understand every line, and ran the tests below locally.

Testing

$ go test ./internal/llmloop -count=1
ok  	github.com/alibaba/open-code-review/internal/llmloop	0.663s

$ go test -race ./internal/llmloop -count=1
ok  	github.com/alibaba/open-code-review/internal/llmloop	4.256s

$ make check
check passed

$ go build ./...

New tests:

  • TestAsyncCompression_DeterministicFailureBlocksSnapshot: one request for the failed snapshot, no resend after failure, and a changed snapshot is allowed to retry.
  • TestAsyncCompression_TransientFailureRetriesOnce: one retry, then the snapshot is blocked.
  • TestAddNextMessage_StopsOnBlockedCompression: the main loop returns StopCompression and still appends the assistant/tool messages.
  • TestSyncCompressionFailureBlocksSnapshot: a synchronous 400 is recorded and the next turn sends no new request.
  • TestPermanentCompressionFailure: error type/status classification.
  • TestCompressionSnapshotID: content, role, and tool-call changes alter the fingerprint.

Checklist

  • make check passes
  • go test -race ./internal/llmloop passes
  • go build ./... passes
  • New files include the SPDX license header
  • Commit author/committer is the contributor; no AI attribution trailers

Record the failed snapshot fingerprint and block resubmission after a deterministic provider rejection or one transient retry. The next main-loop step returns StopCompression instead of sending the unchanged oversized history again. Refs alibaba#1877.
@CLAassistant

CLAassistant commented Nov 21, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@github-actions

github-actions Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

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

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

bug · medium

📄 internal/llmloop/loop.go (L590-L598)

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

The synchronous compress() closure calls runCompression but does not record failures into compressionState. The blocking mechanism only tracks failures from async compression jobs (in triggerAsyncCompression's goroutine). If synchronous compression at line 602 or 619 fails with a permanent provider rejection (e.g., HTTP 400), the failure is logged but not tracked, so the next turn will resubmit the identical request.

Consider recording synchronous compression failures into st using the same failedSnapshotID/failedRetries/blocked logic used in the async path, so that deterministic rejections are blocked regardless of which code path triggers them.

Comment on lines +131 to 136
func (st *compressionState) compressionBlocked(messages []llm.Message) bool {
snapshotID := compressionSnapshotID(messages)
st.mu.Lock()
defer st.mu.Unlock()
return st.blocked && st.failedSnapshotID == snapshotID
}

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
In the common case where no compression failure has occurred (st.blocked == false), this method still computes the full snapshot hash by iterating all messages and calling ExtractText() on each one. Since compressionBlocked is called on every turn in addNextMessage, this adds unnecessary CPU and allocation overhead for the happy path.

Consider short-circuiting with a lock-guarded read of st.blocked first, and only computing the snapshot ID when there is actually a prior failure to compare against.

Suggestion:

Suggested change
func (st *compressionState) compressionBlocked(messages []llm.Message) bool {
snapshotID := compressionSnapshotID(messages)
st.mu.Lock()
defer st.mu.Unlock()
return st.blocked && st.failedSnapshotID == snapshotID
}
func (st *compressionState) compressionBlocked(messages []llm.Message) bool {
st.mu.Lock()
if !st.blocked {
st.mu.Unlock()
return false
}
failedID := st.failedSnapshotID
st.mu.Unlock()
snapshotID := compressionSnapshotID(messages)
return failedID == snapshotID
}

Comment thread internal/llmloop/loop.go Outdated
Comment on lines +587 to +589
if st.compressionBlocked(*messages) {
return StopCompression
}

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 · high
Bug: When compression is blocked, this early return prevents the assistant message and tool results from being appended to messages (that happens at lines 604-612 below). The caller in runMainLoop breaks out of the loop on any non-StopNone return, so the latest LLM response and tool call results are silently dropped from the conversation.

The blocking check should either be moved after the message appends, or the appends should happen before this check. The intent is to stop compression retries, not to discard the current turn's messages.

Apply the failed-snapshot policy to the synchronous compression path as well, and keep the current turn's assistant and tool messages when compression is blocked. Also skip the snapshot hash while no failure is recorded. Refs alibaba#1877.
@cosolar

cosolar commented Nov 21, 2026

Copy link
Copy Markdown
Author

Addressed the three self-review findings in a732d47:

  • Synchronous compress() failures now go through the same compressionState failure tracking as async jobs, so a 400/token-budget rejection is not resubmitted on the next turn.
  • The blocked check now runs after the assistant message and tool results are appended, so the current turn is preserved in the conversation before StopCompression is returned.
  • compressionBlocked short-circuits while no failure is recorded, avoiding the snapshot hash on the happy path.

Added TestSyncCompressionFailureBlocksSnapshot and extended TestAddNextMessage_StopsOnBlockedCompression to cover both behaviors.

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.

Failed async compression clears the pending job and can resubmit the unchanged oversized snapshot

2 participants