Skip to content

fix: remove heartbeat transcript pruning to prevent session corruption - #60998

Merged
obviyus merged 11 commits into
openclaw:mainfrom
nxmxbbd:fix/heartbeat-prune-race-condition
Apr 6, 2026
Merged

obviyus merged 11 commits into
openclaw:mainfrom
nxmxbbd:fix/heartbeat-prune-race-condition

Conversation

@nxmxbbd

@nxmxbbd nxmxbbd commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #39609 — heartbeat transcript pruning via fs.truncate races with concurrent session writers, causing orphaned parentId chains, context collapse, and data loss.

Changes

  1. Remove pruneHeartbeatTranscript() and captureTranscriptState() from src/infra/heartbeat-runner.ts. These used fs.truncate on live session JSONL files without holding the session write lock. HEARTBEAT_OK entries now stay in the JSONL file (append-only).

  2. Filter heartbeat pairs at context build time — New filterHeartbeatPairs() in src/auto-reply/heartbeat-filter.ts removes no-op heartbeat user+assistant pairs from the message array before each model prompt. Only filters pairs where the user message contains the HEARTBEAT_OK instruction AND the assistant response is purely the token (no real content). Applied in src/agents/pi-embedded-runner/run/attempt.ts.

  3. Clean up heartbeat pairs during compaction — truncateSessionAfterCompaction() in src/agents/pi-embedded-runner/session-truncation.ts now also drops filtered heartbeat pairs when rewriting the session file. Compaction already holds the session write lock, so this is safe.

Excluded alternatives

  • Acquiring the session write lock for heartbeat: too invasive, blocks normal turns during heartbeat I/O which can be slow
  • Writing heartbeat entries to a separate file: adds complexity to session reconstruction and compaction without clear benefit
  • Using file-level locking (flock): not portable and doesn't compose with the existing session lock model

Test plan

  • New unit tests for filterHeartbeatPairs, isHeartbeatUserMessage, isHeartbeatOkResponse (18 cases)
  • Updated transcript prune tests to verify append-only behavior
  • Existing session-truncation tests pass (9 cases)
  • pnpm check passes (pre-existing TS errors only, unrelated to this change)

🤖 Generated with Claude Code

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Apr 4, 2026
@greptile-apps

greptile-apps Bot commented Apr 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR replaces the racey fs.truncate-based heartbeat transcript pruning with an append-only JSONL strategy: heartbeat user+assistant pairs are kept on disk, filtered from the in-memory message array at context-build time in attempt.ts, and physically removed during the compaction pass in session-truncation.ts which already holds the session write lock. The approach is sound and directly addresses the race that caused orphaned parentId chains.

Confidence Score: 5/5

Safe to merge — the core race condition fix is correct and the only finding is a minor false-negative edge case in the new filter that, at worst, leaves extra heartbeat pairs in context until compaction.

All findings are P2. The trim-ordering issue in stripMarkup is a false-negative (not a false-positive), so the worst outcome is slightly more context growth between compactions, not data corruption or session misidentification. The primary goal of eliminating the fs.truncate race is fully achieved.

src/auto-reply/heartbeat-filter.ts — stripMarkup trim ordering

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/auto-reply/heartbeat-filter.ts
Line: 45-55

Comment:
**Trim ordering leaves trailing markup after newlines**

The `.trim()` call runs after the regex stripping, not before. For a model response like `"**HEARTBEAT_OK**\n"` (trailing newline is common in streamed output): the leading `**` is stripped correctly, but the trailing-markup regex `/[*\`~_]+$/` fails to match because `$` anchors to the end of the string after the `\n`. The final `.trim()` then produces `"HEARTBEAT_OK**"`, which doesn't equal `HEARTBEAT_TOKEN`, so the pair silently escapes filtering and accumulates in context until compaction.

Adding an intermediate `.trim()` before the regex passes fixes this:

```suggestion
function stripMarkup(text: string): string {
  return (
    text
      .replace(/<[^>]*>/g, " ")
      .replace(/&nbsp;/gi, " ")
      .trim()
      // Strip leading/trailing markdown wrappers
      .replace(/^[*`~_]+/, "")
      .replace(/[*`~_]+$/, "")
      .trim()
  );
}
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "feat: filter heartbeat pairs in context ..." | Re-trigger Greptile

Comment thread src/auto-reply/heartbeat-filter.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 757e88a697

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-prune-race-condition branch from 757e88a to cff7c23 Compare April 4, 2026 18:30

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cff7c23237

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/heartbeat-filter.ts Resolved
Comment thread src/auto-reply/heartbeat-filter.ts Resolved
@nxmxbbd

nxmxbbd commented Apr 4, 2026

Copy link
Copy Markdown
Contributor Author

Fixed the trim ordering issue flagged by Greptile in cff7c23 --- stripMarkup() now trims whitespace before stripping markdown wrappers, so streamed responses like "**HEARTBEAT_OK**\n" are correctly recognized.

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-prune-race-condition branch from cff7c23 to 4505d17 Compare April 6, 2026 09:06

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4505d17679

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-prune-race-condition branch from 4505d17 to 9e424c5 Compare April 6, 2026 09:12
@nxmxbbd

nxmxbbd commented Apr 6, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in 9e424c53 — the duplicate Ollama import was a rebase artifact (upstream moved from plugin-sdk/ollama-runtime.js to extensions/ollama/runtime-api.js; conflict resolution kept both). Removed the stale import path.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9e424c53a8

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

@nxmxbbd
nxmxbbd force-pushed the fix/heartbeat-prune-race-condition branch 2 times, most recently from 6e189a1 to 8175727 Compare April 6, 2026 09:25
@nxmxbbd

nxmxbbd commented Apr 6, 2026

Copy link
Copy Markdown
Contributor Author

CI note (rebase 2026-04-06)

Rebased onto 1a270f81c3 and addressed all bot review feedback (P1 compaction tail, P2 user detection narrowing, P2 response variant matching). CI is re-running — extension shard failures on prior runs were upstream flaky tests (same pattern as merged #61739).

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1dbdddca74

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/heartbeat-filter.ts Resolved
Comment thread src/auto-reply/heartbeat-filter.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 140e658d51

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/heartbeat-filter.ts Resolved
@nxmxbbd

nxmxbbd commented Apr 6, 2026

Copy link
Copy Markdown
Contributor Author

@obviyus This is part of the same heartbeat bug series as #53740 --- fixes a race condition in transcript pruning that can corrupt session files. All bot feedback addressed.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 630ac72061

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/auto-reply/heartbeat-filter.ts Resolved
Comment thread src/auto-reply/heartbeat-filter.ts Resolved

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ce10d1d83d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@obviyus

obviyus commented Apr 6, 2026

Copy link
Copy Markdown
Collaborator

@nxmxbbd please stop pushing to the PR so that I can land it.

@obviyus
obviyus force-pushed the fix/heartbeat-prune-race-condition branch from 80b0907 to 0c85293 Compare April 6, 2026 10:30
@nxmxbbd

nxmxbbd commented Apr 6, 2026

Copy link
Copy Markdown
Contributor Author

All yours — I'll hold off. Thanks for the cleanup commits, much cleaner with stripHeartbeatToken reuse. 🙏

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0c85293226

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@obviyus obviyus self-assigned this Apr 6, 2026
nxmxbbd and others added 11 commits April 6, 2026 16:21
openclaw#39609)

Remove pruneHeartbeatTranscript() and captureTranscriptState() which used
fs.truncate on live session JSONL files without holding the session write
lock. This caused a race condition where concurrent normal turns could end
up with orphaned parentId chains or data loss when truncation removed
entries appended by other writers.

HEARTBEAT_OK entries now stay in the JSONL file (append-only). They are
filtered out at context build time and cleaned up during compaction.

Excluded alternatives:
- Acquiring the session write lock for heartbeat: too invasive, blocks
  normal turns during heartbeat I/O which can be slow.
- Writing heartbeat entries to a separate file: adds complexity to session
  reconstruction and compaction without clear benefit.
- Using file-level locking (flock): not portable and doesn't compose with
  the existing session lock model.
…claw#39609)

Add heartbeat-filter.ts with functions to identify and filter no-op
heartbeat user+assistant pairs from session context. A pair is filtered
only when the user message contains the HEARTBEAT_OK instruction AND the
assistant response is purely the HEARTBEAT_OK token (no real content).

Integration points:
- attempt.ts: filter messages before each prompt call so heartbeat no-ops
  don't consume context window tokens
- session-truncation.ts: drop heartbeat pairs during compaction rewrite to
  prevent unbounded disk growth from append-only heartbeat entries
Addresses Greptile review feedback: stripMarkup() now trims whitespace
before stripping markdown wrappers, preventing false negatives when
heartbeat responses have leading/trailing whitespace around markup.
- P1: Limit heartbeat pair pruning to summarized portion of branch
  during compaction. Pairs in the unsummarized tail (from
  firstKeptEntryId onward) are preserved to avoid dangling compaction
  boundaries.

- P2: Narrow isHeartbeatUserMessage to require instruction phrase
  pattern ('reply HEARTBEAT_OK' or 'respond...HEARTBEAT_OK'), not
  just the bare token. Prevents false positives on normal conversation
  turns that discuss or quote the token.

- P2: Broaden isHeartbeatOkResponse to handle responsePrefix, emoji
  suffixes, and HTML wrappers — matching the detection logic in
  heartbeat-events-filter.ts. Previously only exact match worked.
- P1: Accept short alphanumeric suffixes after HEARTBEAT_OK, using
  the same DEFAULT_HEARTBEAT_ACK_MAX_CHARS (300) threshold as
  stripHeartbeatToken in heartbeat.ts. Prevents no-op ack turns
  like 'HEARTBEAT_OK all good' from accumulating in JSONL history.

- P2: Broaden instruction verb pattern to cover custom heartbeat
  prompts ('return', 'say', 'output', 'answer' in addition to
  'reply' and 'respond').
runHeartbeatOnce classifies empty replies as 'ok-empty' no-ops, but
isHeartbeatOkResponse returned false for empty content, preventing
filterHeartbeatPairs from removing these turns. Without transcript
pruning, they would accumulate in JSONL indefinitely.
@obviyus
obviyus force-pushed the fix/heartbeat-prune-race-condition branch from 326a6ed to cac52ca Compare April 6, 2026 10:55

@obviyus obviyus left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Reviewed latest changes; landing now.

@obviyus
obviyus merged commit 57f9f0a into openclaw:main Apr 6, 2026
8 checks passed
@obviyus

obviyus commented Apr 6, 2026

Copy link
Copy Markdown
Collaborator

Landed.

Thanks @nxmxbbd.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cac52ca520

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1674 to +1678
const filteredMessages = filterHeartbeatPairs(
activeSession.messages,
heartbeatSummary?.ackMaxChars,
heartbeatSummary?.prompt,
);

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.

P2 Badge Filter heartbeat turns before context shaping passes

filterHeartbeatPairs is applied only at this late stage, but runEmbeddedAttempt has already run limitHistoryTurns(...) and assembleAttemptContextEngine(...) on the unfiltered transcript earlier in the same turn. When no-op heartbeat pairs accumulate, they can consume history slots/token budget and cause real user/assistant turns to be trimmed, and this later filter then drops the heartbeat turns anyway, leaving avoidable context loss for the actual prompt. Heartbeat filtering should happen before history limiting and context-engine assembly.

Useful? React with 👍 / 👎.

@nxmxbbd

nxmxbbd commented Apr 6, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for landing it! The other two in the series (#53740 event drain, #42042 memory watcher) are ready whenever you get a chance — no rush.

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request Sep 29, 2026
@nxmxbbd
nxmxbbd deleted the fix/heartbeat-prune-race-condition branch October 27, 2026 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Main session context collapses onto an orphan branch with Compactions: 0

2 participants