Skip to content

feat(active-memory): return partial transcript on timeout - #73219

Merged
Takhoffman merged 6 commits into
openclaw:mainfrom
joeykrug:feat/active-memory-partial-on-timeout
Apr 28, 2026
Merged

Takhoffman merged 6 commits into
openclaw:mainfrom
joeykrug:feat/active-memory-partial-on-timeout

Conversation

@joeykrug

Copy link
Copy Markdown
Contributor

Summary

When the active-memory recall subagent hits its configured timeoutMs
or is otherwise aborted, the plugin currently discards the partial
output the embedded Pi agent has already written to the session
transcript. This PR recovers that work.

Motivation

Recall runs commonly produce a useful summary in the first 30-60s, then
hit timeoutMs while the model is still finishing. Today the user gets
nothing — { status: "timeout", summary: null } — and the partial
transcript is silently dropped.

Change

  • New timeout_partial variant in ActiveRecallResult.
  • readPartialAssistantText(sessionFile) reads the JSONL on timeout,
    joins assistant text, returns null if empty.
  • Two timeout paths (race-loss, abort-during-await) now return
    timeout_partial when partial text is recoverable, or timeout
    (unchanged) when nothing was written.
  • Status line, prompt prefix, and metadata surface partial output the
    same way ok does.
  • Caching only fires for ok (no caching of partial output).
  • Generic-error unavailable path unchanged.

Tests

7 new tests in extensions/active-memory/index.test.ts cover:

  1. Timeout with partial transcript → timeout_partial
  2. Timeout with empty transcript → timeout
  3. Timeout with no transcript path → timeout
  4. Abort-during-await with partial → timeout_partial
  5. Generic error path unchanged → unavailable
  6. shouldCacheResult(timeout_partial) === false
  7. Status line / prompt prefix / metadata all reflect partial summary

Backward compatibility

timeout_partial is a new discriminant; existing callers that
exhaustively switch on result.status will get a TS error and need to
handle it explicitly (intentional — partial output should be surfaced,
not silently treated as full timeout).

Notes

Reported by Joey Krug; the live config currently has timeoutMs: 90000
on Sonnet 4.6 and was hitting timeouts on long-context Signal recalls.

@greptile-apps

greptile-apps Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a timeout_partial status to ActiveRecallResult so that assistant text already written to the session JSONL file is recovered and surfaced to the user when the recall subagent hits its timeout, rather than being silently discarded. The implementation covers both the race-loss and abort-during-await timeout paths, includes 7 new tests, and correctly skips caching for partial results.

  • P1 – empty result caching accidentally removed: The shouldCacheResult change drops result.status === "empty" alongside the intended exclusion of timeout_partial. Previously, a confirmed "no memories found" result was cached for cacheTtlMs to avoid re-running the expensive subagent. Removing this means every subsequent prompt with an empty memory store pays the full subagent cost.
  • P2 – partial-transcript recovery silently fails when persistTranscripts: false: sessionFile points into the ephemeral tempDir, which the subagent's finally block deletes concurrently with buildTimeoutRecallResult's file read. All current tests use persistTranscripts: true; the feature should be documented as only reliably functional in that mode.

Confidence Score: 3/5

Hold for P1 fix — the accidental removal of empty result caching is a silent performance regression on the hot path.

One clear P1 (unintended removal of empty caching that silently breaks a hot-path optimisation) and one P2 (race with tempDir cleanup). The P1 is a one-line fix but it affects every user whose memory store is empty, so the score sits at 3.

extensions/active-memory/index.ts line 1019 (shouldCacheResult)

Comments Outside Diff (1)

  1. extensions/active-memory/index.ts, line 1841-1854 (link)

    P2 Race between partial-transcript read and tempDir cleanup

    When persistTranscripts: false, sessionFile lives inside the ephemeral tempDir. On a race-loss timeout, buildTimeoutRecallResult awaits readPartialAssistantText(sessionFile) while subagentPromise (now aborted) races to its finally block and calls fs.rm(tempDir, { recursive: true, force: true }). If the cleanup wins, readPartialAssistantText gets ENOENT, returns null, and the partial-recovery silently degrades to plain timeout.

    This is benign in terms of correctness (graceful fallback), but it means the feature only works reliably when persistTranscripts: true. A code comment (or an early return when !sessionFile || !persistedDir) would help future readers understand the implicit assumption.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/active-memory/index.ts
    Line: 1841-1854
    
    Comment:
    **Race between partial-transcript read and `tempDir` cleanup**
    
    When `persistTranscripts: false`, `sessionFile` lives inside the ephemeral `tempDir`. On a race-loss timeout, `buildTimeoutRecallResult` awaits `readPartialAssistantText(sessionFile)` while `subagentPromise` (now aborted) races to its `finally` block and calls `fs.rm(tempDir, { recursive: true, force: true })`. If the cleanup wins, `readPartialAssistantText` gets `ENOENT`, returns `null`, and the partial-recovery silently degrades to plain `timeout`.
    
    This is benign in terms of correctness (graceful fallback), but it means the feature only works reliably when `persistTranscripts: true`. A code comment (or an early return when `!sessionFile || !persistedDir`) would help future readers understand the implicit assumption.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/active-memory/index.ts
Line: 1019-1021

Comment:
**`empty` results silently lost from cache**

`empty` was previously cacheable so that a confirmed "no memories found" result would be reused for `cacheTtlMs` instead of spawning a fresh recall subagent on every request. Dropping it here means back-to-back prompts with an empty memory store each pay the full subagent cost.

The PR description says "Caching only fires for `ok` (no caching of partial output)" but that framing is about the new `timeout_partial` status — `empty` should remain cached unless there's a deliberate reason to change it.

```suggestion
  return result.status === "ok" || result.status === "empty";
```

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

---

This is a comment left during a code review.
Path: extensions/active-memory/index.ts
Line: 1841-1854

Comment:
**Race between partial-transcript read and `tempDir` cleanup**

When `persistTranscripts: false`, `sessionFile` lives inside the ephemeral `tempDir`. On a race-loss timeout, `buildTimeoutRecallResult` awaits `readPartialAssistantText(sessionFile)` while `subagentPromise` (now aborted) races to its `finally` block and calls `fs.rm(tempDir, { recursive: true, force: true })`. If the cleanup wins, `readPartialAssistantText` gets `ENOENT`, returns `null`, and the partial-recovery silently degrades to plain `timeout`.

This is benign in terms of correctness (graceful fallback), but it means the feature only works reliably when `persistTranscripts: true`. A code comment (or an early return when `!sessionFile || !persistedDir`) would help future readers understand the implicit assumption.

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

Reviews (1): Last reviewed commit: "feat(active-memory): return partial tran..." | Re-trigger Greptile

Comment on lines 1019 to 1021
function shouldCacheResult(result: ActiveRecallResult): boolean {
return result.status === "ok" || result.status === "empty";
return result.status === "ok";
}

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.

P1 empty results silently lost from cache

empty was previously cacheable so that a confirmed "no memories found" result would be reused for cacheTtlMs instead of spawning a fresh recall subagent on every request. Dropping it here means back-to-back prompts with an empty memory store each pay the full subagent cost.

The PR description says "Caching only fires for ok (no caching of partial output)" but that framing is about the new timeout_partial status — empty should remain cached unless there's a deliberate reason to change it.

Suggested change
function shouldCacheResult(result: ActiveRecallResult): boolean {
return result.status === "ok" || result.status === "empty";
return result.status === "ok";
}
return result.status === "ok" || result.status === "empty";
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/active-memory/index.ts
Line: 1019-1021

Comment:
**`empty` results silently lost from cache**

`empty` was previously cacheable so that a confirmed "no memories found" result would be reused for `cacheTtlMs` instead of spawning a fresh recall subagent on every request. Dropping it here means back-to-back prompts with an empty memory store each pay the full subagent cost.

The PR description says "Caching only fires for `ok` (no caching of partial output)" but that framing is about the new `timeout_partial` status — `empty` should remain cached unless there's a deliberate reason to change it.

```suggestion
  return result.status === "ok" || result.status === "empty";
```

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in f8d0a240ea: shouldCacheResult now caches ok and empty, while timeout_partial remains excluded. I also added tests for the predicate and for repeated NONE recall using the cached empty result.

@joeykrug

Copy link
Copy Markdown
Contributor Author

Posted fixes for all three flagged items:

  • f8d0a240ea fix(active-memory): cache empty recall results (greptile P1 #73219) restores empty as cacheable while keeping timeout_partial uncached, with predicate coverage and a repeated NONE recall cache test.
  • 3f21697d1c fix(active-memory): bound transcript reads on timeout/abort (Aisle CWE-400 #73219) replaces full transcript reads with bounded streaming JSONL parsing for partial assistant text and memory-search debug recovery. Added coverage for a 5 MB transcript, malformed JSONL, and maxLines enforcement.
  • da86586b8a fix(active-memory): redact partial transcript from debug entries (Aisle CWE-200 #73219) keeps recovered partial text available to the active-memory prompt path but persists only metadata like timeout_partial: <N> chars recovered (not persisted).

Validation:

  • pnpm vitest run extensions/active-memory/index.test.ts: 1 file passed, 73 tests passed.
  • pnpm vitest run extensions/active-memory: 2 files passed, 76 tests passed.
  • pnpm vitest run src/cli/run-main.exit.test.ts on this branch: 1 file passed, 15 tests passed.
  • Checked run-main.exit.test.ts with src/cli/run-main.exit.test.ts and src/cli/run-main.ts from upstream/main: 1 file passed, 15 tests passed. I could not reproduce the reported program.option is not a function failure locally on either main files or this branch.
  • pnpm exec oxfmt --check --threads=1 extensions/active-memory/index.ts extensions/active-memory/index.test.ts: passed.
  • git diff --check -- extensions/active-memory/index.ts extensions/active-memory/index.test.ts: passed.

Note: I also attempted the requested /home/exedev/.openclaw/workspace/scripts/lint-fix.sh .; it entered repo-wide linting, reported unrelated Python/shellcheck findings outside this PR, then hung in the parent bash process with no child fixer running. I interrupted it and reverted the unrelated fixer edits, then ran the scoped formatter/checks above on the touched files.

joeykrug and others added 6 commits April 28, 2026 08:41
When the recall subagent times out (race-loss or abort), the embedded
Pi agent has often written some assistant output to the session JSONL
already. This change reads the partial transcript on timeout, runs it
through the same normalize+truncate pipeline as the success path, and
returns it as a new `timeout_partial` status.

- Adds `timeout_partial` variant to `ActiveRecallResult`
- Reads JSONL transcript on timeout via new `readPartialAssistantText`
  helper
- Threads `sessionFile` out of `runRecallSubagent` so the caller can
  recover partial output even when the subagent never resolves
- Surfaces partial output via status line, metadata, and prompt prefix
  the same as a successful recall
- Skips caching for `timeout_partial` (only `ok` results are cached)
- Generic `unavailable` path unchanged
- Adds 7 tests covering all timeout/abort/error paths

Without this, every recall hitting the configured `timeoutMs` ceiling
discards work the model has already done.
@Takhoffman
Takhoffman force-pushed the feat/active-memory-partial-on-timeout branch from 5e96da4 to 9a61a91 Compare April 28, 2026 13:43
@clawsweeper

clawsweeper Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve.

Keep this PR open. Current main still returns plain timeout with summary: null when Active Memory recall times out, and there is no timeout_partial result or partial transcript recovery on main. The PR is a focused implementation candidate for a real bundled Active Memory behavior, has recent author follow-up addressing bot review findings, and is cross-referenced by an open Active Memory timeout report (#73306).

Best possible solution:

Keep the PR open for maintainer review. The likely path is to review the latest head against extensions/active-memory/index.ts and extensions/active-memory/index.test.ts, verify the bot-raised security/performance fixes, run the targeted Active Memory test lane plus the changed gate, and land or request changes. After merge, the related timeout reports can be closed or updated based on the shipped behavior.

What I checked:

  • Current main has no partial-timeout discriminant: ActiveRecallResult only allows empty, timeout, unavailable, and ok; there is no timeout_partial variant on current main. (extensions/active-memory/index.ts:159, 373e7fc24233)
  • Timeout race path still discards partial output on main: When the timeout sentinel wins, current main constructs { status: "timeout", summary: null }, persists only the timeout status line, and returns without reading the subagent transcript. (extensions/active-memory/index.ts:1944, 373e7fc24233)
  • Abort-during-await path also returns null summary: If the controller is aborted while awaiting the subagent, current main returns status: "timeout" with summary: null, so the PR's second intended timeout path is not implemented on main. (extensions/active-memory/index.ts:2007, 373e7fc24233)
  • Existing tests encode old timeout behavior: Current tests assert timeout results are uncached and that late timeout payloads do not become memory context; there is no main-branch coverage for returning partial transcript text on timeout. (extensions/active-memory/index.test.ts:1501, 373e7fc24233)
  • Current docs do not describe shipped partial timeout recovery: The Active Memory docs describe status/debug output, transcript persistence, and timeout tuning, but not a shipped timeout_partial status or bounded partial recall recovery behavior. Public docs: docs/concepts/active-memory.md. (docs/concepts/active-memory.md:155, 373e7fc24233)
  • PR is active and review feedback has been addressed in discussion: Provided PR context shows bot review findings on caching, prompt/sensitive-data handling, and transcript parsing; the author posted follow-up commits and validation output, and the head was force-pushed later the same day. This is review/landing work, not conservative cleanup closure. (5e96da4e7a42)

Remaining risk / open question:

  • Security-sensitive review remains important before merge: recovered assistant transcript text can affect the main prompt path, so maintainers should verify the final head keeps partial output bounded, redacted from persisted debug entries, and clearly treated as untrusted context.
  • The PR is marked mergeable=false in the provided context and has a force-pushed head; reviewers should inspect the latest diff and CI/check results before landing.
  • Related [Bug] Active Memory plugin times out on every run (15s timeout, 0 chars output) - v2026.4.26 #73306 reports Active Memory timeout behavior in released v2026.4.26, so closing this PR before review would remove a plausible implementation path for an active user-visible problem.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 373e7fc24233.

@Takhoffman
Takhoffman merged commit 1690678 into openclaw:main Apr 28, 2026
56 of 58 checks passed
@Takhoffman

Copy link
Copy Markdown
Contributor

Merged in 1690678 after representative verification with pnpm test extensions/active-memory/index.test.ts, targeted oxfmt --check, and git diff --check. I also added a small follow-up on the PR branch so the default temporary-transcript timeout path preserves recovered partial output before cleanup, plus the Unreleased changelog entry.

@aisle-research-bot

aisle-research-bot Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Unhandled read stream errors in streaming JSONL transcript reader can crash process
1. 🟡 Unhandled read stream errors in streaming JSONL transcript reader can crash process
Property Value
Severity Medium
CWE CWE-248
Location extensions/active-memory/index.ts:1410-1416

Description

The new streamBoundedTranscriptJsonl() creates a fs.createReadStream() and passes it into readline.createInterface(), but does not attach an 'error' handler to the underlying file stream.

In Node.js, an EventEmitter 'error' event with no listener becomes an uncaught exception. This can occur if the transcript file is deleted/rotated between stat() and createReadStream(), or removed while reading (notably possible for temporary transcripts cleaned up in runRecallSubagent() while timeout recovery attempts to read partial output). The result is a process crash (denial of service) during best-effort timeout handling.

Vulnerable code:

const stream = fsSync.createReadStream(params.sessionFile, { encoding: "utf8" });
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
for await (const line of rl) { /* ... */ }

Recommendation

Attach explicit error handling for the underlying stream (and ensure the readline interface is closed) so file disappearance or I/O errors don't become unhandled exceptions.

One safe pattern:

import { finished } from "node:stream/promises";

const stream = fsSync.createReadStream(params.sessionFile, { encoding: "utf8" });
stream.on("error", () => {
  rl.close();
});

const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });

try {
  for await (const line of rl) {
    ​// ...
  }
} catch {
  ​// best-effort
} finally {
  rl.close();
  stream.destroy();
  await finished(stream).catch(() => undefined);
}

At minimum, add stream.on('error', () => {}) (or once) to prevent an unhandled 'error' event and close the interface on failure.


Analyzed PR: #73219 at commit 9a61a91

Last updated on: 2026-04-28T13:51:25Z

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…3219)

Verified:
- pnpm test extensions/active-memory/index.test.ts
- pnpm exec oxfmt --check --threads=1 extensions/active-memory/index.ts extensions/active-memory/index.test.ts CHANGELOG.md
- git diff --check

Co-authored-by: joeykrug <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…3219)

Verified:
- pnpm test extensions/active-memory/index.test.ts
- pnpm exec oxfmt --check --threads=1 extensions/active-memory/index.ts extensions/active-memory/index.test.ts CHANGELOG.md
- git diff --check

Co-authored-by: joeykrug <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
sablehead pushed a commit to sablehead/openclaw that referenced this pull request Jun 10, 2026
…3219)

Verified:
- pnpm test extensions/active-memory/index.test.ts
- pnpm exec oxfmt --check --threads=1 extensions/active-memory/index.ts extensions/active-memory/index.test.ts CHANGELOG.md
- git diff --check

Co-authored-by: joeykrug <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…3219)

Verified:
- pnpm test extensions/active-memory/index.test.ts
- pnpm exec oxfmt --check --threads=1 extensions/active-memory/index.ts extensions/active-memory/index.test.ts CHANGELOG.md
- git diff --check

Co-authored-by: joeykrug <[email protected]>
Co-authored-by: Tak Hoffman <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants