Skip to content

fix(telegram): keep delivery mirroring fast in long sessions - #169663

Merged
obviyus merged 3 commits into
mainfrom
fix/telegram-mirror-run-lookup-bounded
Oct 12, 2026
Merged

obviyus merged 3 commits into
mainfrom
fix/telegram-mirror-run-lookup-bounded

Conversation

@obviyus

@obviyus obviyus commented Oct 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #169643

What Problem This Solves

Fixes slow Telegram delivery mirroring as a persistent session accumulates history, without losing the queued-answer correlation introduced in #169019.

User Impact

Delivery finalization no longer searches every historical event for the producing run. Queued answers still appear once in chat history. There is no schema or migration change.

Why This Change Was Made

The combined idempotency/run predicate prevented the idempotency index from narrowing the query. The lookup now resolves supplied keys independently through that index, then reads only assistant candidates starting at the producing run's indexed input. Runs without an indexed input use a recent 4,096-event tail rather than an unlimited history search; very old legacy deliveries outside that tail cannot acquire a new text correlation. Existing delivery identities remain resolvable regardless of age.

The indexed branches use UNION ALL in the existing query boundary; the producing-input and tail bounds are scalar subqueries. This preserves the native compatibility reader without adding main-thread SQLite call sites.

Reported by @obviyus.

Evidence

  • Real append APIs seeded 1,000, 10,000 and 50,000 history events. Median lookup latency across seven samples:

    History events Before After
    1,000 2.44 ms 1.26 ms
    10,000 31.73 ms 4.83 ms
    50,000 178.00 ms 4.39 ms

    The captured query plan changes from a session-wide event scan to the idempotency index plus a sequence-range lookup. Replaying the captured 50k query with counted run-metadata evaluation gives 50,003 evaluations before and 2,049 after, returning the same answer.

  • The new regression fails on the base because tool-result bodies are returned as run candidates, and passes on the fix. Both focused test files pass: 29 tests, including both queued-answer cases from fix(telegram): avoid duplicate history replies for queued messages #169019; total runner time 61.56 s. Targeted formatting/lint and the build pass.

  • All fast baseline-ratchet equivalents pass. The database-worker comparison remains 605 → 605 T1 calls; no exemption was added.

  • Exact head f9c21859b48b05ab0d43a221bc85bdfd1ba68758, built candidate, Telegram Test Server userbot: the 14a queued scenario in a session with 50,000 pre-seeded historical events produces exactly three history rows for its three delivered answers. All six run-owned user/bot messages were deleted by raw TDLib id and each deletion was read back as absent. The credential lease and runner scratch were released.

  • On the same head, a real OpenAI gpt-5-mini turn through an isolated built Gateway completed with P169643_LIVE_OK (2.88 s); the task-only credential file was removed afterward. Both previously cancelled type-check jobs passed local replays of their exact graph lists and root stripes.

Merge danger: two-way door. Reverting restores the previous lookup; this changes no stored format or persisted content. The blast radius is SQLite channel-final mirror correlation, particularly delayed legacy deliveries without an indexed producing input.

@clawsweeper

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

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation plugin: file-transfer size: S labels Oct 12, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 12, 2026
@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR separates indexed delivery-key lookup from sequence-bounded assistant-run correlation.

Example: Finalize a queued Telegram answer in a session containing 50,000 historical events.

  • Before: The reported median mirror lookup takes 178.00 ms.
  • After: The reported median takes 4.39 ms, with three delivered answers represented by exactly three history rows.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused owner-level repair with recorded production-flow proof, useful regression coverage, and no open correctness finding; failed CI remains a landing-workflow concern.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The maintainer records exact-head built-Gateway Telegram Test Server execution in a 50,000-event session, with three delivered answers producing exactly three history rows; indexed lookup measurements exercise the changed storage owner, while the separate provider smoke proves only ordinary turn completion.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Delivery mirroring slows as a persistent Telegram session accumulates retained history.
Reason: The measured improvement serves an existing workflow, and the maintainer-authored direction explicitly accepts the narrow legacy-correlation tradeoff.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

✅ Ready for maintainer review

Keep this PR: it repairs a current-main performance defect while preserving queued-answer correlation, and no actionable patch defect remains.

Priority: P2
Reviewed head: f9c21859b48b05ab0d43a221bc85bdfd1ba68758

Before merge

None.

Findings

None.

Agent review details

How this fits together

Telegram delivery finalization passes delivery identities and a producing run to the shared transcript owner, which reads SQLite correlation facts before recording the delivery mirror.

flowchart TD
  A[Telegram finalized delivery] --> B[Shared transcript mirror owner]
  B --> C[Transcript worker]
  C --> D[Indexed delivery identities]
  C --> E[Sequence bounded assistant candidates]
  D --> F[Correlated delivery receipt]
  E --> F
  F --> G[Chat history]
Loading

Technical review

Best possible solution:

Land the focused indexed-query repair with its documented legacy boundary after satisfying the native CI landing policy.

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

Current-main source exposes the session-wide OR lookup, and the PR records comparable measurements through real append APIs; this review did not execute a reproduction.

Is this the best way to solve the issue?

The repair addresses query selection at the shared owner, reuses existing indexes, and retains idempotency, active-branch selection, and worker ownership without a schema change.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6cf651fb899f.

Provenance checked

  • Run-owned channel-final correlation keeps the original intent (8e2a683: Correlate queued answers with their producing run so intervening transcript rows do not create duplicate history replies.)
  • Unlimited legacy run search changes intended behavior with a stated reason (8e2a683: The original run lookup searched active-path run events without an age bound to recover queued-answer correlation.)
  • Batched identity and anchor lookup keeps the original intent (e0e6f39: Reduce repeated SQLite reads during mirror replay while preserving messages, frozen anchors, and append-time authority.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Ayaan Zaidi: Raw commit 8e2a683 adds src/config/sessions/session-accessor.sqlite-transcript-mirror.ts:94 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 8e2a6832b741; files: src/config/sessions/session-accessor.sqlite-transcript-mirror.ts)
  • Peter Steinberger: Raw commit d0c5963 adds src/config/sessions/session-accessor.sqlite-transcript-mirror.ts:124 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: d0c59630c5a6; files: src/config/sessions/session-accessor.sqlite-transcript-mirror.ts)

PR surface

Source +17, Tests +43, Docs +6. Total +66 across 3 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 67 50 +17
Tests 1 43 0 +43
Docs 1 6 0 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 116 50 +66

Review metrics

Metric Value Why it matters
Production versus test growth Production +17 net lines; tests +43 lines Production growth separates indexed lookup branches within one existing execution boundary; the regression independently checks assistant-only candidates and retained older delivery identities.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This repairs growing mirror-finalization cost in long-lived sessions without an established transport outage or message loss.
  • merge-risk: 🚨 compatibility: New correlation for legacy runs without an indexed input becomes limited to 4,096 recent events; the maintainer-authored PR explicitly accepts and documents this boundary.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-12T06:19:15.519Z sha ac3801c :: needs maintainer review before merge. :: none
  • reviewed 2026-10-12T06:38:29.611Z sha ac3801c :: needs changes before merge. :: [P2] Eliminate the added T1 SQLite call sites
  • reviewed 2026-10-12T07:35:03.951Z sha 917cdbf :: needs changes before merge. :: none

Reviewed October 12, 2026, 3:51 AM ET / 07:51 UTC (Revision 4).

@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. proof: telegram-e2e This PR needs Telegram Test Server proof with the repository E2E skill. labels Oct 12, 2026
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Oct 12, 2026
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

The SQLite worker-ratchet finding is fixed: the complete baseline-ratchet equivalents pass, with normalized T1 calls staying 605 → 605. Indexed branches now share the original query execution boundary through UNION ALL.

The remaining build-artifacts failure on 917cdbf is the lifecycle smoke's agent.wait returning AbortError: agent run aborted, after the build itself passed:

Both failures are in SQLite sessions/transcripts flip built CLI proof > proves the lifecycle through the built gateway CLI entrypoint. The comparison PR does not modify the transcript-mirror reader.

The cancelled type-check logs also exposed an attributable test-only error (messages[0] possibly undefined). That assertion is being changed to the explicit expected message. Both cancelled jobs' exact graph lists and root stripes are being replayed locally; no hosted jobs are being rerun.

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

At f9c2185 the test-only TS2532 error is fixed with an explicit expected message. Both cancelled jobs were replayed using their exact CI graph lists plus root stripes 2/4 and 3/4; all passed, as did the affected regression file. The source implementation is unchanged from the proven 917cdbf head. The independent lifecycle-abort evidence remains https://github.com/openclaw/openclaw/actions/runs/38217941201/job/114707435469 (PR #138087). No hosted job was rerun.

@clawsweeper clawsweeper Bot removed the rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. label Oct 12, 2026
@clawsweeper clawsweeper Bot added rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 12, 2026
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Final head: f9c21859b48b05ab0d43a221bc85bdfd1ba68758.

ClawSweeper is ready on this SHA, with no findings. The aggregate gate is red only because build-artifacts fails the SQLite lifecycle smoke after completing its build:

Both fail SQLite sessions/transcripts flip built CLI proof > proves the lifecycle through the built gateway CLI entrypoint because agent.wait returns AbortError: agent run aborted. The independent PR does not modify this transcript-mirror reader.

All four cancelled jobs are covered by successful local replays on this head using their exact CI graph selections: check-prod-types (core, ui, extensions), and check-test-types-core-2, -3, and -5, including root stripes 1/4, 2/4, and 4/4. The earlier test-only TS2532 is fixed. No hosted jobs were rerun.

The exact-head 50k lookup measurement, Telegram queued scenario and real-provider gate all pass. No further source changes are pending; the remaining CI decision belongs to the maintainer landing workflow.

@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Maintainer override: the only red job is build-artifacts, whose lifecycle smoke fails with 'AbortError: agent run aborted' after a successful build. The same test and error fail on an unrelated PR (https://github.com/openclaw/openclaw/actions/runs/38217941201/job/114707435469). This PR changes only the SQLite transcript-mirror lookup, a lifecycle test for it and docs. The 4 cancelled typecheck jobs passed in exact local replays. ClawSweeper is ready on this exact head with no findings.

@obviyus
obviyus merged commit f479340 into main Oct 12, 2026
121 of 128 checks passed
@obviyus

obviyus commented Oct 12, 2026

Copy link
Copy Markdown
Collaborator Author

Landed in f479340. Telegram mirror lookups stay fast on long sessions.

@obviyus
obviyus deleted the fix/telegram-mirror-run-lookup-bounded branch October 12, 2026 07:58
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 13, 2026
…w#169663)

Since openclaw#169019, the transcript mirror lookup by run id scanned and decoded events across the whole session history, because the JSON-extracted run id inside an OR kept SQLite off its index. Telegram delivery mirroring therefore got slower as a persistent session grew. The lookup now combines the indexed idempotency-key probe and a bounded run lookup with UNION ALL, filters by role in SQL before decoding bodies, and needs no schema change. The count of direct SQLite call sites stays at 605. Measured at 50k events: median 178.00 ms down to 4.39 ms, and run-metadata evaluations from 50,003 to 2,049, with the same row selected. Telegram Test Server proof with 50k historical events: the queued-turn scenario still stores one history row per delivered answer. Fixes openclaw#169643.

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

Labels

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. plugin: file-transfer proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S 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.

[Bug]: Telegram transcript mirror run lookup scans the whole session history

1 participant