Skip to content

Put out-of-order sample datagrams back in order - #217

Merged
cboulay merged 2 commits into
masterfrom
fix/udp-sample-reorder
Nov 6, 2026
Merged

cboulay merged 2 commits into
masterfrom
fix/udp-sample-reorder

Conversation

@cboulay

@cboulay cboulay commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator

Stacked on #215 (base: feat/native-default-central-deprecated). Follow-up to #213.

Problem

About once a minute, sample timestamps step backwards by ~29 samples at 30 kHz. Nothing is lost; two datagrams arrive in the wrong order. Central sees exactly the same reordering, and it happens with or without Central running.

Cause, as seen on the wire: the device normally sends one datagram per millisecond of samples. Its protocol-monitor packet goes out in a datagram of its own about every 1.111 s (33,333 sample periods). When that falls partway through a millisecond, the millisecond's samples are split around it: e.g. 27 samples, then the monitor, then the remaining 3 samples a few microseconds later.

The monitor interval isn't a whole number of milliseconds (33,333 = 30 × 1111 + 3 sample periods), so the split point moves by 3 samples each time and the pattern repeats every 10 monitors, i.e. every 11.11 s. The 27 + 3 split, a 3-sample datagram ~3 µs behind a 27-sample one, is the one Windows occasionally delivers tail-first, although an Npcap capture shows the wire order is correct. Reported to Blackrock so a future firmware release can avoid the split.

Host-side settings didn't help:

  • interrupt moderation off;
  • Defender DisableDatagramProcessing (its windefend_datagram_v4 WFP callout stays installed regardless);
  • running without Central.

This adapter (Realtek 2.5GbE, Microsoft inbox driver) has no RSS.

Fix

cbdev::SampleReorderBuffer (new src/cbdev/src/sample_reorder.h) sits between receivePackets() and callback dispatch in cbdev's receive thread.

  • Hold rule: a datagram is held only if, for some sample group it carries, its first sample comes after a gap and it spans under 0.5 ms — i.e. it's the tail of a split whose head hasn't arrived.
  • Release: the split puts out head, monitor, tail, so with the tail first its head is at most two datagrams behind it.
    • Late head arrives within 2 datagrams: the head is delivered first, then the tail, then anything that queued behind it. Only the late head ever moves.
    • Otherwise: after ConnectionParams::reorder_window (default 2; 0 disables) more datagrams, everything is released in arrival order; the gap was real loss.
    • Idle socket: the receive timeout (blocking sockets) also releases.
    • No timer or select(): holds are bounded by datagram count, so a lost head can never hold data longer than the window.
  • Unaffected cases:
    • In-order traffic is never held.
    • Genuine loss is normally followed by a full millisecond datagram, which isn't held.
    • Each sample group is tracked separately. Every channel picks its own group, so any of groups 1–6 can be active at once at different rates; only groups at 10 kHz and up can mark a tail. Cross-group skew is ignored.
    • Spike and config packets never trigger a hold. Spikes inside a reordered datagram are restored along with it.
  • Reporting: restorations are reported on stderr, rate-limited like cbdev's packet-loss lines. CERELINK_REORDER_STATS=1 prints a per-session summary: datagrams, holds, what ended each hold (head / count / idle), and the most datagrams a late head arrived after its tail.

Measurements (HUB1, 8 ch × 30 kHz)

  • Correctness: over 10 minutes with the fix, 0 reorders reached the application, and cbdev reported 3 restorations. Without the fix, the same run shows 6–11 reorders per 10 minutes.
  • Hold rate (Release, 8 × 60 s runs): 6 holds in ~496,000 datagrams (about 1 in 83,000). Every one was ended by the late head, 23–27 µs later. None ended by timeout or by real loss.
  • CPU, microbenchmark (-O2): 0.2–0.5 µs per datagram, ~0.02–0.05% of a core per device at 1,000 datagrams/s. The 256-channel figure is with cold-cache synthetic data.
  • CPU, end to end: Release simple_device, 8 alternating A/B rounds: 1.88% vs 2.13% of a core. The paired 95% CI is −0.07 to +0.56 points, i.e. not separable from noise.

Tests

  • New: 15 SampleReorder.* unit tests (synthetic datagrams). They cover:
    • the bench case, and a head two datagrams behind its tail;
    • sample-free datagrams queued behind a held tail;
    • real gaps after full datagrams, and after small ones (released after the window);
    • idle-socket release;
    • detection in either of two groups, and all six groups active at once;
    • cross-group skew;
    • interleaved spikes;
    • timestamp resets;
    • disabling the buffer, and padding of held copies.
  • Full suite: MinGW Debug on Windows, ctest 523/523 run serially, including the 94 nPlayServer integration tests (before the count-based rework).

The measurements above were taken with the earlier time-based (3 ms) hold. Every hold then ended by the late head 23–27 µs after the tail, well before the next millisecond's datagram, which the count-based rule also covers. The count-based version has not been re-measured on Windows.

Not covered: a spike-only configuration (no sample group enabled). The monitor still splits datagrams there, but the detector needs sample timestamps.

🤖 Generated with Claude Code

@cboulay
cboulay force-pushed the fix/udp-sample-reorder branch from 1cddabb to d0a43ca Compare November 6, 2026 06:31
cboulay and others added 2 commits November 6, 2026 11:37
About every 1.111 s the device sends its protocol-monitor packet in a
datagram of its own, and when that falls partway through a millisecond
of samples, the millisecond is split around it (e.g. 27 samples, the
monitor, then the remaining 3 a few microseconds later); the split point
cycles with an 11.1 s period. On Windows the small trailing datagram is
occasionally delivered to sockets before the larger one, although the
wire order is correct; Central sees the same reordering. Sample
timestamps then step backwards about once a minute. Reported to
Blackrock so a future firmware release can avoid the split.

cbdev's receive thread now passes each datagram through a
SampleReorderBuffer. A datagram is held when, for some sample group it
carries, its first sample comes after a gap AND it spans under 0.5 ms --
the tail of a split whose head has not arrived. The head is delivered
first when it arrives, then the tail, then anything queued behind it.
In-order traffic is never held; a hold also ends on other sample data
(a real gap) or after ConnectionParams::reorder_hold_us (3 ms; 0
disables). Groups are tracked independently, so group 6 alongside a
slower group 1-4 works, and spikes and config packets never trigger a
hold. Restorations are reported on stderr like packet loss;
CERELINK_REORDER_STATS=1 prints a per-session summary.

Measured on HUB1 (8 ch x 30 kHz, Release): 6 holds in ~496k datagrams
over 8 minutes, each ended by the late datagram 23-27 us later; 0
reorders reached the application. Cost: 0.2-0.5 us per datagram
(~0.02-0.05% of a core per device) in a microbenchmark; not separable
from noise end to end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The split this fixes is head, monitor, tail on the wire; with the tail
delivered first, its head is at most two datagrams behind it. So a held
tail now waits for at most ConnectionParams::reorder_window (2) more
datagrams: the late head is delivered first if it comes, otherwise
everything is released in arrival order. An idle socket (receive
timeout) also releases.

This drops the 3 ms deadline (reorder_hold_us), the select() wait in the
receive loop, the "other samples end the hold" rule and the queue cap.
Holds can no longer outlast a lost head by more than the window.

CERELINK_REORDER_STATS now reports releases by head / count / idle and
the most datagrams a late head arrived after its tail.

Tests cover a head two datagrams behind, real loss released after the
window, idle release, and all six sample groups active at once.

Co-Authored-By: Claude <[email protected]>
@cboulay
cboulay force-pushed the fix/udp-sample-reorder branch from d0a43ca to 9b78c66 Compare November 6, 2026 16:40
@cboulay

cboulay commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Windows bench test: instructions for the agent on the Windows machine

Goal: re-measure the count-based reorder buffer (commit 9b78c66) on the Windows bench, where the reorders were first seen. The macOS results are below for comparison.

1. Build

git fetch origin
git checkout fix/udp-sample-reorder
git pull --ff-only
cmake -B build-rel -S . -DCMAKE_BUILD_TYPE=Release -DCBSDK_BUILD_SHARED=ON
cmake --build build-rel --config Release -j
  • Use the same toolchain as before (MinGW).
  • Sanity check: ctest --test-dir build-rel -R SampleReorder should report 15/15.
  • Run the full suite serially only if there's time. The nPlayServer integration tests bind the device ports, so don't run ctest while the hardware test below is running.

2. Run the test script

Save the script at the bottom of this comment as reorder_check.py in its own directory, outside the repo. Then run, from that directory (PowerShell):

$env:CBSDK_LIB_PATH = "<repo>\build-rel\src\cbsdk\libcbsdk.dll"   # or cbsdk.dll, wherever the shared lib landed
$env:CERELINK_REORDER_STATS = "1"
<repo>\pycbsdk\.venv\Scripts\python -I reorder_check.py --seconds 120 HUB1:8
<repo>\pycbsdk\.venv\Scripts\python -I reorder_check.py --seconds 600 HUB1:8
<repo>\pycbsdk\.venv\Scripts\python -I reorder_check.py --seconds 600 HUB1:256 HUB2:256 NSP:16:ANALOG_IN
  • Order: run the 8-channel runs first; they should see reorders without loss. The full load comes last and may also show real loss.
  • Optionally repeat the 600 s full-load run with Central 7.8 running alongside.
  • Device config: the script sets the first N channels of the given type (default FRONTEND) to RAW (group 6) with disable_others=True. That changes the devices' sample-group setup.

3. What to report, per run

  1. Stderr lines from cbdev:
    • [cbdev] reorder stats (port …): datagrams= holds= (head= count= idle=) head_wait_max= — one line per device, printed when the session closes;
    • any [cbdev] put N out-of-order sample datagrams back in order lines;
    • any [cbdev] dropped … lines.
  2. The script's summary line per device: samples, backwards, gaps, missing_samples, app_queue_dropped.

4. Pass criteria

  • backwards=0 on every device: no reorder reached the app.
  • head_wait_max <= 2. This is the assumption behind the 2-datagram window (head, monitor and tail can arrive in any order). If it is ever 3 or more, or if count > 0 while gaps is 0, report it. Either one means the window is too small.
  • holds is about equal to head in the 8-channel runs: no false holds.
  • At full load, if there is real loss (gaps > 0), count > 0 is expected (a lost head released after the window). backwards should still be 0.

macOS results for comparison (this branch, HUB1 + HUB2 + NSP connected)

Run Samples per device Gaps Backwards Holds (ended by head / count / idle) head_wait_max
HUB1 8 ch RAW, 60 s (+ setup; script crashed before its summary) – – – 1 (1 / 0 / 0) 2
HUB1 8 ch RAW, 120 s 3.6 M 0 0 0 0
HUB1 256 + HUB2 256 + NSP 16 AIN, 300 s 9.0 M 0 0 HUB1: 1 (1 / 0 / 0); others 0 1

macOS reorders too, but rarely. It showed no real sample loss even at full load, so the lost-head path has only been exercised by unit tests. The [cbdev] dropped N of M lines (~0.001%) appeared while the RAW streams were gap-free.

reorder_check.py
"""Configure N RAW channels per device, stream, report reorders and gaps.

Usage: reorder_check.py --seconds 60 HUB1:8 [HUB2:256 NSP:16:ANALOG_IN]
"""
import argparse
import time

import numpy as np
from pycbsdk import ChannelType, DeviceType, SampleRate, Session


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("devices", nargs="+", help="DEVICE:NCHANS")
    ap.add_argument("--seconds", type=float, default=60)
    args = ap.parse_args()

    sessions, chunks = {}, {}
    try:
        for spec in args.devices:
            name, n, *ctype = spec.split(":")
            s = Session(DeviceType[name])
            ct = ChannelType[ctype[0]] if ctype else ChannelType.FRONTEND
            s.set_sample_group(int(n), ct, SampleRate.SR_RAW, disable_others=True)
            s.sync()
            got = len(s.get_group_channels(int(SampleRate.SR_RAW)))
            print(f"{name}: {got} channels in RAW group", flush=True)
            chunks[name] = []

            @s.on_group_batch(SampleRate.SR_RAW)
            def _on(samples, timestamps, _c=chunks[name]):
                _c.append(timestamps.copy())

            sessions[name] = s
        time.sleep(1.0)  # let streams settle
        for c in chunks.values():
            c.clear()
        print(f"collecting {args.seconds:g} s ...", flush=True)
        time.sleep(args.seconds)
        stats = {n: s.stats for n, s in sessions.items()}
    finally:
        for s in sessions.values():
            s.close()  # cbdev prints reorder stats to stderr here

    for name, c in chunks.items():
        ts = np.concatenate(c).astype(np.int64) if c else np.array([], np.int64)
        if len(ts) < 3:
            print(f"{name}: too few samples ({len(ts)})")
            continue
        d = np.diff(ts)
        period = int(np.median(d))
        back = d <= 0
        gap = d > period * 3 // 2
        missing = int(np.sum(np.rint(d[gap] / period) - 1))
        print(f"{name}: samples={len(ts)} period={period}ns backwards={int(back.sum())} "
              f"gaps={int(gap.sum())} missing_samples={missing} "
              f"app_queue_dropped={stats[name].packets_dropped}")
        for i in np.flatnonzero(back)[:5]:
            print(f"    backwards at {i}: step {d[i]} ns")


if __name__ == "__main__":
    main()

🤖 Generated with Claude Code

@cboulay

cboulay commented Nov 6, 2026 •

Copy link
Copy Markdown
Collaborator Author

Windows bench results for 9b78c66

Setup: Windows 10, Realtek 2.5GbE. MinGW Release build with -DCBSDK_BUILD_SHARED=ON; ctest -R SampleReorder 15/15. reorder_check.py as given, with CERELINK_REORDER_STATS=1. Runs 1–3 had Central closed; run 4 had Central 7.8.0 running alongside.

Run Device Samples Backwards Gaps Missing Holds (head / count / idle) head_wait_max
1: HUB1 8 ch RAW, 120 s HUB1 3,599,974 0 0 0 0 (0 / 0 / 0) 0
2: HUB1 8 ch RAW, 600 s HUB1 17,999,701 0 0 0 0 (0 / 0 / 0) 0
3: HUB1 256 + HUB2 256 + NSP 16 AIN, 600 s HUB1 17,999,729 0 0 0 0 (0 / 0 / 0) 0
HUB2 18,000,565 0 0 0 3 (3 / 0 / 0) 1
NSP 18,001,377 0 0 0 0 (0 / 0 / 0) 0
4: same as 3, with Central 7.8 running HUB1 17,999,764 0 0 0 0 (0 / 0 / 0) 0
HUB2 18,000,687 0 0 0 3 (3 / 0 / 0) 1
NSP 18,001,563 0 0 0 0 (0 / 0 / 0) 0

app_queue_dropped=0 on every device in every run.

Pass criteria

  • backwards=0 everywhere: no reorder reached the app.
  • head_wait_max ≤ 1; never 3 or more.
  • count=0 everywhere, with gaps=0, so the window never cut a hold short.
  • No false holds. Note, though, that the 8-channel runs had no reorders at all, so they didn't exercise the buffer.
  • No real loss at full load. The lost-head path is still exercised only by unit tests, as on macOS.

Stderr

  • [cbdev] put N out-of-order sample datagrams back in order: 3 restorations per full-load run, all on HUB2 (port 51003).
  • [cbdev] dropped N of M:
    • throughout every run at 0.0000–0.0047%, plus one 0.098% line early in run 3 (33 of 33,550);
    • all while the RAW streams were gap-free, as on macOS.

Follow-up: run 5, group 5 (SR_30kHz)

To check whether the reorder rate depends on the sample group, I repeated run 2 in group 5. Same script, with a --rate option added to a copy so set_sample_group and on_group_batch use SampleRate.SR_30kHz. HUB2 and the NSP were idle, and Central was closed.

Run Device Samples Backwards Gaps Missing Holds (head / count / idle) head_wait_max
5: HUB1 8 ch group 5, 600 s HUB1 17,999,730 0 0 0 9 (9 / 0 / 0) 1
  • 9 restorations in 10 minutes, all ended by the late head, none reaching the app. That's the same rate as before 9b78c66 on this bench (6–11 per 10 minutes in group 5).
  • head_wait_max=1 and count=0, so the 2-datagram window held with room to spare.
  • The reorder rate depends on the sample group. HUB1 at 8 channels had 0 reorders in 12 minutes of RAW (group 6) and 9 in 10 minutes of group 5. So runs 1–2 passed without exercising the buffer, and run 5 is the HUB1 run that does.
  • Stderr: one [cbdev] dropped 104 of 1008748 packets (0.0103%) line, with no sample gaps.

🤖 Generated with Claude Code

Base automatically changed from feat/native-default-central-deprecated to master November 6, 2026 21:38
@cboulay
cboulay merged commit 7aa7916 into master Nov 6, 2026
@cboulay
cboulay deleted the fix/udp-sample-reorder branch November 6, 2026 23:29
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.

1 participant