Skip to content

fix(matrix): contain sync outage failures - #62779

Merged
gumadeiras merged 14 commits into
mainfrom
codex/matrix-channel-lifecycle-hardening
Apr 8, 2026
Merged

gumadeiras merged 14 commits into
mainfrom
codex/matrix-channel-lifecycle-hardening

Conversation

@gumadeiras

Copy link
Copy Markdown
Member

Summary

  • Problem: Matrix startup reported success before sync was actually ready, and detached Matrix monitor tasks could reject without an owner.
  • Why it matters: a homeserver outage could escalate from a channel-scoped failure into a process-wide unhandled rejection crash loop, bypassing gateway.channelMaxRestartsPerHour.
  • What changed: Matrix startup now waits for ready sync states, monitor status/fatal sync handling is owned inside the Matrix plugin, and detached monitor work is centrally contained and drained on shutdown.
  • What did NOT change (scope boundary): no core Matrix special-casing in gateway orchestration, no new config surface, no global unhandled-rejection policy change.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: the Matrix plugin treated matrix-js-sdk startup as ready too early, then left background room-message/verification tasks detached from channel lifecycle ownership.
  • Missing detection / guardrail: Matrix sync fatality and detached task rejection never fed back into the Matrix channel task, so global unhandled rejection policy killed the whole gateway before channel restart budgeting could apply.
  • Contributing context (if known): matrix-js-sdk emits long-lived sync state transitions after startClient() returns, and replayed/in-flight events during outage windows made orphaned async failures much easier to hit.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: extensions/matrix/src/matrix/sdk.test.ts, extensions/matrix/src/matrix/monitor/index.test.ts, extensions/matrix/src/matrix/monitor/sync-lifecycle.test.ts
  • Scenario the test should lock in: startup does not resolve before ready sync, startup times out/fails on sync fatal, detached monitor task failures do not escape as unhandled rejections, and fatal sync errors reject the Matrix channel task.
  • Why this is the smallest reliable guardrail: the bug lives at the Matrix SDK/monitor seam, below a full gateway e2e but above pure helper-local logic.
  • Existing test that already covers this (if any): none sufficiently covered the startup-readiness or detached-task ownership seam.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

  • Matrix startup now waits for real sync readiness before the channel is considered started.
  • Fatal Matrix sync failures now stop/restart the Matrix channel instead of crashing the whole gateway process.
  • Matrix channel runtime status now reflects starting, healthy, error, and stopped transitions more accurately.

Diagram (if applicable)

Before:
[matrix startClient returns] -> [Matrix marked started] -> [background task rejects] -> [global unhandled rejection] -> [gateway exits]

After:
[matrix startClient returns] -> [wait for ready sync] -> [background task or sync fatal] -> [Matrix channel task rejects] -> [gateway channel restart policy]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation:

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 24 / local repo workspace
  • Model/provider: N/A
  • Integration/channel (if any): Matrix
  • Relevant config (redacted): Matrix account with unreachable homeserver or fatal sync failure after startup

Steps

  1. Configure Matrix and start the gateway with an unreachable or failing homeserver.
  2. Let Matrix startup or replayed inbound event handling hit a sync/background-task failure.
  3. Observe whether the whole gateway exits or only the Matrix channel fails.

Expected

  • Matrix stays channel-scoped: startup waits for readiness, fatal sync failures reject the Matrix channel task, and gateway restart budgeting applies at the channel layer.

Actual

  • Before this change the gateway could exit from unhandled Matrix monitor rejections, bypassing channel restart controls.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: targeted Matrix tests for startup readiness, startup timeout, unexpected sync fatal, detached room-message failure containment, and intentional shutdown STOPPED handling; local pnpm build.
  • Edge cases checked: fatal sync error after startup, detached task rejection sink, intentional shutdown not misclassified as fatal, startup timeout branch with fake timers.
  • What you did not verify: full repo pnpm check remains blocked by unrelated preexisting tsgo failures in extensions/msteams/src/attachments.graph.test.ts, src/agents/subagent-registry.test.ts, and src/infra/host-env-security.test.ts.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (No)
  • Migration needed? (No)
  • If yes, exact upgrade steps:

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: Matrix sync.state = ERROR remains SDK-owned reconnect behavior and is not automatically escalated into channel restart.
    • Mitigation: this PR only escalates clear fatal paths (sync.unexpected_error, unexpected STOPPED, startup readiness failure) to avoid fighting the SDK on transient reconnects.

Copilot AI review requested due to automatic review settings April 8, 2026 00:22
@openclaw-barnacle openclaw-barnacle Bot added channel: matrix Channel integration: matrix size: L maintainer Maintainer-authored PR labels Apr 8, 2026

@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: 69a8b95c3f

ℹ️ 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 thread extensions/matrix/src/matrix/sdk.ts Resolved

Copilot AI 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.

Pull request overview

This PR hardens the Matrix integration against homeserver sync outages by making Matrix startup wait for actual sync readiness and by ensuring monitor/background work is owned and contained within the Matrix channel lifecycle (preventing process-wide unhandled rejections).

Changes:

  • Add Matrix sync-state typing/helpers and wire Matrix sync lifecycle events (sync.state, sync.unexpected_error) through the MatrixClient bridge.
  • Make MatrixClient.start() wait for initial ready sync states (with timeout / fatal handling) before reporting startup success.
  • Introduce a centralized monitor task runner + sync lifecycle/status controllers so detached monitor work is tracked, drained on shutdown, and fatal sync errors fail the channel task (not the whole process).

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
extensions/matrix/src/matrix/sync-state.ts Defines sync state type + readiness/disconnected/terminal helpers.
extensions/matrix/src/matrix/sdk/types.ts Extends Matrix client event map with sync lifecycle events.
extensions/matrix/src/matrix/sdk.ts Waits for initial sync readiness; bridges SDK sync events; tracks current sync state.
extensions/matrix/src/matrix/sdk.test.ts Adds tests for startup readiness gating, unexpected sync errors, and startup timeout.
extensions/matrix/src/matrix/monitor/task-runner.ts Adds tracked detached-task runner + idle draining for shutdown containment.
extensions/matrix/src/matrix/monitor/sync-lifecycle.ts Adds sync fatality ownership to fail the channel task on unexpected STOPPED / sync fatal events.
extensions/matrix/src/matrix/monitor/sync-lifecycle.test.ts Tests fatal sync handling and intentional shutdown STOPPED handling.
extensions/matrix/src/matrix/monitor/status.ts Adds Matrix monitor status controller to publish starting/healthy/error/stopped snapshots.
extensions/matrix/src/matrix/monitor/index.ts Wires status + lifecycle + task runner into the Matrix monitor and abort/fatal handling.
extensions/matrix/src/matrix/monitor/index.test.ts Adds tests for status publishing, detached-task rejection containment, and fatal sync propagation.
extensions/matrix/src/matrix/monitor/events.ts Wraps key event handlers in contained tasks to prevent unhandled rejections.
extensions/matrix/src/channel.ts Plumbs channel lifecycle status sink (ctx.setStatus) into Matrix monitor.
CHANGELOG.md Documents the Matrix/gateway outage containment fix.
Comments suppressed due to low confidence (1)

extensions/matrix/src/matrix/sdk.ts:468

  • startSyncSession() calls this.client.startClient() and then can reject from waitForInitialSyncReady() (timeout / unexpected error / terminal state). On those failure paths, the underlying matrix-js-sdk client remains started and will keep its sync loop running, while MatrixClient.started stays false, so subsequent retries may attempt a second startClient() on an already-running client.

Consider wrapping the post-startClient() startup phase in a try/catch (or try/finally) that stops the SDK client (e.g., via stopSyncWithoutPersist() / client.stopClient()) and resets any related state before rethrowing, so a failed startup does not leak background work or leave the instance in a half-started state.

  private async startSyncSession(opts: { bootstrapCrypto: boolean }): Promise<void> {
    if (this.started) {
      return;
    }

    await this.ensureCryptoSupportInitialized();
    this.registerBridge();
    await this.initializeCryptoIfNeeded();

    await this.client.startClient({
      initialSyncLimit: this.initialSyncLimit,
    });
    await this.waitForInitialSyncReady();
    if (opts.bootstrapCrypto && this.autoBootstrapCrypto) {
      await this.bootstrapCryptoIfNeeded();
    }
    this.started = true;
    this.emitOutstandingInviteEvents();
    await this.refreshDmCache().catch(noop);

Comment thread extensions/matrix/src/matrix/sdk.ts Resolved
@greptile-apps

greptile-apps Bot commented Apr 8, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR contains the Matrix channel startup/reliability fix: MatrixClient.start() now blocks until the SDK reaches a ready sync state (PREPARED/SYNCING/CATCHUP) with a 30-second timeout, fatal sync errors are routed through the channel's own lifecycle (rejecting its task so gateway restart budgeting applies), and detached background handler failures are tracked and drained on shutdown instead of leaking as unhandled rejections.

The three new modules — task-runner.ts, sync-lifecycle.ts, and status.ts — carve out clean, testable seams, and the added test coverage in sdk.test.ts, monitor/index.test.ts, and sync-lifecycle.test.ts directly locks in the startup-readiness, fatal escalation, and rejection-containment invariants.

Confidence Score: 5/5

Safe to merge. The fix is logically correct, well-tested, and scoped entirely to the Matrix extension.

All remaining findings are P2 (documentation/style). The core correctness of the bug fix is sound: startup readiness gating, fatal-error routing through channel lifecycle, and background-task containment all behave correctly. The test coverage directly locks in the key invariants (startup timeout, fatal rejection, detached-task containment, intentional-shutdown STOPPED classification).

No files require special attention.

Vulnerabilities

No security concerns identified. No new network calls, secrets handling changes, or permission surface changes were introduced.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/matrix/src/matrix/monitor/sync-lifecycle.ts
Line: 56-63

Comment:
**`waitForFatalStop` assumes single-caller ownership**

The resolve/reject callbacks are stored in module-level `let` slots, so a second concurrent call to `waitForFatalStop()` would silently overwrite the first caller's references — leaving its promise forever pending. This isn't a live bug (the only call site is the `Promise.race` in `index.ts`), but the invariant is implicit. A short guard comment or an early-throw would make the constraint explicit for future callers.

```suggestion
    async waitForFatalStop(): Promise<void> {
      if (fatalError) {
        throw fatalError;
      }
      // NOTE: only one concurrent caller is supported; a second call would
      // overwrite these slots and the first promise would never settle.
      await new Promise<void>((resolve, reject) => {
        resolveFatalWait = resolve;
        rejectFatalWait = (error) => reject(error);
      });
    },
```

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/matrix/src/matrix/monitor/status.ts
Line: 93-95

Comment:
**Unknown sync states don't update `connected`**

The fallback branch (for future/unknown SDK states that aren't `PREPARED`/`SYNCING`/`CATCHUP`/`RECONNECTING`/`ERROR`/`STOPPED`) updates `healthState` and `lastEventAt` but leaves `status.connected` unchanged. If the SDK ever introduces a state that arrives while `connected === true`, the status would report a connected client in an unknown health state. A brief comment clarifying this is intentional would help readers avoid adding `status.connected = false` here by mistake.

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

Reviews (1): Last reviewed commit: "fix(matrix): contain sync outage failure..." | Re-trigger Greptile

@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: dd310b208d

ℹ️ 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".

@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from dd310b2 to 657e1ce Compare April 8, 2026 03:02

@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: 657e1ce06a

ℹ️ 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 thread extensions/matrix/src/matrix/sdk.ts Resolved
@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 657e1ce to 9cd2677 Compare April 8, 2026 03:11

@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: 9cd2677d7a

ℹ️ 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 thread CHANGELOG.md Resolved
@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 9cd2677 to d0bce95 Compare April 8, 2026 04:18
@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from d3ed4da to 843a52a Compare April 8, 2026 04:33

@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: 843a52a7c5

ℹ️ 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".

@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 97e4a7d to 6b4662e Compare April 8, 2026 05:34

@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: 6b4662e7f2

ℹ️ 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".

@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 274ea16 to 382e4e6 Compare April 8, 2026 06:00

@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: 382e4e667a

ℹ️ 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".

@aisle-research-bot

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

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟡 Medium Unbounded background task tracking enables memory/CPU exhaustion and can block shutdown
2 🟡 Medium Matrix startup abort misclassification via generic AbortError name check
3 🟡 Medium MatrixClient.start() abort/timeout can leave Matrix sync running in background
1. 🟡 Unbounded background task tracking enables memory/CPU exhaustion and can block shutdown
Property Value
Severity Medium
CWE CWE-400
Location extensions/matrix/src/matrix/monitor/task-runner.ts:7-31

Description

createMatrixMonitorTaskRunner tracks every detached handler promise in an in-memory Set until it settles. Event handlers for high-volume Matrix events (room.message, Reaction, verification.summary) are now executed via runDetachedTask, so an attacker who can generate many events (e.g., spamming messages/reactions) can:

  • Create an unbounded number of concurrently in-flight tasks (no concurrency limit/backpressure)
  • Cause sustained memory growth from the growing Set (and promise closures) when handlers are slow
  • Potentially block shutdown indefinitely because waitForIdle() loops until all tracked promises settle; if any handler hangs (network call stuck, deadlock), cleanup will never finish when mode === "persist"

Vulnerable code:

const inFlight = new Set<Promise<void>>();
...
inFlight.add(trackedTask);
...
while (inFlight.size > 0) {
  await Promise.allSettled(Array.from(inFlight));
}

Recommendation

Introduce backpressure and bounded concurrency, and ensure tasks cannot hang forever.

Options (can be combined):

  1. Concurrency limit / queue (preferred):
import pLimit from "p-limit";

const limit = pLimit(25); // tune
const runDetachedTask = (label: string, task: () => Promise<void>) => {
  const trackedTask = limit(async () => {
    await task();
  })
  .catch((err) => { /* log */ })
  .finally(() => inFlight.delete(trackedTask));

  inFlight.add(trackedTask);
  return trackedTask;
};
  1. Timeout + abort propagation: wrap tasks with an AbortSignal (or Promise.race timeout) so stuck handlers eventually settle.

  2. Bound the tracked set: if inFlight.size exceeds a safe threshold, drop/skip low-priority work or coalesce events (e.g., dedupe per room).

  3. In shutdown, consider a max wait for waitForIdle() and then proceed with releaseSharedClientInstance(client, "stop").

2. 🟡 Matrix startup abort misclassification via generic `AbortError` name check
Property Value
Severity Medium
CWE CWE-697
Location extensions/matrix/src/matrix/startup-abort.ts:13-15

Description

isMatrixStartupAbortError treats any Error with name === "AbortError" as an intentional Matrix startup abort.

  • createMatrixStartupAbortError() creates an Error and sets name = "AbortError"
  • isMatrixStartupAbortError() then matches solely on error.name === "AbortError"
  • Many underlying libraries (e.g., fetch/Matrix SDK request layer, undici) may throw abort-related errors with the same name for non-user-initiated reasons (timeouts, internal cancellations, transient network conditions)
  • This causes control-flow changes:
    • In runMatrixStartupMaintenance, such errors are rethrown instead of being logged as non-fatal, potentially aborting startup.
    • In monitorMatrixProvider, if the outer abort signal is already aborted, any AbortError will be treated as a startup abort and the function will cleanup("stop") and return (skipping the normal error propagation path).

This is an error-class confusion issue that can lead to unintended early termination (availability impact) and altered cleanup semantics based on an error name that is not unique to the intended abort condition.

Vulnerable code:

export function isMatrixStartupAbortError(error: unknown): boolean {
  return error instanceof Error && error.name === "AbortError";
}

Recommendation

Use a distinct error type or marker that cannot be confused with generic abort errors from other libraries.

Option A (preferred): custom class + instanceof

export class MatrixStartupAbortError extends Error {
  constructor() {
    super("Matrix startup aborted");
    this.name = "MatrixStartupAbortError";
  }
}

export function createMatrixStartupAbortError(): Error {
  return new MatrixStartupAbortError();
}

export function isMatrixStartupAbortError(err: unknown): err is MatrixStartupAbortError {
  return err instanceof MatrixStartupAbortError;
}

Option B: add a non-enumerable symbol marker

const kMatrixStartupAbort = Symbol.for("openclaw.matrix.startup_abort");

export function createMatrixStartupAbortError(): Error {
  const e = new Error("Matrix startup aborted");
  (e as any)[kMatrixStartupAbort] = true;
  return e;
}

export function isMatrixStartupAbortError(err: unknown): boolean {
  return err instanceof Error && (err as any)[kMatrixStartupAbort] === true;
}

Then keep handling generic AbortError from fetch/SDK as ordinary errors (logged or retried) unless they carry the explicit marker/type.

3. 🟡 MatrixClient.start() abort/timeout can leave Matrix sync running in background
Property Value
Severity Medium
CWE CWE-400
Location extensions/matrix/src/matrix/sdk.ts:487-493

Description

MatrixClient.startSyncSession() starts the underlying matrix-js-sdk client (startClient()), then waits for a ready sync state. If the wait rejects (abort signal, timeout, or unexpected sync error), the function throws without stopping the underlying Matrix client, leaving a live /sync loop running.

This can cause:

  • Unexpected background network activity (continued syncing) after the caller believes startup failed
  • Processing/decryption of events without the intended higher-level application state/handlers being fully initialized
  • Potential resource exhaustion over time (leaked timers/requests), especially if callers retry startup repeatedly

Vulnerable flow:

  • sink: this.client.startClient(...) begins syncing
  • error paths: waitForInitialSyncReady(...) can reject on abort/timeout/unexpected error
  • missing cleanup: no stopClient()/stopSyncWithoutPersist() in these failure paths

Vulnerable code:

await this.client.startClient({ initialSyncLimit: this.initialSyncLimit });
await this.waitForInitialSyncReady({ abortSignal: opts.abortSignal, timeoutMs: opts.readyTimeoutMs });

If waitForInitialSyncReady rejects, the sync loop can continue running.

Recommendation

Ensure the underlying matrix-js-sdk client is stopped if startup fails after startClient().

For example, wrap the post-startClient() startup sequence in try/catch, and stop the client on any failure:

await this.client.startClient({ initialSyncLimit: this.initialSyncLimit });
try {
  await this.waitForInitialSyncReady({ abortSignal: opts.abortSignal, timeoutMs: opts.readyTimeoutMs });
  throwIfMatrixStartupAborted(opts.abortSignal);

  if (opts.bootstrapCrypto && this.autoBootstrapCrypto) {
    await this.bootstrapCryptoIfNeeded(opts.abortSignal);
  }
  throwIfMatrixStartupAborted(opts.abortSignal);

  this.started = true;
  this.emitOutstandingInviteEvents();
  await this.refreshDmCache().catch(noop);
} catch (e) {
  ​// stop any background sync started by startClient()
  this.stopSyncWithoutPersist();
  throw e;
}

This guarantees abort/timeout/unexpected errors during startup do not leave a running sync session behind.


Analyzed PR: #62779 at commit 901bb76

Last updated on: 2026-04-08T18:43:14Z

@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 21250c5 to 27f9d85 Compare April 8, 2026 17:47

@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: 27f9d850c1

ℹ️ 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".

@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: 795ef740b7

ℹ️ 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 thread extensions/matrix/src/matrix/sdk.ts Resolved
@gumadeiras
gumadeiras force-pushed the codex/matrix-channel-lifecycle-hardening branch from 795ef74 to 901bb76 Compare April 8, 2026 18:41
@gumadeiras
gumadeiras merged commit 0c00c3c into main Apr 8, 2026
8 checks passed
@gumadeiras
gumadeiras deleted the codex/matrix-channel-lifecycle-hardening branch April 8, 2026 18:41
@gumadeiras

Copy link
Copy Markdown
Member Author

Merged via squash.

Thanks @gumadeiras!

@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: 901bb767b5

ℹ️ 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".

eleqtrizit pushed a commit that referenced this pull request Apr 8, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
zooqueen pushed a commit to zooqueen/openclaw that referenced this pull request Sep 11, 2026
Merged via squash.

Prepared head SHA: 901bb76
Co-authored-by: gumadeiras <[email protected]>
Co-authored-by: gumadeiras <[email protected]>
Reviewed-by: @gumadeiras
steipete added a commit that referenced this pull request Oct 14, 2026
…of diagnostics (#171606)

## What Problem This Solves

Older channel-plugin code duplicates shared SDK ownership and carries defensive machinery for unsupported internal inputs, synthetic clocks, and throwing diagnostic hooks. Several normal inbound paths also put message content or pairing codes into diagnostics.

## User Impact

Message delivery, account/security policy, conversation identity, provider features, and ordinary shutdown/restart durability remain supported. Inbound message text, malformed Teams consent payloads and pairing codes no longer appear in the repaired diagnostic paths. No configuration, CLI, protocol, SDK export, dependency, schema, retention, or permission changes are required.

## Why This Change Was Made

This is the second old-code channel-plugin pass. Only production files with no origin/main commit in the preceding seven days are included; eligibility is refreshed before every push. The overlapping Feishu Markdown fence repair was removed from this branch once main independently landed it in #171222.

The packet removes **512 net production lines** (+503/-1015; tests, fixtures, test support, generated files, and declarations excluded). It reuses existing public SDK owners for plugin setup composition, secret-contract wiring, receipts, status summaries, process-global maps, error traversal, and account-scoped DM policy. There are no private-core or cross-plugin imports.

## Best-effort tradeoffs accepted

Each removed mechanism below was checked against callers, dependency behavior, and introducing history. Synthetic tests and hypothetical PR race descriptions are not treated as human production reports. Actual incident fixes, live security authority, FIFO, resource bounds, and accepted-write settlement are retained.

- Discord identify clock-skew observation (`c767b37e3b2`): the only added proof jumps the clock from a trillion milliseconds to zero; no human report is linked. A drastic backward clock jump can now prolong reconnect until clock recovery/restart; ordinary five-second parallel identify spacing remains.
- WhatsApp second synchronous close observation (#109886, `bf413374cca`): native Baileys uses EventEmitter and cannot asynchronously close between synchronous check/listener registration. A nonstandard reentrant `newListener` hook can reach the existing bounded timeout; transport-confirmed close and cleanup remain.
- Tlon formatter fallback (#1837, `51720980736`): validated decimal BigInt input cannot fail the pinned @ud formatter. A broken dependency now fails visibly instead of sending the incorrect raw ID that the original threading fix rejected.
- Matrix second private sync waiter (#62779, `0c00c3c2306`): the actual monitor waits once; only a synthetic test calls twice. An unsupported second call may replace the first callbacks; real outage/fatal/abort settlement remains.
- ClickClack outer setup catches (`752567dbc8e`): network/config failures are already caught by their owners; the extra path catches a broken logger/formatter then invokes the same logger again. Such internal failures now surface; ordinary setup diagnostics remain.
- ClickClack second workspace snapshot (`3e352d67278`): verification now resolves ID/name/slug from one provider response. A concurrent rename/removal is observed on the next verification/runtime request rather than an opportunistic second fetch.
- SMS generated-fragment revalidation (#118665, `0758316883f`): raw URL validation stays; only URLSearchParams-generated fragment bytes were checked twice. A monkeypatched/broken encoder is no longer revalidated; length, auth, URL and retry bounds remain.
- Feishu timeout-warning catch (`0028e6040a7`): the cited stuck-task/FIFO issues concern the retained five-minute cap, not a throwing logger. A broken warning hook now rejects that queue call visibly; subsequent same-key work continues.
- Feishu private timeout customization (`0028e6040a7`, `fab8d29d211`, #101949): only tests passed disabled/oversized/custom values. Unsupported direct imports can no longer tune/disable the private cap; all production callers retain five-minute progress/FIFO behavior.
- Reef logger-fatal deferred/race (#162669; synthetic hook in #110870): ordinary transport-error containment and shutdown from the recorded live relay incident stay. A throwing error logger is reported by the scheduler instead of intentionally killing an otherwise healthy inbox.
- Matrix nonfinite media size fallback (`9b71382efb6`, #149128): the sole production producer passes Buffer.byteLength; NaN cases were synthetic cleanup fixtures. Unsupported private NaN calls now carry that supplied value; MIME, encryption, image fields and duration remain.
- Buzz subscription count coercion (`6c7a96e588e`): the sole caller supplies array.length. Unsupported negative/fractional private values are not repaired; the actual room/resource cap remains.
- Teams upload-byte coercion (#104120, `0c8220ebf9a`): both callers supply Buffer.length. Unsupported malformed private counts follow transfer arithmetic; timer clamping and upload budgets stay.
- Nostr zero-count score fallback (`7b6cbf58697`): private entries are synchronously created and incremented together. An unsupported new zero-outcome insertion could score NaN; actual outage/circuit-breaker/failover behavior stays.
- Buzz profile-limit coercion (`ba2510e8fa8`): the only explicit producer supplies the bounded integer budget. Unsupported direct malformed limits are not normalized; ordinary caps, zero-budget and untrusted-event checks stay.
- Feishu card-launcher clock injection/max-Date guard (`05634708e05`): only a synthetic year-275760 test supplies the private clock. A corrupt clock may create an unusable expiry until recovery/restart; effect-side expiry, actor/chat and approval validation stay.
- QA private empty media-batch guard (#115290, `641c82b5bd0`): all three callers prove a nonempty batch. Unsupported direct empty calls take the ordinary text path; real media caps and atomic loading remain.
- Slack private global-map slot revalidation (original sharing fix `55318df83ff`): normal module sharing/replacement is retained. No human private-slot corruption report is linked; third-party mutation/deletion of our private Symbol slot is no longer checked on every read, and restart repairs unsupported corruption.
- Buzz synchronous subscription-construction compensation (`b48984792f4`, `828f88c5ca5`, #130300): native nostr-tools construction emits no callbacks and authored filters are plain/nonempty. Unsupported throwing/cyclic private filters or replaced constructors surface without immediate count/generation/timer compensation; close/deadline/restart recovers temporary state.
- Buzz post-construction inline-EOSE/abort retry (same provenance): native callbacks are asynchronous. A non-native constructor emitting EOSE inline no longer gets a second cleanup attempt; real EOSE-before-CLOSE, late EOSE, close-once, deadlines, queued slots, abort listeners, membership authority and shutdown remain. Fixtures now schedule EOSE with queueMicrotask while retaining assertions.
- Signal clean-end recovery duplication (#10240, `dff4a04c1f5`): clean EOF and transient failures share one backoff tail. An impossible non-abort internal sleep rejection or broken status/logger callback now surfaces rather than entering compensating reconnect; real sleep rejects on abort and actual recovery stays.
- WhatsApp optional native socket-end fallback (`69225003820`): actual callers use WASocket with required end(). An unsupported fake without end fails plainly; normal teardown and its error reporting stay.
- Nextcloud post-synchronous-route abort check (#159067, `5fd7c3d95e0`): the old awaited server-start path became synchronous route registration. A reentrant registry callback abort may briefly publish ready; installed abort cleanup, post-spool-ready check, auth and durable settlement stay.
- Buzz history-count clamps (`132e39bff64`): the actual positive room count and queue-capacity invariant guarantee the result. Unsupported private negative/oversized counts are not repaired; actual FIFO/resource reservations remain.
- LINE frozen-error wrapper (#100996, `f859d78b612`): native SDK HTTPFetchError is mutable; Object.freeze was a synthetic fixture, not a cited human incident. An unsupported frozen replacement error can now fail annotation with TypeError; actual partial-send/recovery contracts stay.
- LINE duplicate missing-receipt invariant (`05eda57b3c7`, #99600, #142092, #165718): all native sends return validated IDs and required receipts. Unsupported fake results use canonical bridge normalization instead of the former private throw; physical-send progress, caption quoting, receipt order and declared capabilities stay. The bridge also preserves already-sanctioned chatId metadata.
- Feishu display-cache extreme-clock guards (`23e1aac9b2c`): introduced with a synthetic max-Date test, no linked human report. Corrupt clocks follow ordinary arithmetic; account scope, positive/negative TTL and the 500-entry bound remain.
- Mattermost reaction-identity extreme-clock guards (`77b334a9845`): only invalid/max-Date tests support the machinery, no linked human report. Corrupt clocks follow arithmetic; token/base-URL scope, ten-minute expiry, delegated conversation/post/self-DM checks and request authority remain.

Other cuts remove duplicate facts/checks under one existing owner and introduce no additional failure tradeoff: Signal subscription/abort state, Zalouser Promise settlement and DM setter, Nextcloud claimed version/lane validation, Teams media/header validation and empty-array merging, Buzz refresh-state identity, Nostr flush identity, Matrix encryption gating, Mattermost runtime-config guard, immutable plugin setup bases, and private Discord/iMessage test overrides.

Matrix's private zero-answer poll fallback is also removed: its sole caller has already passed the shared minimum-two-options validator (`c49b6cc241a`, #163574). No reachable input loses a fallback. Teams attachment header rejection remains owned by the canonical bounded media saver; malformed/oversize headers now use the existing `attachmentView save failed` warning instead of the special malformed-header tag or silent oversized-header skip. The unavailable result and byte protection remain unchanged.

## Evidence

Focused owning-boundary/sibling tests and independent isolated reviews were run per checkpoint. Latest batches passed: Discord/LINE/Matrix/Synology 76 cases (157.00s wrapper), LINE/Feishu/Mattermost 66 cases (132.62s), Mattermost reaction 12 cases, Zalo Personal setup 17 cases (48.97s), and Teams consent/parser/lifecycle 52 cases (29.18s). The Teams malformed-content regression failed on the original handler before the one-line repair. The new Zalo test fixture initially assumed the wrong promotion target; source inspection and an explicit two-account fixture corrected it without changing production behavior or weakening retained assertions.

Production/test extension typechecks and targeted type-aware lint/format pass. Runtime and Madge checks report zero cycles. Existing SDK export checks pass. Earlier fresh cliStartup build and affected built-entry import proof passed; no performance improvement is claimed from dirty-tree profiling. No live accounts, operator state, driver installation, Gateway or remote lease was used.

Final Matrix poll/send/shared-normalization proof passes 55 cases across three shards (138.50s wrapper). Independent full-branch review and the supplemental poll review found no actionable P0–P2 findings.

Two local baseline gates are inherited from the branch base: suppression inventory expects 87 versus the untouched proxy's 88 (current main has repaired the entry); aggregate check-changed stops on stale untouched max-lines entry src/agents/btw.ts after conflict/line-cap gates pass. No allowlist/budget expansion was made. Earlier cold-start timing-sensitive failures remain observations, not claimed repaired/inherited; the complete changed cold-start file subsequently passed all eight cases with unchanged timers/assertions.

The first exact-head hosted run [38503961141](https://github.com/openclaw/openclaw/actions/runs/38503961141) completed in 643 seconds: 51 jobs passed, 25 planned jobs skipped, and the baseline ratchet plus its aggregate gate failed. The defect was ours: removed Slack/Twitch assertions and two removed ClickClack mocks needed exact inventory shrinkage. Those four inventory items are corrected without adding allowances or changing behavior. All actual tests, types, lint, architecture, package boundaries, QA and security jobs passed on that production patch. Final exact-head run [38505676106](https://github.com/openclaw/openclaw/actions/runs/38505676106) passed on `86922ccf92825d4b53b77005119590d1e7759a32`: 55 successful jobs, 25 planned skips, zero failed/cancelled jobs, 643 seconds wall time and 9,679 summed reported job seconds. The exact-head required CI/security gate passes. CodeQL also reports a neutral warning for unselected main configurations; those skipped configurations are not claimed as proof. No CI rerun, inherited-failure admin exception, or green-seeking push was used.

<details>
<summary>Round-2 largest-first coverage log</summary>

Setup/runtime composition is consolidated for Buzz, Nostr, A2A and Google Chat; setup stays dependency-light. Matrix/Feishu secret activation uses the existing factory with activation/order/owner rules unchanged. IRC shares parsing/status owners. LINE shares receipt/progress mapping without routing through legacy media behavior. Zalo Personal shares the existing account-scoped DM policy owner. Privacy regressions reach real WhatsApp/iMessage/Synology inbound and Feishu pairing diagnostic paths while asserting complete dispatch/challenge behavior.

Largest old owners retained after source/caller/history review include iMessage catchup/conversation repair; Matrix formatting/actions/crypto/shutdown; Mattermost interactive access/draft boundary/final receipts; Signal approvals/transport setup; Slack ingress FIFO/thread visibility/workspace identity/streaming; WhatsApp paid-STT/admission/quoted identity/partial delivery; Teams Graph/Bot Framework/upload consent security; Buzz signed membership/archival authority/resource budgets; Nostr circuit breakers/profile mutation auth; LINE provider caps/reply-token/media ordering; Twitch listener/auth resource ownership; SMS callback/API ordering; Synology auth/rate limits/durable acknowledgments; Reef encryption/transport error containment; FaceTime trust/rollback/permissions; and paid X request accounting.

Recent files were deferred, including remaining Teams inbound-body, Tlon admin/approval-text and WhatsApp outbound-content diagnostics; recently landed feature foundations were not treated as dead code. QA setup-base consolidation was held because completing its runtime caller would exceed the one-line recent-file exception. No Phase E standalone memory code was touched. Detailed per-mechanism provenance and checkpoint evidence is retained in the requested round-2 lane ledger.

</details>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 14, 2026
…of diagnostics (openclaw#171606)

## What Problem This Solves

Older channel-plugin code duplicates shared SDK ownership and carries defensive machinery for unsupported internal inputs, synthetic clocks, and throwing diagnostic hooks. Several normal inbound paths also put message content or pairing codes into diagnostics.

## User Impact

Message delivery, account/security policy, conversation identity, provider features, and ordinary shutdown/restart durability remain supported. Inbound message text, malformed Teams consent payloads and pairing codes no longer appear in the repaired diagnostic paths. No configuration, CLI, protocol, SDK export, dependency, schema, retention, or permission changes are required.

## Why This Change Was Made

This is the second old-code channel-plugin pass. Only production files with no origin/main commit in the preceding seven days are included; eligibility is refreshed before every push. The overlapping Feishu Markdown fence repair was removed from this branch once main independently landed it in openclaw#171222.

The packet removes **512 net production lines** (+503/-1015; tests, fixtures, test support, generated files, and declarations excluded). It reuses existing public SDK owners for plugin setup composition, secret-contract wiring, receipts, status summaries, process-global maps, error traversal, and account-scoped DM policy. There are no private-core or cross-plugin imports.

## Best-effort tradeoffs accepted

Each removed mechanism below was checked against callers, dependency behavior, and introducing history. Synthetic tests and hypothetical PR race descriptions are not treated as human production reports. Actual incident fixes, live security authority, FIFO, resource bounds, and accepted-write settlement are retained.

- Discord identify clock-skew observation (`fa56d13411c`): the only added proof jumps the clock from a trillion milliseconds to zero; no human report is linked. A drastic backward clock jump can now prolong reconnect until clock recovery/restart; ordinary five-second parallel identify spacing remains.
- WhatsApp second synchronous close observation (openclaw#109886, `ca60d105ece`): native Baileys uses EventEmitter and cannot asynchronously close between synchronous check/listener registration. A nonstandard reentrant `newListener` hook can reach the existing bounded timeout; transport-confirmed close and cleanup remain.
- Tlon formatter fallback (openclaw#1837, `a898f3d7bb5`): validated decimal BigInt input cannot fail the pinned @ud formatter. A broken dependency now fails visibly instead of sending the incorrect raw ID that the original threading fix rejected.
- Matrix second private sync waiter (openclaw#62779, `aec73fd9ca4`): the actual monitor waits once; only a synthetic test calls twice. An unsupported second call may replace the first callbacks; real outage/fatal/abort settlement remains.
- ClickClack outer setup catches (`9079efe9026`): network/config failures are already caught by their owners; the extra path catches a broken logger/formatter then invokes the same logger again. Such internal failures now surface; ordinary setup diagnostics remain.
- ClickClack second workspace snapshot (`188ce1e28e9`): verification now resolves ID/name/slug from one provider response. A concurrent rename/removal is observed on the next verification/runtime request rather than an opportunistic second fetch.
- SMS generated-fragment revalidation (openclaw#118665, `37690fb4f4b`): raw URL validation stays; only URLSearchParams-generated fragment bytes were checked twice. A monkeypatched/broken encoder is no longer revalidated; length, auth, URL and retry bounds remain.
- Feishu timeout-warning catch (`7a2ce698b8c`): the cited stuck-task/FIFO issues concern the retained five-minute cap, not a throwing logger. A broken warning hook now rejects that queue call visibly; subsequent same-key work continues.
- Feishu private timeout customization (`7a2ce698b8c`, `491abe564ce`, openclaw#101949): only tests passed disabled/oversized/custom values. Unsupported direct imports can no longer tune/disable the private cap; all production callers retain five-minute progress/FIFO behavior.
- Reef logger-fatal deferred/race (openclaw#162669; synthetic hook in openclaw#110870): ordinary transport-error containment and shutdown from the recorded live relay incident stay. A throwing error logger is reported by the scheduler instead of intentionally killing an otherwise healthy inbox.
- Matrix nonfinite media size fallback (`96ff92e82bb`, openclaw#149128): the sole production producer passes Buffer.byteLength; NaN cases were synthetic cleanup fixtures. Unsupported private NaN calls now carry that supplied value; MIME, encryption, image fields and duration remain.
- Buzz subscription count coercion (`d656588ae32`): the sole caller supplies array.length. Unsupported negative/fractional private values are not repaired; the actual room/resource cap remains.
- Teams upload-byte coercion (openclaw#104120, `6d759fe8b17`): both callers supply Buffer.length. Unsupported malformed private counts follow transfer arithmetic; timer clamping and upload budgets stay.
- Nostr zero-count score fallback (`25838b5d7de`): private entries are synchronously created and incremented together. An unsupported new zero-outcome insertion could score NaN; actual outage/circuit-breaker/failover behavior stays.
- Buzz profile-limit coercion (`67bce4fe0d7`): the only explicit producer supplies the bounded integer budget. Unsupported direct malformed limits are not normalized; ordinary caps, zero-budget and untrusted-event checks stay.
- Feishu card-launcher clock injection/max-Date guard (`207f045b11c`): only a synthetic year-275760 test supplies the private clock. A corrupt clock may create an unusable expiry until recovery/restart; effect-side expiry, actor/chat and approval validation stay.
- QA private empty media-batch guard (openclaw#115290, `4dbddeefcc9`): all three callers prove a nonempty batch. Unsupported direct empty calls take the ordinary text path; real media caps and atomic loading remain.
- Slack private global-map slot revalidation (original sharing fix `564ccc6f56a`): normal module sharing/replacement is retained. No human private-slot corruption report is linked; third-party mutation/deletion of our private Symbol slot is no longer checked on every read, and restart repairs unsupported corruption.
- Buzz synchronous subscription-construction compensation (`2bd60a2e983`, `eb99a1b3432`, openclaw#130300): native nostr-tools construction emits no callbacks and authored filters are plain/nonempty. Unsupported throwing/cyclic private filters or replaced constructors surface without immediate count/generation/timer compensation; close/deadline/restart recovers temporary state.
- Buzz post-construction inline-EOSE/abort retry (same provenance): native callbacks are asynchronous. A non-native constructor emitting EOSE inline no longer gets a second cleanup attempt; real EOSE-before-CLOSE, late EOSE, close-once, deadlines, queued slots, abort listeners, membership authority and shutdown remain. Fixtures now schedule EOSE with queueMicrotask while retaining assertions.
- Signal clean-end recovery duplication (openclaw#10240, `1b2dfffddeb`): clean EOF and transient failures share one backoff tail. An impossible non-abort internal sleep rejection or broken status/logger callback now surfaces rather than entering compensating reconnect; real sleep rejects on abort and actual recovery stays.
- WhatsApp optional native socket-end fallback (`3294ef6f0cb`): actual callers use WASocket with required end(). An unsupported fake without end fails plainly; normal teardown and its error reporting stay.
- Nextcloud post-synchronous-route abort check (openclaw#159067, `af36cf97537`): the old awaited server-start path became synchronous route registration. A reentrant registry callback abort may briefly publish ready; installed abort cleanup, post-spool-ready check, auth and durable settlement stay.
- Buzz history-count clamps (`bbde46b881f`): the actual positive room count and queue-capacity invariant guarantee the result. Unsupported private negative/oversized counts are not repaired; actual FIFO/resource reservations remain.
- LINE frozen-error wrapper (openclaw#100996, `a2aad76fdba`): native SDK HTTPFetchError is mutable; Object.freeze was a synthetic fixture, not a cited human incident. An unsupported frozen replacement error can now fail annotation with TypeError; actual partial-send/recovery contracts stay.
- LINE duplicate missing-receipt invariant (`15be48ecd0e`, openclaw#99600, openclaw#142092, openclaw#165718): all native sends return validated IDs and required receipts. Unsupported fake results use canonical bridge normalization instead of the former private throw; physical-send progress, caption quoting, receipt order and declared capabilities stay. The bridge also preserves already-sanctioned chatId metadata.
- Feishu display-cache extreme-clock guards (`ab53c2998a1`): introduced with a synthetic max-Date test, no linked human report. Corrupt clocks follow ordinary arithmetic; account scope, positive/negative TTL and the 500-entry bound remain.
- Mattermost reaction-identity extreme-clock guards (`6199cc7df89`): only invalid/max-Date tests support the machinery, no linked human report. Corrupt clocks follow arithmetic; token/base-URL scope, ten-minute expiry, delegated conversation/post/self-DM checks and request authority remain.

Other cuts remove duplicate facts/checks under one existing owner and introduce no additional failure tradeoff: Signal subscription/abort state, Zalouser Promise settlement and DM setter, Nextcloud claimed version/lane validation, Teams media/header validation and empty-array merging, Buzz refresh-state identity, Nostr flush identity, Matrix encryption gating, Mattermost runtime-config guard, immutable plugin setup bases, and private Discord/iMessage test overrides.

Matrix's private zero-answer poll fallback is also removed: its sole caller has already passed the shared minimum-two-options validator (`306de68c026`, openclaw#163574). No reachable input loses a fallback. Teams attachment header rejection remains owned by the canonical bounded media saver; malformed/oversize headers now use the existing `attachmentView save failed` warning instead of the special malformed-header tag or silent oversized-header skip. The unavailable result and byte protection remain unchanged.

## Evidence

Focused owning-boundary/sibling tests and independent isolated reviews were run per checkpoint. Latest batches passed: Discord/LINE/Matrix/Synology 76 cases (157.00s wrapper), LINE/Feishu/Mattermost 66 cases (132.62s), Mattermost reaction 12 cases, Zalo Personal setup 17 cases (48.97s), and Teams consent/parser/lifecycle 52 cases (29.18s). The Teams malformed-content regression failed on the original handler before the one-line repair. The new Zalo test fixture initially assumed the wrong promotion target; source inspection and an explicit two-account fixture corrected it without changing production behavior or weakening retained assertions.

Production/test extension typechecks and targeted type-aware lint/format pass. Runtime and Madge checks report zero cycles. Existing SDK export checks pass. Earlier fresh cliStartup build and affected built-entry import proof passed; no performance improvement is claimed from dirty-tree profiling. No live accounts, operator state, driver installation, Gateway or remote lease was used.

Final Matrix poll/send/shared-normalization proof passes 55 cases across three shards (138.50s wrapper). Independent full-branch review and the supplemental poll review found no actionable P0–P2 findings.

Two local baseline gates are inherited from the branch base: suppression inventory expects 87 versus the untouched proxy's 88 (current main has repaired the entry); aggregate check-changed stops on stale untouched max-lines entry src/agents/btw.ts after conflict/line-cap gates pass. No allowlist/budget expansion was made. Earlier cold-start timing-sensitive failures remain observations, not claimed repaired/inherited; the complete changed cold-start file subsequently passed all eight cases with unchanged timers/assertions.

The first exact-head hosted run [38503961141](https://github.com/openclaw/openclaw/actions/runs/38503961141) completed in 643 seconds: 51 jobs passed, 25 planned jobs skipped, and the baseline ratchet plus its aggregate gate failed. The defect was ours: removed Slack/Twitch assertions and two removed ClickClack mocks needed exact inventory shrinkage. Those four inventory items are corrected without adding allowances or changing behavior. All actual tests, types, lint, architecture, package boundaries, QA and security jobs passed on that production patch. Final exact-head run [38505676106](https://github.com/openclaw/openclaw/actions/runs/38505676106) passed on `86922ccf92825d4b53b77005119590d1e7759a32`: 55 successful jobs, 25 planned skips, zero failed/cancelled jobs, 643 seconds wall time and 9,679 summed reported job seconds. The exact-head required CI/security gate passes. CodeQL also reports a neutral warning for unselected main configurations; those skipped configurations are not claimed as proof. No CI rerun, inherited-failure admin exception, or green-seeking push was used.

<details>
<summary>Round-2 largest-first coverage log</summary>

Setup/runtime composition is consolidated for Buzz, Nostr, A2A and Google Chat; setup stays dependency-light. Matrix/Feishu secret activation uses the existing factory with activation/order/owner rules unchanged. IRC shares parsing/status owners. LINE shares receipt/progress mapping without routing through legacy media behavior. Zalo Personal shares the existing account-scoped DM policy owner. Privacy regressions reach real WhatsApp/iMessage/Synology inbound and Feishu pairing diagnostic paths while asserting complete dispatch/challenge behavior.

Largest old owners retained after source/caller/history review include iMessage catchup/conversation repair; Matrix formatting/actions/crypto/shutdown; Mattermost interactive access/draft boundary/final receipts; Signal approvals/transport setup; Slack ingress FIFO/thread visibility/workspace identity/streaming; WhatsApp paid-STT/admission/quoted identity/partial delivery; Teams Graph/Bot Framework/upload consent security; Buzz signed membership/archival authority/resource budgets; Nostr circuit breakers/profile mutation auth; LINE provider caps/reply-token/media ordering; Twitch listener/auth resource ownership; SMS callback/API ordering; Synology auth/rate limits/durable acknowledgments; Reef encryption/transport error containment; FaceTime trust/rollback/permissions; and paid X request accounting.

Recent files were deferred, including remaining Teams inbound-body, Tlon admin/approval-text and WhatsApp outbound-content diagnostics; recently landed feature foundations were not treated as dead code. QA setup-base consolidation was held because completing its runtime caller would exceed the one-line recent-file exception. No Phase E standalone memory code was touched. Detailed per-mechanism provenance and checkpoint evidence is retained in the requested round-2 lane ledger.

</details>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: matrix Channel integration: matrix maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Matrix provider connection failure causes rapid gateway process crash loop

2 participants