Skip to content

fix(sync): reach peers the one-shot heads exchange misses (fixes #1255) - #1260

Open
NiKrause wants to merge 3 commits into
orbitdb:mainfrom
NiKrause:fix/sync-heads-1255
Open

NiKrause wants to merge 3 commits into
orbitdb:mainfrom
NiKrause:fix/sync-heads-1255

Conversation

@NiKrause

Copy link
Copy Markdown
Contributor

Fixes #1255.

What goes wrong

A reader that reaches a writer only through a third peer, typically a relay that pins, can stay without the writer's first entry for good. #1255 has the analysis, field logs and a deterministic reproduction. Three gaps in Sync combine:

  1. Heads that arrive through the heads exchange are never published on the topic. Only sync.add() publishes. A peer in the middle learns an entry by exchange and keeps it to itself.
  2. The exchange runs once per peer (the peers cache). A reader that exchanged with the middle peer while that peer was still empty never hears of the entry.
  3. A peer that was already subscribed when the database opened brings no subscription-change. The opener never starts an exchange with it and depends on the other side's dial, which is not retried.

A fourth problem showed up while measuring this between browsers. It is not in the issue yet:

  1. Every exchange this side starts runs inside the per-database PQueue({ concurrency: 1 }), which it shares with pubsub updates. A heads dial to a peer that is reachable only over a limited (circuit relay) connection is not refused at once: libp2p first tries to reach the peer another way, so the dial can take the whole timeout. We measured this with two browsers that reach each other only over a relay's circuit and a relay that pins the database. One browser's dial to the other hung for 6 s (TimeoutError) and then for about 12 s more (LimitedConnectionError). The exchange with the relay, started by the relay's subscription-change, waited behind it in the queue for about 18 s. Every other peer of that database waits the same way.

The fix

All changes are in src/sync.js.

(a) Announce heads learnt by exchange. receiveHeads checks log.has(hash) before onSynced. After the exchange, the heads that were new here are published on the topic once. This happens only on the exchange path, so heads received over pubsub are never re-published and nothing loops. Receivers de-duplicate through the log. A NoPeersSubscribedToTopic error from this publish is not reported, because there is nobody to tell.

(b) Exchange with peers that were already subscribed. start() starts an exchange with each peer in pubsub.getSubscribers(address). If the other side dials at the same moment, whichever exchange runs second finds the peer in peers and returns.

(c) Register the heads handler before subscribing. A peer that sees the subscription may dial at once. A dial that finds no handler fails with UnsupportedProtocolError. The dialling side treats that as "this peer does not have the database" and does not retry.

(d) Emit join once per peer until the peer leaves or disconnects. With (b), both ends can start an exchange at the same time, and that is still one peer joining. Without this guard, the duplicate join broke the count in test/orbitdb-multiple-databases.test.js.

(e) Dial outside the queue. Exchanges that this side starts now run on their own, one per peer. Pubsub updates stay in the queue, in order. An exchange in flight is aborted when its peer unsubscribes or disconnects, or when stop() runs. No error event is emitted for an exchange that stop() aborted. The receiving side (handleReceiveHeads) already ran outside the queue in 4.0.0, so onSynced running next to queued updates is not new.

What this PR does not change: the heads protocol still does not opt into limited connections (runOnLimitedConnection), so an exchange with a peer reachable only over a relayed connection still fails. (e) only stops that failure from delaying the other peers.

Other behaviour changes a reviewer may want to check:

  • leave is emitted when the unsubscribe arrives, no longer after the tasks queued before it.
  • A peer that learns new heads by exchange now makes one extra publish per new head.
  • add() is unchanged.

Tests

New file test/sync-missed-peers.test.js:

  • a reader connected only through a relay. This is the reproduction from Sync never delivers the first entry to a reader connected only through a relay #1255, moved to this repo's test helpers. It sets up a star A–R–B, isolates the writer for its first entry, lets the gossip cache expire, and reconnects the writer so that the relay gets the entry through the heads exchange. The reader must then receive the entry without a manual sync.add().
  • a peer that was subscribed before the database opened. The heads dial of the existing peer is stubbed to throw, so the joiner has to start the exchange itself.
  • a slow dial to one peer. Peer 1's heads dial to peer 3 hangs until it is aborted. A joiner that cannot dial itself must still get peer 1's entry within 8 s.

Changed: test/sync.test.js, "Stopping sync". The test took the last entry passed to onSynced to be the newest head. That was only true because exchanges queued behind updates. With (e), an exchange carrying an earlier head can land after a newer update, and the log joins entries in any order. The test now checks what it is about: the expected entry arrives, and nothing written after stop() does. The changed test also passes against the current src/sync.js.

Without the fix (current main src/sync.js with the new tests), each of the three new tests fails at its own assertion:

1) receives an entry the relay learnt through the heads exchange
   AssertionError: the reader never received the entry the relay holds
2) is exchanged with by the peer that opens the database
   AssertionError: the joiner never received the existing entry
3) does not hold up the exchange with another peer
   AssertionError: the hanging dial held up the exchange with the joiner

test/sync-missed-peers.test.js + test/sync.test.js: 27 passing, 3 failing.

With the fix:

  • full npm test (Node 22.21.0): 547 passing, 0 failing, in three runs in a row
  • npm run lint: clean
  • CI on the fork, Run Tests (Node Minimum Version) (Node 22.23.5): lint clean, 547 passing, the three new tests included
  • browser suite (npm run test:browser, Chromium, Node 22, Ubuntu 24.04): 545 passing, 2 pending (the win32 path-join tests, skipped in browsers as on main), 0 failing; the three new tests pass. Run on the fork, from a CI-only branch that adds one commit pinning Node 22 and running the browser job on a self-hosted Ubuntu 24.04 runner.

A note on this PR's own CI: the Run Tests workflow (lts/*, ubuntu-latest) does not reach the tests on current runners, for reasons unrelated to this change. lts/* now resolves to Node 26.13.1, where c8 fails while loading yargs (ReferenceError: require is not defined in ES module scope), and ubuntu-latest is now Ubuntu 26.04, which Playwright 1.50.1 does not support for chromium-headless-shell. main has the same dependency versions, so it is affected the same way.

On the machine that ran these tests, VPN interfaces stall libp2p dials, so the local runs bound the test libp2p in test/utils/create-helia.js to 127.0.0.1. That change is not part of this PR.

The two commits are kept separate: the first covers (a)–(d), the second covers (e) and the sync.test.js change.

🤖 Generated with Claude Code

NiKrause and others added 3 commits November 24, 2026 20:57
A reader connected to a writer only through a third peer -- a relay that
pins -- could stay without the writer's first entry for good. Three gaps in
Sync combined (orbitdb#1255):

- heads that arrive through the heads exchange were never published on the
  topic, so the middle peer learnt an entry and kept it to itself;
- the exchange runs once per peer, so a reader that exchanged with the
  middle peer while it was still empty never heard of the entry;
- peers subscribed before a database opened brought the opener no
  `subscription-change`, so it never started an exchange with them and
  relied on the other side's dial, which is not retried.

Now:

- heads that were new here and came by exchange are published on the
  topic once (only from the exchange path, so pubsub deliveries are never
  re-published and nothing loops; receivers de-duplicate through the log;
  "no peers subscribed" is not an error);
- `start()` exchanges with every peer already subscribed to the topic;
- the heads handler is registered before subscribing, so a peer that dials
  on seeing the subscription finds it;
- 'join' is emitted once per peer until it leaves or disconnects, since
  both ends may now start an exchange at the same moment.

test/sync-missed-peers.test.js covers both paths: the relay star from the
issue's reproduction (the reader must receive the entry the relay learnt by
exchange, without a manual `sync.add`), and a joiner whose peer cannot dial
it. Both fail without this change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sync ran every heads exchange through its per-database queue, one task at a
time, shared with pubsub updates. A dial to a peer reachable only over a
limited (relayed) connection is not refused at once -- libp2p first tries to
reach the peer some other way -- so it can take the whole `timeout`. Measured
in browsers that meet only over a relay: 6 s, then again 12 s, during which
the exchange with the relay itself waited in the queue. The relay's sync pass
was over before the writer's head reached it, and a reader that depended on
the relay never got the entry.

Exchanges now run on their own, outside the queue; pubsub updates stay in it,
in order. An exchange in flight is called off when its peer leaves,
disconnects or Sync stops (no 'error' for one called off by stop()).

test/sync-missed-peers.test.js: a peer whose heads dial to a third peer hangs
must still exchange with a joiner at once. Fails without this change (the
joiner waits out the timeout), passes with it.

test/sync.test.js "Stopping sync": the test took the *last* head synced to be
the newest one, which held only because the exchange queued behind updates.
An exchange carrying an earlier head may now land after a newer update -- the
log joins in any order. It now checks what it means: the expected entry
arrives, and nothing written after stop() does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Two peers a relay introduces meet over a limited connection first, a circuit
the relay carries, and that is usually where they see each other subscribe.
The heads exchange started then cannot open its stream there, so it fails;
the direct connection that typically follows a moment later (a WebRTC
upgrade) brings no new subscription-change, and nothing tried again. Entries
written before the two met were never exchanged.

Sync now starts the exchange when an unlimited connection to a subscriber of
the database opens, and tries once more if such a connection opened while an
exchange with that peer was still in flight and that exchange then fails.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@NiKrause

Copy link
Copy Markdown
Contributor Author

One more commit: ccc7d94, exchange heads once a usable connection to a subscriber opens.

The gap. Two browsers that a relay introduces usually see each other subscribe over the relay's circuit, a limited connection. The heads exchange started at that moment cannot open its stream there and times out: libp2p does not open a protocol stream on a limited connection unless the protocol allows it, and the heads protocol does not. The direct WebRTC connection that follows a moment later brings no new subscription-change, since the subscription is already known, so nothing starts the exchange again. Entries written before the two met then reach the other side only if a third peer holds them.

How it showed up. In a two-browser end-to-end test, both browsers write right after joining a shared database. Both heads dials timed out after about 5.8 s on the circuit, and WebRTC came up 0–1.5 s later. Neither browser ever received the other's entry, although both stayed connected directly.

The change.

  • Sync now starts the exchange when an unlimited connection (connection.limits == null) to a subscriber of the database opens.
  • If such a connection opens while an exchange with that peer is still in flight, and that exchange then fails, Sync tries once more.
  • Two regression tests are in test/sync-missed-peers.test.js: one where the direct connection opens after the exchange failed, one where it opens while the exchange is still failing.

CI. Run 45805209343 on a CI-only branch, with Node pinned to 22 and the browser job on a self-hosted runner because of the runner drift described above:

  • node: 549 passing
  • browser: 547 passing, 2 pending (win32 path joins)
  • control job: with src/sync.js from the previous head, both new tests fail at their own assertions

This PR's own Run Tests will still be red for the same runner-drift reasons.

NiKrause added a commit to NiKrause/deContact that referenced this pull request Nov 27, 2026
…on the form

- @orbitdb/core 4.0.0 gets orbitdb/orbitdb#1260 as a pnpm patch (src/sync.js only):
  heads learnt by exchange are announced, peers already subscribed are exchanged
  with, the handler is registered before subscribing, and heads dials run outside
  the database's queue. Entries reach a browser connected only through a relay.
- A resent contact request names the request it repeats (resentOf, signed). The
  recipient drops a resend of a request it answered in the dialog; a request made
  anew still asks. Before, a resend that arrived while the answer was on its way
  opened a second dialog.
- The onboarding form, now the first screen of an invitation link (#97), has the
  language switch the passkey screen had (#89).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
NiKrause added a commit to NiKrause/deContact that referenced this pull request Nov 27, 2026
* feat: exchange cards first, create the passkey afterwards (#97)

A browser without deContact that opens an invitation link shows the form at
once. A temporary identity starts once the person starts on the form: a
random root in the page's memory, the did:key and X25519 key derived from it
as from a vault's root. The exchange runs under that DID, both ways.

Once a contact's card has arrived the app offers to secure it with a passkey
(also in Settings). Creating the passkey seals the temporary root into the
new vault's slot, so the DID, the books and the cards stay and nothing is
migrated. Right after, recovery words and the vault file are offered, short
and skippable.

Hardened: nothing of the temporary phase is kept. The root never leaves
memory, no vault is written, and the app's other localStorage writes (links
opened and issued) are held in memory until the identity is secured. While
temporary, leaving the page warns (beforeunload).

"Already have a deContact passkey? Sign in" on the form reopens the link
with today's passkey screen; the inviter is asked only once the person
starts on the form, so the link's one-time token is still unused then.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix: patch OrbitDB's sync, ask once per request, the language switch on the form

- @orbitdb/core 4.0.0 gets orbitdb/orbitdb#1260 as a pnpm patch (src/sync.js only):
  heads learnt by exchange are announced, peers already subscribed are exchanged
  with, the handler is registered before subscribing, and heads dials run outside
  the database's queue. Entries reach a browser connected only through a relay.
- A resent contact request names the request it repeats (resentOf, signed). The
  recipient drops a resend of a request it answered in the dialog; a request made
  anew still asks. Before, a resend that arrived while the answer was on its way
  opened a second dialog.
- The onboarding form, now the first screen of an invitation link (#97), has the
  language switch the passkey screen had (#89).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
NiKrause added a commit to NiKrause/deContact that referenced this pull request Dec 2, 2026
- @orbitdb/core 4.0.0 -> 4.0.2, and an override to 4.0.2 so
  @le-space/orbitdb-access-controller-decontact does not keep its own
  4.0.0 copy.
- The sync patch (orbitdb/orbitdb#1260, not in 4.0.2) moves to
  patches/@[email protected] unchanged; src/sync.js is the same in
  4.0.2, and pnpm applies it.
- README, docs/how-it-works.md and the tests-for-changes spec name the new
  version and patch path.

Co-authored-by: Claude Opus 5.5 <[email protected]>

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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sync never delivers the first entry to a reader connected only through a relay

1 participant