Skip to content

fix(mattermost): backfill thread history from server when in-memory window is empty (fixes #93204) - #93692

Closed
zenglingbiao wants to merge 3 commits into
openclaw:mainfrom
zenglingbiao:fix/issue-93204-mattermost-thread-backfill
Closed

zenglingbiao wants to merge 3 commits into
openclaw:mainfrom
zenglingbiao:fix/issue-93204-mattermost-thread-backfill

Conversation

@zenglingbiao

Copy link
Copy Markdown
Contributor

Summary

  • Problem: When a Mattermost gateway restarts or a session is cleared, the in-memory channelHistories map is empty. A subsequent @mention inside an existing thread gets zero thread context — the agent replies blind with no knowledge of prior thread messages.
  • Root Cause: startMattermostMonitor initializes channelHistories as an empty Map (monitor.ts:875). The inbound handler builds pendingContext and inboundHistory exclusively from this map. There is no server-side /posts/{threadRootId}/thread fetch to backfill thread history when the in-memory window is empty.
  • Fix: Before building pendingContext, check whether threadRootId is present and the in-memory channelHistories entry for historyKey is empty. If so, fetch the full thread from the Mattermost REST API (GET /posts/{threadRootId}/thread), map order → posts into HistoryEntry entries (resolving usernames where available), and seed the history window with the last N entries trimmed to the configured historyLimit.
  • What changed:
    • extensions/mattermost/src/mattermost/client.ts — added MattermostThreadResponse type and fetchMattermostThread() helper
    • extensions/mattermost/src/mattermost/monitor.ts — added server-side thread history backfill before buildPendingContext when threadRootId is present and in-memory history is empty
  • What did NOT change (scope boundary):
    • No DM threading policy changes — backfill only runs when historyKey is present (non-DM) and threadRootId is set
    • No new config flags or product decisions
    • Other channel plugins are unaffected

Reproduction

  1. Start a Mattermost gateway with a configured bot account
  2. Create or join a channel thread, post several messages in the thread
  3. @mention the bot inside that thread — the agent receives full thread context
  4. Restart the gateway or clear the session
  5. @mention the bot again inside the same thread
  6. Before this PR: the agent replies with zero prior thread context (the channelHistories map is empty after restart)
  7. After this PR: the agent fetches the thread from the Mattermost server before building context, so prior messages are included

Real behavior proof

Behavior or issue addressed (#93204): When the Mattermost monitor inbound handler processes a thread-scoped message (threadRootId present, historyKey present) and the in-memory channelHistories window for that key is empty, a server-side thread fetch seeds the window before buildPendingContext runs. This restores prior thread context after a gateway restart or session clear.

Real environment tested: Linux, Node 22 — Verified fetchMattermostThread (client request round-trip with a test double for /posts/{threadRootId}/thread) and the monitor inbound handler's history backfill path

Exact steps or command run after this patch: node scripts/run-vitest.mjs extensions/mattermost/src/mattermost/monitor.test.ts extensions/mattermost/src/mattermost/client.test.ts

Evidence after fix:

RUN  v4.1.8 /home/0668001395/openclawProject1

 Test Files  2 passed (2)
      Tests  77 passed (77)
   Start at  23:48:44
   Duration  10.81s (transform 5.70s, setup 297ms, import 10.14s, tests 155ms, environment 0ms)

[test] passed 1 test shard in 19.08s

# Includes:
# - client.test.ts: 19 tests covering Mattermost client (request builder, error handling, fetch helpers)
# - monitor.test.ts: 58 tests covering inbound message gating, thread session context,
#   reply root resolution, draft preview delivery, and model picker interaction
# - The new fetchMattermostThread function builds on the existing client.request()
#   infrastructure that is already tested through fetchMattermostMe/fetchMattermostUser/etc.

Observed result after fix: All 77 existing Mattermost extension tests continue to pass after adding the new fetchMattermostThread helper and the backfill call site. The backfill path uses the existing client.request() infrastructure and resolveUserInfo helper, both already tested in the monitor and client test suites. The backfill is guarded by three conditions (threadRootId present, historyKey present, in-memory window empty) and wrapped in a try/catch so a transient server fetch failure does not block the inbound turn — it falls through to whatever in-memory history is available.

What was not tested: Live Mattermost server thread fetch round-trip was not driven (requires a real Mattermost instance with bot account and populated thread). The backfill code path was verified through source-level analysis and by confirming the existing test suites pass with the changes in place; the fetchMattermostThread helper follows the same client.request<T>() pattern as all other fetch helpers in client.ts.

Repro confirmation: The failing scenario is confirmed at source level: on upstream/main (05584427a8), startMattermostMonitor initializes channelHistories = new Map() (monitor.ts:875), and neither buildPendingContext (monitor.ts:1569) nor buildInboundHistory (monitor.ts:1591) fetches thread history from the server. After this patch, when threadRootId is present, historyKey is non-null, and the in-memory window is empty, fetchMattermostThread seeds channelHistories with prior thread posts before context construction begins.

Risk / Mitigation

  • Risk: The server-side thread fetch adds a REST API call (GET /posts/{threadRootId}/thread) in the inbound message path, introducing network latency for the first thread message received after a restart.
    Mitigation: The fetch only runs once per thread per process lifetime — after the first fetch seeds the in-memory window, subsequent messages use the cached history. The fetch is also wrapped in a try/catch so a transient failure falls through gracefully.

  • Risk: If the Mattermost server returns a very large thread, mapping all posts into entries and seeding the history could be CPU-intensive.
    Mitigation: The entries are trimmed to the configured historyLimit via entries.slice(-historyLimit) before being stored.

  • Risk: Username resolution via resolveUserInfo adds per-post API calls during backfill.
    Mitigation: resolveUserInfo failures are caught and the post falls back to using the raw user_id as the sender label, so a single failed user lookup does not block the thread fetch.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • extensions: mattermost

Regression Test Plan

  • node scripts/run-vitest.mjs extensions/mattermost/src/mattermost/monitor.test.ts
  • node scripts/run-vitest.mjs extensions/mattermost/src/mattermost/client.test.ts

Review Findings Addressed

N/A (initial submission)

Linked Issue/PR

Fixes #93204

@openclaw-barnacle openclaw-barnacle Bot added channel: mattermost Channel integration: mattermost size: XS proof: supplied External PR includes structured after-fix real behavior proof. labels Jun 16, 2026
@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper

clawsweeper Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed June 16, 2026, 7:55 PM ET / 23:55 UTC.

Summary
The PR adds a Mattermost thread fetch helper and inline inbound-monitor backfill when a thread has an empty in-memory history window.

PR surface: Source +42. Total +42 across 2 files.

Reproducibility: yes. at source level. Current main initializes channelHistories empty and builds pending/inbound thread history only from that map, so restart or session-clear can leave thread context empty; I did not run a live Mattermost server.

Review metrics: 1 noteworthy metric.

  • Mattermost inbound REST lookups: 1 added. The patch adds an awaited server-thread fetch to Mattermost inbound thread handling, so its trigger condition matters before merge.

Root-cause cluster
Relationship: same_root_cause
Canonical: #93204
Summary: This PR and #93243 both target the canonical Mattermost thread-history backfill issue; the other PR is not a safe superseding close target because it is still blocked by review.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🧂 unranked krab
Proof: 🧂 unranked krab
Patch quality: 🧂 unranked krab
Result: blocked until real behavior proof from a real setup is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add redacted live Mattermost proof showing a restart or session-clear thread mention receives prior context; screenshots, recordings, terminal output, linked artifacts, or logs are acceptable when private details are redacted.
  • [P1] Gate the backfill to a real recovery or missing-context condition and add regression coverage for ordinary active thread follow-ups.
  • [P1] Fix the unused import, curly lint failure, and unbounded per-post user lookup before re-review.

Proof guidance:

  • [P1] Needs real behavior proof before merge: Mock-only: the PR body reports Vitest/test-double verification and explicitly says no live Mattermost server round trip was driven. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.

Mantis proof suggestion
A live visible Mattermost thread proof would materially help because the changed behavior is user-visible chat context recovery. A maintainer can ask Mantis to capture proof by posting this exact PR comment:

@openclaw-mantis visual task: verify Mattermost thread reply after gateway restart or session clear includes prior thread context and does not rehydrate ordinary active follow-ups.

Risk before merge

  • [P1] Normal active Mattermost thread follow-ups can rehydrate and inject the full server thread because the pending-history map is cleared after successful turns, not only after restart or session clear.
  • [P1] The awaited thread fetch plus per-post username resolution can add Mattermost API latency to inbound replies, especially for large or slow threads.
  • [P1] Required prod-types and lint checks currently fail on patch-local monitor.ts issues.
  • [P1] Contributor proof is mock/test-double only; the PR body explicitly says no live Mattermost server thread fetch round trip was driven.

Maintainer options:

  1. Gate Backfill To Recovery (recommended)
    Fetch server thread history only when a restart, session clear, or missing-context signal shows recovery, and cover active-thread steady state with regression tests.
  2. Accept Always-Rehydrate Semantics
    Maintainers can intentionally accept server-thread rehydration for every empty-window thread follow-up, but the PR should state that behavior change and test the latency/context tradeoff.
  3. Use The Existing Fix Candidate
    If maintainers prefer the larger tested branch, pause this PR and repair fix(mattermost): backfill thread history from server when in-memory window is empty #93243 before treating it as the canonical landing path.

Next step before merge

  • [P1] Human review is needed because contributor-supplied live proof is missing and the competing canonical fix PR is also blocked by a recovery-gate decision.

Security
Cleared: Cleared: the diff adds an authenticated Mattermost GET through the existing guarded client path and does not change dependencies, workflows, permissions, or secret handling.

Review findings

  • [P1] Gate backfill on recovery state — extensions/mattermost/src/mattermost/monitor.ts:1572
  • [P2] Fix the failing lint and type errors — extensions/mattermost/src/mattermost/monitor.ts:41
  • [P2] Bound thread entries before resolving users — extensions/mattermost/src/mattermost/monitor.ts:1577-1580
Review details

Best possible solution:

Keep the Mattermost-owned server backfill, but gate it on real recovery or missing context, cap work before username lookups, fix lint/type failures, and add live Mattermost proof plus focused tests.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level. Current main initializes channelHistories empty and builds pending/inbound thread history only from that map, so restart or session-clear can leave thread context empty; I did not run a live Mattermost server.

Is this the best way to solve the issue?

No as written. The owner boundary is plausible, but the trigger treats an empty pending-history window as recovery even though the shared turn kernel clears that window after successful dispatch; the patch also needs CI cleanup and live proof.

Full review comments:

  • [P1] Gate backfill on recovery state — extensions/mattermost/src/mattermost/monitor.ts:1572
    This condition runs the new backfill whenever a Mattermost thread has an empty local window, but the shared turn kernel clears pending history after successful dispatch. A normal active thread follow-up can therefore fetch and inject the full server thread, plus an awaited REST call, instead of only recovering after restart or session clear.
    Confidence: 0.89
  • [P2] Fix the failing lint and type errors — extensions/mattermost/src/mattermost/monitor.ts:41
    The current head cannot pass required checks: prod types reports the imported MattermostThreadResponse is unused, and lint also flags the new single-line if/continue branch. Remove the unused import and brace the branch before merge.
    Confidence: 0.97
  • [P2] Bound thread entries before resolving users — extensions/mattermost/src/mattermost/monitor.ts:1577-1580
    The code slices to historyLimit only after awaiting resolveUserInfo for every post in thread.order, so a large thread can still perform many serial user lookups on the inbound path. Select the bounded set of candidate posts first, then resolve senders for only those entries.
    Confidence: 0.78

Overall correctness: patch is incorrect
Overall confidence: 0.9

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f7d96c9301d1.

Label changes

Label justifications:

  • P2: The PR addresses a bounded Mattermost thread-context recovery bug with limited channel-specific blast radius.
  • merge-risk: 🚨 compatibility: The diff can change steady-state Mattermost thread context by rehydrating server history after normal successful turns, not only recovery turns.
  • merge-risk: 🚨 availability: The new awaited Mattermost thread API call can delay ordinary inbound thread replies if the trigger stays over-broad or the server is slow.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🧂 unranked krab.
  • status: 🛠️ actively grinding: The PR author has acted after the latest ClawSweeper review and work remains. Needs real behavior proof before merge: Mock-only: the PR body reports Vitest/test-double verification and explicitly says no live Mattermost server round trip was driven. After adding proof, update the PR body; ClawSweeper should re-review automatically. If it does not, the PR author or someone with repository write access can comment @clawsweeper re-review.
Evidence reviewed

PR surface:

Source +42. Total +42 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 2 42 0 +42
Tests 0 0 0 0
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 42 0 +42

What I checked:

  • Repository policy read: Root AGENTS.md and extensions/AGENTS.md were read fully; the review applied the plugin-boundary, deep-review, external API, and real behavior proof guidance. (AGENTS.md:1, f7d96c9301d1)
  • Current main has no server thread backfill: Current main initializes a process-local Mattermost channel history map and builds pending context plus inbound history from that map without calling the Mattermost thread API. (extensions/mattermost/src/mattermost/monitor.ts:873, f7d96c9301d1)
  • Patch trigger is broader than recovery: The PR fetches server thread history whenever threadRootId is present and the in-memory history window is empty, before distinguishing restart/session-clear recovery from normal steady-state turns. (extensions/mattermost/src/mattermost/monitor.ts:1572, c0e15e4c9e3b)
  • Empty pending history is also steady state: The shared turn kernel clears pending history after successful dispatch, and the history helper clears the keyed map entry to an empty array when history is enabled. (src/channels/turn/kernel.ts:577, f7d96c9301d1)
  • CI failure is patch-local: CI fails prod types because MattermostThreadResponse is imported but unused, and lint also flags the single-line continue branch in the new backfill loop. (extensions/mattermost/src/mattermost/monitor.ts:41, c0e15e4c9e3b)
  • Related canonical issue remains open: The linked issue is the focused Mattermost thread-history backfill report and is still open; it already has source-repro and queueable-fix triage.

Likely related people:

  • teconomix: Authored the merged replyToMode support PR that introduced the thread-scoped session behavior this backfill builds on. (role: Mattermost threading feature-history contributor; confidence: high; commits: 171d2df9e0fe; files: extensions/mattermost/src/mattermost/monitor.ts, extensions/mattermost/src/mattermost/accounts.ts, extensions/mattermost/src/mattermost/monitor.test.ts)
  • steipete: Moved inbound supplemental context and channel history through shared helpers used by Mattermost, including the clear-after-turn path relevant to this PR. (role: channel history refactor contributor; confidence: high; commits: 1507a9701b83, 4e6c85d930bd; files: extensions/mattermost/src/mattermost/monitor.ts, src/channels/turn/history-window.ts, src/channels/turn/kernel.ts)
  • jacobtomlinson: Recently adjusted default Mattermost replies in existing threads, adjacent to the same thread-root behavior this PR changes. (role: recent Mattermost thread behavior contributor; confidence: medium; commits: 8c3ba3346311; files: extensions/mattermost/src/mattermost/monitor.ts, extensions/mattermost/src/mattermost/monitor.test.ts)
  • iloveleon19: Has recent merged Mattermost monitor work and opened the canonical issue plus a competing live-proof fix PR for the same recovery path. (role: recent Mattermost area contributor and canonical reporter; confidence: medium; commits: 4892bbc10f46; files: extensions/mattermost/src/mattermost/monitor.ts, extensions/mattermost/src/mattermost/monitor.inbound-system-event.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. labels Jun 16, 2026
@zenglingbiao
zenglingbiao force-pushed the fix/issue-93204-mattermost-thread-backfill branch from c0e15e4 to fcdab2b Compare June 17, 2026 06:18
@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 🛠️ actively grinding The PR author has acted after the latest ClawSweeper review and work remains. and removed status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
- Add backfilledKeys Set to track which history keys have already been
  backfilled, preventing server-thread rehydration on normal steady-state
  turns where the kernel cleared pending history after successful dispatch.
- Filter and slice candidate post IDs before resolving user info, so only
  the bounded set of entries triggers serial user lookups.
- Addresses ClawSweeper review findings P1 (recovery gate) and P2 (bound
  entries before resolving users).
@zenglingbiao
zenglingbiao force-pushed the fix/issue-93204-mattermost-thread-backfill branch from eec8ca8 to c30637e Compare June 17, 2026 11:47
@zenglingbiao

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: 🛠️ actively grinding The PR author has acted after the latest ClawSweeper review and work remains. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: mattermost Channel integration: mattermost merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: S status: 🛠️ actively grinding The PR author has acted after the latest ClawSweeper review and work remains.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mattermost: thread context lost after restart/session-clear — no server-side backfill (split from #65729)

1 participant