Skip to content

fix(nostr): DMs through a relay are lost after its connection drops - #174074

Open
rodricksz4h5 wants to merge 2 commits into
openclaw:mainfrom
rodricksz4h5:fix/nostr-relay-reconnect
Open

rodricksz4h5 wants to merge 2 commits into
openclaw:mainfrom
rodricksz4h5:fix/nostr-relay-reconnect

Conversation

@rodricksz4h5

@rodricksz4h5 rodricksz4h5 commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #174073

What Problem This Solves

Fixes: the Nostr channel stops receiving DMs through a relay for the rest of the Gateway's life after that relay's WebSocket closes (a relay restart, a crash, a network blip).

User Impact

User impact: when a relay connection drops, the channel subscribes to it again (after 10 s, backing off to once a minute) and receives the DMs sent through it, including ones the relay stored while the socket was down. No configuration change.

Why This Change Was Made

Each relay's DM subscription in startNostrBus is opened once, at startup. When one closes, the bus only reports Subscription closed. With two or more relays (the default) the channel keeps reporting connected, so the health monitor never restarts it, and every DM through the dropped relay is lost. nostr-tools' own reconnect does not cover this on Node: the socket fires error before close and nostr-tools turns reconnects off for a socket that had connected. So the bus now resubscribes a relay itself after an unexpected close, and never during shutdown or abort.

Rebased onto current main, where the per-relay subscription moved into nostr-bus.ts. The replay and admission rules follow the review:

  • Where a resubscription starts. It replays from when that relay's subscription closed (or, if it closed before its EOSE, from where it started), minus the bus's 120 s lookback, and never later than the existing durable cursor's transient-rejection ceiling. A DM that was rejected for a retryable reason (rate limit, backpressure) therefore stays inside the replay even after newer DMs were accepted. Never earlier than the startup baseline.
  • Replay does not use up admission. Events the bus already stored durably in this process are skipped by every relay subscription before admission (nostr-tools alreadyHaveEvent, a bounded set of 4096 ids; rejected events are never added, so they are retried). An event that still reaches durable admission and turns out to be a duplicate hands its rate-window slot back, so even an id that fell out of that set cannot starve a new DM.

Evidence

A Gateway from source (this branch, pnpm build), the Nostr channel and a scripted OpenAI-compatible provider in a Linux container, against three strfry relays in Docker. A second key ("alice") DMed the bot through relay 2 only and watched all three relays for replies. After a warm-up turn, relay 2 was restarted (docker restart); probe-102 was sent 6 s later, while relay 2 was back but before any resubscription, so the relay stored it.

main (356931bbd) this PR (426d852d4)
probe-101 (before the restart) answered in 1 s answered in 1 s
probe-102 (stored on relay 2 during the outage) no reply answered in 5 s, from the resubscription's replay
probe-103, probe-104 (after) no reply: relay 2 disconnected at 13:34:54 and was never subscribed again answered in 1 s each

Trace from the PR run (all UTC):

# alice
13:11:35.741Z  DROP: docker restart ns-relay2
13:11:41.771Z  sent probe-102 via relay2 only     <- relay2 is back, the Gateway is not subscribed: stored on the relay
# Gateway
13:11:36.092   [nostr] [default] Disconnected from relay: ws://host.docker.internal:7002
13:11:36.114   [nostr] [default] Nostr error (subscription): Subscription closed: relay connection failed
13:11:46.141   [nostr] [default] Connected to relay: ws://host.docker.internal:7002/   <- resubscribed 10 s later
# scripted provider
13:11:46.539Z  turn 3 -> pong: probe-102           <- the stored DM reached the agent from the replay
# alice
13:11:46.775Z  reply "pong: probe-102" after 5s
13:12:26.601Z  reply "pong: probe-103" after 1s
13:13:11.726Z  reply "pong: probe-104" after 1s

Tests (pnpm test, Linux, Node 24.22.1):

  • nostr-bus.reconnect.test.ts (new): the real bus and nostr-tools pool against a loopback relay that stores DMs and replays them for each REQ's since; only the resubscribe backoff runs on a controlled clock.
    • the relay drops the socket; the bus resubscribes just behind the outage (not the hour since startup) and receives the next DM;
    • replayed history does not use up admission: with a 10-event window, six handled DMs are replayed on resubscribe and four new DMs still arrive, with no rate_limited rejection;
    • a rate-limited DM stays in the replay: a DM stamped 200 s back is rate-limited, a later DM is accepted, and the resubscription still starts at or before the limited DM, which then arrives.
  • nostr-state-store.test.ts: a duplicate admission hands its rate-window slot back.
  • On main all four fail. With each safeguard removed in turn, its test fails: no id skip and no refund fails the burst test; no transient ceiling fails the rate-limited one (since 1793017805 > 1793017724).
  • nostr-bus.reconnect, nostr-state-store, nostr-bus.inbound, nostr-cursor: 41 + 6 passed. pnpm tsgo:extensions passes; oxlint and oxfmt --check are clean on the changed files.

Merge Risk

Two-way door: reverting restores the old behavior without touching stored state. Blast radius is the Nostr channel's relay subscriptions and its inbound admission count. A relay that keeps closing is retried once a minute, and a real EOSE resets the backoff; that includes a relay that refuses the DM subscription outright (for example strfry's default auth-required for kind 4), which is now retried once a minute with a log line each time. The duplicate refund only applies to events the durable queue already holds, which append nothing.

Not covered: a socket that dies silently and never closes. Nothing detects it, before or after this change; #174073 describes it as a separate follow-up.

@clawsweeper

clawsweeper Bot commented Oct 16, 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 channel: nostr Channel integration: nostr size: M labels Oct 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Resubscribe closed Nostr relay connections with backoff and replay missed DMs while preserving admission capacity.

Example: Relay 2 restarts, then stores probe-102 before the Gateway reconnects.

  • Before: Probe-102 and subsequent DMs through relay 2 receive no reply.
  • After: The Gateway resubscribes after 10 seconds and answers probe-102 from relay history, then answers subsequent DMs.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused, and demonstrated through the shipped Gateway; prior blockers are repaired, with broad current-head CI still pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (logs): The contributor records a source-built Gateway using the Nostr plugin, real Docker strfry relays, and a scripted provider: a relay restart triggers resubscription, an outage-stored DM receives a reply, and later DMs continue working. Subsequent changes narrow an iterator and decode test frames without changing that transport path.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: DMs sent through a disconnected relay stop reaching the agent even after that relay returns.
Reason: Recovery restores the existing DM delivery contract with no new user configuration and demonstrated transport-level value.

Merge readiness

✅ Ready for maintainer review

This PR repairs a current Nostr delivery bug with convincing live evidence. The prior assertion finding is resolved, no new blocking defect was found, and current-head CI remains pending.

Priority: P1
Reviewed head: 2b311544c63f26f491ff0d4ca6c9621c3e92c18d

Before merge

None.

Findings

None.

Agent review details

How this fits together

The Nostr plugin receives encrypted relay events, admits them to the shared durable ingress queue, and dispatches authorized DMs to the agent.

flowchart LR
  Sender[Nostr sender] --> Relay[Nostr relay]
  Relay --> Bus[Nostr bus]
  Bus --> Queue[Durable ingress queue]
  Queue --> Agent[Agent dispatch]
  Bus --> Retry[Resubscription timer]
  Retry --> Relay
Loading

Technical review

Best possible solution:

Keep reconnect scheduling in the existing Nostr bus and retain durable ingress dedupe, replay overlap, and shutdown settlement.

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

Current-main source shows the one-shot subscription path, and the contributor supplies a concrete three-relay before/after reproduction; no target code was executed during this review.

Is this the best way to solve the issue?

The patch repairs the owning relay lifecycle without adding an SDK surface or competing persistence owner, and the additional admission safeguards address observed replay failures.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 27c21c171e94.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 66c6226 adds extensions/nostr/src/nostr-bus.ts:391 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 66c6226c8372; files: extensions/nostr/src/nostr-bus.ts)

PR surface

Source +68, Tests +241. Total +309 across 6 files. Added test files: 1.

View PR surface stats
Area Files Added Removed Net
Source 3 103 35 +68
Tests 3 241 0 +241
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 344 35 +309

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Root-cause cluster

Relationship: same_root_cause
Canonical: #174073
Summary: This PR implements relay-close recovery for the linked bug report; silent sockets that never close remain an explicitly separate concern.

Members:

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

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A dropped relay can silently stop delivering DMs for the remaining Gateway lifetime while the channel still reports connected.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • 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 (4 earlier review cycles)
  • reviewed 2026-10-16T10:04:46.005Z sha b41fd257a79cc65be65c889798281f7fa1b3bab5 :: needs real behavior proof before merge. :: [P1] Preserve replay overlap in the reconnect filter | [P2] Make the new state-store mock satisfy the export ratchet
  • reviewed 2026-10-16T15:16:49.556Z sha 9c82c1f7ce4ed95fa1736713b4eb792f2f437d07 :: needs changes before merge. :: [P1] Prevent replayed history from exhausting new-message admission
  • reviewed 2026-10-16T16:26:19.757Z sha 27a7b13237ebbcb1b8628497cc84cf0f93682534 :: needs changes before merge. :: [P1] Prevent replayed duplicates from exhausting admission | [P2] Keep reconnect progress behind undurable events
  • reviewed 2026-11-15T18:30:09.670Z sha 426d852 :: needs changes before merge. :: [P2] Remove the eviction assertion that breaks the safety ratchet

Reviewed November 15, 2026, 3:55 PM ET / 20:55 UTC (Revision 5).

@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 16, 2026
@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 16, 2026
@rodricksz4h5
rodricksz4h5 force-pushed the fix/nostr-relay-reconnect branch from 27a7b13 to 426d852 Compare October 26, 2026 13:49
@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (the subscription code moved into nostr-bus.ts) and fixed both findings:

  • Replayed duplicates exhausting admission (P1). Root cause: a resubscription gets a fresh nostr-tools known-id set, and admission counts an event before durable dedupe sees it. Every relay subscription now skips ids the bus already stored in this process (alreadyHaveEvent, bounded), and a duplicate that still reaches admission hands its window slot back. Covered through the real bus: six handled DMs replayed into a 10-event window, four new DMs still arrive.
  • Reconnect progress ahead of undurable events (P2). The separate live cursor is gone. A resubscription starts from when that relay closed, held at or below the durable cursor's transient-rejection ceiling, so a rate-limited DM stays in the replay after newer DMs are accepted. Covered through the real bus.

Each test fails with its safeguard removed. The real strfry run on this head is in the body.

@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added the clawsweeper:intake:bug Preliminary submission classification; full source review pending. label Nov 15, 2026
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 15, 2026
@rodricksz4h5
rodricksz4h5 force-pushed the fix/nostr-relay-reconnect branch from 426d852 to 2b31154 Compare November 15, 2026 20:49
@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

Rebased onto current main and fixed the two CI failures:

  • assertion-safety ratchet: the handled-id eviction now narrows the iterator result on done instead of as string, so nostr-bus.ts is back to its baseline of 7.
  • lint (no-base-to-string): the test relay decodes each ws frame by type (Buffer, Buffer[], ArrayBuffer) instead of String(raw).

Behavior is unchanged: eviction only runs when the set holds more than 4096 ids. Locally the ratchet, type-aware oxlint (fails on the old line, passes on the new), oxfmt and tsgo:extensions pass.

@rodricksz4h5

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. 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. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 15, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: nostr Channel integration: nostr P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M 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]: Nostr channel stops receiving DMs through a relay after its connection drops

1 participant