Skip to content

perf(channels): claim idle ingress during durable admission - #175459

Merged
steipete merged 4 commits into
mainfrom
dbasync/chanreq2-idle
Oct 17, 2026
Merged

steipete merged 4 commits into
mainfrom
dbasync/chanreq2-idle

Conversation

@steipete

@steipete steipete commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Problem and design

A durable inbound message required separate enqueue, claim, and completion requests. This change lets the existing queue worker append and claim a fresh singleton in one transaction when its dispatcher is idle and no pending or claimed row precedes it. The existing drain owns the claim before transport acknowledgment and dispatches after acknowledgment settles. Failed acknowledgment stays visible; the durable message remains recoverable. Unknown append outcomes use recovery without retrying the append.

Telegram reuses admitted identity/lane facts, removing a second inspection. Accepted edge: a forum hint learned during append does not reclassify that singleton; later admission and recovery use their own facts. IRC still inspects retained lines to prepare delivery and reject malformed data. Retry ordering, peer ownership, effect authorization, lease-loss cancellation, settlement, and persisted-event validation remain. No schema change, new manager, fencing, or synchronous fallback.

Measured scope

All six alternating arms are complete. Base 4aa0f5a85299c69232ef04ee1060c3b7c6207adb; production candidate 2fcf35c065548d347af6b084f6e8e5bea574d082; M1,C1,M2,C2,M3,C3. Final head 530efbc2d4f2226c3dd67746a52e4a2d2c20a654 changes only the Telegram test fixture; production, APIs, docs, and dependencies are byte-identical. Build, native, and SDK proof are reused on that basis. No latency or PostgreSQL performance claim.

All-thread metric, median [min–max] Base Candidate
Warm causal SQL / requests / Gateway MAIN, 30 turns per side 61 [61–62] / 16 [16–17] / 0 [0–0] 61 [61–62] / 16 [16–17] / 0 [0–0]
Warm raw SQL / requests / Gateway MAIN, 30 turns per side 67.5 [67–101] / 17 [17–23] / 0 [0–13] 67 [67–101] / 17 [17–22] / 0 [0–13]
Whole Gateway SQL / requests / MAIN, three arms per side 3554 [3543–3554] / 904 [898–905] / 148 [148–148] 3596 [3592–3601] / 919 [918–920] / 148 [148–148]
Generic singleton fixed SQL / requests 9 [9–9] / 3 [3–3] 7 [7–7] / 2 [2–2]
Generic singleton whole flow SQL / requests 21 [21–21] / 10 [10–10] 17 [17–17] / 7 [7–7]
Telegram singleton fixed SQL / requests 9 [9–9] / 3 [3–3] 7 [7–7] / 2 [2–2]
Telegram singleton whole flow SQL / requests 15 [15–15] / 9 [9–9] 11 [11–11] / 6 [6–6]

Fixed cost covers enqueue/claim/completion; whole flow includes discovery/settlement. All six completed owner/channel arms have no native SQL errors. Enqueue plus claim falls from 6 SQL/2 requests to one enqueueAndClaim at 4/1; completion stays 3/1. Each singleton also avoids one list and one staleClaims request, saving another 2 SQL/2 requests in the measured whole flow.

Same-lane and distinct-lane ten-event batches stay at fixed 63/21 and whole 93/46 and 75/28 respectively. Album/forward fixed work stays 18/6; polling-batch stays 15/5. Whole Telegram fixture medians (SQL/requests) vary: album 1111/605→1043/537, forward 1126/624→976/474, polling-batch 368/86→351/70. These include setup, 10 ms polling, verification, and teardown; they are not per-message savings. Full ranges are preserved in the report and extraction.

Both causal and raw warm nonregression checks pass; this does not establish a whole-workload cost pass. Whole Gateway medians increase 42 SQL (+1.18%) and 15 requests (+1.66%). Combined boot/connect/first-turn work increases 882 [878–900] SQL / 211 [207–215] requests → 927 [927–954] / 226 [226–229]. Raw first-turn request median rises 100→110; causal first-turn requests rise 53→54. These increases remain a post-merge investigation item.

The shared workload has no inbound channel events. Its ingress work is identical in every arm: boot 1 SQL/0 requests/1 allowed boot MAIN, connect 2/1/0, restart-connect 2/1/0; total 5/2/1, with zero ingress work in warm turns. Extra measured work appears in unchanged catalog/cache/session-maintenance paths: entry-cache snapshots 20 SQL/12 requests→23/13, catalog request stacks increase, and the session-cost cache stack adds 2 median requests. Background medians rise 2182→2228 SQL and 530→544 requests; these independently computed medians are not additive to the whole delta. The trigger for the extra work is not established; unchanged ingress attribution is not proof that the PR caused none of it. All six attribution audits reconcile phases and wire requests, with no missing dispatches or native SQL errors.

The target of two fixed requests applies only to eligible idle singletons, not every message or whole-flow work. O(1) total-burst requests remain unmet: claim/completion still scale per message. Prior #175183 batches ten-event admission from 30 SQL/10 requests to 3/1 and combines the health-read pair from 2/2 to 2/1; those are Stage 1 results.

Proof and limits

Ingress T1: 0→0; repository T1: 182→182; deprecated compatibility: 10→10; dialect mechanical/design/engine: 0/0/0 unchanged. Final CI at synthetic merge 10fb1948 into 65920347 had 60 successful and 24 skipped jobs. All static CI passed, including types, lint, contracts, bundles, Madge (zero cycles), and ratchets. Two behavioral jobs failed with exact pinned-main assertion matches: Telegram young-session conflict (main 7de7f398) and two agent session-event assertions (main 4b791ee3). The aggregate remained red. Security Review succeeded; its CI-gate status mirrored the aggregate. The exception rests on focused main reproductions, not the automated classifier's “unknown” result.

Knip retains 16 exact observed-main findings below; matched source/scanner blobs do not establish identical historical dependency graphs. The complete 155-root native SDK declaration comparison was manually reviewed as additive/type-compatible. The stock per-export semantic renderer did not complete.

Exact observed-main findings
File Symbol Observed main
src/logging/diagnostic-memory.ts resetDiagnosticMemoryForTest fe84346907e6
src/logging/diagnostic-phase.ts resetDiagnosticPhasesForTest fe84346907e6
src/logging/diagnostic-run-activity.ts resetDiagnosticRunActivityForTest fe84346907e6
src/logging/diagnostic-runtime.ts resetDiagnosticActivityForTest fe84346907e6
src/logging/diagnostic-session-recovery-coordinator.ts resetDiagnosticSessionRecoveryCoordinatorForTest fe84346907e6
src/logging/diagnostic-session-state.ts resetDiagnosticSessionStateForTest fe84346907e6
src/logging/diagnostic-stability.ts resetDiagnosticStabilityRecorderForTest fe84346907e6
packages/gateway-protocol/src/compiled/sender-identity.d.ts isSessionParticipantIdentity fe84346907e6
src/agents/command/cli-compaction.test-support.ts systemCompactionHost b46ec6167975
src/agents/embedded-agent-runner/tool-result-truncation.ts toolResultWarningDedupe (toolResultTruncation) b46ec6167975
src/gateway/github-publication.test-support.ts BASE_HEAD b46ec6167975
src/gateway/server-worker-environment-startup.runtime.test-support.ts workerStartupReceipt b46ec6167975
src/infra/backup-create-family.test-support.ts expectVerifiedBackup b46ec6167975
src/infra/backup-create-family.test-support.ts writeFiles b46ec6167975
src/system-agent/system-agent.test-helpers.ts requireTestRecord b46ec6167975
test/gateway-restart.test-support.ts readRestartRow b46ec6167975

Focused owner/adapter tests cover recovery, acknowledgment failure, dedupe, ordering, and claim handoff; all 18 final Telegram drain tests pass. Delayed native Telegram send/reply confirmed one fused admission followed by completion; cold arrival used ordinary enqueue/claim. Native proof cleanup passed. These prove behavior, not SQL counts; crash recovery was simulated. No update-driver cell applies: schema, migrations, update, Doctor, loading, and service lifecycle are unchanged.

Two Codex review rounds were used; no third round. ClawSweeper found no P0/P1/security issue, but P2 remains: inherited enqueueAndClaim can bypass a decorator overriding only enqueue. The fixture repair does not fix that contract. Third-party decorators were not audited. Wrap optional admission methods or omit them; follow-up is explicit opt-in or preserved interception semantics.

Merged as 3f76f0b62d1f0ad0eebe1f74d283eb4f3ac7805c through the authorized head-pinned REST fallback after earlier lane native refusals; no new Stage 2 native landing attempt is claimed. Size: 19 files, +862/−158 (production +395/−136; tests/config +441/−18; docs +25/−3; baseline +1/−1).

@clawsweeper

clawsweeper Bot commented Oct 17, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 17, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T12:36:01.465455Z 530efbc New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram channel: irc size: L labels Oct 17, 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: 32031990f6

ℹ️ About Codex in GitHub

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

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

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

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

Comment on lines +84 to +88
const enqueueAndClaim = admissionQueue.enqueueAndClaim?.bind(admissionQueue);
const idleDrain =
prepared.length === 1 && enqueueAndClaim ? options.getIdleDrain() : undefined;
const ownerId = idleDrain?.idleOwnerId();
if (idleDrain && ownerId && enqueueAndClaim) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Keep enqueue decorators on the fused admission path

When a caller decorates a host queue by spreading it and overriding enqueue—as existing Twitch, Feishu, Nostr, Discord, and other bundled tests do—the spread now also retains the core enqueueAndClaim. For an idle singleton, this capability check invokes that retained native method instead of the override, so the decorator's append failure, gate, or instrumentation is silently skipped and the event can be acknowledged and dispatched. The changed IRC test works around this by deleting enqueueAndClaim, but existing and third-party queue decorators have not been migrated; make fused admission explicitly opt-in or ensure the decorated admission operation is honored.

AGENTS.md reference: AGENTS.md:L52-L53

Useful? React with 👍 / 👎.

@clawsweeper clawsweeper Bot added clawsweeper:intake:feature Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed clawsweeper:intake:feature Preliminary submission classification; full source review pending. labels Oct 17, 2026
@clawsweeper

clawsweeper Bot commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR combines durable append and claim for idle singleton ingress and lets Telegram reuse fresh admission identity and lane facts.

Example: Telegram update 17 arrives while its ingress monitor and queue are idle.

  • Before: The monitor appends the update and later requests its claim separately.
  • After: One worker transaction appends and claims the update; the existing drain waits for the acknowledgment callback before dispatch.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The design has clear owner direction, but the patch introduces a supplied-queue compatibility defect and a deterministic test failure, while required scoped runtime proof is pending.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 2 actionable review findings remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Fresh channel messages incur separate durable append and claim requests before delivery.
Reason: The maintainer-authored direction extends the existing ingress owners and targets a concrete redundant worker request without adding storage or operator configuration.

Merge readiness

⛔ Needs changes before merge - 2 items remain

Keep open as a useful maintainer-directed optimization, with repairs required for bypassed enqueue decorators and the restart-drain regression test.

Priority: P2
Reviewed head: 32031990f6786c1db4532801b3f7b1fa1705a270

Before merge

  • Preserve enqueue decorators when selecting fused admission (P2) - An idle singleton now calls an inherited enqueueAndClaim even when the supplied queue overrides enqueue. Existing Microsoft Teams rejection and Twitch admission-gate fixtures use exactly this pattern, so their append operation is skipped and admission can acknowledge and dispatch instead of rejecting or waiting. The exact-head Microsoft Teams test fails with a resolved promise where sqlite busy was expected. Preserve the decorated admission operation or require an explicit fused-path opt-in; deleting the capability only in IRC leaves the existing contract broken. This independently confirms the previously recorded review concern.
  • Update the restart-drain test for pre-dispatch cancellation (P2) - When restart draining begins while the pending scan is gated, this new check cancels the claim before oldDeliver runs. The existing regression in ingress-monitor.test.ts still waits for oldDeliver to record GatewayDrainingError at line 447, so it times out; exact-head CI reports the empty error collection. Update that regression to assert no delivery, preserved pending data and retry budget, and successful successor recovery under the new cancellation behavior.

Findings

  • [P2] Preserve enqueue decorators when selecting fused admission — src/channels/message/ingress-monitor-admission.ts:84-88
  • [P2] Update the restart-drain test for pre-dispatch cancellation — src/channels/message/ingress-monitor.ts:171-173

Tests

  • Missing end-to-end proof: The scoped live Telegram singleton acknowledgment/topic flow and restart-replay evidence are absent, and the new tests' base-versus-head discrimination is not shown.
Agent review details

How this fits together

Channel plugins submit inspected events to the shared ingress monitor, which persists them through the state worker and hands claims to the drain for delivery, retry, and completion.

flowchart LR
  A[Channel event] --> B[Ingress monitor]
  B --> C[State worker transaction]
  C --> D[Durable ingress queue]
  C --> E[Existing drain]
  B --> F[Transport acknowledgment]
  F --> E
  E --> G[Channel delivery]
Loading

Technical review

Best possible solution:

Keep fused admission with the existing worker and drain owners while preserving decorated queue admission and meaningful restart-recovery coverage.

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

Source tracing establishes the decorator bypass, and exact-head CI shows the matching Microsoft Teams failure; no target code was executed during this review.

Is this the best way to solve the issue?

Combining append and claim inside the existing writer transaction is a coherent optimization, but capability detection must preserve supplied admission behavior.

Full review comments:

  • [P2] Preserve enqueue decorators when selecting fused admission — src/channels/message/ingress-monitor-admission.ts:84-88
    An idle singleton now calls an inherited enqueueAndClaim even when the supplied queue overrides enqueue. Existing Microsoft Teams rejection and Twitch admission-gate fixtures use exactly this pattern, so their append operation is skipped and admission can acknowledge and dispatch instead of rejecting or waiting. The exact-head Microsoft Teams test fails with a resolved promise where sqlite busy was expected. Preserve the decorated admission operation or require an explicit fused-path opt-in; deleting the capability only in IRC leaves the existing contract broken. This independently confirms the previously recorded review concern.
    Confidence: 0.99
  • [P2] Update the restart-drain test for pre-dispatch cancellation — src/channels/message/ingress-monitor.ts:171-173
    When restart draining begins while the pending scan is gated, this new check cancels the claim before oldDeliver runs. The existing regression in ingress-monitor.test.ts still waits for oldDeliver to record GatewayDrainingError at line 447, so it times out; exact-head CI reports the empty error collection. Update that regression to assert no delivery, preserved pending data and retry budget, and successful successor recovery under the new cancellation behavior.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.97

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 9f39528c0cc7.

Provenance checked

  • Shared admission and batch persistence keeps the original intent (4aa0f5a: Batch durable admission preserves ordering, first-payload deduplication, and acknowledgment-after-commit while explicitly leaving singleton fusion for later.)
  • Drain claim custody and settlement keeps the original intent (75e416f: The drain must retain claim ownership through accepted settlement writes so replacement drains cannot race completion, release, or failure.)
  • Fresh Telegram identity and lane inspection changes intended behavior with a stated reason (a0731a6: Asynchronous inspection prepares routing facts before admission and validates claimed identity; this PR explicitly limits reuse to fresh claims and accepts retaining the admitted forum lane.)
  • Claim heartbeat and adoption watchdog changes intended behavior with a stated reason (fc6b9da: The core drain owns lease refresh and pre-adoption stall detection; this PR explains why refresh starts during acknowledgment while dispatch stall timing starts afterward.)
  • Dispatch work-admission lifetime keeps the original intent (c972fda: Started ingress delivery must outlive an inherited request root without bypassing a real Gateway restart drain.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

Acceptance criteria:

  • pnpm test src/channels/message/ingress-monitor.idle-admission.test.ts src/channels/message/ingress-monitor.admission.test.ts src/channels/message/ingress-monitor.test.ts --maxWorkers=1
  • pnpm test extensions/msteams/src/msteams-ingress.test.ts extensions/twitch/src/twitch-ingress.test.ts extensions/nostr/src/nostr-ingress.test.ts extensions/irc/src/irc-ingress.test.ts --maxWorkers=1
  • pnpm test extensions/telegram/src/telegram-ingress-drain.test.ts --maxWorkers=1
  • git diff --check

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 7562b79 adds src/channels/message/ingress-monitor.ts:120 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 7562b79465c0; files: src/channels/message/ingress-monitor.ts)
  • Ayaan Zaidi: Raw commit fc6b9da adds src/channels/message/ingress-drain.ts:620 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fc6b9dad0b13; files: src/channels/message/ingress-drain.ts)
  • Eden: Raw commit c972fda adds src/channels/message/ingress-drain.ts:559 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c972fda893ec; files: src/channels/message/ingress-drain.ts)

PR surface

Source +259, Tests +418, Docs +22. Total +699 across 16 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 10 395 136 +259
Tests 4 418 0 +418
Docs 2 25 3 +22
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 16 838 139 +699

Review metrics

Metric Value Why it matters
Public SDK additions 2 optional members enqueueAndClaim and reuseAdmissionFactsForFreshClaims extend existing public contracts; method presence currently changes decorated singleton admission behavior.

Labels

Label changes:

  • add P2: This is a normal-priority ingress performance improvement with focused compatibility and test repairs.
  • add merge-risk: 🚨 compatibility: Adding enqueueAndClaim changes existing supplied-queue behavior when callers override enqueue but retain other host methods.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a normal-priority ingress performance improvement with focused compatibility and test repairs.
  • merge-risk: 🚨 compatibility: Adding enqueueAndClaim changes existing supplied-queue behavior when callers override enqueue but retain other host methods.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 17, 2026, 7:33 AM ET / 11:33 UTC.

@openclaw-barnacle openclaw-barnacle Bot added the channel: msteams Channel integration: msteams label Oct 17, 2026
@steipete

Copy link
Copy Markdown
Contributor Author

The supplied-queue decorator issue remains an unresolved P2. Idle singleton admission calls an inherited optional enqueueAndClaim method directly, so a wrapper that overrides only enqueue no longer intercepts that admission. Updating the Teams failure-injection fixture covers both paths but does not restore this general decorator contract.

The inspected bundled production callers do not use that override pattern; third-party decorators were not audited. Until the contract is repaired, wrappers must also wrap optional admission methods or omit them. Follow-up: make fused admission an explicit opt-in, or preserve the supplied wrapper’s interception semantics, with a regression proving the decorated operation is observed exactly once.

@steipete
steipete merged commit 3f76f0b into main Oct 17, 2026
159 of 167 checks passed
@steipete
steipete deleted the dbasync/chanreq2-idle branch October 17, 2026 12:45
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 18, 2026
…#175459)

Append and claim eligible idle singleton messages through the existing ingress worker and drain. Preserve retry ordering, deduplication, claimant ownership, durable acknowledgment, and restart recovery. Reuse Telegram admission facts instead of inspecting the same fresh event again.

Focused owner and transport tests, live Telegram singleton proof, types, lint, source contracts, and database ratchets validate the change. Inherited CI findings, SDK comparison limits, and the queue-decorator follow-up are documented in the PR.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: irc channel: msteams Channel integration: msteams channel: telegram Channel integration: telegram docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant