Skip to content

Heads exchange has no framing: heads that arrive in one chunk fail with "CBOR decode error: too many terminals" and are lost #1261

Backlog

Description

@NiKrause

Summary

Sync sends each head with its own stream.send() and decodes every chunk the stream yields as exactly one entry. Nothing marks where one head ends and the next one begins. With libp2p v3 streams the chunk boundaries do not match the sends:

  • The peer that dialled gets all heads of the exchange in one chunk. The answering peer can hit it too, though less often. Decoding fails with CBOR decode error: too many terminals, data makes no sense, and the exchange is abandoned. If no other exchange delivers those heads, the dialling peer never gets them.
  • A head larger than about 256 KiB is split across chunks. Decoding fails with CBOR decode error: not enough data for type, in both directions, so such an entry never crosses the heads exchange.

A single head of normal size always works, which is probably why this has gone unnoticed.

Reproduction

The script uses plain @orbitdb/core 4.0.0, libp2p 3.5.2, @chainsafe/libp2p-yamux 8.0.1, @libp2p/gossipsub 15.0.23 and helia 6.1.4, over TCP on 127.0.0.1. There is no relay code and no patch (the script is at the end).

A hub writes one entry. Several writers each write one entry while apart from the hub, then join it one at a time, so the hub ends up with several concurrent heads. Then a fresh reader joins the hub; this repeats for every trial. The script raises libp2p's inboundConnectionThreshold: every peer comes from 127.0.0.1, and at the default of 5 per second per host, quick trials are refused with ECONNRESET. It records the size of every chunk that a heads stream yields, and on which end of the stream it arrived.

case reader got chunks on the reader's side errors
1 head (control) 1/1, 10 of 10 trials 479 on each of the two streams none
4 heads 4/4, 5 of 5 answered: 484 482 484 479; dialled: 1929 too many terminals, 5 of 5
4 heads, only the reader dials ¹ 0/4, 5 of 5 dialled: 1923 too many terminals, 5 of 5
1 head, only the reader dials ¹ (control) 1/1, 5 of 5 dialled: 477 none
1 head of 300 KB 0/1, 5 of 5 answered: 262132; dialled: 262050 not enough data for type on both streams

¹ The hub's own dialProtocol for the heads protocol is made to throw UnsupportedProtocolError, which Sync skips silently. This leaves the reader's dial as the only exchange. That happens for real whenever the other side's exchange does not run, for example because it lost the race or its dial failed.

1929 = 484 + 482 + 484 + 479: all four heads come as one chunk on the stream the reader dialled. In the 4/4 row they reach the reader anyway, but only through the second exchange, the one the hub dialled. There, the reader is the side that answers and gets them one by one.

Why

src/sync.js at v4.0.0:

  • sendHeads calls stream.send(bytes) once per head and adds no length prefix or delimiter.
  • receiveHeads takes value.subarray() of each chunk and passes it to Entry.decode() as one block.

In libp2p v3, a stream buffers what arrives while nobody reads it and hands the buffer on as one message (onData, addEventListener, dispatchReadBuffer).

  • On the dialling side: exchangeHeads starts reading only after dialProtocol() has resolved. By then the answering side, which sends its heads at once, has usually delivered all of them. They are dispatched together as one chunk.
  • On the sending side: send() also appends to a write buffer, and the stream then sends it in pieces of at most the muxer's message size. That is why a large head is split, and why several sends can also be merged on the way out. That is the likely path for the answering side, which the reproduction does not hit but the field log below does.

This came in with 712fc04 ("use new stream and protocol handler interfaces"). Before that, the heads went through it-pipe into the stream's sink. That was not framed either; I have not measured whether chunk boundaries happened to match heads there.

Seen in the field

A relay that pins OrbitDB databases runs core 4.0.0. It carries the patch from #1260, which does not touch sendHeads or receiveHeads. In 67 local runs of a browser E2E suite, it logged this error 83 times, spread over 14 of those runs. Every one was too many terminals. 73 came from the dialling side (receiveHeads ← exchangeHeads) and 10 from the answering side (← handleReceiveHeads), so the merge happens in both directions in practice. The errors cluster in three specs: two passkey users writing to one list, a passkey session rejoining, and a reload that switches the storage mode. Those tests still passed, because the heads reached the relay some other way (the other direction's exchange, or pubsub). Nothing guarantees that.

Not the same as

Possible fixes

1. The receiver splits heads by CBOR item (wire-compatible). Every head is a single dag-cbor block, including with replication encryption, where it is the block that wraps the ciphertext. So the receiver can buffer the bytes and take one item at a time with cborg's decodeFirst, which returns the remainder. Old senders keep working, and nothing changes on the wire. Tried against the reproduction above:

Measured as a pair in the same run, v4.0.0 against v4.0.0 plus the diff below. Counts are trials:

case v4.0.0 receiver splits by CBOR item
1 head (control) 1/1 in 10 of 10, no errors 1/1 in 10 of 10, no errors
4 heads 4/4 in 10 of 10, but too many terminals in 10 of 10 4/4 in 10 of 10, no errors
4 heads, only the reader dials 0/4 in 10 of 10 4/4 in 10 of 10
1 head of 300 KB, only the reader dials 0/1 in 10 of 10 (not enough data for type) 1/1 in 10 of 10
3 heads of 300 KB each, only the reader dials 0/3 in 5 of 5 3/3 in 5 of 5

The diff is a prototype. A real fix should tell an incomplete item from a malformed one; the prototype waits for the stream's end on any decode error. It should also cap the buffer, and it should collect the bytes in a Uint8ArrayList, because concat on every chunk costs time quadratic in the number of chunks.

Diff against v4.0.0 src/sync.js
--- a/src/sync.js
+++ b/src/sync.js
@@ -3,6 +3,9 @@
 import { TimeoutController } from 'timeout-abort-controller'
 import pathJoin from './utils/path-join.js'
 import { Entry } from './oplog/index.js'
+import { decodeFirst } from 'cborg'
+import { decodeOptions } from '@ipld/dag-cbor'
+import { concat } from 'uint8arrays/concat'
 
 const DefaultTimeout = 30000 // 30 seconds
 
@@ -154,13 +157,30 @@
   }
 
   const receiveHeads = async (peerId, stream) => {
+    // Heads come without framing: one chunk can hold several heads, and one
+    // head can span several chunks. Every head is one dag-cbor block, so split
+    // them by decoding one CBOR item at a time.
+    let pending = new Uint8Array(0)
     for await (const value of stream) {
-      const headBytes = value.subarray()
-      if (headBytes && onSynced) {
-        const entry = await Entry.decode(headBytes, log.encryption.replication?.decrypt, log.encryption.data?.decrypt)
-        await onSynced(entry)
+      pending = concat([pending, value.subarray()])
+      while (pending.byteLength > 0) {
+        let rest
+        try {
+          [, rest] = decodeFirst(pending, decodeOptions)
+        } catch (e) {
+          break // incomplete: wait for more bytes
+        }
+        const headBytes = pending.subarray(0, pending.byteLength - rest.byteLength)
+        pending = rest
+        if (onSynced) {
+          const entry = await Entry.decode(headBytes, log.encryption.replication?.decrypt, log.encryption.data?.decrypt)
+          await onSynced(entry)
+        }
       }
     }
+    if (pending.byteLength > 0) {
+      decodeFirst(pending, decodeOptions) // throws why the rest is not a head
+    }
     if (started) {
       await onPeerJoined(peerId)
     }

cborg would become a direct dependency; today it arrives only through @ipld/dag-cbor.

2. Length-prefixed frames. For example lpStream from @libp2p/utils on both ends. This is cleaner, but it changes the wire format, so it would need a new protocol id (/orbitdb/heads/…) or some negotiation. Otherwise old and new peers misread each other.

Fix 1 could ship as a patch release. Fix 2 could follow when the protocol is next versioned.

Reproduction script (repro.mjs)
// Plain @orbitdb/core 4.0.0 on libp2p v3 over TCP, no relay code, no patch.
//
// A hub peer holds several concurrent heads. A fresh reader joins and exchanges heads with it.
// sendHeads() writes each head with its own stream.send(); receiveHeads() decodes every chunk
// the stream yields as exactly one entry. Nothing frames the entries, so whenever two of them
// arrive in one chunk the reader fails with "CBOR decode error: too many terminals".
//
// Usage: node repro.mjs [writers=3] [trials=10]
//   ONE_WAY=1     the hub opens no heads exchange of its own, so the reader's dial is the only one
//                 (as when the other side's dial loses the race or is refused); shows what is lost
//   PAYLOAD=n     each entry carries n bytes, to see an entry that spans several muxer frames
import { createLibp2p } from 'libp2p'
import { tcp } from '@libp2p/tcp'
import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { identify } from '@libp2p/identify'
import { gossipsub } from '@libp2p/gossipsub'
import { createHelia } from 'helia'
import { createOrbitDB, IPFSAccessController } from '@orbitdb/core'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'

const WRITERS = Number(process.argv[2] ?? 3)
const TRIALS = Number(process.argv[3] ?? 10)
const HEADS_PROTOCOL = '/orbitdb/heads'
const ONE_WAY = process.env.ONE_WAY === '1'
const PAYLOAD = Number(process.env.PAYLOAD ?? 0)
const value = (text) => PAYLOAD ? text + ' ' + 'x'.repeat(PAYLOAD) : text
const root = await mkdtemp(join(tmpdir(), 'cbor-repro-'))
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))

// Record the size of every chunk a heads-exchange stream yields, on both ends.
const chunks = []
const tap = (who, dir, stream, protocol) => {
  if (!String(protocol).startsWith(HEADS_PROTOCOL)) return stream
  const iterate = stream[Symbol.asyncIterator].bind(stream)
  stream[Symbol.asyncIterator] = async function * () {
    for await (const value of iterate()) {
      chunks.push({ who, dir, bytes: value.byteLength })
      yield value
    }
  }
  return stream
}

const peer = async (name) => {
  const libp2p = await createLibp2p({
    addresses: { listen: ['/ip4/127.0.0.1/tcp/0'] },
    transports: [tcp()],
    connectionEncrypters: [noise()],
    streamMuxers: [yamux()],
    // Every peer here comes from 127.0.0.1; the default of 5 inbound connections per second
    // per host refuses quick trials with ECONNRESET during the handshake.
    connectionManager: { inboundConnectionThreshold: Infinity },
    services: {
      identify: identify(),
      pubsub: gossipsub({ allowPublishToZeroTopicPeers: true })
    }
  })
  const dial = libp2p.dialProtocol.bind(libp2p)
  libp2p.dialProtocol = async (peerId, protocol, options) => {
    if (ONE_WAY && name === 'hub' && String(protocol).startsWith(HEADS_PROTOCOL)) {
      const e = new Error('hub opens no exchange of its own (ONE_WAY)')
      e.name = 'UnsupportedProtocolError' // Sync skips this peer silently
      throw e
    }
    return tap(name, 'dialled', await dial(peerId, protocol, options), protocol)
  }
  const handle = libp2p.handle.bind(libp2p)
  libp2p.handle = (protocol, handler, options) =>
    handle(protocol, (stream, connection) => handler(tap(name, 'answered', stream, protocol), connection), options)
  const ipfs = await createHelia({ libp2p })
  const orbitdb = await createOrbitDB({ ipfs, id: name, directory: join(root, name) })
  const db = await orbitdb.open('cbor-repro', { AccessController: IPFSAccessController({ write: ['*'] }) })
  const errors = []
  db.events.on('error', (e) => errors.push(e?.message ?? String(e)))
  return { name, libp2p, ipfs, orbitdb, db, errors }
}

const count = async (db) => (await db.all()).length
const waitFor = async (check, ms) => {
  const until = Date.now() + ms
  while (Date.now() < until) {
    if (await check()) return true
    await sleep(100)
  }
  return false
}
const stop = async (p) => {
  await p.db.close()
  await p.orbitdb.stop()
  await p.ipfs.stop()
}

// The hub and the writers each write one entry while apart: concurrent heads.
const hub = await peer('hub')
await hub.db.add(value('from hub'))
const writers = []
for (let i = 0; i < WRITERS; i++) {
  const w = await peer(`writer${i}`)
  if (w.db.address !== hub.db.address) throw new Error('addresses differ')
  await w.db.add(value(`from writer ${i}`))
  writers.push(w)
}
// Writers join the hub one at a time, so each exchange carries a single head.
for (const w of writers) {
  await w.libp2p.dial(hub.libp2p.getMultiaddrs()[0])
  await waitFor(async () => (await count(hub.db)) >= 2 + writers.indexOf(w), 15000)
  await w.libp2p.hangUp(hub.libp2p.peerId)
}
const total = WRITERS + 1
const heads = await hub.db.log.heads()
const sizes = []
for (const { hash } of heads) sizes.push((await hub.db.log.storage.get(hash)).byteLength)
console.log(`hub: ${await count(hub.db)} entries, ${heads.length} heads of ${sizes.join(', ')} bytes`)
console.log(`hub errors while writers joined: ${hub.errors.length}; ONE_WAY=${ONE_WAY} PAYLOAD=${PAYLOAD}`)
chunks.length = 0

// Fresh readers join the hub, one per trial.
let failed = 0
for (let t = 1; t <= TRIALS; t++) {
  const reader = await peer(`reader${t}`)
  const before = chunks.length
  const hubErrorsBefore = hub.errors.length
  try {
    await reader.libp2p.dial(hub.libp2p.getMultiaddrs()[0])
  } catch (e) {
    reader.errors.push(`dial: ${e.message}`)
  }
  const complete = await waitFor(async () => (await count(reader.db)) === total, 8000)
  const seen = chunks.slice(before).filter((c) => c.who !== 'hub').map((c) => `${c.dir}:${c.bytes}`).join(' ')
  const errs = [...reader.errors, ...hub.errors.slice(hubErrorsBefore).map((m) => `hub: ${m}`)]
  if (!complete || errs.length) failed++
  console.log(`trial ${t}: reader has ${await count(reader.db)}/${total}; chunks ${seen || '-'}; errors: ${errs.join(' | ') || 'none'}`)
  await stop(reader)
}
console.log(`\n${failed} of ${TRIALS} trials incomplete or with errors`)

for (const p of [hub, ...writers]) await stop(p)
await rm(root, { recursive: true, force: true })
process.exit(0)

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions