Skip to content

refactor(channels): route ingress queue through the state broker - #159073

Merged
steipete merged 4 commits into
mainfrom
hostneutral/ingress-final-broker-0926
Sep 26, 2026
Merged

steipete merged 4 commits into
mainfrom
hostneutral/ingress-final-broker-0926

Conversation

@steipete

@steipete steipete commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The shared channel ingress queue still performs operational reads and writes synchronously on the Gateway thread, despite exposing an asynchronous API.

User Impact

Inbound persistence and replay use the existing shared-state SQLite broker. Admission returns only after commit; claim fencing, per-account ordering, dedupe, retention, and accepted-write settlement remain intact. Operational listings observe earlier committed writes and still create a missing database for ordinary read-write queues. Explicit read-only inspection remains noncreating.

Update behavior: no schema, stored-byte, config, port, webhook path, signature, dedupe-window, or retention change; no migration or operator action. The maintainer approved the worker-access change and the broker-ordered listing adjustment. Legacy pre-May-31 Telegram spool import and Telegram startup profiling remain documented follow-ups, as directed.

Why This Change Was Made

All twelve mutations and the operational listings cut over together to preserve one FIFO owner. Diagnostic failed-health, pressure, and account discovery already use read-only workers. Channel parsing and lane policy stay on the host; the worker verifies the prepared ordered snapshot before applying a claim or recovery decision. Custom claim clocks are sampled at transaction admission. Accepted commits settle even if caller authority later revokes.

The drain consumes one coherent pending/claimed snapshot. listUnsettled is optional for existing external queue implementations through the next SDK major. purge accepts an optional cancellation signal, and Telegram passes its existing signal. Runtime construction binds live plugin authority to every operation, replacing the purge-only wrapper. The existing table and database version are unchanged.

Deletes the main-thread queue SQL path and superseded runtime wrapper. The final write cutover is intentionally larger than the fixture slices because mixing native and broker mutations would break admission ordering. Earlier slices removed Telegram directory helpers and consolidated shared fixture scaffolding.

Production +965/-943/net +22; tests and test support +837/-315/net +522; docs +41/-18/net +23; tooling/config +3/-2/net +1. The runtime growth preserves authority and settlement across a worker boundary. All earlier slices plus this candidate total production net +446; test fixture consolidation reduced the original +517 growth to +386 before the final routing/regression coverage.

Evidence

Provider: blacksmith-testbox. Lease tbx_01m3f53n667mcj031n55vm5tj8 (run), frozen install, pnpm tsgo:core (41.13s), pnpm tsgo:extensions:test (78.55s), and inventory generation/check passed. Nine focused owner files passed 144 tests. Single-worker wall cost per file: queue 33.02s; claim ownership 9.28s; readonly access 8.07s; pruning 7.20s; drain lanes 8.50s; monitor 9.44s; plugin-state runtime 14.12s; registry runtime-config 11.08s; Telegram monitor 15.15s. The two changed tooling files passed 381 tests in a combined 192.99s single-worker wall.

The additional 72-file per-config run used pnpm test <explicit routed ingress paths> --maxWorkers=1: 128 core tests and 855 extension tests passed, with two fixture failures over 518.11s. LINE and MS Teams waited for a listPending spy that the coherent snapshot intentionally replaces. Both fixtures now capture the real monitor and await its pump, preserving the eight-delivery cap and queued-row assertions.

Lease tbx_01m3faw6necd61h11wcf6se4hs (run) proved the corrections: pnpm test extensions/line/src/webhook-spool.test.ts --maxWorkers=1 passed 14 tests in 31.09s; pnpm test extensions/msteams/src/msteams-ingress.test.ts --maxWorkers=1 passed 15 in 18.32s. Extension types (79.74s), runtime import cycles (9.38s; zero), Madge cycles (26.36s; zero), SDK exports (0.22s), and docs sanity (54.79s) passed. The existing pruning case with padded protected IDs passed (five tests, 8.46s). Negative controls failed for the intended reasons: removing normalization deleted a protected row; raising either channel's cap to nine caused nine deliveries where eight were required. The production controls were restored and checked.

Worker routing is covered by actual queue operations with calling-thread SQLite primitives refusing execution. Regression probes also cover missing database creation, committed-then-list inside an older ambient snapshot, live authority after awaited policy, custom-clock transaction grants, post-grant settlement, and coherent lane inspection. No weaker guards or assertions were substituted.

Deslop is clean. Codex P0–P2 review is clean after supplying the full unchanged worker kernel: two earlier allegations were disproven by existing normalization and corrupt-row filtering, with direct tests. The final review used a byte-verified capture of the full 35-file diff and the broker/kernel context. Rebase onto 4ab72dd0d2c2cc335569da0603f7778f276a1717 was patch-identical. The maintainer authorized GitHub exact-head auto-merge; required CI remains the gate.

Fresh proof on published source head b828403ef8f309ffda1e4859f6eca3268fdc66cb (same lease): queue/claim/readonly regression suites passed 47 tests in 38.51s; regenerated inventory and its check passed (545 source files, 2543 primitive calls). pnpm plugin-sdk:api:diff --base 4ab72dd0d2c2cc335569da0603f7778f276a1717 --head b828403ef8f309ffda1e4859f6eca3268fdc66cb passed in 242.79s; exports passed in 0.17s. The SDK acknowledgement digest is e2cba13f. No entrypoints were added or removed; the additive queue contract is intentional and documented. Head 0b24c42b9242b07e1a7c60147b4cba5f46d5bd91 refreshed two generated source-line references; the correction below produces source head 7c6b771277b3969d41fd4871d42083a8de7e23ab.

CI run 36259983898 stopped at check-dependencies: the removed native facade had been the final external consumer of an internal ChannelIngressQueueEnqueueResult export. That alias is now private; the public enqueue result union is unchanged. The other jobs were cancelled by fail-fast. On the same Testbox lease, the exact pnpm deadcode:full check passed in 90.78s and core types passed in 39.97s. Fresh Codex P0–P2 review of the one-line correction is clean. No guard, assertion, baseline, or ignore was weakened.

SDK evidence was refreshed for source head 7c6b771277b3969d41fd4871d42083a8de7e23ab: API diff passed in 224.71s, exports in 0.17s; acknowledgement digest ff8eb511. There are no entrypoint additions/removals. Two printed monitor signatures inline the same enqueue-result union after its internal alias becomes private; the structural contract is unchanged, alongside the intentional optional queue additions above.

CI run 36261009416 then required the assertion-safety allowance to shrink from one to zero. Canonical Testbox generation removed that entry and the now-obsolete max-lines exemption. An unrelated generator-proposed allowance was excluded. Checks passed with only the two queue removals: assertion safety 23.00s, max-lines 5.78s; Codex review is clean. Head e7cd48a0aecc6fb13a5820f0314fe9b62a73cbf0 contains that shrink-only correction. Runtime and SDK code are unchanged.

Merged as f0b78f55d6d5acfb052a4512d97088b408a0c28d, verified on origin/main. Exact head e7cd48a0aecc6fb13a5820f0314fe9b62a73cbf0 passed CI run 36262161690.

Completed merged-main live proof and exact controller: blacksmith-testbox lease tbx_01m3fgsbnbassrytjwk2nxs08w, run 36263879658; frozen install, pnpm build passed in 368.81s, and node /tmp/openclaw-ingress-crash-proof.mjs passed in 19.62s. Invalid signature: 403/no admission. Valid webhook: 200/durable acknowledgement; claimed row survived actual Gateway SIGKILL. Three Gateway generations and three valid deliveries produced two handler attempts and one controlled completion; post-completion duplicates did not dispatch. All task leases are stopped, with the final lease verified completed. This proves the selected crash boundary with at-least-once replay and dedupe.

Stack

Landed: #157687 → #158203 → #158233 → #158288 → #158412 → #158477 → #158628 → #158637 → #158860 → #158887 → #158896 → #158928 → #158933 → #158980 → #158987 → #159006 → #159008. This is the final atomic broker cutover and inventory slice. Signed-SMS crash/replay proof follows on merged main.

@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: line Channel integration: line channel: msteams Channel integration: msteams channel: telegram Channel integration: telegram scripts Repository scripts plugin: file-transfer size: XL labels Sep 26, 2026
@steipete
steipete enabled auto-merge (squash) September 26, 2026 17:46
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Sep 26, 2026
@clawsweeper

clawsweeper Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 26, 2026, 2:28 PM ET / 18:28 UTC (Revision 2).

ClawSweeper review

What this changes

Routes durable inbound channel queue operations through the shared SQLite state worker, gives drains one coherent pending-and-claimed listing, and forwards Telegram purge cancellation.

Merge readiness

✅ Ready for maintainer review

Current main still runs operational ingress queue SQL on the Gateway thread. The merged preparation does not complete this work, and the reviewed branch remains necessary. I found no actionable defect introduced by the patch.

Priority: P2
Reviewed head: e7cd48a0aecc6fb13a5820f0314fe9b62a73cbf0

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The cutover has focused worker, channel, and authority coverage with no discrete defect found in source review.
Proof confidence 🐚 platinum hermit (4/6) Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor proof gate does not apply. The PR reports Testbox runs of queue operations through the production SQLite worker, and source tests inspect final rows after plugin revocation; this review did not independently execute them. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor proof gate does not apply. The PR reports Testbox runs of queue operations through the production SQLite worker, and source tests inspect final rows after plugin revocation; this review did not independently execute them. No stored-data contract changes.
Evidence reviewed 9 items Current main: The fetched main queue facade still opens the state database and imports synchronous SQLite operations for operational queue work.
Broker route: The branch captures state context and dispatches queue operations through the shared state worker.
Write admission: Queue mutations execute in the worker transaction and request transaction and commit grants before returning a result.
Findings None None.
Security None None.

How this fits together

Channel plugins queue inbound events before acknowledging transport delivery. The shared state database retains those events while the channel drain claims, dispatches, and completes them.

flowchart LR
  A[Inbound channel event] --> B[Ingress queue request]
  B --> C[Live plugin authority]
  C --> D[Shared state broker]
  D --> E[SQLite ingress rows]
  E --> F[Channel drain]
  F --> G[Dispatch and completion]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +22, Tests +522, Docs +23, Other +1. Total +568 across 37 files.

View PR surface stats
Area Files Added Removed Net
Source 15 958 936 +22
Tests 15 837 315 +522
Docs 4 41 18 +23
Config 0 0 0 0
Generated 0 0 0 0
Other 3 3 2 +1
Total 37 1839 1271 +568

Review metrics

Metric Value Why it matters
Production versus test growth production net +22; tests and support net +522 The small production increase carries worker admission and settlement; the larger test increase covers queue and authority behavior.

Root-cause cluster

Relationship: canonical
Canonical: #159073
Summary: The earlier merged kernel extraction prepares this distinct final worker cutover.

Members:

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

Technical review

Best possible solution:

Keep one broker-backed queue owner and its compatible plugin contract, then record the planned signed-SMS process-kill replay on merged main.

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

Yes, at source level: current main still opens the queue database and runs operational SQLite work on the calling path. This read-only review did not execute a Gateway reproduction.

Is this the best way to solve the issue?

Yes. Reusing the existing shared-state broker is the narrow owner cutover, and the optional listing method preserves external queue implementations.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This shared channel-runtime improvement has broad reach without evidence of an urgent user outage.
  • merge-risk: 🚨 message-delivery: A queue-ordering or settlement regression could affect durable inbound acceptance and replay across channels.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: The supplied repository state identifies a member-authored PR, so the external-contributor proof gate does not apply. The PR reports Testbox runs of queue operations through the production SQLite worker, and source tests inspect final rows after plugin revocation; this review did not independently execute them. No stored-data contract changes.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

  • 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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-09-26T18:08:30.733Z sha 7c6b771 :: blocked before merge. :: none

@steipete
steipete merged commit f0b78f5 into main Sep 26, 2026
246 checks passed
@steipete
steipete deleted the hostneutral/ingress-final-broker-0926 branch September 26, 2026 18:38
@steipete

Copy link
Copy Markdown
Contributor Author

Merged-main live proof passed on f0b78f55d6d5acfb052a4512d97088b408a0c28d, verified on origin/main. Exact PR head e7cd48a0aecc6fb13a5820f0314fe9b62a73cbf0 passed CI run 36262161690 before auto-merge.

Provider: blacksmith-testbox. Lease: tbx_01m3fgsbnbassrytjwk2nxs08w; run 36263879658. In a clean detached checkout of that merged commit:

pnpm install --frozen-lockfile
pnpm build
node /tmp/openclaw-ingress-crash-proof.mjs

Build passed in 368.81s; live proof passed in 19.62s. The controller starts each Gateway with pnpm openclaw gateway run --port <isolated-port> --allow-unconfigured, isolated home/state/config, and a synthetic plugin holding the normal before_dispatch hook. It sends an HMAC-signed Twilio-style POST to the actual Gateway SMS route. The provider credentials and event are synthetic; no external SMS service or operator Gateway is used.

Observed: an invalid signature returned 403 without admission; the valid request returned HTTP 200 with x-openclaw-delivery-accepted: durable. The claimed row was present before SIGKILL and remained durable after the actual Gateway PID exited. Restart replayed it into one controlled completion; duplicate deliveries, including across another restart, caused no additional dispatch. This demonstrates the selected crash window with at-least-once delivery and dedupe, not universal exactly-once external effects.

{"phase":"ready","generation":1,"pid":8197}
{"phase":"invalid-signature-rejected","status":403}
{"phase":"webhook-ack","status":200,"durable":true}
{"phase":"before-kill","row":{"status":"claimed","attempts":0,"completed_at":null},"completions":0}
{"phase":"stop-signal","generation":1,"pid":8197,"signal":"SIGKILL"}
{"phase":"persisted-after-kill","row":{"status":"claimed","attempts":0,"completed_at":null},"completions":0}
{"phase":"ready","generation":2,"pid":8591}
{"phase":"recovered","row":{"status":"completed","attempts":1,"completed_at":1790449178967},"attempts":2,"completions":1}
{"phase":"webhook-ack","status":200,"durable":true}
{"phase":"stop-signal","generation":2,"pid":8591,"signal":"SIGTERM"}
{"phase":"ready","generation":3,"pid":9030}
{"phase":"webhook-ack","status":200,"durable":true}
{"phase":"stop-signal","generation":3,"pid":9030,"signal":"SIGTERM"}
{"phase":"PASS","generations":3,"admissions":3,"attempts":2,"completions":1}

The worker-routing tests independently reject calling-thread SQLite execution while exercising queue operations; missing-database and committed-then-list probes passed. The regenerated inventory records operational reads in broker FIFO and diagnostic reads in read-only workers. No schema or migration is added.

Exact synthetic controller (SHA-256 2bc182d5f45cf7b751999704266aecdb7785419fcb81e3c2e29993694500d441)

Save as /tmp/openclaw-ingress-crash-proof.mjs and run from the built checkout above. It generates ephemeral credentials locally and retires its own Gateway process groups.

import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { randomBytes, createHmac } from 'node:crypto';
import { createWriteStream } from 'node:fs';
import fs from 'node:fs/promises';
import { createServer } from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { DatabaseSync } from 'node:sqlite';

assert.equal(process.platform, 'linux', 'This Testbox controller verifies process exit via /proc.');
const cancellation = new AbortController();
for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, () => cancellation.abort(new Error(`Proof interrupted by ${signal}`)));
}
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'openclaw-ingress-crash-proof-'));
const stateDir = path.join(root, 'state');
const pluginDir = path.join(root, 'proof-plugin');
await fs.mkdir(pluginDir, { recursive: true });
await fs.mkdir(stateDir, { recursive: true });
const eventId = 'SM' + '2'.repeat(32);
const accountSid = 'AC' + '1'.repeat(32);
const authToken = randomBytes(24).toString('hex');
const queueName = JSON.stringify(['sms', 'default']);
const gatewayLog = createWriteStream(path.join(root, 'gateway-live.log'), { mode: 0o600 });
let release = false;
let attempts = 0;
const completions = [];
const blocked = new Set();
const control = createServer((req, res) => {
  if (req.url === '/enter') {
    attempts++;
    if (release) res.end('continue');
    else { blocked.add(res); res.on('close', () => blocked.delete(res)); }
  } else if (req.url === '/complete') {
    completions.push(eventId);
    res.end('recorded');
  } else { res.writeHead(404); res.end(); }
});
await new Promise(resolve => control.listen(0, '127.0.0.1', resolve));
const controlUrl = `http://127.0.0.1:${control.address().port}`;
const reserve = createServer();
await new Promise(resolve => reserve.listen(0, '127.0.0.1', resolve));
const port = reserve.address().port;
await new Promise(resolve => reserve.close(resolve));
const webhookUrl = `http://127.0.0.1:${port}/webhooks/sms`;
const signedUrl = 'https://sms-proof.example.test/webhooks/sms';
await fs.writeFile(path.join(pluginDir, 'openclaw.plugin.json'), JSON.stringify({
  id: 'ingress-proof', name: 'Synthetic ingress crash proof',
  activation: { onStartup: true },
  configSchema: { type: 'object', additionalProperties: false, properties: {} },
}));
await fs.writeFile(path.join(pluginDir, 'index.cjs'), `module.exports = {
  id: 'ingress-proof', register(api) {
    console.log('INGRESS_PROOF_GATEWAY_PID=' + process.pid);
    api.on('before_dispatch', async (event) => {
      if (event.channel !== 'sms' || event.messageId !== ${JSON.stringify(eventId)}) return;
      await fetch(${JSON.stringify(controlUrl + '/enter')});
      await fetch(${JSON.stringify(controlUrl + '/complete')});
      return { handled: true };
    });
  }
};`);
const config = {
  gateway: { mode: 'local', bind: 'loopback', auth: { mode: 'token', token: randomBytes(24).toString('hex') } },
  agents: { ownership: 'explicit', defaults: { model: { primary: 'openai/gpt-5.6-sol' } }, entries: { main: { workspace: path.join(root, 'workspace') } } },
  bindings: [{ agentId: 'main', match: { channel: 'sms', accountId: 'default' } }],
  plugins: { enabled: true, allow: ['sms', 'ingress-proof'], load: { paths: [path.join(pluginDir, 'index.cjs')] }, entries: { sms: { enabled: true }, 'ingress-proof': { enabled: true } } },
  channels: { sms: { enabled: true, accountSid, authToken, fromNumber: '+15550001111', publicWebhookUrl: signedUrl, webhookPath: '/webhooks/sms', dmPolicy: 'allowlist', allowFrom: ['+15550002222'] } },
};
const configPath = path.join(stateDir, 'openclaw.json');
await fs.writeFile(configPath, JSON.stringify(config), { mode: 0o600 });
// The child needs executable lookup, not the lease's provider credentials or operator config.
const env = {
  PATH: process.env.PATH,
  HOME: root,
  TMPDIR: os.tmpdir(),
  LANG: 'C.UTF-8',
  OPENCLAW_STATE_DIR: stateDir,
  OPENCLAW_HOME: root,
  OPENCLAW_CONFIG_PATH: configPath,
  OPENCLAW_NO_RESPAWN: '1',
  OPENCLAW_SKIP_STARTUP_MODEL_PREWARM: '1',
};
let gateway;
let gatewayPid;
let output = '';
let generation = 0;
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function until(predicate, label, timeout = 120000) {
  const start = Date.now();
  while (!(await predicate())) {
    cancellation.signal.throwIfAborted();
    if (Date.now() - start > timeout) throw new Error(`Timed out: ${label}\n${output.slice(-12000)}`);
    if (gateway && (gateway.exitCode !== null || gateway.signalCode !== null)) throw new Error(`Gateway exited ${gateway.exitCode ?? gateway.signalCode}: ${output.slice(-12000)}`);
    await delay(50);
  }
}
async function startGateway() {
  cancellation.signal.throwIfAborted();
  generation++;
  output = '';
  gatewayPid = undefined;
  gatewayLog.write(`\n--- Gateway generation ${generation} ---\n`);
  gateway = spawn('pnpm', ['openclaw', 'gateway', 'run', '--port', String(port), '--allow-unconfigured'], { cwd: process.cwd(), env, detached: true, stdio: ['ignore', 'pipe', 'pipe'] });
  gateway.on('error', error => { output += String(error); });
  for (const stream of [gateway.stdout, gateway.stderr]) stream.on('data', chunk => {
    output += chunk.toString();
    gatewayLog.write(chunk);
    const match = output.match(/INGRESS_PROOF_GATEWAY_PID=(\d+)/);
    if (match) gatewayPid = Number(match[1]);
  });
  await until(async () => {
    if (!gatewayPid || !output.includes('Registered SMS webhook route')) return false;
    return await fetch(`http://127.0.0.1:${port}/readyz`, { signal: AbortSignal.timeout(2000) })
      .then(async response => response.ok && (await response.json()).ready === true)
      .catch(() => false);
  }, 'Gateway readiness');
  console.log(JSON.stringify({ phase: 'ready', generation, pid: gatewayPid }));
}
function readRow() {
  const db = new DatabaseSync(path.join(stateDir, 'state', 'openclaw.sqlite'), { readOnly: true });
  try { return db.prepare('SELECT queue_name, event_id, status, attempts, claim_owner, claim_token, completed_at FROM channel_ingress_events WHERE queue_name=? AND event_id=?').get(queueName, eventId); }
  finally { db.close(); }
}
function rowEvidence() {
  const row = readRow();
  return row && { ...row, claim_token: row.claim_token ? '[present]' : null };
}
async function post(validSignature = true) {
  const form = { AccountSid: accountSid, MessageSid: eventId, From: '+15550002222', To: '+15550001111', Body: 'Synthetic ingress crash recovery proof', NumMedia: '0' };
  const signature = createHmac('sha1', authToken).update(signedUrl + Object.keys(form).sort().map(key => key + form[key]).join('')).digest('base64');
  const response = await fetch(webhookUrl, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', 'x-twilio-signature': validSignature ? signature : 'invalid-synthetic-signature' }, body: new URLSearchParams(form), signal: AbortSignal.any([cancellation.signal, AbortSignal.timeout(30000)]) });
  if (!validSignature) {
    assert.equal(response.status, 403, await response.text());
    assert.equal(response.headers.get('x-openclaw-delivery-accepted'), null);
    assert.equal(readRow(), undefined);
    assert.equal(attempts, 0);
    console.log(JSON.stringify({ phase: 'invalid-signature-rejected', status: response.status }));
    return;
  }
  assert.equal(response.status, 200, await response.text());
  assert.equal(response.headers.get('x-openclaw-delivery-accepted'), 'durable');
  console.log(JSON.stringify({ phase: 'webhook-ack', status: response.status, durable: true }));
}
async function stopGateway(signal) {
  const child = gateway;
  const target = gatewayPid;
  if (target) {
    try { process.kill(target, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; }
    console.log(JSON.stringify({ phase: 'stop-signal', generation, pid: target, signal }));
    const deadline = Date.now() + 30000;
    while (true) {
      const stat = await fs.readFile(`/proc/${target}/stat`, 'utf8').catch(() => '');
      if (!stat || stat.split(') ')[1]?.startsWith('Z ')) break;
      if (Date.now() > deadline) throw new Error(`Gateway ${target} did not stop`);
      await delay(25);
    }
  }
  child.stdout.destroy();
  child.stderr.destroy();
  // The detached process group belongs only to this controller. Retire the pnpm wrapper
  // after observing the actual Gateway exit so a restart never leaves an orphan wrapper.
  try { process.kill(-child.pid, 'SIGKILL'); } catch (error) { if (error.code !== 'ESRCH') throw error; }
  gateway = undefined;
  gatewayPid = undefined;
}

try {
  await startGateway();
  await post(false);
  await post();
  await until(() => attempts === 1, 'pre-completion barrier');
  assert.equal(readRow().status, 'claimed');
  assert.equal(Number(readRow().claim_owner.split(':')[0]), gatewayPid);
  assert.equal(readRow().completed_at, null);
  assert.equal(completions.length, 0);
  console.log(JSON.stringify({ phase: 'before-kill', row: rowEvidence(), completions: completions.length }));
  await stopGateway('SIGKILL');
  assert.equal(readRow().status, 'claimed');
  assert.equal(completions.length, 0);
  console.log(JSON.stringify({ phase: 'persisted-after-kill', row: rowEvidence(), completions: completions.length }));
  release = true;
  await startGateway();
  await until(() => completions.length === 1 && readRow()?.status === 'completed', 'recovered completion');
  assert.equal(attempts, 2);
  assert.equal(readRow().claim_owner, null);
  assert.equal(readRow().claim_token, null);
  console.log(JSON.stringify({ phase: 'recovered', row: rowEvidence(), attempts, completions: completions.length }));
  await post();
  await stopGateway('SIGTERM');
  await startGateway();
  await post();
  await stopGateway('SIGTERM');
  assert.equal(readRow().status, 'completed');
  assert.equal(completions.length, 1);
  assert.equal(attempts, 2);
  console.log(JSON.stringify({ phase: 'PASS', generations: generation, admissions: 3, attempts, completions: completions.length, stateDir }));
} finally {
  if (gateway) await stopGateway('SIGKILL');
  for (const res of blocked) res.destroy();
  control.closeAllConnections();
  await new Promise(resolve => control.close(resolve));
  await fs.writeFile(path.join(root, 'gateway-last.log'), output);
  await new Promise(resolve => gatewayLog.end(resolve));
  console.log(JSON.stringify({ proofArtifacts: root }));
}

MarMarLabs added a commit to MarMarLabs/openclaw that referenced this pull request Sep 26, 2026
121 upstream commits, including nine low-value test batches (d027, d039
to d047) and the msteams webhook move to Gateway routes (openclaw#158939). Two
files outside the generated set changed on both sides and auto-merged.
presentation-card.test.ts loses upstream's own "accepts cards without
markdown tables" test (openclaw#159090), which this branch never edited, and
keeps the branch's additions. The database-workers routing list takes
upstream's new ingress entries (openclaw#159073, openclaw#158848) and keeps the branch's
outbound.handoff.test.ts.

Two conflicts, both generated: docs/.generated/config-baseline.sha256 and
src/config/bundled-channel-config-metadata.generated.ts. Both came from
upstream and were regenerated. config-baseline.counts.json auto-merged to
3746 because each side independently took the channel count from 3744 to
3746 (the branch's Feishu entries, upstream's msteams entries), and the
real count with both is 3748.

build:docker ran in a separate detached checkout of this commit outside the
nested node_modules install. Regenerating there changed those three files
and nothing else, giving core 2463, channel 3748, plugin 4349 as
predicted, a channel hash neither side had, and upstream's core and plugin
lines. The three generated-file checks pass there. The lockfile did not
move. No test this branch moved was deleted upstream in this range, and
the 15 test files upstream deleted outright are ones this branch never
touched. Upstream removed 28 Feishu test declarations and this merge
removes the same 28.

Feishu: 105 files and 1850 tests in the extension project, 17 files and
319 tests in the database-workers project, all 122 Feishu test files on
disk. The forwarder test and the routing guards pass, 1955 tests.
tsgo:core, tsgo:extensions, tsgo:extensions:test, tsgo:test:root, the
line-cap, max-lines and assertion-safety ratchets against upstream/main,
oxlint and oxfmt on the 42 changed code files all pass.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 27, 2026
…nclaw#159073)

## What Problem This Solves

The shared channel ingress queue still performs operational reads and writes synchronously on the Gateway thread, despite exposing an asynchronous API.

## User Impact

Inbound persistence and replay use the existing shared-state SQLite broker. Admission returns only after commit; claim fencing, per-account ordering, dedupe, retention, and accepted-write settlement remain intact. Operational listings observe earlier committed writes and still create a missing database for ordinary read-write queues. Explicit read-only inspection remains noncreating.

Update behavior: no schema, stored-byte, config, port, webhook path, signature, dedupe-window, or retention change; no migration or operator action. The maintainer approved the worker-access change and the broker-ordered listing adjustment. Legacy pre-May-31 Telegram spool import and Telegram startup profiling remain documented follow-ups, as directed.

## Why This Change Was Made

All twelve mutations and the operational listings cut over together to preserve one FIFO owner. Diagnostic failed-health, pressure, and account discovery already use read-only workers. Channel parsing and lane policy stay on the host; the worker verifies the prepared ordered snapshot before applying a claim or recovery decision. Custom claim clocks are sampled at transaction admission. Accepted commits settle even if caller authority later revokes.

The drain consumes one coherent pending/claimed snapshot. `listUnsettled` is optional for existing external queue implementations through the next SDK major. `purge` accepts an optional cancellation signal, and Telegram passes its existing signal. Runtime construction binds live plugin authority to every operation, replacing the purge-only wrapper. The existing table and database version are unchanged.

Deletes the main-thread queue SQL path and superseded runtime wrapper. The final write cutover is intentionally larger than the fixture slices because mixing native and broker mutations would break admission ordering. Earlier slices removed Telegram directory helpers and consolidated shared fixture scaffolding.

Production +964/-942/net +22; tests and test support +837/-315/net +522; docs +41/-18/net +23; tooling +3/-0/net +3. The runtime growth preserves authority and settlement across a worker boundary. All earlier slices plus this candidate total production net +446; test fixture consolidation reduced the original +517 growth to +386 before the final routing/regression coverage.

## Evidence

Provider: blacksmith-testbox. Lease `tbx_01m3f53n667mcj031n55vm5tj8` ([run](https://github.com/openclaw/openclaw/actions/runs/36251856365)), frozen install, `pnpm tsgo:core` (41.13s), `pnpm tsgo:extensions:test` (78.55s), and inventory generation/check passed. Nine focused owner files passed 144 tests. Single-worker wall cost per file: queue 33.02s; claim ownership 9.28s; readonly access 8.07s; pruning 7.20s; drain lanes 8.50s; monitor 9.44s; plugin-state runtime 14.12s; registry runtime-config 11.08s; Telegram monitor 15.15s. The two changed tooling files passed 381 tests in a combined 192.99s single-worker wall.

The additional 72-file per-config run used `pnpm test <explicit routed ingress paths> --maxWorkers=1`: 128 core tests and 855 extension tests passed, with two fixture failures over 518.11s. LINE and MS Teams waited for a `listPending` spy that the coherent snapshot intentionally replaces. Both fixtures now capture the real monitor and await its pump, preserving the eight-delivery cap and queued-row assertions.

Lease `tbx_01m3faw6necd61h11wcf6se4hs` ([run](https://github.com/openclaw/openclaw/actions/runs/36257798905)) proved the corrections: `pnpm test extensions/line/src/webhook-spool.test.ts --maxWorkers=1` passed 14 tests in 31.09s; `pnpm test extensions/msteams/src/msteams-ingress.test.ts --maxWorkers=1` passed 15 in 18.32s. Extension types (79.74s), runtime import cycles (9.38s; zero), Madge cycles (26.36s; zero), SDK exports (0.22s), and docs sanity (54.79s) passed. The existing pruning case with padded protected IDs passed (five tests, 8.46s). Negative controls failed for the intended reasons: removing normalization deleted a protected row; raising either channel's cap to nine caused nine deliveries where eight were required. The production controls were restored and checked.

Worker routing is covered by actual queue operations with calling-thread SQLite primitives refusing execution. Regression probes also cover missing database creation, committed-then-list inside an older ambient snapshot, live authority after awaited policy, custom-clock transaction grants, post-grant settlement, and coherent lane inspection. No weaker guards or assertions were substituted.

Deslop is clean. Codex P0–P2 review is clean after supplying the full unchanged worker kernel: two earlier allegations were disproven by existing normalization and corrupt-row filtering, with direct tests. The final review used a byte-verified capture of the full 35-file diff and the broker/kernel context. Rebase onto `94580ed1416cbe69b173b6ca85a1b1ab2001d55a` was patch-identical. The maintainer authorized GitHub exact-head auto-merge; required CI remains the gate.

Fresh proof on published source head `b828403ef8f309ffda1e4859f6eca3268fdc66cb` (same lease): queue/claim/readonly regression suites passed 47 tests in 38.51s; regenerated inventory and its check passed (545 source files, 2543 primitive calls). `pnpm plugin-sdk:api:diff --base 94580ed --head b828403` passed in 242.79s; exports passed in 0.17s. The SDK acknowledgement digest is `e2cba13f`. No entrypoints were added or removed; the additive queue contract is intentional and documented. Final head `0b24c42b9242b07e1a7c60147b4cba5f46d5bd91` only refreshes two generated source-line references.

Merged-main signed-SMS SIGKILL/replay proof is the remaining post-merge task and will be recorded in this PR.

## Stack

Landed: openclaw#157687 → openclaw#158203 → openclaw#158233 → openclaw#158288 → openclaw#158412 → openclaw#158477 → openclaw#158628 → openclaw#158637 → openclaw#158860 → openclaw#158887 → openclaw#158896 → openclaw#158928 → openclaw#158933 → openclaw#158980 → openclaw#158987 → openclaw#159006 → openclaw#159008. This is the final atomic broker cutover and inventory slice. Signed-SMS crash/replay proof follows on merged main.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: line Channel integration: line channel: msteams Channel integration: msteams channel: telegram Channel integration: telegram docs Improvements or additions to documentation merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. plugin: file-transfer rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant