my-durable 0.0.116 → 0.0.118

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@
7
7
  <meta name="referrer" content="no-referrer" />
8
8
  <link rel="icon" type="image/svg+xml" href="/icons/durable-pi.svg" />
9
9
  <title>Durable Pi | Network</title>
10
- <script type="module" crossorigin src="/assets/index-CRTYV5V2.js"></script>
10
+ <script type="module" crossorigin src="/assets/index-DDRkB11b.js"></script>
11
11
  <link rel="stylesheet" crossorigin href="/assets/index-DD66rPUN.css">
12
12
  </head>
13
13
  <body>
@@ -9,6 +9,13 @@ import type { NetworkDevice, SessionSummary } from "@sdk/api";
9
9
  import type { SessionExport } from "@sdk/client";
10
10
  import { deviceClient, message } from "./hub";
11
11
 
12
+ /** Run-11 h4-6: the download-side ceiling. The SDK already refuses to READ a
13
+ * binary body past 12 MiB (client.ts BINARY_BODY_MAX, r10 h3-1), so a bundle
14
+ * larger than this reaching the FE can only be a framing bug or a tampered
15
+ * peer — and honoring it would materialize the bytes as a Blob + object URL
16
+ * anyway, moving the same OOM to the tab one call later. Exported for tests. */
17
+ export const EXPORT_BUNDLE_MAX_BYTES = 12 * 1024 * 1024;
18
+
12
19
  /** The device's zipped session bundle: raw zip bytes plus the download name. */
13
20
  export type BundleFile = SessionExport;
14
21
  export type BundleTarget = Ref<{
@@ -20,6 +27,13 @@ export type BundleTarget = Ref<{
20
27
  * the retry logic without the DOM. The Blob wraps the zip bytes directly —
21
28
  * no base64 decode since the R8 binary contract. */
22
29
  export function downloadBundle(r: BundleFile) {
30
+ // Run-11 h4-6: refuse BEFORE any DOM work (createElement/Blob/createObjectURL)
31
+ // — over-cap bytes are never materialized. run()'s existing catch turns this
32
+ // into the inline retryable error + toast; the retry surface is unchanged.
33
+ if (r.bytes.byteLength > EXPORT_BUNDLE_MAX_BYTES)
34
+ throw Error(
35
+ `bundle is ${r.bytes.byteLength} bytes, over the ${EXPORT_BUNDLE_MAX_BYTES} byte download cap`,
36
+ );
23
37
  const a = document.createElement("a");
24
38
  // slice() normalizes the buffer to a plain ArrayBuffer (BlobPart typing, TS 5.7).
25
39
  // R16 (run-2 h13): the device is untrusted at the operator origin — the FE
@@ -8,6 +8,7 @@ import { randomUUID } from "node:crypto";
8
8
  import type { Request, Response } from "express";
9
9
  import { DpiError } from "../../../../dpi-sdk/src/errors.js";
10
10
  import { transportFor } from "./transport.js";
11
+ import { reassembledFrameBytes } from "./tunnel-transport.js";
11
12
  import type { MuxFrame } from "../../../../dpi-sdk/src/api.js";
12
13
  import type { NetworkRegistry } from "../../../../dpi-sdk/src/node/registry.js";
13
14
  import type { DeviceMonitor, TunnelTransportSource } from "./monitor.js";
@@ -52,6 +53,32 @@ const RELAY_TREE_CAP_BYTES = 4 * 1024 * 1024;
52
53
  * canonical ones) and measure the tree payload exactly as it does, so every
53
54
  * tree the monitor admits also passes here and nothing it rejects does. */
54
55
  const TREE_RELAY_MAX_SESSIONS = 2000;
56
+ /** Run-11 h1-1 (Unit A; cold-review r11 f1): the relay wrapper's EXACT byte
57
+ * overhead over the frame's own serialization —
58
+ * `{"sub":` (7) + JSON-escaped key + `,"frame":` (9) + `}` (1) = 17 + key
59
+ * bytes. Used by the raw-bytes pre-check in follow() so it faults only
60
+ * frames the authoritative stringify check would also reject. A CONSTANT
61
+ * allowance ≥ the real overhead inverted that direction and faulted LEGAL
62
+ * near-cap chunked frames (the ~480 B band under the cap). Exact math keeps
63
+ * the pre-check admission-identical to the authoritative check for every
64
+ * canonical (device-JSON.stringify'd) frame; only non-canonical raw bytes
65
+ * (hand-crafted whitespace) can diverge — and then the belt-and-braces
66
+ * byteLength(text) check after the single stringify still gates admission. */
67
+ function relayWrapperOverhead(key: string): number {
68
+ return 17 + Buffer.byteLength(JSON.stringify(key));
69
+ }
70
+ /** Run-11 h4-5 (Unit A): per-subscription token bucket for `tree` frames —
71
+ * capacity 4, refill 2/s, reset to full at every (re)connect (see
72
+ * follow()). Trees are whole-document snapshots that supersede each other,
73
+ * so a device pushing a back-to-back burst costs one multi-MiB
74
+ * stringify+copy per frame per tab for a view the next tree replaces
75
+ * anyway. Coalesced frames are counted (relayStats().coalescedTreeFrames →
76
+ * GET /api/network, next to droppedTreeFrames) and the next tree (a healthy
77
+ * device re-pushes on state change within ~500 ms) delivers the fresh view.
78
+ * Only `tree` is gated — snapshot/agents are handshake payloads and every
79
+ * other frame type stays unlimited (scope = h4-5 trees). */
80
+ const TREE_BUCKET_CAPACITY = 4;
81
+ const TREE_BUCKET_REFILL_PER_SEC = 2;
55
82
 
56
83
  const sseBudget = new ByteBudget("hub-sse", HUB_BUFFER_BUDGET_BYTES);
57
84
 
@@ -122,6 +149,10 @@ export class StreamMux {
122
149
  /** Run-9 U5/U8: device-authored tree frames dropped at the relay seam for
123
150
  * exceeding the monitor-mirror bounds — surfaced via relayStats(). */
124
151
  private droppedTreeFrames = 0;
152
+ /** Run-11 h4-5 (Unit A): tree frames coalesced away by the per-follow
153
+ * token bucket (see follow() — the bucket itself is LOCAL to each loop,
154
+ * cold-review r11 f2, so there is no Map state here to leak or share). */
155
+ private coalescedTreeFrames = 0;
125
156
 
126
157
  constructor(
127
158
  private readonly registry: NetworkRegistry,
@@ -159,8 +190,14 @@ export class StreamMux {
159
190
  }
160
191
 
161
192
  /** Read-only relay admission counters for tests and diagnostics. */
162
- relayStats(): { droppedTreeFrames: number } {
163
- return { droppedTreeFrames: this.droppedTreeFrames };
193
+ relayStats(): { droppedTreeFrames: number; coalescedTreeFrames: number } {
194
+ return {
195
+ droppedTreeFrames: this.droppedTreeFrames,
196
+ // run-11 h4-5 (Unit A): token-bucket coalescing, surfaced on
197
+ // GET /api/network next to droppedTreeFrames (main.ts spreads this
198
+ // object verbatim into the relay payload — no shape change needed).
199
+ coalescedTreeFrames: this.coalescedTreeFrames,
200
+ };
164
201
  }
165
202
 
166
203
  /** Wire the tunnel dispatcher source (main.ts, after construction). */
@@ -301,9 +338,39 @@ export class StreamMux {
301
338
  signal: AbortSignal,
302
339
  ) {
303
340
  const backoff = new Backoff(RECONNECT_BACKOFF_S);
341
+ // run-11 h4-5 (Unit A; cold-review r11 f2 rework): the tree token bucket
342
+ // is LOCAL to this follow() loop — one budget per (tab × sub) reader. A
343
+ // Map keyed by sub.key shared across follow() loops let a second tab on
344
+ // the same key drain this loop's budget, and the entry's deletion on the
345
+ // OTHER tab's exit lazily re-armed a FULL bucket here — bypassable
346
+ // shaping. Local state has neither seam. Reset to full at every
347
+ // (re)connect: the device's initial tree (a tab's first full view after a
348
+ // flap) always relays.
349
+ let treeTokens = TREE_BUCKET_CAPACITY;
350
+ let treeTokensAt = Date.now();
351
+ /** Consume one tree token (refill TREE_BUCKET_REFILL_PER_SEC, clamped at
352
+ * capacity; fractional idle credit kept on refuse). False = exhausted —
353
+ * the caller coalesces (snapshots supersede each other; the next tree
354
+ * delivers a strictly fresher view). */
355
+ const admitTree = (): boolean => {
356
+ const now = Date.now();
357
+ const tokens = Math.min(
358
+ TREE_BUCKET_CAPACITY,
359
+ treeTokens + ((now - treeTokensAt) / 1000) * TREE_BUCKET_REFILL_PER_SEC,
360
+ );
361
+ treeTokensAt = now;
362
+ if (tokens < 1) {
363
+ treeTokens = tokens;
364
+ return false;
365
+ }
366
+ treeTokens = tokens - 1;
367
+ return true;
368
+ };
304
369
  while (!signal.aborted) {
305
370
  await this.monitor.whenOnline(sub.deviceId, signal);
306
371
  if (signal.aborted) return;
372
+ treeTokens = TREE_BUCKET_CAPACITY;
373
+ treeTokensAt = Date.now();
307
374
  const device = this.registry.get(sub.deviceId);
308
375
  const transport = device ? transportFor(device, this.tunnel) : undefined;
309
376
  if (!transport?.available) return;
@@ -314,12 +381,6 @@ export class StreamMux {
314
381
  )) {
315
382
  if (!checkDeviceFrame(frame))
316
383
  throw new DpiError("invalid", "Invalid device stream frame");
317
- // run-8 U5: admission bound at the relay seam — checkDeviceFrame is
318
- // shape-only, so agent-event frames rode the ~16MiB transport
319
- // ceiling into per-tab stringify (B4 capped TREE frames at the
320
- // monitor seam only). Serialize ONCE here, admit on its byte size,
321
- // and hand the same string to every tab.
322
- const text = JSON.stringify({ sub: sub.key, frame });
323
384
  // snapshot/agents/network carry whole-document payloads by design
324
385
  // (a session snapshot includes entries + inbox) and legitimately
325
386
  // exceed the per-event cap — capping them turned a large session's
@@ -328,7 +389,7 @@ export class StreamMux {
328
389
  frame.type === "tree" || frame.type === "snapshot" || frame.type === "agents"
329
390
  ? RELAY_TREE_CAP_BYTES
330
391
  : RELAY_FRAME_CAP_BYTES;
331
- if (Buffer.byteLength(text) > cap) {
392
+ const relayCapFault = () =>
332
393
  stream.send({
333
394
  sub: sub.key,
334
395
  frame: {
@@ -339,15 +400,16 @@ export class StreamMux {
339
400
  },
340
401
  },
341
402
  });
342
- continue;
343
- }
344
403
  // Run-9 U5/U8: the monitor seam (state owner) degrades oversized
345
404
  // trees — but the RELAY is a pipe, and the tunnel chunk path exists
346
405
  // precisely to deliver legitimately large trees (tunnel-pacing
347
406
  // contract: a 1.5MB chunked tree arrives intact). The pipe's byte
348
- // cap is RELAY_TREE_CAP_BYTES above; here we mirror only the
349
- // session-COUNT policy. Byte parity with the monitor was tried and
350
- // reverted: it dropped the chunked-tree contract.
407
+ // cap is RELAY_TREE_CAP_BYTES; here we mirror only the session-COUNT
408
+ // policy. Byte parity with the monitor was tried and reverted: it
409
+ // dropped the chunked-tree contract. A count violation faults —
410
+ // never silently drops (r9 relay contract), never consumes a token,
411
+ // and the subscription survives (skip, not cut). Checked FIRST so
412
+ // both paths below share it (cold-review r11 f3 ordering).
351
413
  if (frame.type === "tree") {
352
414
  const sessions = Array.isArray(frame.tree?.sessions) ? frame.tree.sessions : [];
353
415
  if (sessions.length > TREE_RELAY_MAX_SESSIONS) {
@@ -365,6 +427,63 @@ export class StreamMux {
365
427
  continue;
366
428
  }
367
429
  }
430
+ // run-11 h1-1 (Unit A; cold-review r11 f1/f3 rework): chunked
431
+ // (tunnel) frames already know their exact serialized size
432
+ // (reassembledFrameBytes, recorded at the reassembly push seam in
433
+ // tunnel-transport). For them EVERY admission decision precedes the
434
+ // one serialization: an oversized multi-MiB frame faults on
435
+ // raw + EXACT wrapper overhead (relayWrapperOverhead — a constant
436
+ // allowance ≥ the real overhead faulted LEGAL near-cap frames), and
437
+ // a burst tree the token bucket coalesces away costs ZERO
438
+ // stringify. For canonical device JSON (the device's own
439
+ // JSON.stringify — the normal case) the pre-check faults exactly
440
+ // what the authoritative check would; hand-crafted non-canonical
441
+ // raw bytes can only diverge into an early fault (self-harm) or a
442
+ // late catch — the belt-and-braces byteLength(text) check below
443
+ // still gates every admission, so nothing over-cap ever relays.
444
+ const rawBytes = reassembledFrameBytes.get(frame);
445
+ if (rawBytes !== undefined) {
446
+ if (rawBytes + relayWrapperOverhead(sub.key) > cap) {
447
+ relayCapFault();
448
+ continue;
449
+ }
450
+ if (frame.type === "tree" && !admitTree()) {
451
+ // run-11 h4-5 (Unit A): bucket exhausted — coalesce (drop) this
452
+ // legal snapshot silently and count it: unlike the faults above
453
+ // (protocol violations worth surfacing), this is rate shaping of
454
+ // frames that supersede each other; the next tree (a healthy
455
+ // device re-pushes on state change within ~500 ms) delivers a
456
+ // strictly fresher view. Runs AFTER every admission check, so
457
+ // violations still fault and never consume a token.
458
+ this.coalescedTreeFrames++;
459
+ continue;
460
+ }
461
+ // run-8 U5 + h1-1: serialize ONCE — the only stringify on this
462
+ // path — admit on its byte size, hand the same string to the
463
+ // writer. Belt-and-braces after the pre-check: non-canonical raw
464
+ // bytes can re-stringify LONGER than raw (exponent-form numbers,
465
+ // e.g. 1e-9 → 0.000000001), so this check is still load-bearing.
466
+ const text = JSON.stringify({ sub: sub.key, frame });
467
+ if (Buffer.byteLength(text) > cap) {
468
+ relayCapFault();
469
+ continue;
470
+ }
471
+ stream.send({ sub: sub.key, frame }, text);
472
+ if (frame.type === "hello") backoff.reset();
473
+ continue;
474
+ }
475
+ // run-8 U5: inline/LAN frames have no raw-bytes side-channel — this
476
+ // stays the authoritative path: serialize ONCE here, admit on its
477
+ // byte size, and hand the same string to every tab.
478
+ const text = JSON.stringify({ sub: sub.key, frame });
479
+ if (Buffer.byteLength(text) > cap) {
480
+ relayCapFault();
481
+ continue;
482
+ }
483
+ if (frame.type === "tree" && !admitTree()) {
484
+ this.coalescedTreeFrames++;
485
+ continue;
486
+ }
368
487
  stream.send({ sub: sub.key, frame }, text);
369
488
  if (frame.type === "hello") backoff.reset();
370
489
  }
@@ -42,7 +42,10 @@ import type { DeviceTransport, TransportRequest, TransportResponse } from "./tra
42
42
  * (defense in depth — the device already sanitizes before putting it on the wire). */
43
43
  const safeHeaderValue = (value: unknown): string | undefined => {
44
44
  if (typeof value !== "string") return undefined;
45
- const clean = value.replace(/[^\x20-\x7E]/g, "").slice(0, 200).trim();
45
+ const clean = value
46
+ .replace(/[^\x20-\x7E]/g, "")
47
+ .slice(0, 200)
48
+ .trim();
46
49
  return clean.length > 0 ? clean : undefined;
47
50
  };
48
51
  import type { TunnelConnection, TunnelServer } from "./tunnel.js";
@@ -72,9 +75,23 @@ interface Subscription {
72
75
  onAbort: () => void;
73
76
  }
74
77
 
78
+ /** run-11 h1-1 (Unit A): exact serialized size of REASSEMBLED chunked
79
+ * tunnel-data frames, recorded once at the reassembled push seam in
80
+ * `route()`. Downstream consumers (mux relay admission, `relayBytes` budget
81
+ * charging) read the real byte size instead of re-serializing multi-MiB
82
+ * frames to learn it — one serialization per frame on the whole hot path.
83
+ * WeakMap on purpose: the size lives and dies with the frame object, so
84
+ * there is no manual lifetime to manage. Inline/LAN frames get no entry:
85
+ * their size is only knowable by serializing, which the fallback paths do. */
86
+ export const reassembledFrameBytes = new WeakMap<Frame, number>();
87
+
75
88
  /** run-8 U8: the byte size a relayed frame holds in a viewer queue. One extra
76
89
  * serialization per device frame, bounded by the mux relay caps. */
77
90
  function relayBytes(frame: Frame): number {
91
+ // run-11 h1-1 (Unit A): reassembled (chunked) frames already know their
92
+ // exact size — charge it without a second multi-MiB serialization.
93
+ const raw = reassembledFrameBytes.get(frame);
94
+ if (raw !== undefined) return raw;
78
95
  try {
79
96
  return Buffer.byteLength(JSON.stringify(frame));
80
97
  } catch {
@@ -409,15 +426,22 @@ export class TunnelDispatcher {
409
426
  } as unknown as Frame);
410
427
  return;
411
428
  }
412
- if (out.done)
413
- sub.push(
414
- checkDeviceFrame(out.value)
415
- ? out.value
416
- : {
417
- type: "fault",
418
- error: { code: "invalid", message: "Invalid device stream frame" },
419
- },
420
- );
429
+ if (out.done) {
430
+ if (checkDeviceFrame(out.value)) {
431
+ // run-11 h1-1 (Unit A): record the reassembler's exact byte count
432
+ // at the push seam — chunked tunnel-data frames only (this is the
433
+ // sole reassembly path for them). Everything downstream of this
434
+ // subscription queue (mux relay admission, relayBytes charging)
435
+ // reads the WeakMap instead of re-serializing the frame.
436
+ if (out.rawBytes !== undefined) reassembledFrameBytes.set(out.value, out.rawBytes);
437
+ sub.push(out.value);
438
+ } else {
439
+ sub.push({
440
+ type: "fault",
441
+ error: { code: "invalid", message: "Invalid device stream frame" },
442
+ });
443
+ }
444
+ }
421
445
  return;
422
446
  }
423
447
  return;
@@ -670,7 +694,10 @@ export class TunnelDispatcher {
670
694
  queue.push({
671
695
  frame: {
672
696
  type: "fault",
673
- error: { code: "invalid", message: "device stream exceeded this device's relay budget" },
697
+ error: {
698
+ code: "invalid",
699
+ message: "device stream exceeded this device's relay budget",
700
+ },
674
701
  } as unknown as Frame,
675
702
  reservation: null,
676
703
  });
@@ -15,6 +15,10 @@ export const CHUNK_RAW_BYTES = 65_536;
15
15
  export const MAX_CHUNKS_PER_MESSAGE = 256;
16
16
  /** Maximum logical message size including envelope. 16 MiB. */
17
17
  export const LOGICAL_MESSAGE_MAX_BYTES = 16_777_216;
18
+ // Run-11 h1-2 layer 1 — per-event transport gate: a serialized SSE frame over
19
+ // this is FAULTED by the hub's stream send(), never queued (mux.ts "Stream
20
+ // event exceeds ..."), and the hub's REST legs read-cap bodies at the same
21
+ // number (transport.ts readBodyCapped).
18
22
  /** Handshake/control/fault frames must fit without chunking. 4 KiB. */
19
23
  export const CONTROL_FRAME_MAX_BYTES = 4_096;
20
24
  /** Per-message reassembly timeout. 30 s. */
@@ -23,11 +27,28 @@ export const REASSEMBLY_TIMEOUT_MS = 30_000;
23
27
  export const REASSEMBLY_CONCURRENT_PER_CONNECTION = 4;
24
28
  /** Total reassembly + outbound queue budget per device connection. 32 MiB. */
25
29
  export const CONNECTION_BUFFER_BUDGET_BYTES = 33_554_432;
30
+ // Run-11 h1-2 layer 2 — per-writer/per-connection queue bound: every paced SSE
31
+ // writer also holds a LOCAL "sse-viewer" ByteBudget at this same size bounding
32
+ // its active+queued events (node/sse-writer.ts), so one slow tab cannot pin
33
+ // more than 32 MiB before its per-socket cut (layer 3) fires.
26
34
  /** Total hub-wide budget (reassembly + outbound queues + pending REST). 64 MiB. */
27
35
  export const HUB_BUFFER_BUDGET_BYTES = 67_108_864;
36
+ // Run-11 h1-2 layer 4 — hub-wide shared budget: ONE ByteBudget("hub") per hub
37
+ // process (main.ts) is threaded through the stream mux (every browser tab
38
+ // writer) AND the tunnel dispatcher (device reassembly + relay/REST queues),
39
+ // so aggregate fan-out across tabs and devices stays bounded by 64 MiB total.
28
40
 
29
41
  /** Hub → browser SSE buffered-output cap before the viewer is ended. 4 MB. */
30
42
  export const SSE_HUB_VIEWER_BYTES = 4_000_000;
43
+ // Run-11 h1-2 layer 3 — per-socket: this is the socket output cap
44
+ // (writableLength/buffered amount), NOT a logical event size — a viewer that
45
+ // keeps it full is ended (pacedSseWriter maxBufferedBytes) instead of letting
46
+ // the kernel queue grow without bound. Effective SSE chain, in order:
47
+ // per-event 16 MiB (LOGICAL_MESSAGE_MAX_BYTES) → queued ≤32 MiB per writer
48
+ // local ByteBudget (CONNECTION_BUFFER_BUDGET_BYTES; each device connection
49
+ // additionally 32 MiB) → 4 MB per socket (SSE_HUB_VIEWER_BYTES) → 64 MiB
50
+ // hub-wide shared (HUB_BUFFER_BUDGET_BYTES, all tab writers + device
51
+ // reassembly/relay queues). Docs: docs/verification.md "Effective SSE bounds".
31
52
  /** Hub ↔ device WS buffered-output cap per direction before close(1011). 4 MB. */
32
53
  export const WS_BACKPRESSURE_BYTES = 4_000_000;
33
54
  /**
@@ -90,6 +90,24 @@ and hashes of uncommitted source, not just a commit name.
90
90
  - Soak/capacity, real-model/provider acceptance and untested platforms remain
91
91
  separate work. Historical records do not become current acceptance results.
92
92
 
93
+ ## Effective SSE bounds (run-11 h1-2)
94
+
95
+ The hub's streaming memory is bounded by one layered admission chain — every
96
+ layer must pass before bytes reach the socket. The canon numbers live in
97
+ `apps/dpi-sdk/src/protocol/limits.ts`:
98
+
99
+ | Layer | Constant | Bound |
100
+ |---|---|---|
101
+ | Per event (transport gate) | `LOGICAL_MESSAGE_MAX_BYTES` | 16 MiB — an SSE frame over it is faulted, never queued |
102
+ | Queued, per writer | `CONNECTION_BUFFER_BUDGET_BYTES` | 32 MiB local ByteBudget per paced SSE writer; each device connection additionally gets 32 MiB for reassembly + outbound queue |
103
+ | Per socket | `SSE_HUB_VIEWER_BYTES` | 4 MB output cap before a slow viewer is ended (not an event-size limit) |
104
+ | Hub-wide shared | `HUB_BUFFER_BUDGET_BYTES` | 64 MiB covering ALL tab writers plus the device reassembly/relay queues |
105
+
106
+ The per-writer local budget and the per-socket cap fire first (one slow tab is
107
+ isolated); the shared 64 MiB budget bounds the aggregate across tabs and
108
+ devices. This section documents existing behavior (run-11 h1-2); it changed
109
+ no constant and no code path.
110
+
93
111
  ## Memory units
94
112
 
95
113
  The M1 contract is **150 MB = 150,000,000 bytes**, not 150 MiB.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "my-durable",
3
- "version": "0.0.116",
3
+ "version": "0.0.118",
4
4
  "description": "Durable Pi — the durable agent network: hub web UI, device backend daemon, TUI admin and the shared SDK, packaged as one runnable monorepo install",
5
5
  "license": "MIT",
6
6
  "repository": {