Compare commits

..
Author SHA1 Message Date
9d6ee72eb3 Fork card: order is a unique rank per Mind; duplicate-order and order-0 vectors (#86)
Some checks are pending
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Waiting to run
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Waiting to run
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
2026-11-11 00:33:36 +00:00
44149afb7b cultcache-ts: opening a legacy store never rewrites it (#85)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 23:56:57 +00:00
e57fbaee90 Merge pull request 'tools/sprite-silhouette: sprite alpha to CSS shape-outside polygon' (#8) from libby/sprite-silhouette into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-10 23:14:06 +00:00
0c19eddb77 Fork card: a stripped read serves note: null (#84)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 20:59:52 +00:00
43db7af238 Fork card: no fork hidden by fork_unknown (#83)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 20:51:18 +00:00
eb8939011e Fork card: Read visibility line agrees with ruling (c) (#82)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 20:50:47 +00:00
512e0e249f Fork card: read visibility applied at the door (#81)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 20:49:43 +00:00
89755b08b5 Fork card: deciders holds at most 64 (#80)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 20:03:58 +00:00
3d70e3395d Fork card M5: the desk envelope's names (#79)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 19:59:07 +00:00
7d2cde047f Fork card M5: decider list sent per call (#78)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 19:27:52 +00:00
ef648d1a66 Fork card: stored Refused answers carry their 4xx status (#77)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 19:25:54 +00:00
6231ecad5d Fork desk digests: confirmed on Huginn main f0ca504 (#76)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 18:30:43 +00:00
e12ee63840 Fork desk digests: door-form legal_retraction golden (#75)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 18:19:26 +00:00
976f8c3bf2 Fork desk r4: refused retraction target, counted_answer_id, body digest vectors (#74)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 18:14:42 +00:00
soul
de00274cd0 Merge remote-tracking branch 'origin/main' into libby/sprite-silhouette
All checks were successful
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Successful in 21m53s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m19s
2026-11-10 17:40:26 +00:00
a499c58108 CI: concurrency groups, no cancel on tag/dispatch (#71)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-10 17:40:13 +00:00
8ca1d18454 Fork card: cap depends at 8 lines of 1000 bytes (#73)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 18m46s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 52s
2026-11-10 17:16:26 +00:00
e6a279248c CultNet governance contracts: vote API and fork-desk card (#72)
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-10 17:01:43 +00:00
55bf180647 Merge pull request 'CI: Windows jobs workflow_dispatch only, PowerShell on Linux, glibc comment' (#68) from libby/runner-label-docker into main
All checks were successful
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Successful in 15m24s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 46s
2026-11-09 22:21:02 +00:00
soul
356687b717 cultmesh-ts test: result window outlasts the transport ack in the RUDP catalog publish test
All checks were successful
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Successful in 18m17s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
The put's flush is bounded by the result window, so a 25 ms flush and 100 ms window made a slow
ack on a loaded forge runner surface as local_send_failed instead of the window_elapsed the test
checks. Drop the flush override and give the window room.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 22:01:25 +00:00
Libby
a2bb0bced4 cultnet-ts test: wait for loopback datagrams instead of a fixed 100 ms sleep
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 11m15s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m7s
"server mode admits a pinned client that restarts on a new port" asserted the Accept arrived after sleep(100) and failed on the forge runner (ok(accept) undefined, run 894). It now polls for the packet or frame it asserts on, up to 2 s; no assertion changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 20:19:03 +00:00
Libby
ef82811f2e CI: fetch tags in cultmesh-portability checkout
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 13m26s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
scripts/test-declared-dependency-ranges.mjs asserts the clone has release tags; actions/checkout fetches none by default.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 20:03:46 +00:00
Libby
a56ae56b7d CI: install the Rust toolchain on forge Linux runners
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 12m0s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
The act-latest image has no cargo; the cross-runtime CultCache store tests build the Rust interop example and failed with "cargo: not found" once the RUDP flake and pwsh were out of the way.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 19:50:50 +00:00
0fc0eb45ee Merge branch 'main' into libby/runner-label-docker
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 10m54s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
2026-11-09 19:32:08 +00:00
aff69c2914 Merge pull request 'cultmesh-ts test: queued provider registers observed from creation (RUDP replaced-generation flake)' (#70) from libby/rudp-queue-test-unhandled-rejection into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 6m51s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 16s
2026-11-09 19:32:05 +00:00
soul
073efd06e7 ci: rerun 3 (RUDP flake evidence)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m23s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 41s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:53:27 +00:00
88545542bb Merge pull request 'write_admitted messageId: letter or number, no Default_Ignorable, raw compare' (#69) from libby/write-admitted-messageid-rule into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 6m48s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 21s
2026-11-09 16:49:35 +00:00
soul
c9cdbc7edc ci: rerun 2 (RUDP flake evidence)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m38s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:29:33 +00:00
soul
2aade7fdd3 Docs and test comments: correct the Rust duplicate-key citation, say what the TS and Rust duplicate tests pin
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m24s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 21s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:25:50 +00:00
soul
27d9fbca94 write-receipt.md: where a received messageId decides, and the single-parser assumption it relies on
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:07:11 +00:00
soul
e08d5c47f4 GameCult.Networking: a write_admitted frame with more than one messageId key is malformed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:05:21 +00:00
soul
cc5a9cec9b tests first: repeated messageId key, each runtime's declared policy (C# failing)
Vectors admittedMessageIdDuplicates carry [invalid,valid], [valid,invalid], [valid,valid]. Decoders that see the
duplicate (C#, Rust) must refuse all three; map-collapsing decoders (Python, TS, Kotlin) judge the last key.
Python, TS, Kotlin and Rust already behave as declared; C# fails: it accepted [valid,valid].

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 16:04:58 +00:00
soul
a04014e0b4 ci: rerun 1 (RUDP flake evidence)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 12m3s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:50:27 +00:00
soul
b55521d50d cultmesh-ts test: observe queued provider registers from creation so a client timeout is not an unhandled rejection
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m59s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:50:10 +00:00
soul
5679417a82 CI: back to ubuntu-latest, install PowerShell where a Linux job needs pwsh
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 9m13s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 47s
The forge has two labels: docker (node 22, py 3.11) and ubuntu-latest (act-latest, node 24,
py 3.12); neither carries pwsh. Windows legs stay workflow_dispatch only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:26:27 +00:00
soul
a97861945c write-receipt.md: the messageId rule is on the decoded string; byte-level UTF-8 strictness is the reader's, not required
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 32s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Failing after 30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:13:09 +00:00
soul
6c130581a1 cultmesh-kotlin: UTF-8 strictness scoped to the write_admitted frame, not the shared MessagePack reader
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:13:01 +00:00
soul
99273f468c cultnet-ts: refuse a write_admitted messageId that is not well-formed Unicode (lone surrogate)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:12:07 +00:00
soul
2f372eb2f1 GameCult.Networking: check every messageId key of a write_admitted frame, not only the first
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:11:53 +00:00
soul
f378d4fdb0 tests first: duplicate messageId, ill-formed id, scoped UTF-8 strictness, every table range pinned (failing)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Failing before the fix: C# 1 (duplicate messageId, second is U+200B), TypeScript 1 (a + lone surrogate),
Kotlin 1 (a document payload string with a lone surrogate no longer decodes). Python and Rust already pass
the new vectors. The range probes read the generated write-admitted-message-id-ranges.json and pass on the
correct tables; they exist to fail when any range is deleted or narrowed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:11:15 +00:00
soul
8598fd3d12 cultnet-rs: write_admitted messageId from the generated Unicode 16.0 tables (letters and numbers now 16.0, not 15.1)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:05:00 +00:00
soul
c2d2c1d126 GameCult.Networking: write_admitted messageId from embedded Unicode 16.0 tables, not .NET's
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:05:00 +00:00
soul
c4f6e76839 cultmesh-kotlin: write_admitted messageId from embedded Unicode 16.0 tables, not the JDK's
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:04:59 +00:00
soul
87f53498ed cultnet-py: write_admitted messageId from embedded Unicode 16.0 tables, not unicodedata
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:04:59 +00:00
soul
de25b50abd cultnet-ts: write_admitted messageId from embedded Unicode 16.0 tables, not the regex engine's
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:04:59 +00:00
soul
3d37fda496 write_admitted messageId: pin Unicode 16.0, one generator for the embedded tables
scripts/gen-unicode-messageid-tables.py emits each runtime's Letter-or-Number and Default_Ignorable tables from the two UCD 16.0 files; --check fails on a stale or hand-edited table.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:04:59 +00:00
soul
cc931932fc tests first: Unicode 16.0 pin vectors (failing)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m15s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 43s
Failing before the fix: Rust 1 (16100), Python 2 (16100, 10D40), Kotlin 4 (16100, 10D40, 2EBF0, 2EE5D).
TypeScript and C# already pass: their platform data is 16.0 or later.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 15:00:54 +00:00
soul
ba548d192d cultnet-rs: refuse a write_admitted messageId without a letter or number or with a Default_Ignorable code point
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Raw compare. std is_numeric for N; embedded letter (Unicode 15.1) and Default_Ignorable (16.0) range tables.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:49:50 +00:00
soul
d546ef9c7f GameCult.Networking: refuse a write_admitted messageId without a letter or number, with a Default_Ignorable code point, or with invalid UTF-8
Raw compare. .NET Unicode categories for L/N, an embedded Default_Ignorable range table (Unicode 16.0).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:49:50 +00:00
soul
d1a4ebdd68 cultmesh-kotlin: refuse a write_admitted messageId without a letter or number or with a Default_Ignorable code point
Raw compare. JDK Character categories for L/N, an embedded Default_Ignorable range table (Unicode 16.0).
The MessagePack string reader now refuses invalid UTF-8 instead of substituting U+FFFD.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:45:37 +00:00
soul
688562c316 cultnet-py: refuse a write_admitted messageId without a letter or number or with a Default_Ignorable code point
Raw compare. unicodedata for L/N, an embedded Default_Ignorable range table (Unicode 16.0).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:43:26 +00:00
soul
bf55c10199 vector: write_admitted messageId refuses U+FEFF before a letter (kills a trim-before-check decoder)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:42:44 +00:00
soul
4c1537885d cultnet-ts: refuse a write_admitted messageId without a letter or number or with a Default_Ignorable code point
Raw compare, no trim. The platform's regex property tables carry both properties; no table embedded.
D800 vector now driven from wireHex.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:42:01 +00:00
soul
70f8135d2c vector: write_admitted messageId accepts a NUL between letters (rule: letter present, no Default_Ignorable)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:41:11 +00:00
soul
4571a0d4e7 tests first: write_admitted messageId rule vectors (failing)
Pins Heimdall's rule: a write_admitted messageId needs a Unicode letter or number and no
Default_Ignorable_Code_Point, compared raw. Shared vectors plus a runner test in TS, Python,
Kotlin, C# and Rust. No decoder changed; the refuse vectors fail.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:39:51 +00:00
325da81428 Merge pull request 'TS write-receipt client against the real Rust and C# receipt servers (interop harness)' (#67) from libby/write-receipt-ts-interop into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 7m52s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 59s
2026-11-09 14:16:00 +00:00
e4f550ef78 Merge pull request 'cultnet-py: decode write_admitted.v0 and error.v1 against the write-receipt vectors' (#66) from libby/write-receipt-py-interop into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-09 14:15:59 +00:00
59365cea35 Merge pull request 'cultmesh-kotlin: write receipt frames, hash, tracker, vector replay' (#65) from libby/write-receipt-kt-interop into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-09 14:15:58 +00:00
5ba3e9e2aa Merge pull request 'Rust RUDP server: pin blank schemaId/recordKey refusal, decide sequenced refusal per frame' (#63) from libby/rs-receipt-key-tests-per-frame into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-09 14:15:49 +00:00
69703358c0 Merge pull request 'write-receipt: one unreadable text, one blank-field rule (both servers)' (#64) from libby/write-receipt-text-blank-rules into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-09 14:15:48 +00:00
soul
96c5fb1ca4 interop peer: C# store holds the spec's admitted schema-id names (compatible ids)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m32s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 37s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:12:38 +00:00
soul
b8e40dc372 interop test: pace C# relay connections under the server's per-IP per-minute limit
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:10:42 +00:00
soul
1704fb5060 cultmesh-ts: test:interop builds cultcache-ts and cultnet-ts (with contracts) first
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 14:05:57 +00:00
Libby
041a769475 CI: quic-native glibc comment no longer names ubuntu-latest as the runner
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / docker reactive semantics and leases (pull_request) Failing after 4m48s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 32s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:40:39 +00:00
Libby
fc0f83a385 CI: Windows jobs are workflow_dispatch only (no Windows runner exists)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / docker reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:32:41 +00:00
Libby
3e6ec8567c CI: forge runner label is docker, not ubuntu-latest
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / docker reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 13:30:05 +00:00
Libby
8c31933e10 cultnet-py: the write-receipt vector sections include the file's counts
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m35s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 10:38:29 +00:00
Libby
2f3b30ab85 Merge remote-tracking branch 'origin/libby/write-receipt-text-blank-rules' into libby/rs-receipt-key-tests-per-frame
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m39s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m0s
2026-11-09 10:37:49 +00:00
Libby
819df6a666 Merge remote-tracking branch 'origin/libby/write-receipt-text-blank-rules' into libby/write-receipt-ts-interop
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 10m47s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 45s
2026-11-09 10:37:49 +00:00
Libby
e490828278 Merge remote-tracking branch 'origin/libby/write-receipt-text-blank-rules' into libby/write-receipt-py-interop 2026-11-09 10:37:49 +00:00
Libby
6ca9c455b7 cultmesh-kotlin: sendFailed vectors, a tracker that ends with its session, White_Space blank
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m53s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m12s
The replay runner handles the sendFailed event, fails on an event key it does
not know and on a vector count the file did not declare. WriteTracker settles a
write sent after sessionEnd as session_ended. Source ids on a raw document
record are dropped when blank by Unicode White_Space (isBlankText), not Kotlin's
isNullOrBlank, which keeps U+0085 and drops U+001C to U+001F; the vector file's
JSON reader skips JSON whitespace only.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 10:37:48 +00:00
Libby
1136080aaf Merge remote-tracking branch 'origin/libby/write-receipt-text-blank-rules' into libby/write-receipt-kt-interop 2026-11-09 10:34:56 +00:00
Libby
f0c0f936ba write-receipt: seven tracker vectors, a tracker that ends with its session, runners that count
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m39s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 22s
New scenario vectors: id-less error.v1 with one and with two writes unanswered,
sendFailed, an id-less error after the window, a receipt one ms inside the window
and at the exact boundary (late), a send after sessionEnd. The last exposed a
TS tracker leaving such a write pending forever; it now settles session_ended.
The file declares counts, and the TS replay runner fails on a count it did not
run or an event key scenarios.semantics does not name.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 10:34:49 +00:00
Libby
b082101c78 cultnet-ts: a blank text in a raw frame is Unicode White_Space, not trim()
validateBinaryMessageRoot, requireNonEmptyString and requireOptionalStringArray
used String.prototype.trim(), which takes U+FEFF and misses U+0085, so the TS
decoder and the servers disagreed on what names nothing (write-receipt rule 5).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 10:22:15 +00:00
Libby
636b387cf1 write-receipt spec: a repeated or unreceived sequenced packet draws no second answer
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m30s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 16s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:31 +00:00
Libby
6c441d1cda Rust RUDP server: answer a sequenced write once, not once per send
A repeat of a packet the session already took, and a packet too far ahead to be
remembered, delivered no frame and so drew the superseded-write refusal again on
every send, breaking write-receipt rule 1. The refusal now applies only to the
first packet the session takes for a sequence; CultNetRudpSession::has_received
exposes that test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:18 +00:00
Libby
34cceedf98 Rust RUDP server: pin the superseded-write refusal against a releasing packet and the half-space bound
cargo-mutants on the previous commit missed two mutants: `&&` to `||` in the
superseded-packet check (a packet that also releases another write hid it) and
`<` to `<=` at the half-space bound of sequence_at_or_before. A test and two
assertions kill them; the rerun catches 14 of 15 (1 unviable).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:18 +00:00
Libby
4e89f07bff Rust RUDP server: answer a superseded sequenced write; order frame and packet by serial arithmetic
Superseded packet: a reliable-sequenced packet that arrives after a newer one
delivers no frame, yet is acknowledged and never resent, so its write went
unanswered. The test (red first: only "new" was refused, "old" got nothing)
showed the drop happens in the session below frame decoding, but an unfragmented
packet carries its whole frame, so the server can read the id from the packet
payload. Chosen: refuse it from the packet payload. A superseded fragment of a
larger write has no readable id in the packet, so write-receipt.md now says that
write may go unanswered and the client's unconfirmed outcome covers it.

Ordering: frame.sequence <= packet.sequence is replaced by sequence_at_or_before,
serial arithmetic modulo 2^32. Deviation from the brief: cultnet-rs'
at_or_before carries a 4096-sequence receive window made for duplicate detection;
a frame's first fragment may lie further back than that, so reusing it would
leave such a sequenced write unrefused and applied. The new test pins that, and a
hand mutant with the window fails it. A wrapped sequence cannot reach this
compare through the session today (it is judged a duplicate), so the unit test
pins the helper, not an end-to-end wrap.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:18 +00:00
Libby
bd2aff8ed0 Rust RUDP server: decide the sequenced-channel refusal per frame
A sequenced packet's arrival can release held ordered frames in the same delivery; refuse only the packet's own frame.
heimdall-low-refuse-sequenced-per-frame.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:04 +00:00
Libby
4f6ee0db83 Rust RUDP server: pin the refusal of blank schemaId/recordKey on receipt sessions
heimdall-low-rust-keys-untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 09:13:04 +00:00
Libby
04207007d6 interop test: read the store under the record key the blank-field vector set
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 3m0s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
A vector that sets recordKey (zero_width_space_record_key_is_a_name) replaces the harness key, so the admitted case waited for
blank:<name> and timed out against the Rust server, and the refused record-key cases counted applications under a key the server
never saw. Use the key the document carried.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-09 07:45:35 +00:00
Libby
ec8ecd2fb0 Merge write-receipt-text-blank-rules (3b1b7697) into libby/write-receipt-py-interop
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m32s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
2026-11-09 07:38:23 +00:00
Libby
80f1cfa385 Merge write-receipt-text-blank-rules (3b1b7697) into libby/write-receipt-kt-interop
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m5s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
2026-11-09 07:38:23 +00:00
Libby
4b5f343a44 Merge write-receipt-text-blank-rules (3b1b7697) into libby/write-receipt-ts-interop 2026-11-09 07:38:23 +00:00
Libby
3b1b769762 write-receipt spec: name the platforms that disagree accurately
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m3s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:27:17 +00:00
Libby
52204c68c9 write-receipt vectors: U+001C to U+001F and padded names are not blank
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:26:28 +00:00
Libby
140eca5138 cultmesh-ts: TS write-receipt client against the real Rust and C# receipt servers (test:interop)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m56s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:06:55 +00:00
Libby
e4d2446dbe C# InteropPeer: receipt-serve (CultNetDatabaseServer on an ephemeral port) and receipt-relay (LiteNetLib byte shim for the TS client)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:06:55 +00:00
Libby
56b0c1679c cultmesh-rs: receipt_interop_server example, the real RUDP document server on an ephemeral port for the interop harness
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:06:55 +00:00
Libby
f6c61b1ebf cultnet-py: decode cultnet.write_admitted.v0 and cultnet.error.v1 against the write-receipt vectors
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m36s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Strict closed-schema decode, content hash helper, hello capability; vectors contentHash, wire and schemaInvalid replayed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:06:08 +00:00
Libby
cbb336f501 cultmesh-kotlin: decode write_admitted.v0 and error.v1, content hash, WriteTracker, vector replay
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m5s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Strict decode of the two receipt frames (and error.v0), hello capability test,
the dedupe content hash and the client settle rules, ported from cultnet-ts.
write-receipt-vectors.json replays 38/38 (constants, contentHash, wire,
schemaInvalid, scenarios, v0 limit_reached); dedupe and blankFields are server
inputs and not run.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:03:27 +00:00
Libby
db5e8834f3 write-receipt: blank is exactly Unicode White_Space; C# server checks the listed set in one place
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:02:49 +00:00
Libby
ccbe392b28 write-receipt vectors and tests: blank is Unicode White_Space, every code point checked
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 22:02:10 +00:00
Libby
98989f90ea C# tests: a nil payload names nothing (mutant survivor)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m30s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 21:57:38 +00:00
Libby
bc9a1842f5 C# database server: refuse a put that names nothing, one unreadable text
IsUnreadableDocument follows the spec's Required fields rule (blank storedAt, empty payload, blank source ids and tags join blank schemaId/recordKey); ForUnreadableMessage is the single owner of the fixed text. Tests replay the blankFields vectors on receipt and legacy connections.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 21:26:49 +00:00
Libby
e99e9d4bc0 write-receipt spec: one unreadable text, one blank-field rule; Rust server tests pin both
The unreadable-frame text is 'message_invalid: the message could not be read' (the servers' wording; the Rust wire never carried decoder text, only its local rejection display). A put that names nothing (blank schemaId/recordKey/storedAt, empty payload, blank present source ids or tags) is refused as unreadable on every connection; the vectors' blankFields section lists the cases and the Rust server tests replay them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 21:26:49 +00:00
7665df33ae Merge pull request 'TS: write_admitted / error.v1 decoder, WriteTracker, vector replay runner' (#62) from libby/ts-write-receipt-client into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 5m10s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 31s
2026-11-08 19:52:37 +00:00
92b4cb7ce9 Merge pull request 'C#: database server answers writes with write_admitted / error.v1 (write-receipt spec)' (#61) from libby/cs-write-receipt-server into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 19:51:52 +00:00
36494dafb9 Merge pull request 'cultmesh-rs: RUDP document server answers writes with write_admitted / error.v1' (#60) from libby/rs-write-receipt-server into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 19:49:50 +00:00
5bf2428295 Merge pull request 'spec: cultnet write receipt (write_admitted, error id echo, admitted/refused/unconfirmed)' (#59) from libby/cultnet-write-receipt-spec into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 19:49:40 +00:00
Libby
1a228349f1 C#: a put or delete with an empty or blank schemaId or recordKey is refused message_invalid (as an unreadable frame, like the Rust server) and not applied
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m35s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:46:45 +00:00
Libby
621b86ca15 Spec #59: an empty or blank schemaId or recordKey is message_invalid (details.field message, the write's id), never applied; vector for it
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m55s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:45:19 +00:00
Libby
90d252735f cultmesh-rs: a refused reliable-sequenced write is received and acknowledged first, and a refused write counts as session activity
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m11s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 52s
Refusing before session.receive left the packet unacknowledged: the client resent it forever and every later ordered write stalled. The test now uses the same peer and proves a later ordered write is admitted.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:38:43 +00:00
Libby
dc1ae51e92 cultmesh-ts: publishRudpDocumentOnce builds the put before connecting, so a put that cannot be built keeps its cause on both paths
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m13s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:37:08 +00:00
Libby
0fbf2baea6 cultnet-ts, cultmesh-ts: Heimdall's five Lows on send-only (spec wording, error.v1 ack-time refusal tests, build errors keep their cause, presence changelog, ack-cut anchors)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:32:49 +00:00
Libby
89ff3d2cbd cultnet-ts test: the Odin presence publisher is send-only, so a refusal after the transport ack is not awaited
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:26:25 +00:00
Libby
206dbe142b cultmesh-ts: sendOnly tests use one fake server per publish (the reused one threw on the second connect and hung the run); spec names send-only and the presence publisher
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
The hang was the fake server, not the writer: it is bound to one connection id, and two publishes in one test sent a second connect it rejected from inside the socket handler. The unacknowledged-send test also scripted an admit, whose reply piggybacks the put's ack.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:24:52 +00:00
Libby
0caef4d564 WIP (unverified): publishRudpDocumentOnce sendOnly + presence publisher send-only; tests written, cultmesh-ts receipt-client run hung
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 19:24:52 +00:00
Libby
c89c4ee39a cultmesh-ts: test kills the flush-cap mutant
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m58s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:07:54 +00:00
Libby
af1ac72359 cultmesh-ts, cultnet-ts: only write_admitted admits a put (no echo admission); the send is bounded by the result window and a timeout is local_send_failed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:05:42 +00:00
Libby
293b4e83bc cultmesh-ts, cultnet-ts: an unanswered put is unconfirmed on every server, session_ended before a result is an error, a failed local send is its own reason
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:03:39 +00:00
Libby
a67faad27c cultnet-ts: tests for two tracker mutants (send expires other windows; non-answer frames settle nothing)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:03:39 +00:00
Libby
6eea66c57f cultnet-ts, cultmesh-ts: write receipt client (frames, WriteTracker, replay runner, opt-in writer)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:03:39 +00:00
Libby
34bf7aa0ee C#: test kills the schema id detail-value mutant
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m59s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:03:36 +00:00
Libby
40b34295e3 C#: receipt writes need a reliable, non-sequenced channel; a refusal without a record key or schema id carries a null detail value
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:01:59 +00:00
Libby
e4b67a9e0b cultmesh-rs: a receipt session accepts writes only on a reliable, non-sequenced channel; a test pins that a reconnect starts a fresh session
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 10m5s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m8s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 17:00:48 +00:00
Libby
74adad916a Spec #59: receipt writes need a reliable, non-sequenced channel; error.v1 schema description names limit_reached; #55-#58 paragraph states which clients still window-succeed
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 9m8s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m14s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:59:39 +00:00
Libby
48cf3b3323 C#: tests kill the replay-details and unreliable non-write mutants
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:45:29 +00:00
Libby
0a67b4d8aa C#: a remembered refusal keeps its code and field, never the write's strings, and replays in fixed text; a write on an unreliable channel of a receipt session is refused message_invalid (channel)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:42:22 +00:00
Libby
1a05df2524 cultmesh-rs: server-wide remembered-write budget is a maintained counter; a session whose refusal set overflowed refuses unseen ids after the budget frees
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m35s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m1s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:36:10 +00:00
Libby
2c5203dc82 Spec #59: local_send_failed is its own unconfirmed reason
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m31s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:34:52 +00:00
Libby
3443e1dc93 Spec #59: error.v1 code enum names limit_reached; server-wide budget is a conformance column; an overflowed refusal set refuses unseen ids for the session
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 16:34:19 +00:00
Libby
c8f869e54e cultnet-rs, cultmesh-rs: null or missing document/schemaId refused naming the field; budget tests use literal bytes; unreliable-refusal local failure test
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m33s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:32:03 +00:00
Libby
d7b36416c6 cultmesh-rs: pin limit-refusal memory bound and legacy unreliable drop (mutant-driven tests)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:30:36 +00:00
Libby
ef5cd88111 C#: v0 errors for snapshot, shard log and variant refusals carry fixed text, never an exception's message
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m35s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:13:58 +00:00
Libby
d654cb2b99 C#: tests kill the refusal-set bound and abandoned-rehash mutants
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:12:31 +00:00
Libby
1447ccd8dd cultnet-rs, cultmesh-rs: write_admitted in spec field order; server-wide remembered-write budget over digest entries; id size limit; limit refusals remembered; unreliable writes refused; local failure is its own goodbye
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m14s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:09:28 +00:00
Libby
c4d1efe000 C#: receipt ids capped at 256 bytes and held as digests; limit refusals remembered, no slot freed; required fields refused with fixed text; RUDP server advertises no receipt frames
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:07:23 +00:00
Libby
734087766a Spec #59: id size, digest memory, limit refusals remembered, required fields, reliable channel, local send failure, per-class conformance table
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m0s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:04:21 +00:00
Libby
541d734675 C#: a forward is retryable only when provably not sent; unconfirmed otherwise; refusals carry fixed text
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultNetWriteNotSentException names the pre-send boundary (connect, hello, no endpoint,
or a send port that proves nothing was written). Every other forwarding failure keeps
the session claim. ForUnownedSchema and the routing refusal no longer carry exception text.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 15:02:56 +00:00
Libby
b89a883700 spec: C# RUDP schema server is not receipt-capable; advertise only if end to end
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:58:51 +00:00
Libby
2e5df24e96 C#: loopback test for the unreadable-frame answer; Server.Port seam; the answer now reaches the wire
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
An undecodable frame is classed legacy by Decode, so the schema-side guard was unreachable
and a receipt peer was never answered. The guard moves to the legacy decode.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:58:17 +00:00
Libby
74b8a4cbf8 C#: drop the redundant Silent state of a write claim (a silent claim is an unanswered one)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:53:05 +00:00
Libby
0182a6d40b cultnet-rs, cultmesh-rs: remembered-write cap refusal is error.v1 limit_reached; pin authorize-once with a counting sink
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m19s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 41s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:32:49 +00:00
Libby
ed5f9d30d1 C#: receipt server follows Heimdall's review of #61
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m30s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 21s
Look the id up first and authorize only on first sighting; remember refusals within the cap; never re-forward an id whose primary stayed silent; end the connection when an answer cannot be queued; fixed refusal texts; limit_reached cap refusal; commit-point doc on ApplyPut/Delete.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:32:39 +00:00
Libby
eafcdcdf7c cultnet: add limit_reached to error.v1 code enum, with captured vector
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m51s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:29:18 +00:00
Libby
5f699c27fa cultmesh-rs: a put reusing a delete's id is refused (mutant-driven test)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:27:54 +00:00
Libby
d4f440ac7c cultmesh-rs: receipt server looks the id up first, remembers refusals, answers deletes and unqueueable refusals
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m47s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Follows Heimdall's second review of #60: replay by (session,id) before any
authorization; refusals stored with their hash; delete shares the dedupe
table and settles capability; a refusal the queue cannot take ends the
session; a peer's refusal frames and a receipt session's refused deletes are
not violations; the write limit has its own fixed text; the sink trait says
Ok means committed and visible.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:22:50 +00:00
Libby
b0ea18371f C#: database server answers writes with write_admitted / error.v1 (write-receipt spec)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m46s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
Opt-in per connection by the first hello (or first write); the server answers a
capable hello with its own. A put or delete commits, then gets write_admitted under
its id; every refusal is error.v1 with the id (an unreadable frame carries the id
when it still holds one). (actor, messageId) dedupe is bound to the content hash and
asked only after the write authority grants; same id other content is message_invalid.
The shard write forwarder says hello, waits for the primary's receipt, and the server
relays only what the primary answered under the original id.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 14:04:37 +00:00
Libby
7a560b1984 spec: dedupe scope is at least the session; a resend after a reconnect is a new write
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m52s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 41s
Per Heimdall's review. The dedupe key lives for the life of its session, bounded per
session without forgetting an id the server promised to answer. A longer retention
is optional and never to be relied on. After a reconnect callers resend only writes
that are idempotent by record key and read back before resending any other.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:58:39 +00:00
Libby
8bd31a5d4a cultmesh-rs: receipt server follows Heimdall's review of #60
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m11s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
A refused put, a full dedupe table and a reused id refuse the write, not the
session; only a protocol violation ends one. A frame that does not decode but
holds a messageId is refused with that id. The server answers a receipt-capable
hello with its own, listing both frames. The sink's authorization (new
authorize_raw_document, default admit) runs before the session's remembered
writes are consulted. A second hello does not change the capability: it is set
once, by the first hello or the first write. A receipt that cannot be queued, and
a write the payload budget would drop silently, end the session instead of
leaving the write unanswered. Refusals to a receipt-capable session are queued
reliably.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:56:17 +00:00
Libby
45e95984e5 WIP C# write-receipt server (not built, not tested): messages, content hash, per-peer dedupe state, receipt-aware wait
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:41:14 +00:00
Libby
9f73047c29 cultmesh-rs: RUDP document server answers writes with write_admitted / error.v1 (write-receipt spec)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
cultnet-rs gains cultnet.write_admitted.v0, cultnet.error.v1 (v0 + messageId) and
write_content_hash. The server opts a session in only when its hello lists both frames
(framing only; admission rules are unchanged). On an opted-in session an admitted put is
answered with a receipt carrying its id after the sink accepts it, a refusal is an error.v1
naming the id, a resend of the same content is re-receipted without reaching the sink, and the
same id with other content is refused message_invalid (never the old receipt). Other sessions
are answered exactly as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:38:46 +00:00
Libby
ab7bc771e3 spec: write receipt per Heimdall's review (dedupe by actor+content hash, admitted-late, 5 s window, capability is framing only)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m28s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 2m19s
- messageId unique per authenticated actor and session; dedupe key (actor, id) bound to SHA-256 of
  [operation, schemaId, recordKey, payload]; same id with other content is message_invalid, never the old receipt.
- A late answer after the window is recorded on the write (admitted_late / refused_late); no blind resend.
- A forwarder with no primary answer relays nothing; the client reports unconfirmed.
- RECEIPT_RESULT_WINDOW_MS 5000 (default), LEGACY_RESULT_WINDOW_MS 500 (fallback only), DEDUPE_RETENTION_MS as vector constants.
- The hello capability changes framing only and never authorizes.
- Batches can commit partially; the caller owns retry.
- Vectors: constants, worked content hashes, 7 dedupe cases, late-answer and window scenarios.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:31:49 +00:00
Libby
662ae048d8 spec: cultnet write receipt (write_admitted.v0, error.v1 id echo, three-outcome clients)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Specification and shared vectors only, no runtime code. A write is answered
exactly once with cultnet.write_admitted.v0 or cultnet.error.v1 carrying its
messageId; the new frames go only to connections whose hello lists them (today's
TS decoder rejects unknown keys and versions, so "old clients ignore it" is
false). Clients settle admitted | refused | unconfirmed; the result window is the
pre-receipt fallback and ends unconfirmed. Wire vectors, schema-invalid cases and
16 replay scenarios in write-receipt-vectors.json.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:28:46 +00:00
dc5abedffc Merge pull request 'C#: SubmitDocumentAsync and the shard write forwarder complete on the result frame' (#58) from libby/cs-client-ack-finding into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 7m52s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 31s
2026-11-08 13:24:39 +00:00
Libby
09e6a528b8 C#: SubmitDocumentAsync and the shard write forwarder complete on the result frame
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m41s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 32s
CultNetWriteCompletion.SendAndAwaitResultAsync registers a refusal handler before
the send, then waits a result window (default 500 ms; CultMeshClientOptions.
SubmitResultWindow, CultNetSchemaWriteForwarderOptions.ResultWindow). A
cultnet.error.v0 inside it rejects with the new CultNetWriteRefusedException
(Code: write_not_authorized, message_invalid, ...) whatever its order against the
send or transport ack; a send returning no longer completes the write. The
forwarder's refusal now throws on the same path as an unreachable primary, so
CultNetDatabaseServer.TryForwardPutAsync/DeleteAsync no longer report a refused
forward as done. Raw send primitives (C# schema client/session, Python, Kotlin)
carry the doc line: fire-and-forget, an ack or a return is not admission, read the
result frame.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:24:27 +00:00
1b3b625474 Merge pull request 'cultmesh-rs: single and batch publish complete on the result frame, not the transport ack' (#57) from libby/rs-client-ack-finding into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 13:18:41 +00:00
Libby
675a6494c1 cultmesh-rs: single and batch publish complete on the result frame, not the transport ack
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m10s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m12s
One loop now serves both: every put acknowledged, then a refusal frame (typed
cultnet.error.v0) fails the call in either order against the ack, and a success
frame or the end of the new result_window option (default 500 ms) completes it.
The batch no longer waits on flush_reliable alone, so it cannot hide a refusal.
Raw send primitives (CultNetRudpSocketTransportConnection::send/send_reliable/
flush_reliable, tcp_framed send) carry the doc line: fire-and-forget, an ack or
a return is not admission, read the result frame.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:18:40 +00:00
Libby
3c68d7d19c Merge remote-tracking branch 'origin/main' into libby/rs-client-ack-finding 2026-11-08 13:15:17 +00:00
3162e2ea66 Merge pull request 'cultnet-ts: the Odin presence publisher completes on the result frame, not the ack' (#56) from libby/ts-client-ack-finding-cultnet into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 13:15:08 +00:00
Libby
531fce567d cultnet-ts test: cancel the Odin stub's delayed send when the test ends
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m47s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 57s
The stub's 120 ms second packet fired after peer.close() and threw
ERR_SOCKET_DGRAM_NOT_RUNNING as an uncaught exception, failing whichever
publisher test was running when the timer landed (load-dependent). Timers are
now cleared in the test's after hook instead of swallowing the error.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 13:14:49 +00:00
Libby
0b326fa5ee WIP cultnet-ts: Odin presence publisher completes on the result frame, not the ack (passes alone; two publisher tests fail inside the parallel full run, unexplained)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m32s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 30s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:36:23 +00:00
Libby
cdbe5889e0 merge main 2026-11-08 11:35:00 +00:00
ff1c92d2fe Merge pull request 'cultmesh-ts: a put completes on its result frame, not on the transport ack' (#55) from libby/ts-client-ack-finding-cultmesh into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 5m38s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 31s
2026-11-08 11:34:56 +00:00
Libby
7082c9488b cultmesh-ts: a put completes on its result frame, not on the transport ack
publishRudpDocumentOnce resolved when peer.flush returned (ack only) and read no frame, so a
refused put resolved. It now rejects with CultMeshRudpWriteRefusedError (the peer's typed
cultnet.error.v0: write_not_authorized, message_invalid) whether the refusal arrives before the ack,
after it, or within resultWindowMs (default 500 ms) after it; a success reply ends the wait early.
publishRudpDocumentAndWaitForReceipt rejects with the same typed error instead of timing out.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:34:55 +00:00
Libby
dc7eec7e6e merge main 2026-11-08 11:33:16 +00:00
d4e4a2c085 Merge pull request 'GameCult.Networking test: the RUDP schema client delivers a refused put's result frame whatever the order of the ack' (#54) from libby/cs-client-ack-is-not-admission into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:30:21 +00:00
8cfc41d665 Merge pull request 'cultmesh-py test: a put the server refused is reported refused after its reliable ack arrived' (#53) from libby/py-client-ack-is-not-admission into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:30:18 +00:00
6f2092171f Merge pull request 'cultmesh-rs test: a publish whose refusal arrives before the ack is refused' (#52) from libby/rs-client-ack-is-not-admission into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:30:15 +00:00
de1d6b3444 Merge pull request 'cultnet-ts test: the Odin presence publisher does not complete on the ack when the refusal arrives first' (#51) from libby/ts-client-ack-is-not-admission-cultnet into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:30:12 +00:00
822d660627 Merge pull request 'cultmesh-ts test: publishRudpDocumentAndWaitForReceipt reports a refused put as refused' (#50) from libby/ts-client-ack-is-not-admission into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:30:09 +00:00
Libby
c1d24146db GameCult.Networking test: the RUDP schema client delivers a refused put's result frame whatever the order of the ack
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m11s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m10s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:29:50 +00:00
Libby
c6da8fc54a cultmesh-py test: a put the server refused is reported refused after its reliable ack arrived
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m26s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 37s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:28:23 +00:00
Libby
9e734447f6 cultmesh-rs test (FAILS, findings): publish completes on the ack when the refusal follows it; the batch publish completes on the ack whatever the refusal
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m32s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:27:53 +00:00
Libby
f53930bc13 cultmesh-rs test: a publish whose refusal arrives before the ack is refused
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m16s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:27:48 +00:00
Libby
dfd090dc55 cultmesh-ts test (FAILS, a finding): publishRudpDocumentOnce completes on the ack of a refused put
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m38s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m18s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:27:07 +00:00
Libby
4f90ea8156 cultmesh-ts test: publishRudpDocumentAndWaitForReceipt reports a refused put as refused, whether the ack comes before or after the refusal
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m50s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m24s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:27:06 +00:00
Libby
7766348c75 cultnet-ts test (FAILS, a finding): the Odin presence publisher completes on the ack when the refusal follows it
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:26:22 +00:00
Libby
08cf3b34b5 cultnet-ts test: the Odin presence publisher does not complete on the ack when the refusal arrives first
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m59s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:26:22 +00:00
7486f0a326 Merge pull request 'cultmesh-rs: send the capped frame's answer reliably and end the session once it is acknowledged' (#48) from libby/rs-capped-answer-reliable into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:21:28 +00:00
Libby
b2077fa2bf cultmesh-rs: a Pong in the capped grace acknowledges nothing; the grace deadline saturates
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m57s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m41s
A Ping in the 2 s grace after the capped frame was answered with a Pong built from the
session's ack state, which includes the capped frame. Every reply while the session is
ending now zeroes its ack fields. The deadline no longer wraps at the end of the clock.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:21:08 +00:00
3915a4e5f5 Merge pull request 'GameCult.Networking: resend the capped frame's answer until acknowledged, then end the session' (#49) from libby/cs-capped-answer-reliable into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 11:10:54 +00:00
Libby
0b1a468ddd GameCult.Networking: resend the capped frame's answer until acknowledged, then end the session
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 8m47s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m13s
The schema server answered the 8th undecodable frame and ended the peer's session in the same
call; ending clears the session's pending reliable packets, so a lost datagram was never
resent. The session now stays until the peer has acknowledged every answer (a lost one is
resent by PollResends) or a 2 s grace runs out, serves nothing after the capped frame
meanwhile, and then sends the goodbye.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:10:48 +00:00
Libby
03141bc93b cultmesh-rs: send the capped frame's answer reliably and end the session once it is acknowledged
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
The capped (8th) refusal went out unreliable and unordered with the goodbye at once, so a
lost datagram left the peer without it. It is now queued like any response and resent until
the peer acknowledges it; the session ends then (or after a 2 s grace) and serves nothing
after the capped frame meanwhile. The answer, its resends and the poll that carried the
capped frame acknowledge nothing, as every refusal. A reliable queue that cannot take the
answer ends the session at once with the unreliable refusal, as before.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 11:04:22 +00:00
337168812e Merge pull request 'cultmesh-ts: resend the capped frame's answer until acknowledged, then end the session' (#47) from libby/ts-capped-answer-reliable into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-08 10:59:27 +00:00
Libby
9e5edeca52 cultmesh-ts: resend the capped frame's answer until acknowledged, then end the session
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m6s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
endCappedSession deleted the session right after the answer was sent, so the resend
timer never saw it and a lost datagram left the peer without the answer. The session
now stays until the peer has acknowledged every reply (a lost one is resent) or a 2 s
grace runs out, serves nothing after the capped frame meanwhile, and then sends the goodbye.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 10:59:23 +00:00
fe73795d89 Merge pull request 'cultmesh-py: answer an unreadable RUDP frame and end the session after 8 consecutive refusals' (#45) from libby/py-refused-frames-cap into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 6m3s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 57s
2026-11-08 09:54:41 +00:00
Libby
bf81695537 cultmesh-py: answer the capped frame reliably and end the session once the answer is acknowledged
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m17s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 52s
The 8th refusal was sent unreliable and unordered with only the first response,
then the goodbye at once, so a lost datagram left the peer without it. All answers
now go the normal reliable path; the session ends when the peer has acknowledged
them (a lost one is resent) or after a 2 s grace, and serves nothing after the
capped frame meanwhile.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:54:37 +00:00
b1d6ec098d Merge pull request 'cultmesh-ts: end a RUDP session after 8 consecutive unreadable frames or authority-refused deletes' (#44) from libby/ts-refused-frames-cap into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 09:52:26 +00:00
Libby
23c7ce3738 cultmesh-ts: count and answer a frame that decodes but is no message the parser takes
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m9s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m17s
A map with an unknown schemaVersion was rethrown: unanswered, uncounted toward the
session cap. It is now answered message_invalid, reported, and counted like any other
unreadable frame, so the cap holds for it.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:52:22 +00:00
51d2d0cf46 Merge pull request 'GameCult.Networking: answer an undecodable RUDP frame message_invalid and end the session at 8 in a row' (#46) from libby/cs-refused-frames-cap into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 09:47:22 +00:00
Libby
89bbb277bd GameCult.Networking: answer an undecodable RUDP frame message_invalid and end the session at 8 in a row
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 7m10s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m20s
Heimdall's parity ruling. The schema server ended a peer's session on the first
frame it could not decode. It now answers message_invalid (field "message") and
keeps the session; RudpCultNetSchemaServer.MaxConsecutiveRefusedFrames (8)
consecutive undecodable frames end it after the last is answered, and any
decoded frame resets the run. Handler faults still end the session at once.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:47:08 +00:00
Libby
b4979cb65b cultmesh-py: answer an unreadable RUDP frame and end the session after 8 consecutive refusals
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Heimdall's parity ruling. A frame that is no msgpack map used to be dropped
silently; it is now answered message_invalid (field "message") and the session
kept. MAX_CONSECUTIVE_REFUSED_FRAMES (8) consecutive unreadable frames, or
consecutive deletes the write authority refuses, end the session after the
capped frame is answered. The authority's decision is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:43:41 +00:00
Libby
621e05d552 cultmesh-ts: end a RUDP session after 8 consecutive unreadable frames or authority-refused deletes
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
Heimdall's parity ruling. The refusal is still answered and the session kept
below the cap; the frame that reaches CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES
is answered too, then the session ends. The write-authority decision is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:41:18 +00:00
4828c41646 Merge pull request 'cultmesh-rs: keep the session through an unreadable frame or refused delete; end at 8 in a row' (#43) from libby/keep-session-invalid-cap into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-08 09:36:55 +00:00
Libby
a0d9ed0cc5 cultmesh-rs: keep the session through an unreadable frame or refused delete; end it at 8 in a row
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 3m28s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 56s
Heimdall's parity ruling: the refusal is answered on the live session, and
MAX_CONSECUTIVE_REFUSED_FRAMES (8) consecutive undecodable frames (reset by
any decoded frame) or refused deletes (reset by any decoded non-delete) end
it. The sink gate is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:36:41 +00:00
fb705cbc1d Merge pull request 'cultmesh-rs: RUDP document server refuses unreadable frames and deletes with typed errors' (#42) from libby/rs-rudp-typed-refusals into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 09:33:41 +00:00
Libby
34be64789e cultmesh-rs: RUDP document server refuses unreadable frames and deletes with typed errors
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m40s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 32s
An undecodable schema frame was dropped and a DocumentDelete ignored, both
silently. Now the first is refused message_invalid (details.field "message")
and the second write_not_authorized naming the record, each with a fixed
reason, ending the peer's session as the other refusals do. The sink gate is
unchanged. Both bytes are pinned against the shared error-vectors.json.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:33:27 +00:00
a95b43d48f Merge pull request 'cultnet error contract: one message_invalid code replaces malformed_document_put/delete' (#41) from libby/error-message-invalid into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 4m36s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 21s
2026-11-08 09:17:52 +00:00
Libby
a558f3ad3b cultmesh-py: pin details.field on the message_invalid refusals of a malformed or unstorable put
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m43s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:14:12 +00:00
Libby
8f71bff69c cultnet error contract: one message_invalid code replaces malformed_document_put/delete
Q6-A of docs/cultnet-error-contract-cut.md. message_invalid joins the closed
cultnet.error.v0 code enum (both schema copies), with details.field naming the
request field at fault ("message" when the whole frame cannot be read).
C# ForMessageInvalid, Rust CultNetErrorCode::MessageInvalid, TS
cultNetMessageInvalidError and Python message_invalid_error all write the same
captured bytes (error-vectors.json plus the C# and Rust cases). cultmesh-py and
cultmesh-ts refuse malformed puts and deletes with it; the C# subscription
servers use it for the missing subscriptionId.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:14:12 +00:00
fd119ea36c Merge pull request 'cultmesh-ts: write authority decide timeout counts as a typed refusal' (#40) from libby/ts-decide-timeout into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 09:13:11 +00:00
Libby
386f036849 cultmesh-ts: test that a grant arriving after the decide timeout is refused and never reaches the handler
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m41s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 57s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 09:13:08 +00:00
Libby
43abf9762f cultmesh-ts: refuse an unusable writeAuthorityTimeoutMs at construction
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m2s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
Review finding: NaN, Infinity or >2^31-1 becomes a 1 ms Node timer and would
refuse every write that is not instant; 0 and negatives were silently clamped.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 05:59:25 +00:00
Libby
3f150799f0 cultmesh-ts: write authority decide timeout counts as a typed refusal
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m41s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 31s
A never-settling decide() held up the later frames of its session. The
server now races it against writeAuthorityTimeoutMs (default 5000) and
refuses with write_not_authorized on expiry. The granted-path test now
asserts the canonical schemaId the authority saw.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 05:50:07 +00:00
e8b2e44496 Merge pull request 'semver-policy: exact commands for reading the workflow at the tagged sha; evidence for the cultcache-ts-v0.15.0 run' (#39) from eureka/tag-sha-workflow-step into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 6m42s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 21s
2026-11-08 03:52:59 +00:00
3dd9bde017 semver-policy: exact commands for the before-pushing-a-tag step, and the 0.15.0 run's evidence
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m19s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 03:51:27 +00:00
cbae9ec6fe Merge pull request 'docs: drop stale cultcache-ts tag-trigger claim from the content map' (#38) from libby/ts-tag-trigger-docs into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-08 03:49:17 +00:00
Libby
6822da6187 semver-policy, content-map: follow review of the cultcache-ts tag-trigger text
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 03:49:16 +00:00
Libby
5155c5b834 content-map: no cultcache-ts tag triggers publish-packages on main
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m47s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 51s
The C5 plan still said the cultcache-ts tag triggers the npm publish; F16 and the workflow say it does not. npm view 404 re-checked 2026-11-08.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 03:48:36 +00:00
250d616f8f Merge pull request 'cultmesh-ts: write authority for the RUDP document server' (#37) from libby/cultmesh-ts-write-authority into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 5m14s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 26s
2026-11-07 20:21:27 +00:00
Libby
3f4139549e cultmesh-ts: CHANGELOG states the refusal size bound
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 20:21:26 +00:00
Libby
ada30be84e cultmesh-ts: gate before shard refusal, bound the refusal, harden tests
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m2s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
A put with wrong-typed shard fields is judged with null shard fields first, then
refused as malformed once granted. The refusal's record key and reason are
clipped so it fits maxPayloadBytes. The allocation test watches transient
allocations; catch-path and delete tests assert ids, operation, reply count,
onError and handlers. README/CHANGELOG no longer claim the schema is resolved
after the gate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 20:13:49 +00:00
Libby
1689b62597 cultmesh-ts: gate unreadable writes, malformed refusals, payload tests
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m22s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 1m5s
A frame that fails to decode or parse is judged as the write it looks like, so
an ungranted peer gets write_not_authorized instead of silence; a granted peer
gets onError and a malformed_document_put/delete refusal. Adds raw-frame tests
(int, 2**70, oversized claimed length, non-decoding, non-map document) and
the timing residual note.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:57:42 +00:00
Libby
1bc05d7b06 cultmesh-ts: document server asks a write authority before applying a peer put or delete
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Deny by default with a grant-all opt-in; the gate runs before the put is sized,
resolved or decoded; refusal is the typed write_not_authorized. Adds
onDocumentDeleteRaw, refuses wrong-typed shard fields before the gate, grants
all writes in the existing server tests, and ports the cultmesh-py
remote-write-authority tests (no forwarding).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:52:42 +00:00
Libby
474e27fcb3 WIP B 2026-11-07 19:36:40 +00:00
f0731c6b91 Merge pull request 'cultnet-ts: typed write_not_authorized factory and canonical schema id' (#36) from libby/cultnet-ts-write-refusal into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 6m33s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 36s
2026-11-07 19:36:36 +00:00
Libby
2016ad7457 cultnet-ts: write_not_authorized blank-reason check is C# IsNullOrWhiteSpace
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m11s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
Review: trim() differs from string.IsNullOrWhiteSpace on U+0085 and U+FEFF; use the
package's isNullOrWhiteSpaceCSharp and pin both in the test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:36:32 +00:00
Libby
d0c0156874 cultnet-ts: typed write_not_authorized factory and canonical schema id
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
cultNetWriteNotAuthorizedError(recordKey, reason?) writes the C# ForRemoteWriteRefused
bytes (pinned to error-vectors.json). CultNetDocumentRegistry.canonicalSchemaId resolves
the id a put or delete writes under, from the id alone, for a server's write authority.
No behaviour change for existing callers; the registry already had a delete apply.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:35:21 +00:00
10c1f4dd00 Merge pull request 'cultmesh-rs: a sink's refusal of a put is a typed write_not_authorized' (#35) from libby/cultmesh-rs-typed-refusal into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-07 19:31:48 +00:00
Libby
74ccfaf67a cultmesh-rs: a sink's refusal of a put is a typed write_not_authorized
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m48s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 55s
The RUDP document server sent a host sink's refusal as an untyped Error (code None).
It now sends write_not_authorized with details naming the record, as C#, TS and
Python do; the text stays the fixed variant text, never the sink's. The rejection
carries the put's record_key. Other rejections stay untyped. Unit test pins the
bytes to the error-vectors.json write_not_authorized vector; integration tests
check code/details on the wire and that a refused put reaches no sink.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:30:54 +00:00
608ddb94f7 Merge pull request 'cultmesh-py: bind the TCP+UDP pair for port 0 without the race' (#34) from libby/cultmesh-py-port-race into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-07 19:28:51 +00:00
Libby
cff68d5528 cultmesh-py: bind test proves only the UDP number was taken
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:28:50 +00:00
Libby
e0f5e13a1b cultmesh-py: bind the TCP+UDP pair for port 0 without the race
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m46s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 46s
CultMeshLocalServer.start bound TCP to port 0 and then bound UDP to whatever number
the kernel picked, failing with EADDRINUSE whenever another process held that
number for UDP (this host has hundreds of UDP listeners), and left the accept
thread running on failure. Port 0 now retries with a fresh pair (bounded); both
sockets bind before any thread starts; an explicit port still fails honestly.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:25:38 +00:00
e2dc04e724 Merge pull request 'cultmesh-py: peer writes need a write authority (default-deny)' (#33) from libby/cultmesh-py-remote-write-authority into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-07 19:19:27 +00:00
Libby
87c4ac366d cultmesh-py: refuse wrong-typed shard fields before the write gate
A non-string shardId or non-int shardEpoch (bool is not int) on a put or delete
is a malformed_document_put/delete before the authority is asked, so a
shard-scoped authority cannot be bypassed by a shard the store would file under
str(shardId). The authority receives the fields as sent.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:19:26 +00:00
Libby
f074c3d45f cultmesh-py: document why schema resolution precedes the write gate
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m39s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 30s
Comment at the gate and a README residual; no behaviour change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:17:30 +00:00
Libby
61a1d872b3 cultmesh-py: gate runs before an ungranted peer's payload is touched
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
raw_put_target resolves only a put of the wire shape (string key, bytes payload),
so an int payload is never converted (bytes(10**9)) before the authority speaks.
Shard fields of the wrong type reach the authority as None. Tests: huge payload
refused without allocating, RUDP peer path (endpoint and transport), shard types.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:14:12 +00:00
Libby
2947e15088 cultmesh-py: peer writes need a write authority (default-deny)
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m36s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 20s
Finishes the remote-write gate: exports, daemon --allow-peer-writes, the gate is
total (an ungranted peer learns nothing from malformed/unowned-put replies),
existing server tests grant explicitly, 12 tests port RemoteWriteAuthorityTests
(forwarding has no Python counterpart), refusal bytes pinned to error-vectors.json.
README documents the breaking change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 19:07:32 +00:00
Libby
7a721204ae WIP cultmesh-py: remote write authority gate (not finished, not for merge)
Adds write_authority.py, node.raw_put_target/raw_delete_target, the gate in
_handle_raw_put/_handle_raw_delete with the peer passed in, and serve_node/serve params.
Missing: __init__ exports and imports in facade.py/session.py, daemon --allow-peer-writes,
tests, README and Breaking note. Untested.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:59:47 +00:00
d00222761c Merge pull request 'Docs: cultcache-ts publishing is off; tag runs use the tagged workflow' (#32) from libby/publish-docs-cleanup into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Failing after 5m5s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Successful in 36s
2026-11-07 16:53:04 +00:00
Libby
bf5a09bd04 publish-packages: say that cultcache-ts publishing is off; keep the tag pin readable
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m5s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 25s
The header comment, semver-policy and F16 of the content map still listed cultcache-ts-v*
as a trigger. They now say publishing is deliberately off and that a tag run uses the
workflow at the tagged commit (cultcache-ts-v0.15.0 sits on 7d292085, before the guard).
semver-policy gains a "Before pushing a tag" note. The guard's comment moves above `tags:`:
inside the list it broke the three `workflow:` tests of check-changelog-semver.test.mjs,
which read `tags:` followed directly by its items.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:53:03 +00:00
e75285c067 Merge pull request 'publish-packages: cultcache-ts-v* tags no longer trigger publish' (#31) from libby/disable-cultcache-ts-tag-publish into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-07 16:38:12 +00:00
Libby
8569825630 publish-packages: stop cultcache-ts-v* tags from triggering the npm publish
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 6m38s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
Publishing @gamecult/cultcache-ts is deliberately disabled until ruled on, and whether
NPM_TOKEN is set is unknown. The other tag patterns and workflow_dispatch are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:38:11 +00:00
7d29208539 Merge pull request 'cultcache-ts 0.15.0: fold 0.14.1, 0.14.2 and Unreleased; raise consumer ranges' (#30) from libby/cultcache-ts-0.15.0 into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
Publish packages / cultcache-py to PyPI (push) Has been skipped
Publish packages / cultmesh-py to PyPI (push) Has been skipped
Publish packages / cultnet-py to PyPI (push) Has been skipped
Publish packages / @gamecult/cultcache-ts to npm (push) Failing after 9m25s
2026-11-07 16:34:31 +00:00
Libby
7ac9e60bdc cultcache-ts 0.15.0: fold the untagged 0.14.1/0.14.2 and Unreleased into one entry
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m57s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
0.14.1 and 0.14.2 were never tagged; cultcache-ts-v0.14.0 is the last release. The
Unreleased exports (SchemaConflictError, schemaIdentityOf, the document payload codec)
are in no tagged release, which is what failed the declared-ranges check. Package and
lockfile go to 0.15.0 and every consumer range (cultnet-ts, cultmesh-ts, cultmesh-browser)
moves to ^0.15.0, since a 0.x caret does not admit a new minor.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:31:04 +00:00
da515b0f5e Merge pull request 'Fix build:ts: one text-only error factory in cultnet-ts (6 TS2345 in cultmesh-ts)' (#29) from libby/cultmesh-ts-error-message-sites into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-07 16:27:31 +00:00
Libby
d0fcd3e36e cultnet-ts, cultmesh-ts: one factory for the text-only error message
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m15s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
PR #20 made routingHint, code and details required on CultNetErrorMessage; six call sites in
cultmesh-ts still built the message without them, so build:ts failed with TS2345. cultnet-ts
now owns cultNetTextError(error), the legacy-union decode uses it too, and the call sites
and two test expectations call it. The types are unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:27:24 +00:00
8477d8dc74 Merge pull request 'npm: scope cultnet-ts, cultmesh-ts, cultmesh-browser under @gamecult' (#28) from libby/scope-npm-packages into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
2026-11-07 16:25:15 +00:00
Libby
286a9af389 npm: scope cultnet-ts, cultmesh-ts and cultmesh-browser under @gamecult
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 5m49s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 36s
Unscoped npm names are unclaimed and open to dependency confusion; cultcache-ts was
already @gamecult/cultcache-ts. package.json names, intra-repo dependencies, package-lock,
import specifiers (src, tests, samples, docs/start, first-call docs test), the workspace
list in run-typescript-workspaces, the verify-eve module map and package READMEs now use
the scoped names. Directory names, workspace paths in CI and release tag prefixes are
unchanged. Historical cut docs and past CHANGELOG entries keep the old names.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:25:10 +00:00
655cb2c909 Merge pull request 'cultcache-rs: pin the one-global rule on load_soa (PR #15 gap)' (#27) from libby/cultcache-rs-load-soa-global-test into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-07 16:18:28 +00:00
Libby
08715ac55c cultcache-rs: pin the one-global rule on load_soa
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Failing after 4m50s
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Successful in 26s
load_soa installs a whole table and checks it with refuse_second_globals, but no test
reached that call (PR #15 covered put paths and pull_all). A table holding two records
of a global type is refused with CultCacheSecondGlobal and the prior view survives; a
table with one global loads and replaces the view.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-07 16:17:05 +00:00
ec7a009b02 Merge pull request 'cultnet: add unsupported_schema_version to the closed cultnet.error.v0 code set' (#26) from libby/error-code-unsupported-schema-version into main
Some checks failed
CultMesh QUIC native / Build win32-x64 (push) Has been skipped
CultMesh QUIC native / Build linux-x64 (push) Has been skipped
CultMesh QUIC native / Release native binaries (push) Has been skipped
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (push) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (push) Has been cancelled
2026-11-07 16:16:17 +00:00
Libby
86faf53f86 tools/sprite-silhouette: README sample uses the real void/neutral size
Some checks failed
CultMesh QUIC native / Build win32-x64 (pull_request) Has been skipped
CultMesh QUIC native / Build linux-x64 (pull_request) Has been skipped
CultMesh QUIC native / Release native binaries (pull_request) Has been skipped
CultMesh portability and performance / ubuntu-latest one-command multiplayer onboarding (pull_request) Has been cancelled
CultMesh portability and performance / windows-latest one-command multiplayer onboarding (pull_request) Has been cancelled
CultMesh portability and performance / ubuntu-latest reactive semantics and leases (pull_request) Has been cancelled
CultMesh portability and performance / windows-latest reactive semantics and leases (pull_request) Has been cancelled
CultNet cross-runtime interop / C# / TypeScript / Rust / Python / Kotlin (pull_request) Has been cancelled
CultMesh QUIC native / Verify committed binaries match SHA256SUMS (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:50:08 +00:00
Libby
62c734f5b2 tools/sprite-silhouette: sprite alpha silhouette to a CSS shape-outside polygon
Zero-dependency Node tool: PNG alpha, threshold 0.35, outer contour of the largest
8-connected shape, Douglas-Peucker to a pixel tolerance, percent coordinates keyed by
cast-art pose id. Ten tests, including every pose in the shared catalogue.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:49:52 +00:00
178 changed files with 38712 additions and 696 deletions

View file

@ -8,6 +8,12 @@ on:
pull_request: pull_request:
workflow_dispatch: workflow_dispatch:
concurrency:
# A newer push or PR update replaces the older run on the same ref. Tag pushes and
# workflow_dispatch runs are never cancelled: a tag run carries a release.
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
jobs: jobs:
reactive-and-resource-lifetime: reactive-and-resource-lifetime:
name: ${{ matrix.os }} reactive semantics and leases name: ${{ matrix.os }} reactive semantics and leases
@ -16,12 +22,16 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
# The forge runner is Ubuntu-only: Windows legs run on workflow_dispatch (GitHub or a Windows runner), Ubuntu gates push and PR. # The forge runner (label `ubuntu-latest`) is Linux-only and no Windows runner exists: the Windows leg runs on workflow_dispatch only (GitHub or a Windows runner), the ubuntu-latest leg gates push and PR. Windows push/PR triggers return in the PR that registers a Windows runner.
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }} os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }}
steps: steps:
- name: Check out CultLib - name: Check out CultLib
uses: actions/checkout@v4 uses: actions/checkout@v4
with:
# The declared-dependency-range test builds the admitted releases from their tags.
fetch-depth: 0
fetch-tags: true
- name: Set up .NET - name: Set up .NET
uses: actions/setup-dotnet@v4 uses: actions/setup-dotnet@v4
@ -45,6 +55,34 @@ jobs:
- name: Install Python CultLib packages - name: Install Python CultLib packages
run: python -m pip install -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py run: python -m pip install -e packages/cultcache-py -e packages/cultnet-py -e packages/cultmesh-py
# The forge runner images carry no cargo either (the cross-runtime store tests build the Rust interop example); GitHub's hosted images do.
- name: Install Rust toolchain
if: runner.os == 'Linux'
shell: bash
run: |
set -euo pipefail
if ! command -v cargo >/dev/null && [ ! -x "$HOME/.cargo/bin/cargo" ]; then
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
fi
echo "$HOME/.cargo/bin" >> "$GITHUB_PATH"
# The forge runner images carry no pwsh; GitHub's Windows and hosted images do.
- name: Install PowerShell
if: runner.os == 'Linux'
shell: bash
run: |
set -euo pipefail
if command -v pwsh >/dev/null; then pwsh -Version; exit 0; fi
SUDO=""; [ "$(id -u)" -eq 0 ] || SUDO="sudo"
PWSH_VERSION=7.4.6
curl -fsSL "https://github.com/PowerShell/PowerShell/releases/download/v${PWSH_VERSION}/powershell-${PWSH_VERSION}-linux-x64.tar.gz" -o "${RUNNER_TEMP:-/tmp}/powershell.tar.gz"
$SUDO mkdir -p /opt/microsoft/powershell/7
$SUDO tar -xzf "${RUNNER_TEMP:-/tmp}/powershell.tar.gz" -C /opt/microsoft/powershell/7
$SUDO chmod +x /opt/microsoft/powershell/7/pwsh
$SUDO ln -sf /opt/microsoft/powershell/7/pwsh /usr/local/bin/pwsh
echo "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1" >> "$GITHUB_ENV"
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 pwsh -Version
- name: Verify explicit reactive scheduling across runtimes - name: Verify explicit reactive scheduling across runtimes
shell: pwsh shell: pwsh
run: ./scripts/verify-reactive-document-scaling.ps1 run: ./scripts/verify-reactive-document-scaling.ps1
@ -60,8 +98,8 @@ jobs:
--logger "console;verbosity=minimal" --logger "console;verbosity=minimal"
# The TypeScript side of the CultMesh authority rules. This job is the # The TypeScript side of the CultMesh authority rules. This job is the
# only one that runs on both Windows and Linux for main, codex/** and # only one that runs on Linux for main, codex/** and pull requests (and on
# pull requests: cultnet-interop.yml is windows-latest and main-only, so # Windows too under workflow_dispatch): cultnet-interop.yml is windows-latest and dispatch-only, so
# until these steps existed the shared verifier's tests never ran on # until these steps existed the shared verifier's tests never ran on
# Linux at all, and the browser client's never ran in CI on any OS. # Linux at all, and the browser client's never ran in CI on any OS.
# packages/cultnet-ts verifies both vector files (content.test.ts judges both # packages/cultnet-ts verifies both vector files (content.test.ts judges both

View file

@ -1,7 +1,7 @@
name: CultNet cross-runtime interop name: CultNet cross-runtime interop
# workflow_dispatch only: this job is Windows-only (pwsh Kotlin build, setup steps), and the forge # workflow_dispatch only: this job is Windows-only (pwsh Kotlin build, setup steps), and the forge
# runner is Ubuntu-only, so a push or pull_request trigger would queue a job that can never run. # runner is Ubuntu-only (no Windows runner exists; push and pull_request return in the PR that registers one), so a push or pull_request trigger would queue a job that can never run.
# Run it from GitHub or any Windows runner. # Run it from GitHub or any Windows runner.
on: on:
workflow_dispatch: workflow_dispatch:

View file

@ -8,15 +8,26 @@ name: Publish packages
# directly, which is already how Ghostlight, Epiphany, CodexConnector and Odin # directly, which is already how Ghostlight, Epiphany, CodexConnector and Odin
# consume the core stack. # consume the core stack.
# #
# Tag a release to publish, for example `cultcache-ts-v0.13.6` or # Tag a Python release to publish, for example `cultnet-py-v0.1.0`. The tag's
# `cultnet-py-v0.1.0`. The tag's version must match the version in the package # version must match the version in the package manifest;
# manifest; scripts/release-after-suite.mjs refuses the release otherwise rather # scripts/release-after-suite.mjs refuses the release otherwise rather than
# than shipping a mislabelled artifact. # shipping a mislabelled artifact.
#
# npm publishing of @gamecult/cultcache-ts is deliberately off: `cultcache-ts-v*`
# is not a tag trigger until it is ruled on (the cultcache-ts job below runs from
# workflow_dispatch only, which publishes nothing). A tag run uses the workflow
# file at the tagged commit, not the one on main, so a tag on an older commit
# (`cultcache-ts-v0.15.0` sits on 7d292085, before the guard) still runs that
# commit's triggers and jobs. Read this file at the tagged sha before pushing a tag.
on: on:
push: push:
# cultcache-ts-v* is deliberately not a trigger: publishing @gamecult/cultcache-ts is disabled
# until it is ruled on, and whether NPM_TOKEN is set is unknown, so a pushed tag must not reach
# `npm publish`. The cultcache-ts jobs below still run from workflow_dispatch, which publishes nothing.
# (The comment sits above `tags:` because the tag-prefix pin in scripts/check-changelog-semver.test.mjs
# reads the list as `tags:` followed directly by its items.)
tags: tags:
- "cultcache-ts-v*"
- "cultcache-py-v*" - "cultcache-py-v*"
- "cultnet-py-v*" - "cultnet-py-v*"
- "cultmesh-py-v*" - "cultmesh-py-v*"

View file

@ -18,6 +18,12 @@ on:
pull_request: pull_request:
workflow_dispatch: workflow_dispatch:
concurrency:
# A newer push or PR update replaces the older run on the same ref. Tag pushes and
# workflow_dispatch runs are never cancelled: a tag run carries a release.
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions: permissions:
contents: read contents: read
@ -49,11 +55,12 @@ jobs:
# workflow_dispatch and a cultmesh-quic-native-v* tag run the two builds. # workflow_dispatch and a cultmesh-quic-native-v* tag run the two builds.
# A dry (workflow_dispatch) run uploads artifacts and creates no release. # A dry (workflow_dispatch) run uploads artifacts and creates no release.
# No Windows runner is registered on the forge, so this job is workflow_dispatch only
# (run it on GitHub or a Windows runner). The tag trigger returns in the PR that registers one.
# Until then a tag push skips the release job, which needs this build.
build-win32-x64: build-win32-x64:
name: Build win32-x64 name: Build win32-x64
if: >- if: github.event_name == 'workflow_dispatch'
github.event_name == 'workflow_dispatch' ||
(github.event_name == 'push' && startsWith(github.ref, 'refs/tags/cultmesh-quic-native-v'))
runs-on: windows-latest runs-on: windows-latest
timeout-minutes: 20 timeout-minutes: 20
steps: steps:
@ -92,8 +99,8 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
# Q6 A: this pinned Debian 13 container is the only permitted Linux # Q6 A: this pinned Debian 13 container is the only permitted Linux
# release builder. The digest is the pin; the `debian:13` tag is only a # release builder. The digest is the pin; the `debian:13` tag is only a
# label. The artifact links against this image's glibc (2.41); a bare # label. The artifact links against this image's glibc (2.41);
# ubuntu-latest runner carries glibc 2.39, which is not the deploy host's # a bare runner's OS image has its own glibc (a GitHub ubuntu-latest image carried 2.39), which is not the deploy host's
# OS (docs/typescript-quic-realtime-cut.md:2192-2197). # OS (docs/typescript-quic-realtime-cut.md:2192-2197).
container: container:
image: debian:13@sha256:f324c7ff54321e8d9c588493a20244965938ce0aa50bbd1022d38010e9ffc4b1 image: debian:13@sha256:f324c7ff54321e8d9c588493a20244965938ce0aa50bbd1022d38010e9ffc4b1

View file

@ -114,7 +114,10 @@ copies), the C# `CultNetErrorMessage` factory, the Rust `CultNetErrorCode`, and
`selection_invalid`, `cursor_stale`, `cursor_invalid`, `reference_outside_target`, `variant_unsupported`, `selection_invalid`, `cursor_stale`, `cursor_invalid`, `reference_outside_target`, `variant_unsupported`,
`unowned_schema` (a write, or a remote put or delete, for a schema and key no shard owns), `unowned_schema` (a write, or a remote put or delete, for a schema and key no shard owns),
`write_not_authorized` (a peer's put or delete its server's remote write authority did not grant) and `write_not_authorized` (a peer's put or delete its server's remote write authority did not grant) and
`unsupported_schema_version` (a message whose `schemaVersion` the peer does not speak; `details` names `schemaVersion` and the offered value). `unsupported_schema_version` (a message whose `schemaVersion` the peer does not speak; `details` names `schemaVersion` and the offered value) and
`limit_reached` (a receipt-capable server's per-session remembered-write table is full, so a new write is refused; `details` all null) and
`message_invalid` (a request that lacks a required field or carries an ill-typed one: a document-put or delete, or a subscription without an id; `details.field` names the request field, or `message` when the whole frame cannot be read).
A malformed put or delete is `message_invalid`, not a per-operation code: the peer knows which operation it sent.
## Live Invariants ## Live Invariants

View file

@ -28,7 +28,7 @@
"code": { "code": {
"description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it. The set is a closed enum: Rust and TypeScript refuse a message whose code is not listed, so adding a code is one coordinated change across every runtime (this schema, the C# factory, the Rust CultNetErrorCode, and a captured-bytes case for each).", "description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it. The set is a closed enum: Rust and TypeScript refuse a message whose code is not listed, so adding a code is one coordinated change across every runtime (this schema, the C# factory, the Rust CultNetErrorCode, and a captured-bytes case for each).",
"type": ["string", "null"], "type": ["string", "null"],
"enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported", "unowned_schema", "write_not_authorized", "unsupported_schema_version"] "enum": [null, "selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported", "unowned_schema", "write_not_authorized", "unsupported_schema_version", "message_invalid"]
}, },
"details": { "details": {
"description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.", "description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.",
@ -36,7 +36,7 @@
"additionalProperties": false, "additionalProperties": false,
"required": ["field", "value", "asOf", "current"], "required": ["field", "value", "asOf", "current"],
"properties": { "properties": {
"field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended. unowned_schema: \"schemaId\". write_not_authorized: \"recordKey\". unsupported_schema_version: \"schemaVersion\".", "type": ["string", "null"] }, "field": { "description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended. unowned_schema: \"schemaId\". write_not_authorized: \"recordKey\". unsupported_schema_version: \"schemaVersion\". message_invalid: the request field that is missing or ill-typed (\"message\" when the whole frame cannot be read).", "type": ["string", "null"] },
"value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended. unowned_schema: the schema id no shard owns. write_not_authorized: the key of the refused write. unsupported_schema_version: the schemaVersion the peer does not speak.", "type": ["string", "null"] }, "value": { "description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended. unowned_schema: the schema id no shard owns. write_not_authorized: the key of the refused write. unsupported_schema_version: the schemaVersion the peer does not speak.", "type": ["string", "null"] },
"asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 }, "asOf": { "description": "cursor_stale: the cursor's own minted asOf.", "type": ["integer", "null"], "minimum": 0 },
"current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 } "current": { "description": "cursor_stale: the answering server's current asOf.", "type": ["integer", "null"], "minimum": 0 }

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,195 @@
# CultNet fork-desk contract v0 (specification)
Status: specification, drafted for Heimdall (Bifrost receiver), Huginn (the second door) and Void (Ratatoskr desk). No runtime implements it yet.
Rule source: `/opt/commons/handoff/fork-desk-answer-binding-20261110.md` (Heimdall; sections 1.1 to 1.5, 1.3a to 1.3d), amended by the Persona briefs of 2026-11-10 (Eureka's fit check). Where this page differs from that file it says so under "Differences from the binding file".
Format source: the fork desk artifact in `/opt/commons/handoff/fork-desk-original/` (ruling `eureka-substrate:ruling:fork-desk-nibu-format`).
Files here: `fork-card.schema.json` (one schema, a `$defs` entry per document), `fork-card-vectors.json`. Conformance: `tests/GameCult.Networking.Tests/GovernanceVectorTests.cs` (C#) and `packages/cultnet-ts/test/governance-vectors.test.ts` (TypeScript), both generated against vectors written by `scripts/gen-governance-vectors.py`. Each suite computes every hash with its own code and replays every scenario through a reference judge written from this page.
All documents are CultNet map-mode: every key written, nil where absent, closed schemas. Field names are snake_case as in the binding file and the mind's records; `schemaVersion` keeps CultNet's spelling (open choice 1). The bytes of every document are pinned in the vectors as `messagePackHex`.
## Documents
| schema id | what | who writes it |
|---|---|---|
| `gamecult.fork.card.v0` | the fork as shown | the publisher (a Mind's card projection) |
| `gamecult.fork.answer_request.v0` | the answer a decider sends | the client; Bifrost forwards it unchanged to Huginn's second door |
| `gamecult.desk_answer.v0` | the stored answer with one tagged outcome | Huginn only |
| `gamecult.fork.answer_result.v0` | what the sender gets back for a stored answer | Bifrost, from the stored `desk_answer` |
| `gamecult.fork.refusal.v0` | a body refused at the door; nothing stored | Bifrost |
| `gamecult.fork.record.v0` | a fork's answers plus the derived counted answer | a projection of the stored `desk_answer`s |
| `gamecult.fork.ruling_cite.v0` | the citation a ruling carries | the Mind admitting the ruling |
| `gamecult.fork.list_request.v0` | list a Mind's forks (Transport) | the desk |
| `gamecult.fork.list.v0` | a page of entries, counts and a stamp | Bifrost, projected from Huginn |
| `gamecult.fork.read_request.v0` | read one fork (Transport) | the desk |
| `gamecult.fork.entry.v0` | one card with its record | Bifrost, projected from Huginn |
| `gamecult.fork.unavailable.v0` | the outcome is not confirmed (the second door or Huginn did not answer); retry with the same `request_id` | Bifrost |
### card
`{schemaVersion, fork_id, title, context, options[{id, text}], recommendation, depends[], leans, flag, raised_in, deciders[], status, ruling, ruled_from[], order, options_hash}`.
- `fork_id`: the mind's `question` key, `<campaign>:question:<label>`.
- **Hashed (the shown members):** `title`, `context`, `options` (each `{id, text}`, in shown order), `recommendation` (an option id, **never nil**: the stored `question` requires `recommended`), `depends` (strings, each one of the stored question's `depends` lines verbatim, at most 8, each at most 1000 UTF-8 bytes (the stored `Line`), in shown order, empty when none; the stored kind holds prose lines, so a line may read like a reference such as `campaign:kind:label` but is hashed as the text it is).
- **Not hashed:** `fork_id` (bound beside the hash), `leans` (an option id or nil), `flag`, `raised_in`, `deciders`, `status` (`open` or `closed`), `ruling` (the ruling id when a ruling closed the fork; nil when the card is open, and nil on a closed card whose question was withdrawn or otherwise resolved with no ruling), `ruled_from` (answer ids a ruling has been admitted from; non-empty only on a closed card), `order`, and `options_hash` itself.
- **`deciders` is read-only data.** The list is set outside the Mind, through Bifrost's admin path, and **Bifrost sends it per call**: Huginn keeps no copy (M5). The card projection copies the list the call carried. **The list holds one to 64 ids** (Huginn's bound), on the card and in the per-call list alike (vectors `deciders_at_the_cap_of_64`, `deciders_65`); the per-call list has no schema here, so the bound is stated for the cut that builds it. A question's own `audience` may only narrow it. A Mind never writes it, so a Mind cannot add itself and answer its own fork.
- Rules a schema cannot say, each with a negative vector: a `depends` line is at most 1000 UTF-8 bytes (the schema bounds 8 lines and 1000 characters; bytes need the rule); option ids are unique; `order` is unique among a Mind's cards (a list with two cards on one `order` is refused, naming both fork ids); `recommendation` and `leans` name an option; deciders are unique; an open card names no `ruling` and its `ruled_from` is empty (a ruling that answers a fork closes it); `ruled_from` is non-empty only when `ruling` is set; a closed card may name no ruling (the question was withdrawn, superseded or deferred: step 6 reads `status`, not the ruling); `options_hash` equals the hash of the shown members.
### Options hash (canonical bytes)
`options_hash` = lowercase hex SHA-256 of the UTF-8 bytes of the following, byte for byte:
1. Build an object with exactly the five members `title`, `context`, `options`, `recommendation`, `depends`. Each option is an object with exactly `id` and `text`.
2. **NFC-normalise every string, object keys included.** No trimming, no newline rewriting, no case folding. A string with a lone surrogate is not a card (it has no UTF-8). Normalisation stability makes NFC stable across Unicode versions for already-assigned code points; a runtime's own normaliser is trusted and the vectors include a decomposed pair and astral code points (open choice 2).
3. Serialise as RFC 8785 (JCS): no whitespace; object keys sorted by UTF-16 code unit, which for these ASCII keys is `context, depends, options, recommendation, title` and, inside an option, `id, text`; array order is as shown (option order and `depends` order are part of the hash).
4. Strings are written in double quotes; only `"` and `\` are backslash-escaped, U+0008, U+0009, U+000A, U+000C, U+000D as `\b \t \n \f \r`, every other code point below U+0020 as `\u00xx` in lowercase hex; everything else is written raw as UTF-8 (U+007F, U+2028, `<`, `&` and astral code points included).
5. **Numbers and nulls:** the member set contains none. There is no number to canonicalise (a number anywhere in the five members is a defect) and `recommendation` is never nil, so no nil is hashed.
`fork_id` is not in the hash and is bound beside it in its own field, so one hash cannot be replayed under another fork. The publisher computes the hash and stores it in the card; the client recomputes it from what it rendered and refuses to send on a mismatch; the receiver recomputes from its stored fork, never from the client.
Vectors `optionsHash`: the seven of the binding file (`heimdall_A..G`), computed by the Python generator, by the C# suite and by the TypeScript suite independently, plus text, title, context and `depends`-order mutations, a case showing the unshown members do not move the hash, escapes and markup, and astral ids. Each suite also mutates every shown member, an option id included, and asserts the hash changes.
### answer_request
`{schemaVersion, fork_id, options_hash, answer, retracted, retracts, answered_at, request_id}`. **`request_id`** is set by the client, a lowercase D-format UUID, one per intended answer, kept across retries; the first stored answer that carries it binds it to the stamped `answerer`. "Same body" means every field equal, `answered_at` included, so a client resends identical bytes. A **retry with the same `request_id` and the same body returns the stored outcome unchanged** (a `Refused` one included; a replayed `stale_fork` carries the **current** card, because a stored `desk_answer` has no card field and no storage is added for one) and **never adds a Revision**; the same `request_id` with a different body is `request_id_conflict` (409, a refusal, nothing stored). The same id from another account is another request, judged on its own: Y reusing X's `request_id` with a body identical to X's gets **Y's own new answer, with its own answer id, stamped Y**; X's stored outcome (a `Refused` one included) is never returned in its place, and Y's request neither conflicts with it nor replays it. An `of` that names the counted answer is allowed, because answer ids are not secret between deciders (vectors V14: an off-list X's `Refused`, then a decider Y's identical body is its own `Counted`; X's `Counted`, then Y's identical body is its own `Revision` whose `of` names X's answer, and X's later retry still returns X's answer). Both suites assert it on every scenario: a response's `answerer` is the step's account, and an id first bound by another account never yields that account's answer id or document. **`retracted` is part of the body**: the same `request_id` with `retracted: true` and then `false` (or the reverse) and every other field equal is `request_id_conflict`, for the illegal forms as for any other (vectors `R1_retracted_true_then_false_...`, `R1_retracted_false_then_true_...`). Each illegal form's own retry, byte for byte, replays its stored `bad_retraction` (vectors `R1_a_retraction_with_an_answer_...`, `R1_a_retraction_with_no_target_...`, `R1_a_plain_answer_with_a_target_...`). A body refused at step 1 or 2 binds nothing, so its id is free to reuse; so a target-less retraction resent with `retracted: false` (no answer, no retraction) is `body_invalid` at step 2, not a conflict. The lookup comes after steps 1 and 2 and before the fork is looked up, so a retry gets its stored outcome even if the card has since changed. `answer` is `{choice, note}` (at least one non-nil) or nil on a retraction. `choice` is an option id; `note` is the person's words, verbatim, 1 to 4000 **UTF-8 bytes**, not blank. A schema counts characters, not bytes, so its `maxLength: 4000` (code points) is only the looser bound and both suites enforce the byte limit as a rule: 4000 ASCII bytes pass; 1000 astral characters (4000 bytes) pass and 1001 (4004) fail; `e` plus a combining acute is 3 bytes, so 1333 of them and an `x` pass and 1334 fail; 1999 two-byte characters plus three ASCII (4001 bytes) fail. A note over the limit is `body_invalid`. `answered_at` is the client's claim. **A request never carries `answerer` or `authority`**: both are stamped by Huginn (`answerer` from the verified subject the receiver passes; `authority` from the door's configuration). A body that names either key at any depth is refused whole, never stripped (`body_forbidden_field`); any other unknown key is `body_unknown_field`. The request type Bifrost sends over the second door is this document; it has no field for either key, so a client cannot supply them by construction, and Bifrost's scan is the first line, not the only one. How Huginn receives the verified subject is the door's authenticated context, not a body field (open choice 3). In map-mode `retracted` is always written (the binding file's optional `retracted` becomes `false`).
### desk_answer (the stored kind)
`{schemaVersion, answer_id, fork_id, outcome, of, retracts, code, options_hash, choice, note, answered_at, received_at, claim_in_future, answerer, authority, request_id}`, key `<campaign>:desk_answer:<question-label>.n<seq>`; `answer_id` is `n<seq>`, assigned by Huginn per question, and **an answer is named by its answer id** everywhere (`retracts`, `of`, `ruled_from`).
The stamped `authority` field of a stored answer is an **attribution**: the role the verified account holds (`Operator`, `Steward`, `Member`), copied from Bifrost's state. A stored answer confers no authority. Authority exists only where a ruling cites a counted answer ("Operator authority" below); the field keeps the binding file's spelling (open choice 8). One tagged `outcome`, each variant carrying only its own link:
- `Counted`: the answer that counts. `of`, `retracts`, `code` nil.
- `Revision`: a later passing answer, kept, not counted while the first stands. `of` names the counted answer at the time.
- `Retraction`: the stored form of `retracted: true` plus `retracts`. `retracts` names the answer retracted; `choice` and `note` nil. The illegal pair (a retraction with no target, or a target with no retraction) cannot be written.
- `Refused`: any refusal from steps 4 to 7 or R1 and R2, with its `code`, stored too. `choice` and `note` keep what the body carried, and so does `retracts`: a refused body that named a target (a retraction of any refusal code, or a plain answer carrying one) projects it as `n<seq>`, never nil; a refused body that named none has `retracts` nil. `of` is nil.
`received_at` is Huginn's admission time; "first" means first by admission order (the `n<seq>` ordinal), never by `answered_at`. `claim_in_future` is true when `answered_at` is more than five minutes after `received_at`: accepted but flagged. It is a function of the two stored values, so the writer compares against the `received_at` it stores, at the precision it stores it (a flag decided against an unrounded clock and a stored second-truncated `received_at` disagrees with the document it sits in). **Not stored, and no answer id:** a body refused at step 1 or 2 (Bifrost; it never reaches Huginn), and a body naming an unknown fork (step 3; Huginn answers it from its stored forks, but with no question there is nothing to key a record under). Each gets a `refusal` and is dropped. A malformed body is therefore never stored, and neither is an unknown fork. Every refusal from step 4 on is stored. **`unavailable`** (503) is not a refusal and not in the refusal set: Bifrost answers it when the second door or Huginn did not answer after the auth steps and the body shape passed (a bad body is still refused first). **It says the outcome is NOT CONFIRMED, never that nothing was stored**: a timeout after the request reached Huginn may have stored it. It carries no answer id. The desk retries the same request with the same `request_id` and learns the outcome: the stored one if Huginn had it, a fresh one if not. It covers **calls 1 and 2 as well as the answer POST** when Huginn cannot be reached (Transport; a read has no outcome to confirm, so a retry is plain). `retryAfterSeconds` is nil when Bifrost has no hint.
**The mind's record and this document.** Huginn keeps the answer as its own record kind (`epiphany.pipeline.desk_answer.v2`, key `<campaign>:desk_answer:<question-label>.n<seq>`, the outcome as one externally tagged value, the fork as `fork`). The second door projects it to this document and nothing else crosses: `answer_id` is the key's `n<seq>` part, `fork_id` is the stored `fork`, the tagged outcome flattens into `outcome`, `of`, `retracts` and `code`, and the six refusal codes are spelt as in the schema (snake_case; the record's enum spells them in the mind's own PascalCase). On the wire an answer is named by its `n<seq>` alone, always inside the fork whose `fork_id` the document carries; a runtime that holds the full record key converts at the door, in one place. `body_sha256` and any other digest Huginn keeps to decide "same body" stay in the record: Huginn alone decides a replay or a `request_id_conflict` and Bifrost never compares bodies, so no digest is a field of this document. A digest is a valid way to decide it only if it covers `fork_id`, `options_hash`, `answer.choice`, `answer.note`, `retracted`, `retracts` and `answered_at` (every field of the request but `request_id`), is computed by Huginn and never read from a client.
**Huginn's digest, pinned in the vectors (`bodyDigests`; informative, not a wire document).** SHA-256 of one compact JSON object as `serde_json::to_string` writes it (UTF-8, no spaces), lowercase hex, keys in this order, `null` for a missing value, strings verbatim: `fork`, `options_hash`, `answered_at`, `choice`, `note`, `retracts` (the **full stored key** `<campaign>:desk_answer:<label>.n<seq>`: the door converts the wire's `n<seq>` before the digest), then, **only for the three illegal forms** (R1: a retraction carrying an answer, a retraction naming no target, a plain answer carrying a target), `illegal_retraction: true` and `retracted: true|false`. `request_id` is not in it. A plain answer and a legal retraction carry neither trailing key, so their digests are the ones Huginn main pins (`8a4d5b2e`, `9f807538`) and do not move. `9f807538` is pinned for a target no door produces (`Q1.1`); the golden for the real legal retraction is the door's form, the wire's `n1` converted to `Q1.n1` (`84576840`, vector `legal_retraction_door_form`, also main-valid). Source: Eureka's `desk-body-digest-order-20261110.md`, computed with `sha256sum`; the generator, the C# suite and the TypeScript suite recompute every digest from the input fields. **Status:** the three `retracted` goldens (`935cab1a`, `82b24ccc`, `34ef86ed`, and `79eee623` for form (i) with a null target) are the form of `cut-desk-digest-retracted.r2`, merged as Huginn #30. Eureka reports that these four and the door-form legal retraction (`84576840`) reproduce byte for byte on Huginn main `f0ca504` (the #30 fix); that run is hers, reported to us, and was not rerun here. Before #30, Huginn main (`7ea11b4`) wrote `illegal_retraction` alone, so forms (i) and (iii) collided there (`69074cc6`, pinned as `illegal_i_and_iii_alike_on_main`). The wire contract does not wait on it: the conflict scenarios are pinned in `scenarios`.
### Counting rules (in order; the first failure refuses with that code)
| step | rule | refusal | stored |
|---|---|---|---|
| 1 | verified session or bearer | `unauthenticated` (401) | no |
| 2 | closed body; no `answerer`/`authority` at any depth; type-correct; not (no `answer` and not a retraction) | `body_forbidden_field`, `body_unknown_field`, `body_invalid` (400) | no |
| 3 | `fork_id` is a stored fork | `fork_unknown` (404) | no |
| 4 | `options_hash` equals the stored fork's hash | `stale_fork` (409) | **yes**; the result carries the current card |
| 5 | the stamped `answerer` is on `deciders` | `not_a_decider` (403) | yes |
| 6 | the fork is open (`status: open`) | `fork_closed` (409) | yes |
| 7 | `choice`, if present, is an option id | `choice_invalid` (400) | yes |
| 8 | first passing answer for `(fork_id, options_hash)` is `Counted`; later passing answers are `Revision`s naming the counted one | | yes |
| 9 | a Matrix edit, redaction or reaction changes nothing | | no event is an answer |
**Retraction** (`retracted: true`, `retracts: <answer id>`, `answer: nil`, `options_hash` still carried, so step 4 applies) passes steps 1 to 6, then:
- R1 form: it carries no `answer`, it names a `Counted` or `Revision` answer of this fork under this `options_hash`; else `bad_retraction` (400). A retraction naming an answer already retracted is `already_retracted` (409). `retracts` on a body that is not a retraction is `bad_retraction`.
- R2 who: the original answerer or any other decider; step 5 already requires a decider.
- R3 is dropped and its label stays vacant, so R4 keeps its name in the binding file. A ruling that answers a fork closes it (Eureka and Heimdall, 2026-11-10), so a ruling cannot cite an answer on an open fork (that is the stale-click gap, and a card with `ruled_from` set and `status: open` is invalid), and a retraction after a ruling meets step 6: refused `fork_closed`, stored. There is no `ruled` code (vector `V10a_a_ruling_that_closed_the_fork_makes_a_retraction_fork_closed`).
- R4 counted answer: retracting the counted answer removes it from the count and the next passing answer in admission order counts again. Retracting an answer that was not counted changes nothing. After every answer is retracted, a fresh answer is `Counted`. Records stay append-only.
**The counted answer is derived**, not stored: the first `Counted` or `Revision` answer under the card's current `options_hash` that no `Retraction` names. When the card changes, answers under the old hash stop counting and the next answer under the new hash is `Counted` (vectors `a_changed_card_...`). The `record` projection carries it as `counted_answer_id`.
### Operator authority
A ruling may carry `authority: Operator` only if it cites (`ruling_cite.answer_id`) a stored `desk_answer` whose outcome is `Counted` and whose stamped attribution (the answer's `authority` field) is `Operator` (or a stamped relay of her words from a mapped door, which this contract does not model). The citation is what gives a ruling authority: an attribution on an answer is a fact about the account, and authority exists only where a ruling cites a counted answer. The cited answer id is what `ruled_from` lists on the closed card. Negative vectors (`rulingCites`): no citation, a `Revision`, a `Refused` answer, a Counted answer by a non-operator, an answer that does not exist. Other authorities need no citation.
## Transport
Source: the desk's client needs (Ratatoskr PR #24 section 12, `ratatoskr-desk-spec-20261110.md`) and Heimdall's binding file, `/opt/commons/handoff/fork-desk-answer-binding-20261110.md`, section 1.3c, which is the source for the second door. **Everything in this section is spec text for Bifrost to build; no route, scope or audience below exists in Bifrost today.** The routes (with the `{mind}` segment), the scope names `desk.read` and `desk.answer`, the audience `bifrost-desk` and the auth order are Heimdall's rulings (his file, sections 4.1 to 4.3a); this page writes them as documents and vectors.
**Authorities.** Cards are projected **read-only from Huginn**: Bifrost never authors a card, a ruling or a status, and the desk never writes one. Bifrost verifies the bearer, resolves the actor from its `sub` (a `UserAccount.Id`), and for an answer forwards a typed `DeskAnswer` on the peer-checked second door to Huginn, then returns **Huginn's outcome unchanged**: the stored `desk_answer` in an `answer_result`, or its refusal. The wire of the second door is **pending**: Eureka's cut spec follows her record PR, so this page defines the documents the desk sees and not the bytes between Bifrost and Huginn (open choice 3).
| call | route (proposal) | request | response | token |
|---|---|---|---|---|
| 1 list | `GET /api/desk/{mind}/forks?status=&cursor=&limit=` | `list_request`: `mind` from the path, the rest from the query string | `list` | audience `bifrost-desk`, scope `desk.read` |
| 2 read | `GET /api/desk/{mind}/forks/{fork_id}` (the id percent-encoded) | `read_request`, its `mind` and `fork_id` from the path | `entry`, or `refusal` `fork_unknown` (404) | `desk.read` |
| 3 answer | `POST /api/desk/{mind}/answers` | `answer_request` as the body; `fork_id` stays in the body, the Mind is the route's and is no body field | `answer_result` (200 for `Counted`, `Revision` and `Retraction`; a stored `Refused` answer keeps the `answer_result` body and takes its code's status from the counting-rules table: `stale_fork` 409, `not_a_decider` 403, `fork_closed` 409, `choice_invalid` 400, `bad_retraction` 400, `already_retracted` 409, as the vectors' `results` pin; a replay returns the same status as the first call; the desk reads `outcome` and `code` from the body), or a `refusal`, or `unavailable` | audience `bifrost-desk`, scope `desk.answer` |
**The `{mind}` segment** (Heimdall's rulings M1 to M5; vectors `transport.mindRoutes`).
- **M1.** `{mind}` is looked up in a **fixed configured list** of Mind ids, each mapped in configuration to that Mind's socket on the peer-checked door. The segment is percent-decoded once and compared, ordinally, with the list's ids: no case folding, trimming or Unicode normalisation, and a decoding failure is a miss. It is **never joined into a path, a socket name or a query**, so a value off the list opens nothing (`../x`, `a/b`, `a%2fb`, `eureka%00`, a 4 KB string, `GAMECULT-CHAT` for `gamecult-chat`, a trailing space, bytes that are not UTF-8: all unknown, 404, no socket opened).
- **M2.** An unknown Mind gets **the same refusal as an unknown fork**: `fork_unknown`, 404, the same bytes (the document's `error` names neither the Mind nor the fork). The list of Minds is not probeable. Auth is judged first, so a caller without a valid token, scope or Active membership learns nothing about which Minds exist.
- **M3.** On the POST the route's Mind must hold `fork_id`: step 3 is judged against **that Mind's** stored forks, so a `fork_id` the route's Mind does not hold is `fork_unknown` and nothing is stored, in either Mind. A fork cannot be answered through another Mind's route. A body that names `mind` is `body_unknown_field`: the Mind is the route's.
- **M4.** Scopes are **not per Mind**: `desk.read` and `desk.answer` open the routes of every configured Mind; every reader sees every fork's card and outcome, and which forks a caller may answer is the decider list.
- **M5. The decider list is sent per call.** Bifrost holds the admin-set list and sends it with **every answer, read and list request** to Huginn, as a typed field on the same peer-checked door; Huginn keeps no copy of it. Because it travels with read and list too, a projected card's `deciders` is the list of that call, and step 5 judges an answer against the list the same call carried. It comes only from Bifrost's admin-set state: never from a Mind and never from any request body a client controls: no HTTP field, header or query parameter on any desk route sets or extends it, and a body naming `deciders` is `body_unknown_field` (scenario `M5_...`). A request carrying it from a Mind's own door or session is refused. **This is Bifrost and Huginn work and no vector here can test it** (the typed field and the door's wire are pending, open choice 3); the rule is stated so that the cut that builds the request has it. (Heimdall's ruling, #minds 2026-11-10 19:26Z; it replaces the earlier reading of a list Huginn receives once and holds.) **Envelope names:** the desk's envelope on that door uses the names this page uses, `mind`, `authority`, `subject` and `deciders`, with no conversion at the door (Eureka, #minds 2026-11-10 19:58Z); `deciders` is a per-call list of short ids at the envelope's top level beside `subject`, never inside the request body, and Huginn keeps no copy.
Calls 1 and 2 are enough for a read-only desk. Every response is the pinned MessagePack document or its JSON form with the same keys (open choice 1 of `vote-api.md`: the media type is unsettled).
**Auth, in order, per route.** (1) A bearer, else `unauthenticated` (401). (2) The token's audience is `bifrost-desk`: **the Matrix Authentication Service token chat holds today is refused, and so is any `votes.*` token** (audience `bifrost-votes`), both as `unauthenticated`. (3) The scope the route needs, else `insufficient_scope` (403): `desk.read` for calls 1 and 2, `desk.answer` for call 3, and neither implies the other. (4) The account behind `sub` is an Active member, else `forbidden` (403), as in the vote API; scope is judged first. (5) For call 3 the body is then shaped (steps 1 and 2 above), so **a non-Active member who sends a bad body, including one naming `answerer` or `authority`, gets `forbidden`, not a body refusal**; a body naming either key at any depth is `body_forbidden_field` only for an Active member. (6) Only then is Huginn asked, so `unavailable` never hides an auth or body refusal. A `votes.*` token touches none of the three. Heimdall's file leaves the audience and the claims check open; `insufficient_scope`, `forbidden`, `request_invalid` (400, a list or read request that fails its document) and `request_id_conflict` are added to the door refusals.
**List.** `list_request`: `{mind, status, cursor, limit}`. `mind` is the route's `{mind}`, a Mind id from the configured list. `status` is `open`, `recorded` or nil for both; `recorded` means a closed card. Cards come **newest first by `order`**. `order` is the card's unique rank per Mind: an integer from 0 that never changes once the card exists, later questions only appending (Huginn derives it from the Mind's questions sorted by admission ordinal, then key). A Mind never holds two cards of one `order`; a list or card set that does is refused, and the refusal names both fork ids. 0 is legal, but no cursor names it (`c0` fails the cursor pattern): a page ending at order 1 returns `c1`, and the next page returns the order-0 card alone with `next_cursor` nil. `limit` is 0 to 50; **`limit` 0 returns no entries, only the counts and the stamp**, which is what "N open" on the Mind's header needs. `cursor` is nil or `c<N>`: the cards whose `order` is below N; a client treats it as opaque and sends back the `next_cursor` it was given. `list`: `{mind, stamp, open_count, recorded_count, forks[entry], next_cursor}`. The counts cover every card the viewer may see, whatever `status` and `cursor` asked for. `stamp` is `s<N>`, N the receiver's last-seen Huginn admission ordinal for the Mind's desk documents: the same stamp means the same state, so a desk polls `limit` 0 and fetches bodies only when the stamp moves. `next_cursor` is nil on the last page. An `entry` is `{card, record}`: the card and its `record` (the answers with their outcomes and the derived `counted_answer_id`).
**Read.** `read_request` is `{mind, fork_id}`; the response is the `entry` for one fork of that Mind. Its `card.options_hash` is **computed by the server** from the five shown members as in "Options hash" and the client recomputes it from what it rendered; a card whose hash is not the hash of its members is no card (negative vector `card_hash_wrong`). The record's `fork_id` and `options_hash` are the card's, and `counted_answer_id` is derived, not copied (negative vectors for each). Every `desk.read` holder sees every fork's card and outcome in a configured Mind; only a decider's notes depend on the caller, going to callers in the admin-set `deciders` list, which Bifrost enforces at the door (ruling `desk-read-visibility`, option (c)); `fork_unknown` is only for a fork id that does not exist under the route's Mind (an unknown Mind answers the same, M2), so no fork is ever hidden by it, and a caller without `desk.read` is refused by the auth order above (`insufficient_scope`) before any lookup. **Bifrost applies visibility at the door; Huginn returns the whole record to the door.** Every `desk.read` holder sees cards and outcomes; notes (a decider's own words) only go to callers in the admin-set `deciders` list. The read and list shapes are unchanged and carry no audience field (`eureka-substrate:question:desk-read-visibility`, Heimdall's option (c)). A stripped read serves a decider's `note` as `note: null`, never omitted (map-mode: every key is written); `desk_answer.note` is already nullable in the schema, so a served record validates as it stands.
**Answer.** The body is the `answer_request` and nothing else a client may set: `fork_id`, `options_hash`, `answer`, `answered_at`, `request_id` (plus `retracted` and `retracts`, written `false` and nil unless the call retracts). The response is the stored outcome: `Counted`, `Revision`, `Retraction`, or `Refused` with its code, and the **`counted_answer_id`** the fork has once this call is applied (`n<seq>` or nil; derived as in "The counted answer is derived", the same value the `record` projection carries, so the desk needs no second read). A replay returns the stored outcome with the `counted_answer_id` current at the retry, not the one it had when first stored. **A `stale_fork` refusal carries the current card** in `answer_result.card`, so the desk can show the new fork without another read. Nothing is stored for a step 1 or 2 refusal, an unknown fork (or an unknown Mind, or a fork another Mind holds) or a `request_id_conflict`. `unavailable` promises nothing either way.
**Vectors (`transport` in `fork-card-vectors.json`).** `listRequest`, `readRequest` and `entry` (valid and invalid, with bytes); `listInvalid` (including `two_cards_share_one_order`, whose `refusal` is the exact text both judges must produce: `order 4 is shared by <first fork id> and <second fork id>`); `listScenarios` (six scenarios: over one Mind's five cards, paged open-only, recorded-only, all and `limit` 0; an empty Mind; and `order_zero_is_legal_but_no_cursor_names_it`, four cards of orders 3 to 0 paged by 3, whose first page ends at order 1 with `c1` and whose second page is the order-0 card with `next_cursor` nil; each response with its bytes, the cursor of page two being page one's `next_cursor`); `authCases` (twenty-two cases: the MAS token, three `votes.*` tokens, a desk token with the other route's scope, a non-Active member on each route, and Huginn down on each route, with auth and membership judged first). Both suites replay the list requests through a reference judge and the auth cases through another. `mindRoutes` (a configured list of two Minds with their sockets and forks; 57 cases over the three routes: bad and percent-encoded segments, unknown Mind against unknown fork with `sameResponse` pairs of equal bytes, the POST on a Mind that does not hold the fork, scopes that are not per Mind, and auth judged before the Mind lookup) is replayed by both suites through a reference judge that reports the refusal, the socket it would open and the Mind that stored an answer. Top-level `unavailable` pins the 503 document. Scenarios pin: an `unavailable` where Huginn never had the request, retried into a `Counted` answer; an `unavailable` where Huginn had stored it, whose retry returns the stored outcome and adds no Revision; a replayed `Refused` with its card; `request_id_conflict`; the same id from another account; and a non-Active member with a bad body, with the door down, getting `forbidden` first. A bad body is refused before the door is asked.
**Bifrost must still build:** all three routes; the `bifrost-desk` audience and the `desk.read` and `desk.answer` scopes on the OIDC token it issues to chat; the configured Mind list and its sockets (M1); the projection of cards and records from Huginn, the stamp, the cursor and the counts; the `DeskAnswer` call on the second door and the pass-through of its outcome; the decider list, sent with every answer, read and list request from the admin-set list only (M5); the `unavailable` answer. **Huginn must still build** the second door's wire, the per-call decider list it receives with each answer, read and list request, keeping no copy (M5), and the read side the projection uses (Eureka's cut spec, after her record PR). **The desk may build today** against the vectors: nothing in them needs a live service.
## Old format, the mind's record, and what maps to what
The old desk (`index.html`) read `questions/<id>` and wrote `answers/<id>` in a shared store. The mind's `question` record is the source in the new design; the card is its projection.
| old desk | mind `question` record | card |
|---|---|---|
| `qid`, `id` | key `campaign:question:label` | `fork_id` |
| `title` | `title` | `title` |
| `body` | `question` (the long text) | `context` |
| `depends`: a free string | `depends`: up to 8 prose lines (`huginn schema question`) | `depends`: the lines verbatim |
| `options[{key, label, text}]` | `options[{label, text}]` | `options[{id, text}]` |
| option `key` | option `label` (a slug, the id) | option `id` |
| option `label` (a human title) | none | **dropped**: not stored, not hashed; shown text is `text` |
| `rec` (a key) | `recommended` (a label) | `recommendation` (an id), never nil |
| `lean` ("Self leans" mark) | none | `leans` (an id or nil), not hashed |
| `flag` (the provisional line) | none | `flag` (a string or nil), not hashed |
| `status` open or closed, `ruling` | derived from the resolution (status is never written): any resolution of the question closes it; the ruling is the one that answered it | `status`, `ruling`, both a projection (`ruling` is nil on an open card and on a card closed with no ruling) |
| `order` | none (unique rank per Mind, from 0) | `order` |
| none | `raised_in`, `asked_on` | `raised_in`; `asked_on` is not carried |
| none | none | `deciders` (outside the Mind), `ruled_from`, `options_hash` |
| answer `{choice: key or null, note, question, updatedAt}`, one mutable document per question | none | `answer_request` then an append-only `desk_answer` |
| `note`: her words verbatim | | `answer.note`, verbatim |
| "Clear pick": `choice` back to null so the note stands alone | | an `answer` with `choice` nil and `note` set, as the first answer or as a `Revision` |
| "Changing an answer is fine until it's admitted as a ruling" | | a later answer is a `Revision`; `Retraction` withdraws one; neither changes who counted first, and a ruling that answers the fork closes it, after which no answer or retraction is taken (`fork_closed`) |
Differences that need Void's choice: the old page **overwrites** one answer per question and the new store **appends**, so the booth cannot show "your answer" as one mutable field (it shows the latest answer by the person, plus its history); the old page needs no identity and the new one stamps `answerer` from a verified session; the old `label` has nowhere to live unless the card's `text` carries it.
## Transport note for Void: Matrix event versus how the mind carries questions
How a mind carries a question today: a typed `question` record in Huginn (`huginn view`, `huginn query`); the Persona relays it to the operator in chat, and the operator's reply comes back as chat text that Self reads and admits as a `ruling` in her words. Identity is whoever the chat attributes the message to; nothing binds an answer to the question text she saw.
Option A, **a Matrix event in the Mind's room with the answer as a reply.** Gains: it sits where people already are, needs no sign-in beyond Matrix, and the thread shows the exchange. Loses: the sender is an mxid, not a Bifrost account, so `answerer` and `authority` have no verified source; an edit or redaction changes the visible message but not the decision (binding rule 9), so the thread and the record can disagree; there is nowhere to carry `options_hash`, so a stale card cannot be refused; and a reply is free text, so `choice` is lost.
Option B, **Bifrost receives the answer and Huginn stores it** (the design in this page; Ratatoskr PR #24 also withdraws the Matrix carrier). Gains: a verified account, a bound hash, refusals that are stored and visible, one counted answer, retractions. Loses: the booth needs Bifrost sign-in, which does not reach chat yet (Bifrost PR #9 and #37 design it), so until then the desk is read-only; and the exchange is no longer in the room.
**Recommendation: B, with Matrix as presentation only.** The Mind may post a card as a listing and a link into the desk; no Matrix event is ever an answer (rule 9). Confidence: high on the rule (it is Heimdall's and Eureka's already), moderate on the interim, where read-only until sign-in is a real cost; if the operator needs to answer before sign-in reaches chat, the honest stopgap is the old path (chat text, Self admits a ruling in her words) rather than a Matrix reply the record cannot bind.
## Differences from the binding file
- Spelling: every field is as the binding file names it (`fork_id`, `options_hash`, `answered_at`, `retracted`, `retracts`, `answer.choice`, `answer.note`, `recommendation`, `depends`, option `id`), except that `schemaVersion` keeps CultNet's camelCase and `answer_id` replaces the earlier `receipt id` (Persona brief).
- Map-mode writes every key: `retracted` is always present; nothing is "optional".
- `Refused` stores every refusal from steps 4 to 7 and R1 and R2 (his section 1.3b); only steps 1 and 2 and `fork_unknown` are not stored. The binding file does not say whether `fork_unknown` is stored; it cannot be keyed without a question, so it is not (open choice 4).
- The binding file's `choice_valid` has no named refusal code; this page names it `choice_invalid`. `fork_known` is `fork_unknown`. A type-invalid body is `body_invalid`.
- `ruled` (his R3 and V10) is dropped: a ruling that answers a fork closes it, so the case is `fork_closed` (V4, V10a). His file drops it too.
- Heimdall's section 1.3e (Q1 to Q6, V12 to V18) is the source for `request_id`; this page matches it, with two notes. Q1's open item is settled by his ruling: a replayed `stale_fork` returns the current card. In V14 a decider's identical body is a `Revision` whose `of` necessarily names the first account's counted answer id (the record shows it to every decider), so "never contains X's answer_id" holds for Y's answer id and document, not for `of` (Heimdall: `of` naming the counted answer is allowed); the vector with an off-list first account pins the case with a `Counted`, which has no `of`.
- `request_id` (on the request and the stored `desk_answer`) and `request_id_conflict` are this page's: his file has no idempotency key, and a retry after `unavailable` needs one. Eureka's `desk_answer` kind and Huginn's request type must carry it.
- Transport: the routes, the `{mind}` segment, the scopes, the audience and the auth order are his rulings (4.1 to 4.3a); the documents (list, read, `unavailable`) are this page's. The note limit is 4000 UTF-8 bytes here, as his 1.1 leaves the unit unsaid.
- The recommendation is never nil. The binding file's earlier vectors D and E used a nil recommendation; its updated D and E use `"a"`, as here.
- Hash vectors: A, B, C, D, E, F and G of the binding file are reproduced digest for digest by the Python generator, the C# suite and the TypeScript suite (the generator prints `same` for each; none differs).
## Open choices
1. Case of field names: snake_case for the fork documents (as the binding file) beside camelCase for the vote documents (as Bifrost's serializer). One convention would be tidier.
2. NFC across runtimes relies on each runtime's normaliser; a pinned table, as `write-receipt.md` does for letters, would remove the reliance. The risk is only for code points assigned after a runtime's Unicode version.
3. How Huginn learns the verified subject: the second door's authenticated context (the peer credential names Bifrost the service, not the member), so the subject must travel beside the request. This contract has no envelope for it.
4. Whether `fork_unknown` and shape refusals should leave an audit record somewhere other than a `desk_answer`.
5. Whether `leans` and `flag`, which the booth shows, should join the hash. The binding file's five members do not include them; a changed lean would not make an answer stale.
6. What the person sees of a retracted counted answer when the next answer counts: this contract only says the count moves.
7. `received_at` is not in the binding file's stored fields; it is kept for `claim_in_future` and could be dropped if the `n<seq>` answer ordinal alone decided answer order.
8. The stamped `authority` field is an attribution, not an authority (above); renaming it `attribution` would say so, at the price of a new key the door must also refuse in a body.
9. The claims Bifrost verifies are PR #24's open item 5. (The audience `bifrost-desk`, the three routes and the scope names are ruled by Heimdall.)
10. The second door's wire between Bifrost and Huginn (pending Eureka's cut spec). `unavailable` is a document of its own, outside the refusal set, so a desk can retry it; calls 1 and 2 use it too when Huginn is down (vectors `huginn_down_*`).
11. While a known Mind's door is down its routes answer `unavailable` (503) and an unknown Mind answers `fork_unknown` (404), so the two are distinguishable for that period. M2 makes them identical only when every door is up; making them identical when one is down means answering `unavailable` for any `{mind}` not on the list, which tells a client nothing about which Minds exist but also hides a typo. Heimdall's to rule; the vectors do not pin it.

View file

@ -0,0 +1,986 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/governance/fork-card.schema.json",
"title": "CultNet fork-desk contract v0",
"description": "A fork card, the answer request a decider sends, the stored desk_answer with its tagged outcome, the result and door refusals returned to the sender, the record a fork keeps, and the ruling citation. Map-mode: every key is written, nil where absent. A request never carries answerer or authority: Huginn stamps both. Rule source: /opt/commons/handoff/fork-desk-answer-binding-20261110.md. Spec: fork-card.md. Vectors: fork-card-vectors.json.",
"$defs": {
"hex64": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"instant": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,7})?Z$"
},
"id": {
"type": "string",
"minLength": 1
},
"answerId": {
"type": "string",
"pattern": "^n[1-9][0-9]*$"
},
"option": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"text"
],
"properties": {
"id": {
"type": "string",
"minLength": 1
},
"text": {
"type": "string",
"minLength": 1
}
}
},
"ref": {
"type": "object",
"additionalProperties": false,
"required": [
"kind",
"id"
],
"properties": {
"kind": {
"type": "string",
"minLength": 1
},
"id": {
"type": "string",
"minLength": 1
}
}
},
"card": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"fork_id",
"title",
"context",
"options",
"recommendation",
"depends",
"leans",
"flag",
"raised_in",
"deciders",
"status",
"ruling",
"ruled_from",
"order",
"options_hash"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.card.v0"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"title": {
"type": "string",
"minLength": 1
},
"context": {
"type": "string"
},
"options": {
"type": "array",
"minItems": 2,
"items": {
"$ref": "#/$defs/option"
}
},
"recommendation": {
"type": "string",
"minLength": 1
},
"depends": {
"type": "array",
"maxItems": 8,
"items": {
"type": "string",
"minLength": 1,
"maxLength": 1000
}
},
"leans": {
"oneOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"flag": {
"oneOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"raised_in": {
"oneOf": [
{
"$ref": "#/$defs/ref"
},
{
"type": "null"
}
]
},
"deciders": {
"type": "array",
"minItems": 1,
"items": {
"type": "string",
"minLength": 1
},
"maxItems": 64
},
"status": {
"enum": [
"open",
"closed"
]
},
"ruling": {
"oneOf": [
{
"type": "string",
"minLength": 1
},
{
"type": "null"
}
]
},
"ruled_from": {
"type": "array",
"items": {
"$ref": "#/$defs/answerId"
}
},
"order": {
"type": "integer",
"minimum": 0
},
"options_hash": {
"$ref": "#/$defs/hex64"
}
}
},
"words": {
"type": "string",
"minLength": 1,
"maxLength": 4000,
"pattern": "^(?![\\t-\\r \\u0085   - 

   ]+$)[\\s\\S]+$",
"description": "At most 4000 UTF-8 bytes, which a schema cannot say: maxLength here counts code points and is only the looser bound (a code point is at least one byte). The byte limit is a rule both suites enforce (fork-card.md, answer_request)."
},
"answerObject": {
"oneOf": [
{
"type": "object",
"additionalProperties": false,
"required": [
"choice",
"note"
],
"properties": {
"choice": {
"$ref": "#/$defs/id"
},
"note": {
"$ref": "#/$defs/words"
}
}
},
{
"type": "object",
"additionalProperties": false,
"required": [
"choice",
"note"
],
"properties": {
"choice": {
"$ref": "#/$defs/id"
},
"note": {
"type": "null"
}
}
},
{
"type": "object",
"additionalProperties": false,
"required": [
"choice",
"note"
],
"properties": {
"choice": {
"type": "null"
},
"note": {
"$ref": "#/$defs/words"
}
}
}
]
},
"answerRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"fork_id",
"options_hash",
"answer",
"retracted",
"retracts",
"answered_at",
"request_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.answer_request.v0"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"answer": {
"oneOf": [
{
"$ref": "#/$defs/answerObject"
},
{
"type": "null"
}
]
},
"retracted": {
"type": "boolean"
},
"retracts": {
"oneOf": [
{
"$ref": "#/$defs/answerId"
},
{
"type": "null"
}
]
},
"answered_at": {
"$ref": "#/$defs/instant"
},
"request_id": {
"$ref": "#/$defs/requestId"
}
}
},
"deskAnswerCounted": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"answer_id",
"fork_id",
"outcome",
"of",
"retracts",
"code",
"options_hash",
"choice",
"note",
"answered_at",
"received_at",
"claim_in_future",
"answerer",
"authority",
"request_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.desk_answer.v0"
},
"answer_id": {
"$ref": "#/$defs/answerId"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"outcome": {
"const": "Counted"
},
"of": {
"type": "null"
},
"retracts": {
"type": "null"
},
"code": {
"type": "null"
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"choice": {
"oneOf": [
{
"$ref": "#/$defs/id"
},
{
"type": "null"
}
]
},
"note": {
"oneOf": [
{
"$ref": "#/$defs/words"
},
{
"type": "null"
}
]
},
"answered_at": {
"$ref": "#/$defs/instant"
},
"received_at": {
"$ref": "#/$defs/instant"
},
"claim_in_future": {
"type": "boolean"
},
"answerer": {
"$ref": "#/$defs/id"
},
"authority": {
"$ref": "#/$defs/id"
},
"request_id": {
"$ref": "#/$defs/requestId"
}
}
},
"deskAnswerRevision": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"answer_id",
"fork_id",
"outcome",
"of",
"retracts",
"code",
"options_hash",
"choice",
"note",
"answered_at",
"received_at",
"claim_in_future",
"answerer",
"authority",
"request_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.desk_answer.v0"
},
"answer_id": {
"$ref": "#/$defs/answerId"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"outcome": {
"const": "Revision"
},
"of": {
"$ref": "#/$defs/answerId"
},
"retracts": {
"type": "null"
},
"code": {
"type": "null"
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"choice": {
"oneOf": [
{
"$ref": "#/$defs/id"
},
{
"type": "null"
}
]
},
"note": {
"oneOf": [
{
"$ref": "#/$defs/words"
},
{
"type": "null"
}
]
},
"answered_at": {
"$ref": "#/$defs/instant"
},
"received_at": {
"$ref": "#/$defs/instant"
},
"claim_in_future": {
"type": "boolean"
},
"answerer": {
"$ref": "#/$defs/id"
},
"authority": {
"$ref": "#/$defs/id"
},
"request_id": {
"$ref": "#/$defs/requestId"
}
}
},
"deskAnswerRetraction": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"answer_id",
"fork_id",
"outcome",
"of",
"retracts",
"code",
"options_hash",
"choice",
"note",
"answered_at",
"received_at",
"claim_in_future",
"answerer",
"authority",
"request_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.desk_answer.v0"
},
"answer_id": {
"$ref": "#/$defs/answerId"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"outcome": {
"const": "Retraction"
},
"of": {
"type": "null"
},
"retracts": {
"$ref": "#/$defs/answerId"
},
"code": {
"type": "null"
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"choice": {
"type": "null"
},
"note": {
"type": "null"
},
"answered_at": {
"$ref": "#/$defs/instant"
},
"received_at": {
"$ref": "#/$defs/instant"
},
"claim_in_future": {
"type": "boolean"
},
"answerer": {
"$ref": "#/$defs/id"
},
"authority": {
"$ref": "#/$defs/id"
},
"request_id": {
"$ref": "#/$defs/requestId"
}
}
},
"deskAnswerRefused": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"answer_id",
"fork_id",
"outcome",
"of",
"retracts",
"code",
"options_hash",
"choice",
"note",
"answered_at",
"received_at",
"claim_in_future",
"answerer",
"authority",
"request_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.desk_answer.v0"
},
"answer_id": {
"$ref": "#/$defs/answerId"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"outcome": {
"const": "Refused"
},
"of": {
"type": "null"
},
"retracts": {
"oneOf": [
{
"$ref": "#/$defs/answerId"
},
{
"type": "null"
}
]
},
"code": {
"enum": [
"stale_fork",
"not_a_decider",
"fork_closed",
"choice_invalid",
"bad_retraction",
"already_retracted"
]
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"choice": {
"oneOf": [
{
"$ref": "#/$defs/id"
},
{
"type": "null"
}
]
},
"note": {
"oneOf": [
{
"$ref": "#/$defs/words"
},
{
"type": "null"
}
]
},
"answered_at": {
"$ref": "#/$defs/instant"
},
"received_at": {
"$ref": "#/$defs/instant"
},
"claim_in_future": {
"type": "boolean"
},
"answerer": {
"$ref": "#/$defs/id"
},
"authority": {
"$ref": "#/$defs/id"
},
"request_id": {
"$ref": "#/$defs/requestId"
}
}
},
"deskAnswer": {
"oneOf": [
{
"$ref": "#/$defs/deskAnswerCounted"
},
{
"$ref": "#/$defs/deskAnswerRevision"
},
{
"$ref": "#/$defs/deskAnswerRetraction"
},
{
"$ref": "#/$defs/deskAnswerRefused"
}
]
},
"answerResult": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"answer",
"card",
"counted_answer_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.answer_result.v0"
},
"answer": {
"$ref": "#/$defs/deskAnswer"
},
"card": {
"oneOf": [
{
"$ref": "#/$defs/card"
},
{
"type": "null"
}
]
},
"counted_answer_id": {
"oneOf": [
{
"$ref": "#/$defs/answerId"
},
{
"type": "null"
}
]
}
}
},
"refusal": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"code",
"error"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.refusal.v0"
},
"code": {
"enum": [
"unauthenticated",
"body_forbidden_field",
"body_unknown_field",
"body_invalid",
"fork_unknown",
"insufficient_scope",
"forbidden",
"request_invalid",
"request_id_conflict"
]
},
"error": {
"type": "string",
"minLength": 1
}
}
},
"record": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"fork_id",
"options_hash",
"counted_answer_id",
"answers"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.record.v0"
},
"fork_id": {
"$ref": "#/$defs/id"
},
"options_hash": {
"$ref": "#/$defs/hex64"
},
"counted_answer_id": {
"oneOf": [
{
"$ref": "#/$defs/answerId"
},
{
"type": "null"
}
]
},
"answers": {
"type": "array",
"items": {
"$ref": "#/$defs/deskAnswer"
}
}
}
},
"rulingCite": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"ruling_id",
"authority",
"answer_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.ruling_cite.v0"
},
"ruling_id": {
"type": "string",
"minLength": 1
},
"authority": {
"type": "string",
"minLength": 1
},
"answer_id": {
"oneOf": [
{
"$ref": "#/$defs/answerId"
},
{
"type": "null"
}
]
}
}
},
"cursor": {
"type": "string",
"pattern": "^c[1-9][0-9]*$",
"description": "Opaque to a client. c<N> means: the cards whose order is below N."
},
"stamp": {
"type": "string",
"pattern": "^s[0-9]+$",
"description": "s<N>, N the receiver's last-seen Huginn admission ordinal for the Mind's desk documents. Two lists with the same stamp are the same state."
},
"listRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"mind",
"status",
"cursor",
"limit"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.list_request.v0"
},
"mind": {
"$ref": "#/$defs/id"
},
"status": {
"oneOf": [
{
"enum": [
"open",
"recorded"
]
},
{
"type": "null"
}
]
},
"cursor": {
"oneOf": [
{
"$ref": "#/$defs/cursor"
},
{
"type": "null"
}
]
},
"limit": {
"type": "integer",
"minimum": 0,
"maximum": 50
}
}
},
"readRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"mind",
"fork_id"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.read_request.v0"
},
"mind": {
"$ref": "#/$defs/id"
},
"fork_id": {
"$ref": "#/$defs/id"
}
}
},
"entry": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"card",
"record"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.entry.v0"
},
"card": {
"$ref": "#/$defs/card"
},
"record": {
"$ref": "#/$defs/record"
}
}
},
"list": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"mind",
"stamp",
"open_count",
"recorded_count",
"forks",
"next_cursor"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.list.v0"
},
"mind": {
"$ref": "#/$defs/id"
},
"stamp": {
"$ref": "#/$defs/stamp"
},
"open_count": {
"type": "integer",
"minimum": 0
},
"recorded_count": {
"type": "integer",
"minimum": 0
},
"forks": {
"type": "array",
"maxItems": 50,
"items": {
"$ref": "#/$defs/entry"
}
},
"next_cursor": {
"oneOf": [
{
"$ref": "#/$defs/cursor"
},
{
"type": "null"
}
]
}
}
},
"unavailable": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"code",
"error",
"retryAfterSeconds"
],
"properties": {
"schemaVersion": {
"const": "gamecult.fork.unavailable.v0"
},
"code": {
"const": "unavailable"
},
"error": {
"type": "string",
"minLength": 1
},
"retryAfterSeconds": {
"oneOf": [
{
"type": "integer",
"minimum": 1
},
{
"type": "null"
}
]
}
},
"description": "The outcome is NOT CONFIRMED: the request may have reached Huginn and been stored before the reply was lost. Retry with the same request_id to learn the outcome."
},
"requestId": {
"type": "string",
"pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
"description": "Set by the client, a lowercase D-format UUID. Bound to the stamped answerer by the first stored answer that carries it."
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,107 @@
# CultNet vote API v0 (specification)
Status: specification, drafted for Heimdall (Bifrost) and a Ratatoskr voting module. No server implements it yet.
Files here: `vote-api.schema.json` (one schema, a `$defs` entry per document), `vote-api-vectors.json`. Conformance suites: `tests/GameCult.Networking.Tests/GovernanceVectorTests.cs` (C#) and `packages/cultnet-ts/test/governance-vectors.test.ts` (TypeScript). The vectors are written by `scripts/gen-governance-vectors.py`.
Facts it rests on: `/opt/commons/handoff/bifrost-browser-voting-facts.md` (Bifrost `416f11a`; `416f11a..276f611` changes four files: a Standard-close concurrency fix in `MotionGovernanceService.cs`, two test files and `docs/deploy-main-to-live.md`; none touches the sealed API, so the facts hold at `276f611`) and Bifrost PR #37 (`docs/ratatoskr-voting-auth.md`, see "PR #37" below).
## Scope
**Which API covers which.** This contract covers **sealed-ballot motions only** (`gamecult.sealed_ballot.v0`). **Standard motions are not covered here.** Bifrost PR #37 also serves them (`PUT /api/votes/motions/{id}/ballot`, a receipt `{motionId, choice, revision, castAtUtc, receiptId}`), and that API is #37's own: this page defines no document for it, and a Standard motion id sent to any exchange below is answered `not_found`. Today Standard motions have no JSON read or cast API at all, no Mind path, and no receipt (open choice 1). The contract names four exchanges and one refusal document:
| exchange | request | response |
|---|---|---|
| motion list | `gamecult.vote.motion_list_request.v0` | `gamecult.vote.motion_list.v0` |
| motion read | `gamecult.vote.motion_read_request.v0` | `gamecult.vote.motion.v0` |
| cast (commit or reveal) | `gamecult.vote.cast.v0` | `gamecult.vote.receipt.v0` |
| any refusal | | `gamecult.vote.refusal.v0` |
Every document is CultNet map-mode: all keys are written, nil where absent, and the schema is closed (`additionalProperties: false`). Instants are RFC 3339 UTC with a `Z` and up to seven fractional digits. Ids are lowercase `D`-format UUIDs. A motion states `highStakes`, a boolean fixed when the motion opens and never changed after (Bifrost PR #37, D2): it is the property that makes a commit demand a fresh sign-in (`reauthentication_required`). The bytes of every document are pinned by `messagePackHex` in the vectors (shortest integers, shortest strings, keys in the order the schema lists them); JSON with the same keys is the xenos-boundary form of the same documents (open choice 4: the wire format).
## Documents
- **motion_list_request**: `{schemaVersion, phase}`; `phase` is `Commit`, `Reveal`, `Closed` or nil for all.
- **motion_list**: `{schemaVersion, motions: [{id, title, round, phase, commitClosesAtUtc, closesAtUtc, highStakes}]}`. **Heimdall must add this endpoint**: Bifrost has no list route for sealed motions today, only fetch-by-id. No pagination in v0 (open choice 2).
- **motion_read_request**: `{schemaVersion, motionId}`.
- **motion**: Bifrost's `SealedMotionState` with its names: `{schemaVersion, id, title, summary, round, priorMotionId, ballotSchema, phase, candidates (two or more), commitClosesAtUtc, closesAtUtc, highStakes, yourVoterId, yourCommitment (a receipt or nil), announcement}`. It never carries a tally, a turnout, or another voter's commitment or ballot (a `tally` key is a negative vector). `yourVoterId` is the voter's `UserAccount.Id`, the `voterUserAccountId` of the commitment.
- **cast**: `{schemaVersion, motionId, verb, commitment, ballot}` with exactly one of two shapes: `verb: "commit"` with a 64-hex `commitment` and `ballot: nil`, or `verb: "reveal"` with `commitment: nil` and a `ballot`. One document for both verbs; today's two routes (`/commit`, `/reveal`) may stay, taking this document as the body, with a `verb` that must match the route (open choice 3).
- **ballot** (inside a reveal): `{schema: "gamecult.sealed_ballot.v0", motionId, round, candidate, reason, salt, persona}`. `candidate` and `reason` are single-line and **already trimmed** (no Unicode White_Space at either end, using the White_Space list of `write-receipt.md`); the contract refuses an untrimmed value rather than trimming it, so the bytes hashed are the bytes sent. **This is a behaviour change Bifrost must make:** it trims `candidate` and `reason` silently on reveal today (facts file section 3c, `SealedBallotService.cs:154, 385-387`), so an untrimmed reveal is accepted and hashed trimmed; under this contract it is `invalid` (open choice 5). `reason` is 1 to 280 characters counted in UTF-16 code units, as Bifrost counts. A JSON Schema `maxLength` counts code points, so the schema alone accepts up to 280 astral characters; both suites add the rule (vectors `cast_reveal_reason_140_astral_280_units` valid, `ballot_reason_141_astral_282_units` refused). `salt` is 32 to 128 lowercase hex. `persona` is `""` for a member and a printable-ASCII, space-free id of at most 64 characters for a Mind.
- **receipt**: Bifrost's `SealedBallotReceipt`: `{schemaVersion, motionId, voterUserAccountId, commitment, revision (>= 1), committedAtUtc, revealed}`. The receipt for a reveal has `revealed: true` and **echoes nothing of the ballot** (no candidate, reason or salt; negative vectors for each).
- **refusal**: `{schemaVersion, code, error, retryAfterSeconds}`; the `code` set is closed:
| code | HTTP | trigger |
|---|---|---|
| `unauthenticated` | 401 | no bearer, or one Heimdall does not know (the API must answer this, not redirect to a sign-in page) |
| `reauthentication_required` | 401 | a commit on a `highStakes` motion with no sign-in fresh enough (#37 D2: `prompt=login`, `max_age`); the voter signs in again at the top level and retries |
| `forbidden` | 403 | authenticated but not an Active member, or a Mind key used on a route it may not call |
| `not_found` | 404 | unknown motion id, a Standard motion id, or a reveal with no prior commit |
| `wrong_phase` | 409 | commit outside Commit, reveal outside Reveal |
| `contended` | 409 | a reveal raced the close fence: send it again |
| `invalid` | 400 | the body fails the schema or an in-document rule (untrimmed text, candidate not in the motion, `round` or `motionId` mismatch, `persona` wrong for the credential) |
| `commitment_mismatch` | 400 | a reveal whose canonical bytes do not hash to the stored commitment |
| `payload_too_large` | 413 | body over 4096 bytes |
| `rate_limited` | 429 | cast rate exceeded, per account; `retryAfterSeconds >= 1`, mirrored in `Retry-After` |
| `held` | 503 | the Ratatoskr voting brake is set (#37 D5): nothing is read or stored while it is |
Each code has a vector (`refusals`), and every failure of the schema has a negative vector (`invalid`).
**Not on Bifrost's member API yet.** The **413 body cap of 4096 bytes** and the **429 per-account cast limit** are not on Bifrost's member sealed API today (facts file sections 3c and 5): both exist only on the Mind intake route (4096 bytes; 30 requests a minute per source address). #37 proposes 30 casts per 10 minutes per account for the member routes (its D6). `reauthentication_required` and `held` are #37 proposals (D2, D5) and exist nowhere in code. All four are spec text until Heimdall builds them.
**Two refusals Bifrost must split first.** Bifrost returns a reveal whose bytes do not hash to the stored commitment as a plain `400` `Invalid` ("The ballot does not match the stored commitment."), the same status and error type as every other bad body, so `commitment_mismatch` and `invalid` are one today. It returns a contended reveal (a race with the close fence, `SealedBallotService.cs:186-189`) as `WrongPhase` `409`, the same type as a reveal outside the Reveal phase, so `contended` and `wrong_phase` are one today. A client cannot tell "send it again" from "too late", or "wrong ballot" from "malformed body", until Bifrost splits each pair.
## Commitment
`commitment = lowercase hex SHA-256 of the UTF-8 bytes of`
gamecult.sealed_ballot.v0 \n {motionId} \n {voterUserAccountId} \n {persona} \n {round} \n {candidate} \n {reason} \n {salt}
with `\n` U+000A, ids in `D` format, `round` in decimal, `persona` empty for a member. This is Bifrost's formula as the code has it (`SealedBallotService.cs:154, 385-387`); `docs/sealed-ballot-motion.md:22-23` omits `{persona}` and is stale. The vectors give the canonical bytes (`canonicalHex`) and the digest for a member, a Mind, non-ASCII text, and a decomposed-versus-precomposed pair (no normalisation: they are different ballots). `pairs` pins what a reveal must match: the right ballot matches; a changed reason, another voter id, or a dropped persona does not, and the answer is `commitment_mismatch`.
## Receipts the voter can check later
A cast returns the receipt. The voter checks it later in two places that must agree byte for byte with it: `motion.yourCommitment` on a motion read (a commit receipt is present from the commit; the revision counts re-commits), and, after close, the `commitment` the result lists for them. The contract adds no receipt id or signature: the receipt is the commitment, its revision and the time (open choice 6).
## Personas
A Persona votes only on sealed motions, through a Mind key (Bifrost binds an Ed25519 public key 1:1 to an Active member account). The ballot's `persona` is the bound persona id and the commitment covers it, so a Mind's ballot cannot be replayed as a member's (`pairs`: dropping the persona does not match). The Mind-intake route today takes a signed `MindEnvelope` anonymously; this contract does not model that envelope, nonce or signature (open choice 7). Standard motions have no Mind path.
## Authentication
On the wire the credential is an opaque `Authorization: Bearer` header. The token route, claims, scopes and audience belong to Heimdall and Bifrost and are not designed here. A request without a usable bearer is answered `unauthenticated` as a typed refusal.
**Auth per route, now and after #37.** Routes are Bifrost's; this contract fixes the documents, not the paths (open choice 3).
| exchange | today (`/api/sealed-motions`, facts file 3c) | after #37 (`/api/votes`) |
|---|---|---|
| motion list | no route | bearer, scope `votes.read` |
| motion read | session cookie + Active member | bearer, scope `votes.read` |
| commit, reveal | session cookie + Active member | bearer, scope `votes.cast`, audience `bifrost-votes`; a high-stakes commit also needs a fresh sign-in |
| Mind cast | anonymous; the Ed25519 signature on a `MindEnvelope` is the credential | unchanged: Minds never use `/api/votes` (#37) |
| open a motion, Mind-key registry | session cookie + moderator | unchanged, cookie only |
Today a member route has **no bearer scheme**: it accepts the host-only `__Host-bifrost_session` cookie and answers an unauthenticated call with a redirect to the sign-in page, not a 401. After #37 `/api/votes` is bearer-only and answers a typed 401. The wire header stays an opaque bearer either way; only Bifrost knows which of the two it is checking.
## PR #37 (Bifrost `docs/ratatoskr-voting-auth.md`, head `447a7cb`)
Checked 2026-11-10 by an Eyes pass over the PR and the schema; conflicts for Heimdall:
1. **Standard motions.** The PR serves them (`PUT /api/votes/motions/{id}/ballot {choice, comment?}`, a receipt `{motionId, choice, revision, castAtUtc, receiptId}`); the contract is sealed-only and answers `not_found` for a Standard id.
2. **Verb model.** The PR keeps `POST .../commit` and `.../reveal` and adds `GET .../result`; the contract has one `cast` document and no result document.
3. **List and read as GET.** The PR names GET routes; the contract's request documents carry a `phase` filter and a `motionId`. The mapping (query string and path) is undefined until Heimdall fixes the routes.
4. **Refusals.** The PR lists 401/403/404/409/429 with `WWW-Authenticate`; the contract adds 400 (`invalid`, `commitment_mismatch`) and 413, and a typed body.
5. **Minds.** The PR says Minds never use `/api/votes` and keeps the anonymous signed `/mind` route; the contract carries `persona` in the ballot and a `forbidden` case for a Mind key on a route it may not call. The PR's token is never a Persona's.
6. **Authority.** The contract's `unauthenticated` says a bearer "Heimdall does not know"; the PR makes Bifrost the OIDC issuer (a second client, scopes `votes.read` and `votes.cast`, audience `bifrost-votes`) and notes that Bifrost OIDC is not live (its D7).
7. **Rate limits.** The PR keys per account (30 casts per 10 minutes); the contract now says per account too, and neither exists on the member API yet (above).
8. **Wire format.** The PR's errors are JSON; the contract's vectors are MessagePack. Nothing settles the media type.
9. **The PR's seven open decisions** (consent for `votes.cast`, re-authentication, no refresh token, grant revocation, a Ratatoskr brake, rate numbers, MAS rollout order) assume nothing the contract contradicts. D2 (re-authentication at cast) is answered yes for sealed commit in this contract: `reauthentication_required`, with `highStakes` fixed at open. D5 (a brake) is `held`.
## Open choices for Heimdall
1. Standard motions in v0 or a v1 (the PR already serves them).
2. Pagination and filters on the list.
3. One `cast` route or the two existing ones; `verb` redundancy.
4. Wire format: MessagePack documents with a JSON export, or JSON only (the PR is JSON).
5. Refuse untrimmed `candidate` and `reason` (this contract) or keep trimming server-side.
6. Whether a receipt should carry an id or a server signature so a voter can prove it to a third party.
7. The Mind path: keep the signed envelope on its own route, or take Mind keys as a bearer credential.
8. `reason` length in UTF-16 code units (as Bifrost) or code points.
9. Whether the result document (`GET .../result`) joins this contract.

View file

@ -0,0 +1,420 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/governance/vote-api.schema.json",
"title": "CultNet vote API v0 (sealed-ballot motions)",
"description": "Typed documents for listing, reading and casting on sealed-ballot motions, and the receipt a cast returns. Map-mode: every key is written, nil where absent. Spec: vote-api.md. Vectors: vote-api-vectors.json.",
"$defs": {
"uuid": {
"type": "string",
"pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
},
"instant": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}(\\.[0-9]{1,7})?Z$"
},
"hex64": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"trimmedLine": {
"type": "string",
"minLength": 1,
"pattern": "^(?![\\t-\\r \\u0085   - 

   ])[^\\n\\r\\u0085

]+(?<![\\t-\\r \\u0085   - 

   ])$"
},
"ballot": {
"type": "object",
"additionalProperties": false,
"required": [
"schema",
"motionId",
"round",
"candidate",
"reason",
"salt",
"persona"
],
"properties": {
"schema": {
"const": "gamecult.sealed_ballot.v0"
},
"motionId": {
"$ref": "#/$defs/uuid"
},
"round": {
"type": "integer",
"minimum": 1
},
"candidate": {
"$ref": "#/$defs/trimmedLine"
},
"reason": {
"type": "string",
"minLength": 1,
"maxLength": 280,
"pattern": "^(?![\\t-\\r \\u0085   - 

   ])[^\\n\\r\\u0085

]+(?<![\\t-\\r \\u0085   - 

   ])$"
},
"salt": {
"type": "string",
"pattern": "^[0-9a-f]{32,128}$"
},
"persona": {
"type": "string",
"pattern": "^[!-~]{0,64}$"
}
}
},
"motionListRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"phase"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.motion_list_request.v0"
},
"phase": {
"oneOf": [
{
"enum": [
"Commit",
"Reveal",
"Closed"
]
},
{
"type": "null"
}
]
}
}
},
"motionListItem": {
"type": "object",
"additionalProperties": false,
"required": [
"id",
"title",
"round",
"phase",
"commitClosesAtUtc",
"closesAtUtc",
"highStakes"
],
"properties": {
"id": {
"$ref": "#/$defs/uuid"
},
"title": {
"type": "string",
"minLength": 1
},
"round": {
"type": "integer",
"minimum": 1
},
"phase": {
"enum": [
"Commit",
"Reveal",
"Closed"
]
},
"commitClosesAtUtc": {
"$ref": "#/$defs/instant"
},
"closesAtUtc": {
"$ref": "#/$defs/instant"
},
"highStakes": {
"type": "boolean",
"description": "Fixed when the motion opens and never changed after: a high-stakes sealed motion needs a fresh sign-in at commit (Bifrost PR #37, D2)."
}
}
},
"motionList": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"motions"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.motion_list.v0"
},
"motions": {
"type": "array",
"items": {
"$ref": "#/$defs/motionListItem"
}
}
}
},
"motionReadRequest": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"motionId"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.motion_read_request.v0"
},
"motionId": {
"$ref": "#/$defs/uuid"
}
}
},
"receipt": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"motionId",
"voterUserAccountId",
"commitment",
"revision",
"committedAtUtc",
"revealed"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.receipt.v0"
},
"motionId": {
"$ref": "#/$defs/uuid"
},
"voterUserAccountId": {
"$ref": "#/$defs/uuid"
},
"commitment": {
"$ref": "#/$defs/hex64"
},
"revision": {
"type": "integer",
"minimum": 1
},
"committedAtUtc": {
"$ref": "#/$defs/instant"
},
"revealed": {
"type": "boolean"
}
}
},
"motion": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"id",
"title",
"summary",
"round",
"priorMotionId",
"ballotSchema",
"phase",
"candidates",
"commitClosesAtUtc",
"closesAtUtc",
"highStakes",
"yourVoterId",
"yourCommitment",
"announcement"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.motion.v0"
},
"id": {
"$ref": "#/$defs/uuid"
},
"title": {
"type": "string",
"minLength": 1
},
"summary": {
"type": "string"
},
"round": {
"type": "integer",
"minimum": 1
},
"priorMotionId": {
"oneOf": [
{
"$ref": "#/$defs/uuid"
},
{
"type": "null"
}
]
},
"ballotSchema": {
"const": "gamecult.sealed_ballot.v0"
},
"phase": {
"enum": [
"Commit",
"Reveal",
"Closed"
]
},
"candidates": {
"type": "array",
"minItems": 2,
"items": {
"$ref": "#/$defs/trimmedLine"
}
},
"commitClosesAtUtc": {
"$ref": "#/$defs/instant"
},
"closesAtUtc": {
"$ref": "#/$defs/instant"
},
"highStakes": {
"type": "boolean",
"description": "Fixed when the motion opens and never changed after: a high-stakes sealed motion needs a fresh sign-in at commit (Bifrost PR #37, D2)."
},
"yourVoterId": {
"$ref": "#/$defs/uuid"
},
"yourCommitment": {
"oneOf": [
{
"$ref": "#/$defs/receipt"
},
{
"type": "null"
}
]
},
"announcement": {
"oneOf": [
{
"type": "string"
},
{
"type": "null"
}
]
}
}
},
"commitCast": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"motionId",
"verb",
"commitment",
"ballot"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.cast.v0"
},
"motionId": {
"$ref": "#/$defs/uuid"
},
"verb": {
"const": "commit"
},
"commitment": {
"$ref": "#/$defs/hex64"
},
"ballot": {
"type": "null"
}
}
},
"revealCast": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"motionId",
"verb",
"commitment",
"ballot"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.cast.v0"
},
"motionId": {
"$ref": "#/$defs/uuid"
},
"verb": {
"const": "reveal"
},
"commitment": {
"type": "null"
},
"ballot": {
"$ref": "#/$defs/ballot"
}
}
},
"cast": {
"oneOf": [
{
"$ref": "#/$defs/commitCast"
},
{
"$ref": "#/$defs/revealCast"
}
]
},
"refusal": {
"type": "object",
"additionalProperties": false,
"required": [
"schemaVersion",
"code",
"error",
"retryAfterSeconds"
],
"properties": {
"schemaVersion": {
"const": "gamecult.vote.refusal.v0"
},
"code": {
"enum": [
"unauthenticated",
"forbidden",
"reauthentication_required",
"not_found",
"wrong_phase",
"contended",
"invalid",
"commitment_mismatch",
"payload_too_large",
"rate_limited",
"held"
]
},
"error": {
"type": "string",
"minLength": 1
},
"retryAfterSeconds": {
"oneOf": [
{
"type": "integer",
"minimum": 1
},
{
"type": "null"
}
]
}
}
}
}
}

View file

@ -0,0 +1,122 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/interop/cultnet.error.v1.schema.json",
"title": "CultNet Error Message v1",
"description": "cultnet.error.v0 plus messageId (write-receipt.md). Sent in place of cultnet.error.v0 only to a connection that declared the write-receipt capability. v0 is unchanged: its schema is closed (additionalProperties false), so an extra key would make a v0 peer reject the frame instead of ignoring it. Map-mode: every key is written, messageId nil when the error answers no readable message. The code enum is the v0 enum plus limit_reached (write-receipt.md, Remembered-write limits).",
"type": "object",
"required": [
"schemaVersion",
"error",
"routingHint",
"code",
"details",
"messageId"
],
"additionalProperties": false,
"properties": {
"schemaVersion": {
"const": "cultnet.error.v1"
},
"error": {
"type": "string",
"minLength": 1
},
"routingHint": {
"description": "Optional shard routing detail for an authority failure. Null for every selection/cursor refusal code (R-N).",
"type": [
"object",
"null"
],
"additionalProperties": false,
"required": [
"shard",
"reason"
],
"properties": {
"shard": {
"type": [
"object",
"null"
]
},
"reason": {
"type": "string"
}
}
},
"code": {
"description": "Machine-readable refusal code (R-N). Additive: a v0 peer that does not know this field ignores it. The set is a closed enum: Rust and TypeScript refuse a message whose code is not listed, so adding a code is one coordinated change across every runtime (this schema, the C# factory, the Rust CultNetErrorCode, and a captured-bytes case for each). limit_reached: a receipt-capable server refuses a NEW write because its per-session remembered-write table (1024 entries) or its server-wide memory budget is full; messageId is the write's id.",
"type": [
"string",
"null"
],
"enum": [
null,
"selection_invalid",
"cursor_stale",
"cursor_invalid",
"reference_outside_target",
"variant_unsupported",
"unowned_schema",
"write_not_authorized",
"unsupported_schema_version",
"message_invalid",
"limit_reached"
]
},
"details": {
"description": "Code-specific structured detail (R-N). Every field is populated only for the code that defines it; the others are null, not omitted.",
"type": [
"object",
"null"
],
"additionalProperties": false,
"required": [
"field",
"value",
"asOf",
"current"
],
"properties": {
"field": {
"description": "selection_invalid: the selection field that failed. variant_unsupported: \"subscriptionId\", when a subscription was ended. unowned_schema: \"schemaId\". write_not_authorized: \"recordKey\". unsupported_schema_version: \"schemaVersion\". message_invalid: the request field that is missing or ill-typed (\"message\" when the whole frame cannot be read). limit_reached: no field; details stay all null. message_invalid also names \"messageId\" (over 256 bytes), \"document\", \"schemaId\" or \"channel\" (write on an unreliable channel).",
"type": [
"string",
"null"
]
},
"value": {
"description": "selection_invalid: the offending value, when there is one string worth naming. variant_unsupported: the id of the subscription that ended. unowned_schema: the schema id no shard owns. write_not_authorized: the key of the refused write. unsupported_schema_version: the schemaVersion the peer does not speak.",
"type": [
"string",
"null"
]
},
"asOf": {
"description": "cursor_stale: the cursor's own minted asOf.",
"type": [
"integer",
"null"
],
"minimum": 0
},
"current": {
"description": "cursor_stale: the answering server's current asOf.",
"type": [
"integer",
"null"
],
"minimum": 0
}
}
},
"messageId": {
"description": "The messageId of the write (or other request) this error answers, echoed byte for byte. Null only when the frame was unreadable or carried no messageId.",
"type": [
"string",
"null"
],
"minLength": 1
}
}
}

View file

@ -0,0 +1,16 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://github.com/GameCult/CultLib/contracts/cultnet/interop/cultnet.write-admitted.schema.json",
"title": "CultNet Write Admitted",
"description": "The receipt for one admitted document put or delete (write-receipt.md). Sent only after the write's commit point, only to a connection that declared the write-receipt capability, once per messageId. Map-mode: every key is written, none is nil. A receipt never carries an error, and an error.v1 never carries admission.",
"type": "object",
"required": ["schemaVersion", "messageId", "operation", "schemaId", "recordKey"],
"additionalProperties": false,
"properties": {
"schemaVersion": { "const": "cultnet.write_admitted.v0" },
"messageId": { "description": "The messageId of the put or delete this admits, echoed byte for byte.", "type": "string", "minLength": 1 },
"operation": { "enum": ["put", "delete"] },
"schemaId": { "description": "The schemaId of the admitted write, echoed.", "type": "string", "minLength": 1 },
"recordKey": { "description": "The recordKey of the admitted write, echoed.", "type": "string", "minLength": 1 }
}
}

View file

@ -145,6 +145,22 @@
"current": null "current": null
} }
} }
},
{
"name": "message_invalid",
"messagePackHex": "85AD736368656D6156657273696F6EB063756C746E65742E6572726F722E7630A56572726F72D93E6D6573736167655F696E76616C69643A2052617720707574206D65737361676573206D75737420636F6E7461696E206120646F63756D656E74206D61702EAB726F7574696E6748696E74C0A4636F6465AF6D6573736167655F696E76616C6964A764657461696C7384A56669656C64A8646F63756D656E74A576616C7565C0A461734F66C0A763757272656E74C0",
"message": {
"schemaVersion": "cultnet.error.v0",
"error": "message_invalid: Raw put messages must contain a document map.",
"routingHint": null,
"code": "message_invalid",
"details": {
"field": "document",
"value": null,
"asOf": null,
"current": null
}
}
} }
] ]
} }

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,89 @@
# CultNet write receipt (specification)
Status: specification. No runtime implements it yet; the conformance follow-ups below do.
Rules: Heimdall's ruling of 2026-11-08 (a write completes on its result frame; an ack or a return is not admission).
Files here: `cultnet.write-admitted.schema.json`, `cultnet.error.v1.schema.json`, `write-receipt-vectors.json`. They move to `contracts/cultnet/` when the first runtime implements them.
## The problem
A put or delete today has two answers on the wire: nothing (admitted, or the server never read it) and `cultnet.error.v0` (refused, with no id saying which write). A transport ack proves delivery. Clients that completed on the ack, or on a window with no refusal, reported refused writes as done (CultLib #55 to #58 bound this with a result window; this spec replaces the window with an answer).
## Frames
**`cultnet.write_admitted.v0`**: `{ schemaVersion, messageId, operation: "put"|"delete", schemaId, recordKey }`, every key written, none nil. Sent once a put or delete is admitted. The id echoes the write's `messageId` byte for byte; `operation`, `schemaId`, `recordKey` echo the write.
**A `write_admitted` `messageId` is valid only if it contains at least one Unicode letter (`\p{L}`) or number (`\p{N}`) and no Default_Ignorable_Code_Point (DerivedCoreProperties).** The compare is raw: the id is echoed byte for byte, so a decoder never trims or normalizes it (`" a "` is valid; U+2800 is not, and neither is `a` followed by U+200B). Unlike the Required fields rule, this is not a White_Space test. The letters, numbers and Default_Ignorable code points are those of **Unicode 16.0** in every runtime, taken from tables embedded in each runtime and generated by `scripts/gen-unicode-messageid-tables.py` from `DerivedGeneralCategory.txt` (Lu Ll Lt Lm Lo Nd Nl No) and `DerivedCoreProperties.txt`; no runtime asks its platform's Unicode data, so a runtime's own Unicode version cannot change a result. Bumping the version is one coordinated change: regenerate the five tables and update the vectors that pin the version in the same commit. The rule is on the decoded string, which must be well-formed Unicode: a lone surrogate refuses. A runtime whose MessagePack reader rejects invalid UTF-8 refuses the frame earlier; byte-level strictness is a property of the reader and is not required of a decoder. A frame with more than one `messageId` key is malformed: a decoder that can see the duplicate (the C# and Rust decoders) refuses it; a decoder that collapses the map (Python, TypeScript, Kotlin) judges the value it ends up with, the last key, and refuses if that value is invalid, so no decoder echoes an invalid id (vectors `admittedMessageIdDuplicates` declare each policy and every runner asserts its own). A decoder refuses an invalid id the way it refuses an empty or ill-typed one; the rule is for `write_admitted` only and `error.v1` is unchanged.
**Where a received `messageId` decides, and what that relies on.** Beyond echoing it, a received `messageId` is used in exactly two places. On a server, the remembered-write key `(actor, messageId)` with the content hash, the per-session limit and the replay of rule 5 are taken from the id of the write frame the server itself parsed. On a client, the write tracker attributes a `write_admitted` or `error.v1` to a write by equality with the id of a write that client itself sent (a frame naming an id not in flight settles nothing), and attributes an id-less error by the count of unanswered writes, not by any id. Both rely on the receiver being the only parser of that frame: a decoder's `messageId` on a frame that carries more than one `messageId` key is not trusted for any authorization, dedupe, replay or ordering decision, and the map-collapsing runtimes (Python, TypeScript, Kotlin, and C#'s typed deserializer on write frames) cannot see the duplicate. If a frame is ever parsed by two runtimes in a chain (a relay, proxy or forwarder that re-reads it), or a consumer needs `messageId` for authorization, dedupe, replay or ordering beyond echo and equality with a self-sent id, all runtimes must first refuse a duplicate `messageId` key (a spec change plus byte-level duplicate detection in the runtimes that decode to a map) before that use lands. Today Rust refuses a repeated key on write frames and on `write_admitted` (serde's `duplicate field messageId`, and `refuse_duplicate_keys` for the raw-list frames such as `document_put_raw`), though its `readable_message_id` names the first key when it names an unreadable frame; C# does not on write frames (a duplicate-key write is deduped on its last id, while the id it names in a refusal for an unreadable frame is read from the first key), and the Python server (`cultmesh_py/server.py`) only echoes the id while the TypeScript and Kotlin code matches it by equality with a request it sent.
**`cultnet.error.v1`**: `cultnet.error.v0` plus a required `messageId` (string or nil). The code enum is v0's plus `limit_reached` (see Remembered-write limits); `cultnet.error.v1.schema.json` is the authority for the closed set. Sent in place of `error.v0` to a receipt-capable connection. `messageId` is the id of the request the error answers; nil only when the frame was unreadable or carried no id.
Why a new error version and not an extra key on v0: the v0 schema is closed (`additionalProperties: false`) and the TypeScript decoder (Ajv over the closed schemas) rejects unknown keys and unknown `schemaVersion`s, and `parseCultNetMessage` throws on an unknown version; Rust's decoder errors on an unknown version too. Unknown-key tolerance of the Rust, Python and Kotlin error decoders was not checked, so none is assumed, so a surprise key or frame breaks an old client's whole receive path. Old clients are therefore never sent either new frame. This reverses the "old clients ignore it" assumption, which is false for today's decoders.
## Capability: opting in
A connection is receipt-capable when its `cultnet.hello.v0` (sent before its first write; the schema channel is reliable and ordered) lists both `cultnet.write_admitted.v0` and `cultnet.error.v1` in `supportedMessageVersions`. A server MUST NOT send either new frame to any other connection, and answers it exactly as before (no receipt, `error.v0`). A receipt-capable server lists both in its own hello, so a client can tell a legacy server from a receipt server that has not answered yet. A client that sends no hello gets legacy behaviour. A server advertises the two frames in its hello only if it implements the receipt rules end to end.
**The capability changes framing only; it never authorizes.** A hello authenticates nothing and grants nothing: who may write, and which keys, is decided by the server from the transport-authenticated actor exactly as without the capability. Declaring the capability never makes a refused write admitted, never widens an actor's authority, and never changes what a write does; it selects only which frame the answer arrives in.
## Server rules
1. **One answer.** For every put or delete on a receipt-capable connection the server sends exactly one of `write_admitted` or `error.v1`, carrying that write's `messageId`. Never both, never two different answers.
2. **After the commit point.** `write_admitted` is sent only after the write is committed by the same rule that makes it visible to readers. Receipt of the bytes, parse, or authorisation alone is not admission.
3. **Id on every refusal.** Every refusal of a write, whatever its code (`write_not_authorized`, `message_invalid`, `unowned_schema`, `unsupported_schema_version`, shard authority errors, ...), is an `error.v1` whose `messageId` is the write's id. When the frame is readable enough to find the id, it is found; `message_invalid` for a missing or ill-typed field still carries the id. Nil only when no id can be read.
4. **Batches.** There is no batch frame; a batch is N writes, each with its own `messageId`, each answered under rules 1 to 3. A failed batch names its member by that id. A server may not collapse a batch into one answer.
5. **Identity and idempotent resend.** A `messageId` is unique per authenticated actor and session: the client mints it, never reuses it for different content in that session, and a server never accepts the id of one actor as the id of another. The server's dedupe key is `(actor, messageId)`, where *actor* is the transport-authenticated identity, never a name the hello or the frame claims. Alongside the key it keeps the **content hash** of the write and the answer it gave. The content hash is SHA-256 of the MessagePack array `[operation, schemaId, recordKey, payload]`, where `payload` is the raw document payload as a MessagePack `bin` for a put and nil for a delete (the vectors give worked hashes). **Scope: at least the session.** The key lives for the life of the session it was made in, and a server may bound how many writes it remembers per session (see Remembered-write limits; a server never forgets an id it promised to answer). A server MAY keep the key longer for the same actor, up to `DEDUPE_RETENTION_MS` (10 minutes), but a client MUST NOT rely on it: **a reconnect is a new session, and a resend on the new session is a new write.**
- Same key, same content hash, answer was `write_admitted`: answer `write_admitted` again with the same body. The write is not applied twice.
- Same key, same content hash, answer was a refusal: the same refusal again.
- **Same key, different content hash: refuse `message_invalid` (details `field: "messageId"`) and never re-send the old receipt.** Old receipts are for the old content; showing one for new content would report an unapplied write as admitted. The original write's state is unchanged.
- **Id size.** A write's `messageId` is at most 256 bytes of UTF-8. A longer id is refused `message_invalid` (`details.field: "messageId"`, the refusal's `messageId` the id as received, text fixed per Fixed texts) BEFORE anything is remembered: no table entry, no digest, no budget charge. Such a refusal is therefore not replayed from the table; a resend is refused afresh, identically.
- **What is remembered.** Per entry a server keeps only fixed-size digests (SHA-256) of the `messageId` and of the content hash, plus the answer (`admitted`, or the refusal's code and details). Memory per entry is bounded independent of id length and payload size. Lookup compares digests.
- **Remembered-write limits.** The per-session table holds at most 1024 entries. A server MAY also enforce a server-wide memory budget across all sessions (reference: 32 MiB of remembered entries). A NEW write (a key not already in the table) that would exceed either bound is refused `limit_reached` for that write alone, `messageId` the write's id, `details` all null; the write is not applied and the session continues. A resend of a remembered key is still answered from the table.
- **Limit refusals are remembered.** A `limit_reached` refusal is remembered like any other: a resend of the same id and content hash replays `limit_reached`. No slot is freed mid-session, so an id refused at a bound never becomes admitted later in that session (a server at the cap keeps the refused digest pair in a bounded refusal set of at most 1024 per session, outside the entry budget; past it, a further new write is refused `limit_reached` without being remembered, and the session refuses every id it has not seen for the rest of its life, even if a server-wide budget has since freed, so a refusal that was not remembered is never followed by an admission of the same id). The client mints a new id on a new session.
- **Required fields.** A put or delete whose document or `schemaId` is null or missing is refused `message_invalid` with `details.field` `"document"` or `"schemaId"` (the first missing in that order) and fixed text; the write is not applied. A put or delete that is present but names nothing is not "missing": the write is refused `message_invalid` exactly as a frame that does not read, with `details.field` `"message"`, the fixed unreadable text and the write's id (vector `error_v1_empty_schema_id_is_unreadable_and_names_the_write`), and is never applied; a server must not hand it to its store. Names nothing means, on a put or delete, a `schemaId` or `recordKey` that is blank; on a put's document, also a `storedAt` that is blank, a `payload` of zero bytes (a MessagePack value is at least one byte, so an empty payload is no document), a `sourceRuntimeId`, `sourceAgentId` or `sourceRole` that is present and blank, and a `tags` entry that is blank. **Blank** means empty or made only of Unicode White_Space code points (the PropList property) and nothing else, in every runtime, whatever its platform's own whitespace test says. The set is exactly U+0009 to U+000D, U+0020, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F and U+3000. U+200B, U+200C, U+200D, U+2060, U+FEFF, U+180E and U+001C to U+001F are not White_Space (some platforms' whitespace tests accept U+001C to U+001F or U+180E, for example Java's `Character.isWhitespace` and older .NET, so a runtime must check the list, not its platform test): a string of them names something. The vectors list both sets (`whiteSpaceCodePoints`, `notWhiteSpaceCodePoints`) and a runtime checks every code point in every covered field. Absent or nil source ids and tags, and an empty `tags` list, are valid. The rule holds on every connection, receipt-capable or not (a legacy connection is refused with the `error.v0` of the same code, details and text); the vectors' `blankFields` section lists each case.
- **Fixed texts.** The `error` string of these refusals is fixed, so vectors can compare it: `message_invalid: messageId exceeds 256 bytes`, `message_invalid: document is required`, `message_invalid: schemaId is required`, `message_invalid: the message could not be read` (a frame that does not decode, or a write that names nothing; the text is the same for both and never carries a decoder's own wording), `message_invalid: receipt sessions require the reliable channel`, `limit_reached: the session's remembered-write limit is full`.
- **Reliable channel only.** A write is accepted on a receipt session only on a channel that is reliable and not sequenced (reliable ordered and reliable unordered both qualify; a sequenced channel drops superseded packets, so a write on it can vanish without trace). A write arriving on any other channel is refused `message_invalid` with `details.field: "channel"` (the transport profile's word for it) and fixed text. Receipts and refusals travel the reliable channel; a write that could be lost without trace cannot be answered once. The server refuses a sequenced write whenever it can read the write's id: from the delivered frame, and from a superseded packet that carries its whole frame. A write sent as several fragments whose frame is superseded is dropped whole and may go unanswered; the client's unconfirmed outcome covers it. A repeat of a packet the server already took, or a packet too far ahead to be taken, draws no further answer (rule 1).
- Past the session (or a server's longer retention, if it keeps one) a resend is a new write.
6. **Forwarded writes.** A server that forwards a non-primary write answers the original peer only with what the primary answered: the primary's receipt becomes `write_admitted` with the original id, its refusal becomes `error.v1` with the original id. If the forward gets no answer the server relays nothing: no receipt, no error, no synthesized refusal. The client's own rule below then reports the write as unconfirmed. A forwarder never turns an absent or ambiguous primary answer into an admission.
7. **Looks alike.** An admitted and a refused write differ in `schemaVersion`; a receipt has no `error`, an `error.v1` has no admission. A transport ack is neither.
## Client rules: three outcomes
A write settles as exactly one of:
- **admitted**: a `write_admitted` whose `messageId` is the write's.
- **refused**: an `error.v1` whose `messageId` is the write's, carrying its `code` and `details` as the typed error.
- **unconfirmed**: nothing settled it. Reasons: `window_elapsed` (the result window ran from the *send* and passed with no answer; see Result window), `session_ended` (the peer closed the session, or it ended, before the write was answered; a write registered after the session ended settles this way when it is sent) and `local_send_failed` (the client's own send of this write failed). A local send failure is never reported as refused: no server answer exists, and the write may or may not have left the machine. Unconfirmed is not success and not refusal. APIs that return a value return the tri-state; APIs that throw throw a distinct refused error and a distinct unconfirmed error and return normally only for admitted. A caller that needs admission treats unconfirmed as not admitted. Resend with the same `messageId` and unchanged content, **on the same session**, is safe against a receipt-capable server (rule 5). After a reconnect the resend is a new write, and a legacy server may apply a resend twice: the caller resends only writes that are idempotent by record key (a put of the same content to the same key, a delete of a key), and reads the record back before resending any other.
**Result window.** Two named constants (also in the vectors): `RECEIPT_RESULT_WINDOW_MS = 5000`, the default against a receipt-capable server (its hello lists both frames); `LEGACY_RESULT_WINDOW_MS = 500`, used only as the fallback against a server whose hello does not list them (or that sent none). The window runs from the send. It ends when the write's age reaches it: an answer arriving at exactly that instant is late. A receipt-capable server that has not answered within its window is reported as unconfirmed like any other; clients log it as a server that missed its window.
**Late answers.** An answer for a write that already settled `unconfirmed` does not change what the caller was told, but the client records it on the write: a late `write_admitted` makes the write's recorded state `admitted_late`, a late refusal makes it `refused_late`. The write handle exposes that state, and a caller that got `unconfirmed` MUST consult it (and the record) before resending: it must not blind-resend a write that was admitted late. A resend on the same session with the same id and content is harmless on a receipt-capable server (rule 5); across a reconnect the caller follows the idempotence rule above.
**Legacy answers.** An `error.v0`, or an `error.v1` with nil `messageId`, names no write. It is attributed to a write only when exactly one write on the connection is unanswered; it then refuses that write. With two or more unanswered writes it settles none of them and each ends unconfirmed at its window. A frame naming a `messageId` that is not in flight settles nothing.
**Batches can commit partially.** A batch is N independent writes with no atomicity: some members may be admitted while others are refused or unanswered, and nothing is rolled back. The client reports each member's outcome and a batch result is only their set: admitted if every member is admitted, refused if any member is refused (naming the members), otherwise unconfirmed (naming the unanswered members). The caller owns retry: it resends exactly the members that are not admitted, with their original ids.
## Changes to what #55 to #58 shipped
Those clients complete *successfully* when the window ends with no refusal. Under this spec that case is `unconfirmed`. The TypeScript one-shot writer (#62) already reports it so: it resolves `admitted` only on a `write_admitted` carrying the put's id, and no other frame, a put echoed under the same id included, ever counts as admission. A caller whose server cannot answer a write yet (Odin, until it is receipt-capable) opts into the explicit send-only mode per call (`sendOnly: true`), which resolves the distinct outcome `sent` once the transport has acknowledged the put and never `admitted`. The Idunn presence publisher is send-only by its own function (`sendPresenceDocument`, not the `sendOnly` option): the same `sent` result, plus a rejection if a refusal naming the put (or naming nothing) arrives by the transport ack. Receipts and send-only are both opt-in, neither is the default. The C# and Rust clients of #55 to #58 keep the window-success until their conformance work lands, and callers of those must not read it as admission.
## Vectors
`write-receipt-vectors.json`: `constants` (the named windows and retention), `contentHash` (worked dedupe hashes), `dedupe` (server replay cases for rule 5), `wire` (MessagePack hex plus the decoded message for each new frame; the bytes are spec-authored with msgpack-python and every runtime's first conformance PR re-captures them with its own encoder and must match), `schemaInvalid` (frames that must be refused by a validator, each with why), and `blankFields` (server input cases for the Required fields rule: which document fields make a put unreadable, which are accepted), `admittedMessageId` (the `write_admitted` id rule above: code-point lists, each marked refuse or accept; a lone surrogate, and a frame that repeats the key, are carried as whole frames in `wireHex`, because a lone surrogate is not valid UTF-8 and only some runtimes' strings can hold it; `write-admitted-message-id-ranges.json` lists every range of the embedded tables, and each runtime probes the first and last point of each range and the points either side), `scenarios` (event replays with the outcome each write must settle as; the clock is abstract; each case names its window constant). A conformant client passes every scenario; a conformant server's answers for the same inputs satisfy server rules 1 to 7.
## Conformance status
| Server class | Advertises both frames | Server-wide memory budget (MAY, Remembered-write limits) |
|---|---|---|
| `CultNetDatabaseServer` | yes | not implemented: only the per-session limit of 1024 applies |
| Shard write forwarder | yes | not implemented: only the per-session limit of 1024 applies |
| Rust RUDP document server | yes | implemented (32 MiB default, `max_remembered_write_bytes`) |
| C# RUDP schema server (`CultNetRudpSchemaServer`, `src/GameCult.Networking/CultNetRudpSchemaServer.cs`) | no | n/a |
Advertising is per server class, not per transport. A class advertises both frames in its hello only if it implements the receipt rules end to end; the C# RUDP schema server stays "no" until it answers writes with receipts.
Cross-runtime check: `packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts` (`npm run test:interop` in `packages/cultmesh-ts`) runs the TypeScript client (`WriteTracker`, the decoder, the one-shot writer) against the real Rust RUDP document server and the real `CultNetDatabaseServer` over loopback, one scenario set against both. Known gap it records as a todo: the Rust RUDP document server refuses every delete (`write_not_authorized: the server does not take deletes`), where this spec has an admitted delete receipted like a put.
## Conformance follow-ups (not in this PR)
C# server and client, Rust, TypeScript, Python, Kotlin: emit and parse the two frames; hello capability; tri-state client outcome; replace the #55 to #58 window-success; re-capture the wire vectors in each runtime. Server write paths include the shard write forwarder (rule 6) and the Odin catalog.

View file

@ -34,7 +34,7 @@ ran under the session scratchpad (`imagination/`), not in the repo.
| F13 | Cross-process precedent for C# against a Node provider exists. `packages/cultnet-ts/test/interop/cultnet-interop.test.ts:536-560` spawns the TS QUIC provider, then runs `dotnet test --filter NativeConnectorReceivesFromExternalProvider` with the endpoint in `CULTMESH_NATIVE_EXTERNAL_ENDPOINT`. The C# test skips without the variable (`tests/GameCult.Mesh.Quic.Native.Tests`, line 21). | source | | F13 | Cross-process precedent for C# against a Node provider exists. `packages/cultnet-ts/test/interop/cultnet-interop.test.ts:536-560` spawns the TS QUIC provider, then runs `dotnet test --filter NativeConnectorReceivesFromExternalProvider` with the endpoint in `CULTMESH_NATIVE_EXTERNAL_ENDPOINT`. The C# test skips without the variable (`tests/GameCult.Mesh.Quic.Native.Tests`, line 21). | source |
| F14 | `cultnet-ts` is CommonJS. Its `./wire`, `./contracts` and `./authority` subpaths import only `@msgpack/msgpack`, `ajv` and `cultcache-ts/document`, so they are browser-safe. Its root `index` pulls `node:` modules (`peer`, `rudp`, `transport`, `security` and others). `cultmesh-browser` (ESM) already imports `cultnet-ts/wire`, `/contracts` and `/authority`. `cultmesh-ts` loads `koffi` lazily, inside a function (`realtime-quic-native.ts:139`), so a new subpath of it pays no native load. The root has `esbuild` ^0.28.1 as a devDependency. | source, grep | | F14 | `cultnet-ts` is CommonJS. Its `./wire`, `./contracts` and `./authority` subpaths import only `@msgpack/msgpack`, `ajv` and `cultcache-ts/document`, so they are browser-safe. Its root `index` pulls `node:` modules (`peer`, `rudp`, `transport`, `security` and others). `cultmesh-browser` (ESM) already imports `cultnet-ts/wire`, `/contracts` and `/authority`. `cultmesh-ts` loads `koffi` lazily, inside a function (`realtime-quic-native.ts:139`), so a new subpath of it pays no native load. The root has `esbuild` ^0.28.1 as a devDependency. | source, grep |
| F15 | TS packages build with `tsc` and test with `node --test dist-test/test/*.test.js` per workspace. `scripts/run-typescript-workspaces.mjs` runs them in order `cultcache-ts, cultnet-ts, cultmesh-ts, cultmesh-browser`, after `check-typescript-tests-wired.mjs`. No StrykerJS config exists in CultLib (`docs/mutation-testing.md:156-159`). | source | | F15 | TS packages build with `tsc` and test with `node --test dist-test/test/*.test.js` per workspace. `scripts/run-typescript-workspaces.mjs` runs them in order `cultcache-ts, cultnet-ts, cultmesh-ts, cultmesh-browser`, after `check-typescript-tests-wired.mjs`. No StrykerJS config exists in CultLib (`docs/mutation-testing.md:156-159`). | source |
| F16 | **No CultLib TS package except `cultcache-ts` has a publish job.** `publish-packages.yml` triggers on `cultcache-ts-v*`, `cultcache-py-v*`, `cultnet-py-v*` and `cultmesh-py-v*` only. Tags `cultnet-ts-v0.1.1` and `cultmesh-ts-v0.1.1` exist, but no workflow consumes them. `npm view` returns 404 anonymously for `cultnet-ts`, `cultmesh-ts`, `cultmesh-browser` and even `@gamecult/cultcache-ts` (`@gamecult/cultcache-ts` may be private; unverified). The doctrine's rule of at most three tags per push stands (SKILL.md:674). | source; `npm view` | | F16 | **No CultLib TS package except `cultcache-ts` has a publish job.** `publish-packages.yml` triggered on `cultcache-ts-v*`, `cultcache-py-v*`, `cultnet-py-v*` and `cultmesh-py-v*` when this was written; it now triggers on the three `-py-v*` patterns only, because npm publishing is deliberately off until ruled on (a tag run uses the workflow at the tagged commit, so `cultcache-ts-v0.15.0` on `7d292085`, before that change, still ran the old one). Tags `cultnet-ts-v0.1.1` and `cultmesh-ts-v0.1.1` exist, but no workflow consumes them. `npm view` returned 404 anonymously on 2026-11-08 for `cultnet-ts`, `cultmesh-ts`, `cultmesh-browser` and even `@gamecult/cultcache-ts` (`@gamecult/cultcache-ts` may be private; unverified). The doctrine's rule of at most three tags per push stands (SKILL.md:674). | source; `npm view` |
| F17 | StreamPixels consumes CultLib as the git submodule `vendor/CultLib` (gitlink `30ee8b97`) with `file:` deps and `pnpm.overrides`. Its CI and Idunn recipes build the vendored workspaces (`npm ci --ignore-scripts`, then build `cultcache-ts`, `cultnet-ts` and `cultmesh-ts`). `apps/web` depends only on `cultnet-ts` today, not on `cultmesh-browser`. | StreamPixels `.gitmodules`, `apps/*/package.json`, CI workflow lines 62-95 | | F17 | StreamPixels consumes CultLib as the git submodule `vendor/CultLib` (gitlink `30ee8b97`) with `file:` deps and `pnpm.overrides`. Its CI and Idunn recipes build the vendored workspaces (`npm ci --ignore-scripts`, then build `cultcache-ts`, `cultnet-ts` and `cultmesh-ts`). `apps/web` depends only on `cultnet-ts` today, not on `cultmesh-browser`. | StreamPixels `.gitmodules`, `apps/*/package.json`, CI workflow lines 62-95 |
| F18 | The Rust reader sets two guards that the TS reader should match. A caller cap `max_bytes` is checked before any request. And a zero-size chunk is refused unless it is the only one, because a manifest of zero-size chunks would be a request flood. | source `cultnet-rs/src/content.rs:364-385` | | F18 | The Rust reader sets two guards that the TS reader should match. A caller cap `max_bytes` is checked before any request. And a zero-size chunk is refused unless it is the only one, because a manifest of zero-size chunks would be a request flood. | source `cultnet-rs/src/content.rs:364-385` |
| F19 | `BuildChunkUri` on more endpoint shapes, as `AbsoluteUri` (what `HttpClient` sends). `https://h` and `https://h/` both give `https://h/?chunkHash=…&recordKey=k`. `https://h:443/x` drops the default port. `https://H.Example/X/` lowercases the host and keeps the path's case. `https://h/x#frag` keeps the fragment after the query. `https://h/x?a=%20b+c` keeps the existing query verbatim and joins with `&`. **`https://h/x?` (an empty query) gives `https://h/x?&chunkHash=…`**, because `UriBuilder.Query` is `?`, which is not blank. `https://[::1]:8443/c` keeps the bracketed host. `Uri.EscapeDataString("!'()*~-._ +é𐐀")` is `%21%27%28%29%2A~-._%20%2B%C3%A9%F0%90%90%80`: unlike JS `encodeURIComponent`, it escapes `!'()*`. | probe: `dotnet fsi` on .NET 10, the three lines of `BuildChunkUri` (`CultMeshHttpsContentTransport.cs:114-122`) copied verbatim | | F19 | `BuildChunkUri` on more endpoint shapes, as `AbsoluteUri` (what `HttpClient` sends). `https://h` and `https://h/` both give `https://h/?chunkHash=…&recordKey=k`. `https://h:443/x` drops the default port. `https://H.Example/X/` lowercases the host and keeps the path's case. `https://h/x#frag` keeps the fragment after the query. `https://h/x?a=%20b+c` keeps the existing query verbatim and joins with `&`. **`https://h/x?` (an empty query) gives `https://h/x?&chunkHash=…`**, because `UriBuilder.Query` is `?`, which is not blank. `https://[::1]:8443/c` keeps the bracketed host. `Uri.EscapeDataString("!'()*~-._ +é𐐀")` is `%21%27%28%29%2A~-._%20%2B%C3%A9%F0%90%90%80`: unlike JS `encodeURIComponent`, it escapes `!'()*`. | probe: `dotnet fsi` on .NET 10, the three lines of `BuildChunkUri` (`CultMeshHttpsContentTransport.cs:114-122`) copied verbatim |
@ -276,11 +276,10 @@ remains:
history (Keep a Changelog headings). history (Keep a Changelog headings).
- A Soul pass over the release diff, then four tags: `cultcache-ts-v…`, - A Soul pass over the release diff, then four tags: `cultcache-ts-v…`,
`cultnet-ts-v0.3.0`, `cultmesh-ts-v0.2.0` and `cultmesh-browser-v0.4.0`. `cultnet-ts-v0.3.0`, `cultmesh-ts-v0.2.0` and `cultmesh-browser-v0.4.0`.
These go in **two pushes** (at most three tags per push, SKILL.md): These go in **two pushes** (at most three tags per push, SKILL.md). No
`cultcache-ts` first, because its tag triggers `publish-packages.yml` `-ts-v*` tag triggers `publish-packages.yml` on main (F16), so these tags
(F16), and the three plane tags second. Whether the `cultcache-ts` tag's publish nothing;
npm publish job still runs, and to where, is checked before that push; follow-up `npm-publish-ts-packages` owns npm publishing.
follow-up `npm-publish-ts-packages` owns the rest.
- The consumer's pickup (StreamPixels bumping `vendor/CultLib` to the - The consumer's pickup (StreamPixels bumping `vendor/CultLib` to the
tagged commit) is StreamPixels' B-cuts, not this campaign. tagged commit) is StreamPixels' B-cuts, not this campaign.
- Size: about 60 lines of version and CHANGELOG text; a short Hands pass. - Size: about 60 lines of version and CHANGELOG text; a short Hands pass.

View file

@ -441,8 +441,8 @@ consumer that waits wants delivered, which is now just Acknowledged.
| `cultmesh-rs/src/lib.rs:781-838` `request_raw_snapshot_from_rudp_catalog` (Idunn `src/drivers.rs:5527` uses it) | a hand-rolled loop until `Acknowledged`, then the response | Cut 4: `wait_acknowledged` | | `cultmesh-rs/src/lib.rs:781-838` `request_raw_snapshot_from_rudp_catalog` (Idunn `src/drivers.rs:5527` uses it) | a hand-rolled loop until `Acknowledged`, then the response | Cut 4: `wait_acknowledged` |
| `cultmesh-rs/src/lib.rs:870-900` `publish_cultnet_message_to_rudp_catalog` (Odin `odin-daemon`) | a hand-rolled loop until `Acknowledged`, then disconnect. The doc at `:869` claims "application admission" | Cut 4: `wait_acknowledged`; the doc says delivered to the document server's sink (`rudp_document_server.rs:343-372`) | | `cultmesh-rs/src/lib.rs:870-900` `publish_cultnet_message_to_rudp_catalog` (Odin `odin-daemon`) | a hand-rolled loop until `Acknowledged`, then disconnect. The doc at `:869` claims "application admission" | Cut 4: `wait_acknowledged`; the doc says delivered to the document server's sink (`rudp_document_server.rs:343-372`) |
| `cultmesh-rs/src/lib.rs:918-938` `publish_cultnet_messages_to_rudp_catalog` (Ghostlight `mesh.rs:323`) | `flush_reliable`, then drop. **Several ordered frames, then close** | None; flush now means it | | `cultmesh-rs/src/lib.rs:918-938` `publish_cultnet_messages_to_rudp_catalog` (Ghostlight `mesh.rs:323`) | `flush_reliable`, then drop. **Several ordered frames, then close** | None; flush now means it |
| `cultmesh-ts/src/index.ts:6070-6098` `publishRudpDocumentOnce` (Heimdall, StreamPixels, Stonks, weksa, Bifrost, VoidBot, Hermodr) | `peer.flush` (`cultnet-ts/src/peer.ts:109-110`), then close | None. Cut 5 moves its connect-and-wait helper (`index.ts:6603-6650`) into cultnet-ts | | `cultmesh-ts/src/index.ts:6211-6303` `publishRudpDocumentOnce` (Heimdall, StreamPixels, Stonks, weksa, Bifrost, VoidBot, Hermodr) | `peer.flush` (`cultnet-ts/src/peer.ts:109-110`), then close | None. Cut 5 moves its connect-and-wait helper (`index.ts:6603-6650`) into cultnet-ts |
| `cultnet-ts/src/idunn-odin-presence-publisher.ts:89-215` `publishDocument`, behind `createIdunnRuntimePresencePublisher`. **StreamPixels' service runs this**: `apps/service/scripts/idunn-entry.mjs` runs `deployment/idunn/runtime-presence.mjs`, which calls `createIdunnRuntimePresencePublisher` (`:46`) from its vendored CultLib `542ddd3` (StreamPixels `a49f7d8`; pass 2's `30ee8b9` is stale), where it lives under its older name `cultnet-ts/src/idunn-runtime-authority.ts:206` | a hand-rolled session loop (`:186-208`) until `outstandingReliablePacketCount === 0`. It does resend (`:205`). It drops `readyToSend` (`:198`), so promoted queued packets wait for the resend timer. It pins `initialSequence: 1` (`:103`) and never sends a Disconnect, so Odin's hub keeps each publish's peer until it times out (each publish binds a new port, so each is a new peer) | Cut 5: the socket transport, `connectAndWait`, `send("schema")`, `flush`, `close` (which sends the Disconnect, `rudp.ts:956-969`) | | `cultnet-ts/src/idunn-odin-presence-publisher.ts:97-136` `sendPresenceDocument` (formerly `publishDocument`), behind `createIdunnRuntimePresencePublisher`. **StreamPixels' service runs this**: `apps/service/scripts/idunn-entry.mjs` runs `deployment/idunn/runtime-presence.mjs`, which calls `createIdunnRuntimePresencePublisher` (`:46`) from its vendored CultLib `542ddd3` (StreamPixels `a49f7d8`; pass 2's `30ee8b9` is stale), where it lives under its older name `cultnet-ts/src/idunn-runtime-authority.ts:206` | a hand-rolled session loop (`:186-208`) until `outstandingReliablePacketCount === 0`. It does resend (`:205`). It drops `readyToSend` (`:198`), so promoted queued packets wait for the resend timer. It pins `initialSequence: 1` (`:103`) and never sends a Disconnect, so Odin's hub keeps each publish's peer until it times out (each publish binds a new port, so each is a new peer) | Cut 5: the socket transport, `connectAndWait`, `send("schema")`, `flush`, `close` (which sends the Disconnect, `rudp.ts:956-969`) |
| `cultnet-ts/src/signed-daemon-health.ts:104-162` `publishSignedDaemonHealth` (Hermodr, Odin `idunn-rudp.cjs`) | a hand-rolled loop: sends the packets `sendMany` admitted, waits up to 500 ms for the **first** Ack packet of any content (`:146-153`), swallows the timeout, closes. Resends run inside that wait (`:303`) but promoted queued packets are never sent | Cut 5, as above. Today a write not acked within 500 ms, or any payload over 32 packets, is reported published | | `cultnet-ts/src/signed-daemon-health.ts:104-162` `publishSignedDaemonHealth` (Hermodr, Odin `idunn-rudp.cjs`) | a hand-rolled loop: sends the packets `sendMany` admitted, waits up to 500 ms for the **first** Ack packet of any content (`:146-153`), swallows the timeout, closes. Resends run inside that wait (`:303`) but promoted queued packets are never sent | Cut 5, as above. Today a write not acked within 500 ms, or any payload over 32 packets, is reported published |
| `cultnet-ts/src/operation-service.ts` | the operation response | none (the response is the proof) | | `cultnet-ts/src/operation-service.ts` | the operation response | none (the response is the proof) |
| C# `FlushReliable` callers: Gjallar `Program.cs:3055-3080` (two ordered frames, flush, dispose) | flush | None | | C# `FlushReliable` callers: Gjallar `Program.cs:3055-3080` (two ordered frames, flush, dispose) | flush | None |

View file

@ -26,7 +26,7 @@ caught before it ships instead of written up afterward.
| `org.gamecult.cultlib` | Unity UPM | `scripts/build-unity-package.ps1`, consumed by git tag | | `org.gamecult.cultlib` | Unity UPM | `scripts/build-unity-package.ps1`, consumed by git tag |
| `org.gamecult.caching.unity` | Unity UPM | tagged directly (no build script; see "Coverage gaps") | | `org.gamecult.caching.unity` | Unity UPM | tagged directly (no build script; see "Coverage gaps") |
| `org.gamecult.cultmath` | Unity UPM | `packages/cultmath/scripts/build-unity-package.ps1`, consumed by git tag | | `org.gamecult.cultmath` | Unity UPM | `packages/cultmath/scripts/build-unity-package.ps1`, consumed by git tag |
| `@gamecult/cultcache-ts` | npm | `.github/workflows/publish-packages.yml` | | `@gamecult/cultcache-ts` | npm | `.github/workflows/publish-packages.yml`, `workflow_dispatch` only; npm publishing is off (see "Coverage gaps") |
| `cultcache-py` | PyPI | `.github/workflows/publish-packages.yml` | | `cultcache-py` | PyPI | `.github/workflows/publish-packages.yml` |
| `cultnet-py` | PyPI | `.github/workflows/publish-packages.yml` | | `cultnet-py` | PyPI | `.github/workflows/publish-packages.yml` |
| `cultmesh-py` | PyPI | `.github/workflows/publish-packages.yml` | | `cultmesh-py` | PyPI | `.github/workflows/publish-packages.yml` |
@ -198,8 +198,8 @@ or a missing declaration refuses), and:
proof: with no tag of its own prefix it is a first release. The suite test proof: with no tag of its own prefix it is a first release. The suite test
that pins every declared prefix guards it: each prefix is declared once, each that pins every declared prefix guards it: each prefix is declared once, each
workflow tag trigger must be a declared prefix, and each such package's prefix workflow tag trigger must be a declared prefix, and each such package's prefix
must be a workflow trigger or, for the Caching Unity package the workflow does must be a workflow trigger or, for a package the workflow does not tag-trigger
not build, the prefix of tags that hold its own manifest at the tag's own (the Caching Unity package, `cultcache-ts`), the prefix of tags that hold its own manifest at the tag's own
version, so a typo or a copied prefix fails the suite. Nothing releases version, so a typo or a copied prefix fails the suite. Nothing releases
without the suite passing; see below for how each release path runs it. without the suite passing; see below for how each release path runs it.
Releases run from a full clone with every tag (`fetch-depth: 0` in CI), the Releases run from a full clone with every tag (`fetch-depth: 0` in CI), the
@ -352,10 +352,40 @@ own path into the DLL. No `global.json` pins the .NET SDK, so the same refusal
at unchanged source and CRLF checkout means this SDK or host differs from the at unchanged source and CRLF checkout means this SDK or host differs from the
one that built the tracked DLL. one that built the tracked DLL.
### Before pushing a tag
A tag run uses the workflow files at the tagged commit, not the ones on main, and
the forge's GitHub mirror forwards the tag, so both CI systems run it. Before
pushing any tag, resolve the commit it will point at and read the tag-triggering
workflows as they are at that commit:
```
sha=$(git rev-parse <commit-the-tag-will-point-at>)
git ls-tree -r --name-only "$sha" .github/workflows
git show "$sha":.github/workflows/publish-packages.yml | sed -n '/^on:/,/^jobs:/p'
```
Confirm that the tag's prefix is a trigger there if you mean it to publish, and
is not if you do not. Do the same for every other workflow listed that has a
`tags:` trigger. A guard merged after that commit does not protect a tag that
points before it.
`cultcache-ts-v0.15.0` was pushed on `7d292085`, which predates the guard, and
its push started a publish run on both systems (GitHub run 42392334869, forge run
454). The forge job log shows how it ended: the Publish step ran
`release-after-suite.mjs`, whose `npm test` failed (11 cross-runtime tests,
`cargo: not found` on the runner), so it printed "@gamecult/cultcache-ts's own
tests failed; not releasing." and never reached `npm publish`. Neither
`cultcache-ts` nor `@gamecult/cultcache-ts` exists on the npm registry
(both return 404, checked 2026-11-08). The GitHub run's own log needs a login
to read, so its failure cause is inferred from the identical workflow and sha.
### Coverage gaps ### Coverage gaps
`publish-packages.yml` only triggers on `cultcache-ts-v*`, `cultcache-py-v*`, `publish-packages.yml` only triggers on `cultcache-py-v*`, `cultnet-py-v*`, and
`cultnet-py-v*`, and `cultmesh-py-v*` tag pushes — it does not build or gate `cultmesh-py-v*` tag pushes (`cultcache-ts-v*` is deliberately not a trigger: npm
publishing is off until ruled on, and the cultcache-ts job runs from
`workflow_dispatch` only, publishing nothing) — it does not build or gate
the Unity UPM packages at all; those are consumed directly by git tag the Unity UPM packages at all; those are consumed directly by git tag
(`unity/org.gamecult.cultlib`, `packages/cultmath/unity/org.gamecult.cultmath`, (`unity/org.gamecult.cultlib`, `packages/cultmath/unity/org.gamecult.cultmath`,
`src/GameCult.Unity/Assets/Caching`), so a workflow trigger on their tags `src/GameCult.Unity/Assets/Caching`), so a workflow trigger on their tags

View file

@ -284,7 +284,7 @@ public static class CultNetFirstCall
Source: [`packages/cultnet-ts/test/first-call.test.ts`](../../packages/cultnet-ts/test/first-call.test.ts), run by Source: [`packages/cultnet-ts/test/first-call.test.ts`](../../packages/cultnet-ts/test/first-call.test.ts), run by
`npm test` in `packages/cultnet-ts` (build `packages/cultcache-ts` first: `npm run build` there). The test imports `npm test` in `packages/cultnet-ts` (build `packages/cultcache-ts` first: `npm run build` there). The test imports
from `../src` where the block reads `cultnet-ts`. More: `packages/cultnet-ts/README.md`. from `../src` where the block reads `@gamecult/cultnet-ts`. More: `packages/cultnet-ts/README.md`.
```ts ```ts
import { createServer, connect } from "node:net"; import { createServer, connect } from "node:net";
@ -294,7 +294,7 @@ import {
CultNetDocumentRegistry, CultNetDocumentRegistry,
createTcpFramedCultNetPeer, createTcpFramedCultNetPeer,
defineCultNetDocumentBinding, defineCultNetDocumentBinding,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
const noteDocument = defineDocumentType({ const noteDocument = defineDocumentType({
type: "note", type: "note",

View file

@ -9,7 +9,7 @@ leave because both lease the same document.
| Piece | Status | | Piece | Status |
| --- | --- | | --- | --- |
| Two clients, real WebSockets, real `cultmesh-browser` client, one arena: join, see each other, move, leave | **tested** (`arena.test.ts`) | | Two clients, real WebSockets, real `@gamecult/cultmesh-browser` client, one arena: join, see each other, move, leave | **tested** (`arena.test.ts`) |
| Edge clamp, and the source below matching the files that ran | **tested** | | Edge clamp, and the source below matching the files that ran | **tested** |
| Browser bundle builds and the page is served | **tested** (HTTP fetch only) | | Browser bundle builds and the page is served | **tested** (HTTP fetch only) |
| The page running in a real browser, two windows | **not yet**: no browser on the host that built this recipe | | The page running in a real browser, two windows | **not yet**: no browser on the host that built this recipe |
@ -19,7 +19,7 @@ leave because both lease the same document.
| Dropped players: a closed tab that never sent `leave` stays in the arena | **not yet**: operations do not carry a connection identity to the authority | | Dropped players: a closed tab that never sent `leave` stays in the arena | **not yet**: operations do not carry a connection identity to the authority |
| `CultCache` in the browser | **not yet**: the `@gamecult/cultcache-ts` entry imports Node built-ins, so the client keeps the decoded document in a variable and only `./document` is imported | | `CultCache` in the browser | **not yet**: the `@gamecult/cultcache-ts` entry imports Node built-ins, so the client keeps the decoded document in a variable and only `./document` is imported |
No `cultmesh-ts` or `cultnet-ts` TypeScript authority server exists. The server below is the CultNet No `@gamecult/cultmesh-ts` or `@gamecult/cultnet-ts` TypeScript authority server exists. The server below is the CultNet
message handling a provider owes, written in this recipe with the `ws` package. message handling a provider owes, written in this recipe with the `ws` package.
## Run it ## Run it
@ -61,8 +61,8 @@ export const arenaSize = 100;
import { createServer, type RequestListener, type Server } from "node:http"; import { createServer, type RequestListener, type Server } from "node:http";
import { CultCache } from "@gamecult/cultcache-ts"; import { CultCache } from "@gamecult/cultcache-ts";
import { defineDocumentRegistry } from "@gamecult/cultcache-ts/document"; import { defineDocumentRegistry } from "@gamecult/cultcache-ts/document";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetMessage } from "cultnet-ts/contracts"; import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetMessage } from "@gamecult/cultnet-ts/contracts";
import { WebSocketServer, type WebSocket } from "ws"; import { WebSocketServer, type WebSocket } from "ws";
import { arenaDocument, arenaKey, arenaSize, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts"; import { arenaDocument, arenaKey, arenaSize, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts";
@ -163,7 +163,7 @@ export async function startArena(port = 0, host = "127.0.0.1", onRequest?: Reque
## client.ts ## client.ts
```ts ```ts
import { CultMeshBrowserClient, CultMeshBrowserOdinRendezvous, decodeCultNetOperationPayload, decodeCultNetPayload } from "cultmesh-browser"; import { CultMeshBrowserClient, CultMeshBrowserOdinRendezvous, decodeCultNetOperationPayload, decodeCultNetPayload } from "@gamecult/cultmesh-browser";
import { arenaDocument, arenaKey, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts"; import { arenaDocument, arenaKey, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts";
// Runs unchanged in a browser or in Node 22+: both have a global WebSocket. // Runs unchanged in a browser or in Node 22+: both have a global WebSocket.

View file

@ -1,4 +1,4 @@
import { CultMeshBrowserClient, CultMeshBrowserOdinRendezvous, decodeCultNetOperationPayload, decodeCultNetPayload } from "cultmesh-browser"; import { CultMeshBrowserClient, CultMeshBrowserOdinRendezvous, decodeCultNetOperationPayload, decodeCultNetPayload } from "@gamecult/cultmesh-browser";
import { arenaDocument, arenaKey, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts"; import { arenaDocument, arenaKey, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts";
// Runs unchanged in a browser or in Node 22+: both have a global WebSocket. // Runs unchanged in a browser or in Node 22+: both have a global WebSocket.

View file

@ -1,8 +1,8 @@
import { createServer, type RequestListener, type Server } from "node:http"; import { createServer, type RequestListener, type Server } from "node:http";
import { CultCache } from "@gamecult/cultcache-ts"; import { CultCache } from "@gamecult/cultcache-ts";
import { defineDocumentRegistry } from "@gamecult/cultcache-ts/document"; import { defineDocumentRegistry } from "@gamecult/cultcache-ts/document";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetMessage } from "cultnet-ts/contracts"; import { encodeCultNetMessageForWire, parseCultNetMessage, type CultNetMessage } from "@gamecult/cultnet-ts/contracts";
import { WebSocketServer, type WebSocket } from "ws"; import { WebSocketServer, type WebSocket } from "ws";
import { arenaDocument, arenaKey, arenaSize, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts"; import { arenaDocument, arenaKey, arenaSize, authorityRuntimeId, verseId, type ArenaState } from "./schema.ts";

41
package-lock.json generated
View file

@ -482,6 +482,18 @@
"resolved": "packages/cultcache-ts", "resolved": "packages/cultcache-ts",
"link": true "link": true
}, },
"node_modules/@gamecult/cultmesh-browser": {
"resolved": "packages/cultmesh-browser",
"link": true
},
"node_modules/@gamecult/cultmesh-ts": {
"resolved": "packages/cultmesh-ts",
"link": true
},
"node_modules/@gamecult/cultnet-ts": {
"resolved": "packages/cultnet-ts",
"link": true
},
"node_modules/@jsdevtools/ono": { "node_modules/@jsdevtools/ono": {
"version": "7.1.3", "version": "7.1.3",
"resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz", "resolved": "https://registry.npmjs.org/@jsdevtools/ono/-/ono-7.1.3.tgz",
@ -865,18 +877,6 @@
"dev": true, "dev": true,
"license": "Python-2.0" "license": "Python-2.0"
}, },
"node_modules/cultmesh-browser": {
"resolved": "packages/cultmesh-browser",
"link": true
},
"node_modules/cultmesh-ts": {
"resolved": "packages/cultmesh-ts",
"link": true
},
"node_modules/cultnet-ts": {
"resolved": "packages/cultnet-ts",
"link": true
},
"node_modules/esbuild": { "node_modules/esbuild": {
"version": "0.28.1", "version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
@ -1184,7 +1184,7 @@
}, },
"packages/cultcache-ts": { "packages/cultcache-ts": {
"name": "@gamecult/cultcache-ts", "name": "@gamecult/cultcache-ts",
"version": "0.14.2", "version": "0.15.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@msgpack/msgpack": "^3.1.3", "@msgpack/msgpack": "^3.1.3",
@ -1200,15 +1200,16 @@
} }
}, },
"packages/cultmesh-browser": { "packages/cultmesh-browser": {
"name": "@gamecult/cultmesh-browser",
"version": "0.4.0", "version": "0.4.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@gamecult/cultcache-ts": "^0.14.0", "@gamecult/cultcache-ts": "^0.15.0",
"cultnet-ts": "^0.3.0" "@gamecult/cultnet-ts": "^0.3.0"
}, },
"devDependencies": { "devDependencies": {
"@gamecult/cultmesh-ts": "^0.2.0",
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"cultmesh-ts": "^0.2.0",
"typescript": "^5.9.0" "typescript": "^5.9.0"
}, },
"engines": { "engines": {
@ -1216,11 +1217,12 @@
} }
}, },
"packages/cultmesh-ts": { "packages/cultmesh-ts": {
"name": "@gamecult/cultmesh-ts",
"version": "0.2.0", "version": "0.2.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@gamecult/cultcache-ts": "^0.14.0", "@gamecult/cultcache-ts": "^0.15.0",
"cultnet-ts": "^0.3.0", "@gamecult/cultnet-ts": "^0.3.0",
"koffi": "3.3.0" "koffi": "3.3.0"
}, },
"devDependencies": { "devDependencies": {
@ -1233,10 +1235,11 @@
} }
}, },
"packages/cultnet-ts": { "packages/cultnet-ts": {
"name": "@gamecult/cultnet-ts",
"version": "0.3.0", "version": "0.3.0",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@gamecult/cultcache-ts": "^0.14.1", "@gamecult/cultcache-ts": "^0.15.0",
"@msgpack/msgpack": "^3.1.3", "@msgpack/msgpack": "^3.1.3",
"ajv": "^8.17.1" "ajv": "^8.17.1"
}, },

View file

@ -1121,6 +1121,25 @@ class CultCacheTests(unittest.TestCase):
catalog_entry=catalog_entry, catalog_entry=catalog_entry,
) )
def test_pulling_a_synthetic_pre_v1_envelope_array_leaves_the_file_bytes_identical(self) -> None:
try:
import msgpack # type: ignore
except ImportError:
self.skipTest("msgpack optional dependency is not installed")
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "legacy.cc"
legacy = msgpack.packb(
[{"key": "note:hello", "type": "note", "payload": {"title": "Hello"}, "storedAt": "2026-10-20T00:00:00Z"}],
use_bin_type=True,
)
path.write_bytes(legacy)
envelopes = SingleFileMessagePackBackingStore(path).pull_all()
self.assertEqual([e.key for e in envelopes], ["note:hello"])
self.assertEqual(path.read_bytes(), legacy)
self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), ["legacy.cc"])
def test_legacy_key_global_loads_without_writing_and_first_write_leaves_one_global(self) -> None: def test_legacy_key_global_loads_without_writing_and_first_write_leaves_one_global(self) -> None:
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
settings = define_document_type("settings", global_document=True) settings = define_document_type("settings", global_document=True)

View file

@ -6136,6 +6136,27 @@ mod tests {
Ok(()) Ok(())
} }
#[test]
fn pulling_a_synthetic_pre_v1_envelope_array_leaves_the_file_bytes_identical() -> Result<()> {
// SYNTHETIC pre-v1 vector: no real file of this shape is known; the Rust envelope payload is binary.
let temp = tempfile::tempdir()?;
let path = temp.path().join("legacy.cc");
let legacy = rmp_serde::to_vec_named(&vec![CultCacheEnvelope {
key: "note:hello".to_string(),
r#type: "note".to_string(),
payload: vec![0x90],
stored_at: "2026-10-20T00:00:00Z".to_string(),
schema_id: None,
}])?;
fs::write(&path, &legacy)?;
let envelopes = SingleFileMessagePackBackingStore::new(&path).pull_all()?;
assert_eq!(envelopes.iter().map(|e| e.key.as_str()).collect::<Vec<_>>(), ["note:hello"]);
assert_eq!(fs::read(&path)?, legacy);
Ok(())
}
#[test] #[test]
fn a_newer_store_is_named_once_its_header_string_is_complete() -> Result<()> { fn a_newer_store_is_named_once_its_header_string_is_complete() -> Result<()> {
let vector = fs::read( let vector = fs::read(

View file

@ -2,7 +2,8 @@
//! (`src/GameCult.Caching/CultCache.cs`) and the one-global rule its commit enforces. //! (`src/GameCult.Caching/CultCache.cs`) and the one-global rule its commit enforces.
use cultcache_rs::{ use cultcache_rs::{
CacheBackingStore, CultCache, CultCacheSecondGlobal, DatabaseEntry, SingleFileMessagePackBackingStore, CacheBackingStore, CultCache, CultCacheSecondGlobal, CultCacheSoaTable, DatabaseEntry,
SingleFileMessagePackBackingStore,
}; };
#[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)]
@ -321,3 +322,31 @@ fn loading_a_store_that_holds_two_globals_is_refused() {
assert!(loading.pull_all_backing_stores().unwrap_err().is::<CultCacheSecondGlobal>()); assert!(loading.pull_all_backing_stores().unwrap_err().is::<CultCacheSecondGlobal>());
assert_eq!(loading.get_global::<Settings>().unwrap(), None, "a refused load installs nothing"); assert_eq!(loading.get_global::<Settings>().unwrap(), None, "a refused load installs nothing");
} }
// load_soa installs a whole table at once, so the one-global rule has to hold there too: a table holding two
// records of a global type is refused whole and the prior view survives.
#[test]
fn loading_an_soa_table_that_holds_two_globals_is_refused() {
let source = cache();
let (first, _) = source.prepare_entry("g1", &settings("one")).unwrap();
let (second, _) = source.prepare_entry("g2", &settings("two")).unwrap();
let mut loading = cache();
loading.put("g0", &settings("prior")).unwrap();
loading.put("plain:1", &Plain { value: "prior".into() }).unwrap();
let refusal = loading
.load_soa(CultCacheSoaTable::from_envelopes(vec![first.clone(), second]))
.unwrap_err();
let second_global = refusal.downcast_ref::<CultCacheSecondGlobal>().expect("a typed refusal");
let mut named = [second_global.existing_key.as_str(), second_global.key.as_str()];
named.sort();
assert_eq!(named, ["g1", "g2"], "the refusal names both records");
assert_eq!(loading.get_global::<Settings>().unwrap(), Some(settings("prior")), "a refused load keeps the prior view");
assert_eq!(loading.get::<Plain>("plain:1").unwrap(), Some(Plain { value: "prior".into() }));
// One global in the table is the rule's own case, not a second.
loading.load_soa(CultCacheSoaTable::from_envelopes(vec![first])).unwrap();
assert_eq!(loading.get_global::<Settings>().unwrap(), Some(settings("one")));
assert_eq!(loading.get::<Plain>("plain:1").unwrap(), None, "a load replaces the view");
}

View file

@ -3,29 +3,35 @@
All notable changes to `@gamecult/cultcache-ts` are recorded here, following All notable changes to `@gamecult/cultcache-ts` are recorded here, following
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/). [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased ## [Unreleased]
### Changed
- Opening a legacy (pre-v1) store is a pure read: payloads that were not bytes are normalized in memory and the
file is left as it was, so a codec that refuses the content cannot lose the old bytes. The next push, delete or
flush rewrites the file as v1, merging what the open read.
- `SingleFileStoreRead` no longer carries `repairedLegacyPayload`; no consumer used it.
## [0.15.0]
0.14.1 and 0.14.2 were never tagged or published; this entry carries them with the Unreleased work, and `cultcache-ts-v0.14.0` is the previous release.
### Breaking ### Breaking
- A single-file store written as `cultcache.store.v3` is read and written: a record that holds an element id (an owned list element with an `[CultElementId]` member, carried through every write) marks the store v3, and a v3 store is carried through a rewrite with its ids. A runtime from before this change refuses a v3 store by name. - A single-file store written as `cultcache.store.v3` is read and written: a record that holds an element id (an owned list element with an `[CultElementId]` member, carried through every write) marks the store v3, and a v3 store is carried through a rewrite with its ids. A runtime from before this change refuses a v3 store by name.
- A single-file store refuses a zero-byte file as `StoreUnreadableError`; only a path with nothing at it is an empty store. A header this runtime does not read is refused, and the refusal echoes the header only as `cultcache.store.v<digits>`. - A single-file store refuses a zero-byte file as `StoreUnreadableError`; only a path with nothing at it is an empty store. A header this runtime does not read is refused, and the refusal echoes the header only as `cultcache.store.v<digits>`.
- A write over a file the reader refuses (`StoreUnreadableError`, from `push`, `pushAll` and `delete`) refuses and leaves the file as it is. A flush used to replace such a file. A write set cannot merge with a disk it cannot read, so the file is repaired or removed by its owner before the store writes again. - A write over a file the reader refuses (`StoreUnreadableError`, from `push`, `pushAll` and `delete`) refuses and leaves the file as it is. A flush used to replace such a file. A write set cannot merge with a disk it cannot read, so the file is repaired or removed by its owner before the store writes again. A full `pushAll` over a file with no readable stamp does not replace it: the reader refuses it. The stamp rule has one owner, `refuseUnreadFormat`, asked only by the one reader that every write consults under the lock. The reader judges the stamp from the header before it decodes the body, so a newer store is refused by name whether or not its body is whole.
- This reverses the 0.14.2 `pushAll` fix in two ways. A full `pushAll` over a file with no readable stamp no longer replaces it (healing it): the reader refuses it, and the file is left as it is. And a `cultcache.store.v3` stamp is read, not refused. The stamp rule has one owner, `refuseUnreadFormat`, asked only by the one reader that every write consults under the lock. The reader judges the stamp from the header before it decodes the body, so a newer store is refused by name whether or not its body is whole.
- A dangling symbolic link at the store path is an I/O error with code `ENOENT`, not an empty store. - A dangling symbolic link at the store path is an I/O error with code `ENOENT`, not an empty store.
### Added ### Added
- `@gamecult/cultcache-ts/browser`, also what a bundler resolves for the package root under the `browser` export condition: the root surface without `SingleFileMessagePackBackingStore` and `readSingleFileStore`, so it imports no `node:*` built-in and no `koffi` and bundles with esbuild `platform: "browser"`. The Node entry exports exactly what it did. - `@gamecult/cultcache-ts/browser`, also what a bundler resolves for the package root under the `browser` export condition: the root surface without `SingleFileMessagePackBackingStore` and `readSingleFileStore`, so it imports no `node:*` built-in and no `koffi` and bundles with esbuild `platform: "browser"`. The Node entry exports exactly what it did.
- `readSingleFileStore(path)`, the one synchronous reader of a single-file store, for consumers that must read a store file rather than decode it themselves. `pullAll`, `push`, `delete` and `pushAll` ask the same reader. - `readSingleFileStore(path)`, the one synchronous reader of a single-file store, for consumers that must read a store file rather than decode it themselves. `pullAll`, `push`, `delete` and `pushAll` ask the same reader.
- `StoreUnreadableError` for a store file this runtime cannot read, `SchemaConflictError` for a write the catalog cannot describe, and `schemaIdentityOf` with its result type `CultCacheSchemaIdentity` (`schemaId`, `schemaName`, `schemaVersion`, `compatibleSchemaIds`), the one derivation of a definition's identity. - `StoreUnreadableError` for a store file this runtime cannot read, `SchemaConflictError` for a write the catalog cannot describe, and `schemaIdentityOf` with its result type `CultCacheSchemaIdentity` (`schemaId`, `schemaName`, `schemaVersion`, `compatibleSchemaIds`), the one derivation of a definition's identity.
- The document payload codec, exported from `@gamecult/cultcache-ts/document`: `decodeDocumentPayload`, `encodeDocumentPayload`, and the two named byte escapes `documentPayloadFromBytes` and `documentPayloadBytes`.
- `SingleFileStoreRead`, exported: the result type of `readSingleFileStore` (`absent`, `format`, `envelopes`, `repairedLegacyPayload`). - `SingleFileStoreRead`, exported: the result type of `readSingleFileStore` (`absent`, `format`, `envelopes`, `repairedLegacyPayload`).
- `CultCacheInspection.format` is `StoreFormat | "legacy.envelope-array"`: it reports `cultcache.store.v3` for a v3 store. - `CultCacheInspection.format` is `StoreFormat | "legacy.envelope-array"`: it reports `cultcache.store.v3` for a v3 store.
- A soft `pushAll` writes only where nothing is at the path, leaves a store it can read byte for byte, and refuses what the reader refuses. - A soft `pushAll` writes only where nothing is at the path, leaves a store it can read byte for byte, and refuses what the reader refuses.
## [0.14.2]
### Added
- `SingleFileMessagePackBackingStore` takes a cross-process write lock on `<file>.lock`, - `SingleFileMessagePackBackingStore` takes a cross-process write lock on `<file>.lock`,
interoperable with the C# and Rust runtimes (`flock` on Unix, `LockFileEx` on Windows). interoperable with the C# and Rust runtimes (`flock` on Unix, `LockFileEx` on Windows).
`push` and `delete` read the current file, merge and replace it under the lock, so concurrent `push` and `delete` read the current file, merge and replace it under the lock, so concurrent
@ -35,27 +41,16 @@ All notable changes to `@gamecult/cultcache-ts` are recorded here, following
is, but C# writers can still overwrite records a concurrent TypeScript writer added. is, but C# writers can still overwrite records a concurrent TypeScript writer added.
- The staged file is fsynced before the replace, and on Unix the directory after it. A - The staged file is fsynced before the replace, and on Unix the directory after it. A
directory sync failure after the replace is reported as replaced but not durable. directory sync failure after the replace is reported as replaced but not durable.
### Changed
- The Windows replace is a POSIX-semantics rename first (it lands while C# and Rust readers
hold the store open), falling back to a write-through `MoveFileExW`, with 25 attempts 20 ms
apart on errors 5, 32 and 33. Writers wait up to 30 s for the lock.
- Opening a legacy store that needs healing rewrites it under the lock, from a read taken
under the lock.
### Fixed
- A full `pushAll` reads the store's header under the lock first and refuses a store format
this runtime does not read (the same error a read gives), leaving the file as it was. A
file with no readable stamp is still replaced, so a whole write heals it. Soft `pushAll`
is unchanged. The stamp is decoded by the decoder a read uses, so a stamp followed by bytes
that are not UTF-8 is refused by a whole write as a read refuses it.
### Dependencies
- `koffi` 3.3.0, loaded only on the first write.
## [0.14.1]
### Added
- `checkPayloadDepth` is re-exported from `@gamecult/cultcache-ts/document`, so dependents - `checkPayloadDepth` is re-exported from `@gamecult/cultcache-ts/document`, so dependents
(`cultnet-ts/content`) bound payload nesting with the same check the cache (`cultnet-ts/content`) bound payload nesting with the same check the cache
applies on decode. applies on decode.
### Changed
- The Windows replace is a POSIX-semantics rename first (it lands while C# and Rust readers
hold the store open), falling back to a write-through `MoveFileExW`, with 25 attempts 20 ms
apart on errors 5, 32 and 33. Writers wait up to 30 s for the lock.
### Dependencies
- `koffi` 3.3.0, loaded only on the first write.

View file

@ -357,7 +357,7 @@ That is the TypeScript version of the original CultCache trick:
- the top-level MessagePack value is `[formatVersion, schemaCatalog, records]` - the top-level MessagePack value is `[formatVersion, schemaCatalog, records]`
- each record is `[key, schemaId, storedAt, payload]` - each record is `[key, schemaId, storedAt, payload]`
- each catalog entry is `[schemaId, schemaName, schemaVersion, contentHash, canonicalSchemaJson, compatibleSchemaIds, members]` - each catalog entry is `[schemaId, schemaName, schemaVersion, contentHash, canonicalSchemaJson, compatibleSchemaIds, members]`
- it still reads the older TS/Rust-style envelope array and rewrites repaired legacy payloads as v1 snapshots - it still reads the older TS/Rust-style envelope array (object payloads are normalized in memory; opening never rewrites the file) and replaces it with a v1 snapshot on the next push, delete or flush
- it queues local writes in order, then takes the shared `<file>.lock` (`flock` on Unix, `LockFileEx` on Windows, via koffi, loaded on the first write) for each one, so C#, Rust and TypeScript writers exclude each other; the read a write merges from is taken under that lock - it queues local writes in order, then takes the shared `<file>.lock` (`flock` on Unix, `LockFileEx` on Windows, via koffi, loaded on the first write) for each one, so C#, Rust and TypeScript writers exclude each other; the read a write merges from is taken under that lock
- it fsyncs the staged file and, on Unix, the directory after the replace; on Windows it replaces with a POSIX-semantics rename and falls back to a write-through `MoveFileExW`, retrying briefly on sharing violations - it fsyncs the staged file and, on Unix, the directory after the replace; on Windows it replaces with a POSIX-semantics rename and falls back to a write-through `MoveFileExW`, retrying briefly on sharing violations
- it persists raw MessagePack payload bytes inside schema-addressed records - it persists raw MessagePack payload bytes inside schema-addressed records

View file

@ -1,6 +1,6 @@
{ {
"name": "@gamecult/cultcache-ts", "name": "@gamecult/cultcache-ts",
"version": "0.14.2", "version": "0.15.0",
"description": "CultCache-style typed persistence for TypeScript with schema-backed polymorphic MessagePack storage.", "description": "CultCache-style typed persistence for TypeScript with schema-backed polymorphic MessagePack storage.",
"main": "dist/index.js", "main": "dist/index.js",
"types": "dist/index.d.ts", "types": "dist/index.d.ts",

View file

@ -47,21 +47,11 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
} }
async pullAll(): Promise<CultCacheEnvelope[]> { async pullAll(): Promise<CultCacheEnvelope[]> {
// The disk decides the header: a file that is gone or legacy is not marked. // A pure read: the disk decides the header, and a legacy file is normalized in memory only. The file is rewritten
this.#format = STORE_FORMAT_VERSION; // as v1 by the next push, delete or flush, which merges what this read returns; opening never replaces bytes the
// consumer's codec has not yet accepted.
const disk = this.#readDisk(); const disk = this.#readDisk();
this.#format = disk.format; this.#format = disk.format;
if (disk.repairedLegacyPayload) {
// The heal decides from its own read, taken under the store lock.
await this.#enqueue(async () => {
const again = this.#readDisk();
this.#format = again.format;
if (again.repairedLegacyPayload) {
await this.#writeAll([], again.envelopes);
}
});
}
return disk.envelopes; return disk.envelopes;
} }
@ -158,7 +148,7 @@ export class SingleFileMessagePackBackingStore implements CacheBackingStore {
export function readSingleFileStore(path: string): SingleFileStoreRead { export function readSingleFileStore(path: string): SingleFileStoreRead {
const data = readStoreBytes(path); const data = readStoreBytes(path);
if (data === undefined) { if (data === undefined) {
return { absent: true, format: STORE_FORMAT_VERSION, envelopes: [], repairedLegacyPayload: false }; return { absent: true, format: STORE_FORMAT_VERSION, envelopes: [] };
} }
try { try {
@ -395,8 +385,6 @@ export type SingleFileStoreRead = {
absent: boolean; absent: boolean;
format: StoreFormat; format: StoreFormat;
envelopes: CultCacheEnvelope[]; envelopes: CultCacheEnvelope[];
// A legacy file whose payloads were not bytes: reading it repairs them, and the store rewrites the file.
repairedLegacyPayload: boolean;
}; };
function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent"> { function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent"> {
@ -420,7 +408,7 @@ function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent">
storedAt: record.storedAt, storedAt: record.storedAt,
}; };
}); });
return { format: snapshot.format, envelopes, repairedLegacyPayload: false }; return { format: snapshot.format, envelopes };
} }
const legacy = decodeLegacyEnvelopeArray(decoded); const legacy = decodeLegacyEnvelopeArray(decoded);
@ -428,19 +416,8 @@ function decodeStoreFile(data: Uint8Array): Omit<SingleFileStoreRead, "absent">
throw new Error("CultCache file is not a recognized CultCache MessagePack store."); throw new Error("CultCache file is not a recognized CultCache MessagePack store.");
} }
let repairedLegacyPayload = false; const normalized = legacy.map((entry) => ({ ...entry, payload: normalizePayload(entry.payload) }));
const normalized = legacy.map((entry) => { return { format: STORE_FORMAT_VERSION, envelopes: envelopeArraySchema.parse(normalized).map((entry) => ({ ...entry, payload: documentPayloadFromBytes(entry.payload) })) as CultCacheEnvelope[] };
const payload = normalizePayload(entry.payload);
if (payload !== entry.payload) {
repairedLegacyPayload = true;
}
return {
...entry,
payload,
};
});
return { format: STORE_FORMAT_VERSION, envelopes: envelopeArraySchema.parse(normalized).map((entry) => ({ ...entry, payload: documentPayloadFromBytes(entry.payload) })) as CultCacheEnvelope[], repairedLegacyPayload };
} }
function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined { function decodeSnapshot(decoded: unknown): DecodedSnapshot | undefined {

View file

@ -504,46 +504,56 @@ test("SingleFileMessagePackBackingStore refuses a record whose schema the catalo
await assert.rejects(() => cache.pullAllBackingStores(), StoreUnreadableError); await assert.rejects(() => cache.pullAllBackingStores(), StoreUnreadableError);
}); });
test("SingleFileMessagePackBackingStore heals legacy envelopes whose payload was persisted as an object", async () => { const legacyNoteType = defineDocumentType({
const noteDocument = defineDocumentType({
type: "note", type: "note",
schema: z.object({ schema: z.object({ title: z.string(), body: z.string().optional() }),
title: z.string(),
body: z.string(),
}),
}); });
// SYNTHETIC pre-v1 file (no real one is known): an envelope array with object payloads.
async function legacyNoteStore(second: unknown): Promise<{ storePath: string; bytes: Uint8Array }> {
const storePath = join(await mkdtemp(join(tmpdir(), "cultcache-ts-")), "legacy.msgpack"); const storePath = join(await mkdtemp(join(tmpdir(), "cultcache-ts-")), "legacy.msgpack");
const envelopePayload = { const bytes = encode([
title: "Hello", { key: "note:hello", type: "note", payload: { title: "Hello", body: "world" }, storedAt: "2026-10-20T00:00:00Z" },
body: "world", { key: "note:other", type: "note", payload: second, storedAt: "2026-10-20T00:00:00Z" },
}; ]);
await writeFile(storePath, bytes);
await writeFile( return { storePath, bytes };
storePath, }
encode([
{
key: "note:hello",
type: "note",
payload: envelopePayload,
storedAt: new Date().toISOString(),
},
]),
);
test("a codec that refuses a synthetic pre-v1 store's content leaves the file byte-identical", async () => {
const { storePath, bytes } = await legacyNoteStore({ title: 42 });
const cache = CultCache.builder() const cache = CultCache.builder()
.withDocumentType(noteDocument) .withDocumentType(legacyNoteType)
.withGenericStore(new SingleFileMessagePackBackingStore(storePath))
.build();
await assert.rejects(() => cache.pullAllBackingStores());
assert.deepEqual([...(await readFile(storePath))], [...bytes]);
assert.deepEqual((await readdir(dirname(storePath))).sort(), ["legacy.msgpack"]);
});
test("a synthetic pre-v1 store is read untouched and becomes v1 only when the consumer writes, keeping its other entries", async () => {
const { storePath, bytes } = await legacyNoteStore({ title: "Other" });
const cache = CultCache.builder()
.withDocumentType(legacyNoteType)
.withGenericStore(new SingleFileMessagePackBackingStore(storePath)) .withGenericStore(new SingleFileMessagePackBackingStore(storePath))
.build(); .build();
await cache.pullAllBackingStores(); await cache.pullAllBackingStores();
assert.deepEqual(cache.getRequired(noteDocument, "note:hello"), envelopePayload); assert.deepEqual(cache.getRequired(legacyNoteType, "note:hello"), { title: "Hello", body: "world" });
assert.deepEqual([...(await readFile(storePath))], [...bytes], "reading does not rewrite the file");
const rewritten = decode(await readFile(storePath)) as unknown[]; await cache.put(legacyNoteType, "note:new", { title: "New" });
assert.equal(rewritten[0], "cultcache.store.v1"); assert.equal((decode(await readFile(storePath)) as unknown[])[0], "cultcache.store.v1");
const records = rewritten[2] as unknown[][];
assert.equal(records.length, 1); const reopened = CultCache.builder()
assert.ok(records[0]?.[3] instanceof Uint8Array); .withDocumentType(legacyNoteType)
.withGenericStore(new SingleFileMessagePackBackingStore(storePath))
.build();
await reopened.pullAllBackingStores();
assert.deepEqual(reopened.getRequired(legacyNoteType, "note:hello"), { title: "Hello", body: "world" });
assert.deepEqual(reopened.getRequired(legacyNoteType, "note:other"), { title: "Other" });
assert.deepEqual(reopened.getRequired(legacyNoteType, "note:new"), { title: "New" });
}); });
test("CultCache rejects a second generic backing store", async () => { test("CultCache rejects a second generic backing store", async () => {

View file

@ -471,44 +471,70 @@ test("the store lock is released when the operation throws", async () => {
} }
}); });
// SYNTHETIC pre-v1 vector: no real file of this shape is known to exist. A top-level array of {key,type,payload,storedAt}
// whose payload is not binary (an object, a Node Buffer JSON, an int array) is what the removed heal-on-open rewrote.
const legacyObjectPayload = (): Uint8Array => const legacyObjectPayload = (): Uint8Array =>
encode([{ key: "note:hello", type: "note", payload: { title: "Hello" }, storedAt: "2026-10-20T00:00:00Z" }]); encode([{ key: "note:hello", type: "note", payload: { title: "Hello" }, storedAt: "2026-10-20T00:00:00Z" }]);
test("an open that heals a legacy store waits for the store lock and heals from its own read", async () => { test("opening a synthetic pre-v1 store with object payloads returns them normalized and leaves the file untouched, even while another holder has the lock", async () => {
const directory = await scratch(); const directory = await scratch();
try { try {
const path = join(directory, "legacy.cc"); const path = join(directory, "legacy.cc");
const legacy = legacyObjectPayload(); const legacy = legacyObjectPayload();
await writeFile(path, legacy); await writeFile(path, legacy);
const store = new SingleFileMessagePackBackingStore(path); const store = new SingleFileMessagePackBackingStore(path);
let healed: Promise<unknown> | undefined;
let settled = false;
await withStoreWriteLock(path, async () => { await withStoreWriteLock(path, async () => {
healed = store.pullAll().then(() => { const [lockHeld] = await Promise.all([readdir(directory)]);
settled = true; const envelopes = await within(store.pullAll(), 5000, "an open does not wait for the write lock");
assert.deepEqual(envelopes.map((entry) => entry.key), ["note:hello"]);
assert.deepEqual(decode(documentPayloadBytes(envelopes[0].payload)), { title: "Hello" });
assert.deepEqual([...(await readFile(path))], [...legacy]);
assert.deepEqual((await readdir(directory)).sort(), lockHeld.sort(), "an open adds no lock or temp file");
}); });
await sleepFor(300); assert.deepEqual([...(await readFile(path))], [...legacy]);
assert.equal(settled, false, "the heal must wait for the lock"); assert.deepEqual((await readdir(directory)).filter((name) => name !== "legacy.cc" && name !== "legacy.cc.lock"), []);
assert.deepEqual([...(await readFile(path))], [...legacy], "the file keeps its legacy bytes while the lock is held elsewhere");
});
await within(healed!, 5000, "the heal");
assert.equal((decode(await readFile(path)) as unknown[])[0], "cultcache.store.v1");
} finally { } finally {
await rm(directory, { recursive: true, force: true }); await rm(directory, { recursive: true, force: true });
} }
}); });
test("push and delete over a legacy store that needs healing finish instead of waiting on their own lock", async () => { test("opening a synthetic pre-v1 store with Buffer-JSON and int-array payloads normalizes them in memory and leaves the file untouched", async () => {
const directory = await scratch();
try {
const path = join(directory, "legacy.cc");
const inner = encode({ title: "Hello" });
const legacy = encode([
{ key: "a", type: "note", payload: { type: "Buffer", data: [...inner] }, storedAt: "2026-10-20T00:00:00Z" },
{ key: "b", type: "note", payload: [...inner], storedAt: "2026-10-20T00:00:00Z" },
]);
await writeFile(path, legacy);
const envelopes = await new SingleFileMessagePackBackingStore(path).pullAll();
assert.deepEqual(envelopes.map((entry) => entry.key), ["a", "b"]);
for (const envelope of envelopes) {
assert.deepEqual(decode(documentPayloadBytes(envelope.payload)), { title: "Hello" });
}
assert.deepEqual([...(await readFile(path))], [...legacy]);
assert.deepEqual(await readdir(directory), ["legacy.cc"]);
} finally {
await rm(directory, { recursive: true, force: true });
}
});
test("push and delete over a synthetic pre-v1 store write v1 and keep the other legacy entries, normalized payloads included", async () => {
const directory = await scratch(); const directory = await scratch();
try { try {
const path = join(directory, "legacy.cc"); const path = join(directory, "legacy.cc");
await writeFile(path, legacyObjectPayload()); await writeFile(path, legacyObjectPayload());
const store = new SingleFileMessagePackBackingStore(path); const store = new SingleFileMessagePackBackingStore(path);
await within(store.push(entryOf("a")), 5000, "push"); await within(store.push(entryOf("a")), 5000, "push");
assert.equal((decode(await readFile(path)) as unknown[])[0], "cultcache.store.v1");
assert.deepEqual((await store.pullAll()).map((entry) => entry.key).sort(), ["a", "note:hello"]);
await writeFile(path, legacyObjectPayload()); await writeFile(path, legacyObjectPayload());
await within(store.delete(entryOf("a")), 5000, "delete"); await within(store.delete(entryOf("a")), 5000, "delete");
const keys = (await store.pullAll()).map((entry) => entry.key); assert.equal((decode(await readFile(path)) as unknown[])[0], "cultcache.store.v1");
assert.deepEqual(keys, ["note:hello"]); const kept = await store.pullAll();
assert.deepEqual(kept.map((entry) => entry.key), ["note:hello"]);
assert.deepEqual(decode(documentPayloadBytes(kept[0].payload)), { title: "Hello" });
} finally { } finally {
await rm(directory, { recursive: true, force: true }); await rm(directory, { recursive: true, force: true });
} }
@ -697,7 +723,7 @@ test("a store file of an unrecognized shape is refused, and a store naming a mis
} }
}); });
test("opening a store that needs no healing writes nothing: a missing store leaves no lock file, a legacy store with byte payloads keeps its bytes", async () => { test("opening writes nothing: a missing store leaves no lock file, a legacy store with byte payloads keeps its bytes", async () => {
const directory = await scratch(); const directory = await scratch();
try { try {
const absent = join(directory, "nested", "absent.cc"); const absent = join(directory, "nested", "absent.cc");

View file

@ -1,8 +1,14 @@
# Changelog # Changelog
All notable changes to `cultmesh-browser` are recorded here, following All notable changes to `@gamecult/cultmesh-browser` are recorded here, following
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/). [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Breaking
- The package is renamed `cultmesh-browser` to `@gamecult/cultmesh-browser` (the repo already scopes `@gamecult/cultcache-ts`), so the unscoped name cannot be claimed by someone else. Import from `@gamecult/cultmesh-browser` and its subpaths; the API is unchanged. Depends on `@gamecult/cultnet-ts`; the interop test uses `@gamecult/cultmesh-ts`.
## [0.4.0] ## [0.4.0]
### Added ### Added

View file

@ -1,6 +1,6 @@
# CultMesh Browser # CultMesh Browser
`cultmesh-browser` is the browser-safe CultMesh client boundary. It owns one `@gamecult/cultmesh-browser` is the browser-safe CultMesh client boundary. It owns one
WebSocket session for a stable Verse/authority-runtime target, retains explicit raw WebSocket session for a stable Verse/authority-runtime target, retains explicit raw
document leases across route replacement, and correlates typed CultNet document leases across route replacement, and correlates typed CultNet
operations with provider receipts. operations with provider receipts.
@ -95,7 +95,7 @@ WebCrypto `crypto.subtle`; without WebCrypto it fails with
endpoint CultMesh resolved is the only host the reader trusts. endpoint CultMesh resolved is the only host the reader trusts.
```ts ```ts
import { fetchVerifiedContent } from "cultmesh-browser"; import { fetchVerifiedContent } from "@gamecult/cultmesh-browser";
const bytes = await fetchVerifiedContent(endpoint, manifest, { const bytes = await fetchVerifiedContent(endpoint, manifest, {
signal: AbortSignal.timeout(30_000), signal: AbortSignal.timeout(30_000),

View file

@ -1,5 +1,5 @@
{ {
"name": "cultmesh-browser", "name": "@gamecult/cultmesh-browser",
"version": "0.4.0", "version": "0.4.0",
"description": "Browser-safe CultMesh document leases and typed operations over CultNet WebSocket transport.", "description": "Browser-safe CultMesh document leases and typed operations over CultNet WebSocket transport.",
"type": "module", "type": "module",
@ -41,12 +41,12 @@
"node": ">=20" "node": ">=20"
}, },
"dependencies": { "dependencies": {
"@gamecult/cultcache-ts": "^0.14.0", "@gamecult/cultcache-ts": "^0.15.0",
"cultnet-ts": "^0.3.0" "@gamecult/cultnet-ts": "^0.3.0"
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^24.0.0", "@types/node": "^24.0.0",
"cultmesh-ts": "^0.2.0", "@gamecult/cultmesh-ts": "^0.2.0",
"typescript": "^5.9.0" "typescript": "^5.9.0"
} }
} }

View file

@ -3,8 +3,8 @@
// The response's declared length and coding are never consulted (Fetch decodes codings; the bytes received are the evidence). // The response's declared length and coding are never consulted (Fetch decodes codings; the bytes received are the evidence).
// Hashing, hex rules, record keys, the loopback rule and manifest validation belong to cultnet-ts and are only called here. // Hashing, hex rules, record keys, the loopback rule and manifest validation belong to cultnet-ts and are only called here.
import { EMPTY_SHA256, chunkRecordKey, parseSha256Hex, sha256Hex, validateManifest, type CultMeshCdnArtifactManifest } from "cultnet-ts/content"; import { EMPTY_SHA256, chunkRecordKey, parseSha256Hex, sha256Hex, validateManifest, type CultMeshCdnArtifactManifest } from "@gamecult/cultnet-ts/content";
import { isLoopbackEndpoint } from "cultnet-ts/authority"; import { isLoopbackEndpoint } from "@gamecult/cultnet-ts/authority";
export type CultMeshContentErrorCode = export type CultMeshContentErrorCode =
| "manifest-invalid" | "too-large" | "insecure-endpoint" | "webcrypto-unavailable" | "network" | "manifest-invalid" | "too-large" | "insecure-endpoint" | "webcrypto-unavailable" | "network"

View file

@ -1,6 +1,6 @@
import { decodeDocumentPayload } from "@gamecult/cultcache-ts/document"; import { decodeDocumentPayload } from "@gamecult/cultcache-ts/document";
import type { AnyCultCacheDocumentDefinition, CultCacheDocumentValue } from "@gamecult/cultcache-ts"; import type { AnyCultCacheDocumentDefinition, CultCacheDocumentValue } from "@gamecult/cultcache-ts";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
encodeCultNetMessageForWire, encodeCultNetMessageForWire,
parseCultNetMessage, parseCultNetMessage,
@ -16,7 +16,7 @@ import {
type CultMeshVerseCatalogResponseMessage, type CultMeshVerseCatalogResponseMessage,
type CultMeshSessionAcceptedMessage, type CultMeshSessionAcceptedMessage,
type CultMeshSessionOpenMessage, type CultMeshSessionOpenMessage,
} from "cultnet-ts/contracts"; } from "@gamecult/cultnet-ts/contracts";
import { import {
base64ToBytes, base64ToBytes,
bytesToBase64, bytesToBase64,
@ -31,7 +31,7 @@ import {
type CultMeshAuthorityTrustMode, type CultMeshAuthorityTrustMode,
type CultMeshAuthorityTrustPolicy, type CultMeshAuthorityTrustPolicy,
type CultMeshP256PublicKey, type CultMeshP256PublicKey,
} from "cultnet-ts/authority"; } from "@gamecult/cultnet-ts/authority";
export * from "./content.js"; export * from "./content.js";
export type CultMeshBrowserIdentity = CultMeshAuthorityIdentity; export type CultMeshBrowserIdentity = CultMeshAuthorityIdentity;

View file

@ -11,7 +11,7 @@ import { gzipSync } from "node:zlib";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { build } from "esbuild"; import { build } from "esbuild";
import { EMPTY_SHA256, packContent, sha256Hex, type CultMeshCdnArtifactManifest } from "cultnet-ts/content"; import { EMPTY_SHA256, packContent, sha256Hex, type CultMeshCdnArtifactManifest } from "@gamecult/cultnet-ts/content";
import { CultMeshContentError, fetchVerifiedChunk, fetchVerifiedContent, type CultMeshContentErrorCode } from "../src/content.js"; import { CultMeshContentError, fetchVerifiedChunk, fetchVerifiedContent, type CultMeshContentErrorCode } from "../src/content.js";

View file

@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import { codecs, defineDocumentType, documentPayloadFromBytes } from "@gamecult/cultcache-ts"; import { codecs, defineDocumentType, documentPayloadFromBytes } from "@gamecult/cultcache-ts";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
encodeCultNetMessageForWire, encodeCultNetMessageForWire,
parseCultNetMessage, parseCultNetMessage,
@ -12,7 +12,7 @@ import {
type CultNetRawDocumentRecord, type CultNetRawDocumentRecord,
type CultMeshVerseCatalogResponseMessage, type CultMeshVerseCatalogResponseMessage,
type CultMeshSessionOpenMessage, type CultMeshSessionOpenMessage,
} from "cultnet-ts/contracts"; } from "@gamecult/cultnet-ts/contracts";
import { import {
CultMeshBrowserClient, CultMeshBrowserClient,

View file

@ -5,8 +5,8 @@ import { readFileSync } from "node:fs";
import { createServer } from "node:https"; import { createServer } from "node:https";
import type { AddressInfo } from "node:net"; import type { AddressInfo } from "node:net";
import { createInterface } from "node:readline"; import { createInterface } from "node:readline";
import { chunkRecordKey } from "cultnet-ts/content"; import { chunkRecordKey } from "@gamecult/cultnet-ts/content";
import { createContentChunkHandler, createDirectoryChunkStore, toNodeListener, type ContentChunkAnswer, type ContentChunkRequest } from "cultmesh-ts/content"; import { createContentChunkHandler, createDirectoryChunkStore, toNodeListener, type ContentChunkAnswer, type ContentChunkRequest } from "@gamecult/cultmesh-ts/content";
const [storeDir, corruptDir, keyPem, certPem, escapeKey] = process.argv.slice(2) as [string, string, string, string, string]; const [storeDir, corruptDir, keyPem, certPem, escapeKey] = process.argv.slice(2) as [string, string, string, string, string];
const say = (line: object): void => { process.stdout.write(`${JSON.stringify(line)}\n`); }; const say = (line: object): void => { process.stdout.write(`${JSON.stringify(line)}\n`); };

View file

@ -3,7 +3,7 @@
import { createHash } from "node:crypto"; import { createHash } from "node:crypto";
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { decodeManifest } from "cultnet-ts/content"; import { decodeManifest } from "@gamecult/cultnet-ts/content";
import { fetchVerifiedChunk, fetchVerifiedContent, CultMeshContentError } from "../../src/content.js"; import { fetchVerifiedChunk, fetchVerifiedContent, CultMeshContentError } from "../../src/content.js";
const [endpointsJson, manifestsDir, only] = process.argv.slice(2) as [string, string, string | undefined]; const [endpointsJson, manifestsDir, only] = process.argv.slice(2) as [string, string, string | undefined];

View file

@ -12,7 +12,7 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path"; import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { promisify } from "node:util"; import { promisify } from "node:util";
import { EMPTY_SHA256, encodeManifest, packContent } from "cultnet-ts/content"; import { EMPTY_SHA256, encodeManifest, packContent } from "@gamecult/cultnet-ts/content";
const execFileAsync = promisify(execFile); const execFileAsync = promisify(execFile);
const here = dirname(fileURLToPath(import.meta.url)); // dist-test/test/interop const here = dirname(fileURLToPath(import.meta.url)); // dist-test/test/interop

View file

@ -2,8 +2,8 @@ import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import { documentPayloadBytes, documentPayloadFromBytes, type DocumentPayload } from "@gamecult/cultcache-ts"; import { documentPayloadBytes, documentPayloadFromBytes, type DocumentPayload } from "@gamecult/cultcache-ts";
import { decodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue } from "@gamecult/cultnet-ts/wire";
import type { CultNetRawDocumentRecord } from "cultnet-ts/contracts"; import type { CultNetRawDocumentRecord } from "@gamecult/cultnet-ts/contracts";
import { decodeCultNetPayload } from "../src/index.js"; import { decodeCultNetPayload } from "../src/index.js";

View file

@ -474,3 +474,14 @@ powershell -ExecutionPolicy Bypass -File .\packages\cultmesh-kotlin\build.ps1
The build writes `artifacts/cultmesh-kotlin/cultmesh-kotlin.jar`. The build writes `artifacts/cultmesh-kotlin/cultmesh-kotlin.jar`.
It also runs the built-in RUDP packet fixture and localhost UDP socket It also runs the built-in RUDP packet fixture and localhost UDP socket
self-test. self-test.
## Write Receipt
`WriteReceipt.kt` decodes `cultnet.write_admitted.v0` and `cultnet.error.v1` (and `error.v0`) strictly against their
closed schemas (`decodeWriteAdmitted`, `decodeErrorFrame`), computes the dedupe `writeContentHash`, tests a hello with
`helloAdvertisesWriteReceipts`, and settles sent writes as admitted, refused or unconfirmed in `WriteTracker`
(pure state machine, abstract clock; the caller owns transport and timers). Kotlin has no write client yet, so nothing
sends a put and waits on this. `WriteReceiptVectors.kt` replays
`contracts/cultnet/interop/write-receipt-vectors.json` (constants, contentHash, wire, schemaInvalid, scenarios; the
server-side `dedupe` and `blankFields` sections are not run); `build.ps1` runs it after the self-test, or run
`CultMeshKt write-receipt-vectors <path>`.

View file

@ -26,4 +26,7 @@ $sources = Get-ChildItem $src -Recurse -Filter *.kt | Select-Object -ExpandPrope
if ($LASTEXITCODE -ne 0) { throw "kotlinc failed with exit code $LASTEXITCODE" } if ($LASTEXITCODE -ne 0) { throw "kotlinc failed with exit code $LASTEXITCODE" }
& $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt & $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt
if ($LASTEXITCODE -ne 0) { throw "cultmesh-kotlin self-test failed with exit code $LASTEXITCODE" } if ($LASTEXITCODE -ne 0) { throw "cultmesh-kotlin self-test failed with exit code $LASTEXITCODE" }
$vectors = Join-Path $repoRoot "contracts\cultnet\interop\write-receipt-vectors.json"
& $java -cp "$jarPath;$kotlinStdlib" org.gamecult.cultmesh.CultMeshKt write-receipt-vectors $vectors
if ($LASTEXITCODE -ne 0) { throw "write-receipt vector replay failed with exit code $LASTEXITCODE" }
Write-Host "Built $jarPath" Write-Host "Built $jarPath"

View file

@ -19,6 +19,7 @@ import java.net.Socket
import java.net.SocketTimeoutException import java.net.SocketTimeoutException
import java.net.URI import java.net.URI
import java.nio.ByteBuffer import java.nio.ByteBuffer
import java.nio.charset.CodingErrorAction
import java.nio.charset.StandardCharsets import java.nio.charset.StandardCharsets
import java.security.SecureRandom import java.security.SecureRandom
import java.security.MessageDigest import java.security.MessageDigest
@ -808,6 +809,7 @@ interface CultNetSchemaMessageTransport : AutoCloseable {
val profile: CultNetTransportProfile val profile: CultNetTransportProfile
val stats: CultNetTransportStats val stats: CultNetTransportStats
/** Fire-and-forget: an ack or a return is not admission; read the result frame. */
fun sendSchemaMessage(message: CultNetMessage) fun sendSchemaMessage(message: CultNetMessage)
fun receiveSchemaMessage(timeoutMs: Long = 1_000, pollIntervalMs: Long = 5): CultNetMessage? fun receiveSchemaMessage(timeoutMs: Long = 1_000, pollIntervalMs: Long = 5): CultNetMessage?
@ -1099,9 +1101,9 @@ data class CultNetRawDocumentRecord(
"payloadEncoding" to payloadEncoding, "payloadEncoding" to payloadEncoding,
"payload" to payload.copyOf(), "payload" to payload.copyOf(),
) )
if (!sourceRuntimeId.isNullOrBlank()) wire["sourceRuntimeId"] = sourceRuntimeId if (!isBlankText(sourceRuntimeId)) wire["sourceRuntimeId"] = sourceRuntimeId
if (!sourceAgentId.isNullOrBlank()) wire["sourceAgentId"] = sourceAgentId if (!isBlankText(sourceAgentId)) wire["sourceAgentId"] = sourceAgentId
if (!sourceRole.isNullOrBlank()) wire["sourceRole"] = sourceRole if (!isBlankText(sourceRole)) wire["sourceRole"] = sourceRole
if (tags.isNotEmpty()) wire["tags"] = tags if (tags.isNotEmpty()) wire["tags"] = tags
return wire return wire
} }
@ -2363,6 +2365,9 @@ fun parseCultNetMessage(payload: ByteArray): CultNetMessage {
if (schemaVersion !is String || schemaVersion.isBlank()) { if (schemaVersion !is String || schemaVersion.isBlank()) {
throw IOException("CultNet schema-v0 messages must declare schemaVersion") throw IOException("CultNet schema-v0 messages must declare schemaVersion")
} }
// A write_admitted id is echoed byte for byte, so that frame alone is read again with invalid UTF-8 refused; document payload
// strings elsewhere keep decoding as before.
if (schemaVersion == WRITE_ADMITTED_VERSION) MessagePackReader(payload, strictUtf8 = true).readAny()
val body = linkedMapOf<String, Any?>() val body = linkedMapOf<String, Any?>()
for ((key, value) in decoded) { for ((key, value) in decoded) {
if (key !is String) throw IOException("CultNet schema-v0 message keys must be strings") if (key !is String) throw IOException("CultNet schema-v0 message keys must be strings")
@ -3167,13 +3172,16 @@ class CultNetRudpSocketTransportConnection(
return connected return connected
} }
/** Fire-and-forget: an ack or a return is not admission; read the result frame. */
fun send(channelId: String, payload: ByteArray) { fun send(channelId: String, payload: ByteArray) {
session.sendMany(channelId, payload, channelSendOptions(channelId, nowMs()), maxFragmentBytes).forEach { sendPacket(it) } session.sendMany(channelId, payload, channelSendOptions(channelId, nowMs()), maxFragmentBytes).forEach { sendPacket(it) }
framesSent += 1 framesSent += 1
} }
/** Fire-and-forget: an ack or a return is not admission; read the result frame. */
fun send(channelId: String, payload: String) = send(channelId, payload.toByteArray(StandardCharsets.UTF_8)) fun send(channelId: String, payload: String) = send(channelId, payload.toByteArray(StandardCharsets.UTF_8))
/** Fire-and-forget: an ack or a return is not admission; read the result frame. */
fun sendSchema(payload: ByteArray) = send("schema", payload) fun sendSchema(payload: ByteArray) = send("schema", payload)
fun sendSchema(payload: String) = sendSchema(payload.toByteArray(StandardCharsets.UTF_8)) fun sendSchema(payload: String) = sendSchema(payload.toByteArray(StandardCharsets.UTF_8))
@ -3409,6 +3417,7 @@ fun main(args: Array<String>) {
rudpClientBindsLoopbackOnlyForALoopbackEndpoint() rudpClientBindsLoopbackOnlyForALoopbackEndpoint()
rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames() rudpSocketTransportHandshakesAndCarriesReliableOrderedSchemaFrames()
rudpSocketTransportCarriesFragmentedReliableOrderedSchemaFrames() rudpSocketTransportCarriesFragmentedReliableOrderedSchemaFrames()
rawDocumentRecordDropsOnlyWhiteSpaceSourceIds()
return return
} }
@ -3420,6 +3429,7 @@ fun main(args: Array<String>) {
"rudp-dial-message-once" -> rudpDialSchemaMessageOnce(options) "rudp-dial-message-once" -> rudpDialSchemaMessageOnce(options)
"serve" -> interopServe(options) "serve" -> interopServe(options)
"dial" -> interopDial(options) "dial" -> interopDial(options)
"write-receipt-vectors" -> if (!replayWriteReceiptVectors(args.getOrNull(1) ?: error("usage: write-receipt-vectors <vectors.json>"))) kotlin.system.exitProcess(1)
else -> error("Unknown mode ${args[0]}") else -> error("Unknown mode ${args[0]}")
} }
} }
@ -6145,7 +6155,8 @@ private fun requireSchemaResponse(message: CultNetMessage?, expectedSchemaVersio
return response return response
} }
class MessagePackReader(payload: ByteArray) { /** [strictUtf8] makes a str whose bytes are not UTF-8 throw instead of becoming U+FFFD; only the write_admitted frame asks for it. */
class MessagePackReader(payload: ByteArray, private val strictUtf8: Boolean = false) {
private val input = DataInputStream(ByteArrayInputStream(payload)) private val input = DataInputStream(ByteArrayInputStream(payload))
private var pushed = -1 private var pushed = -1
@ -6300,7 +6311,10 @@ class MessagePackReader(payload: ByteArray) {
code == 0xdb -> input.readInt() code == 0xdb -> input.readInt()
else -> throw IOException("expected string") else -> throw IOException("expected string")
} }
return String(readPayload(length), StandardCharsets.UTF_8) val bytes = readPayload(length)
if (!strictUtf8) return String(bytes, StandardCharsets.UTF_8)
return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes)).toString()
} }
private fun readBinaryAfterCode(code: Int): ByteArray { private fun readBinaryAfterCode(code: Int): ByteArray {

View file

@ -0,0 +1,129 @@
// generated, Unicode 16.0.0, by scripts/gen-unicode-messageid-tables.py (inputs sha256 24a07ef9fabf71e3); do not edit
package org.gamecult.cultmesh
// (low, high) pairs, flattened and sorted.
internal val LETTER_OR_NUMBER: IntArray = intArrayOf(
0x30, 0x39, 0x41, 0x5A, 0x61, 0x7A, 0xAA, 0xAA, 0xB2, 0xB3, 0xB5, 0xB5, 0xB9, 0xBA, 0xBC, 0xBE, 0xC0, 0xD6, 0xD8,
0xF6, 0xF8, 0x2C1, 0x2C6, 0x2D1, 0x2E0, 0x2E4, 0x2EC, 0x2EC, 0x2EE, 0x2EE, 0x370, 0x374, 0x376, 0x377, 0x37A,
0x37D, 0x37F, 0x37F, 0x386, 0x386, 0x388, 0x38A, 0x38C, 0x38C, 0x38E, 0x3A1, 0x3A3, 0x3F5, 0x3F7, 0x481, 0x48A,
0x52F, 0x531, 0x556, 0x559, 0x559, 0x560, 0x588, 0x5D0, 0x5EA, 0x5EF, 0x5F2, 0x620, 0x64A, 0x660, 0x669, 0x66E,
0x66F, 0x671, 0x6D3, 0x6D5, 0x6D5, 0x6E5, 0x6E6, 0x6EE, 0x6FC, 0x6FF, 0x6FF, 0x710, 0x710, 0x712, 0x72F, 0x74D,
0x7A5, 0x7B1, 0x7B1, 0x7C0, 0x7EA, 0x7F4, 0x7F5, 0x7FA, 0x7FA, 0x800, 0x815, 0x81A, 0x81A, 0x824, 0x824, 0x828,
0x828, 0x840, 0x858, 0x860, 0x86A, 0x870, 0x887, 0x889, 0x88E, 0x8A0, 0x8C9, 0x904, 0x939, 0x93D, 0x93D, 0x950,
0x950, 0x958, 0x961, 0x966, 0x96F, 0x971, 0x980, 0x985, 0x98C, 0x98F, 0x990, 0x993, 0x9A8, 0x9AA, 0x9B0, 0x9B2,
0x9B2, 0x9B6, 0x9B9, 0x9BD, 0x9BD, 0x9CE, 0x9CE, 0x9DC, 0x9DD, 0x9DF, 0x9E1, 0x9E6, 0x9F1, 0x9F4, 0x9F9, 0x9FC,
0x9FC, 0xA05, 0xA0A, 0xA0F, 0xA10, 0xA13, 0xA28, 0xA2A, 0xA30, 0xA32, 0xA33, 0xA35, 0xA36, 0xA38, 0xA39, 0xA59,
0xA5C, 0xA5E, 0xA5E, 0xA66, 0xA6F, 0xA72, 0xA74, 0xA85, 0xA8D, 0xA8F, 0xA91, 0xA93, 0xAA8, 0xAAA, 0xAB0, 0xAB2,
0xAB3, 0xAB5, 0xAB9, 0xABD, 0xABD, 0xAD0, 0xAD0, 0xAE0, 0xAE1, 0xAE6, 0xAEF, 0xAF9, 0xAF9, 0xB05, 0xB0C, 0xB0F,
0xB10, 0xB13, 0xB28, 0xB2A, 0xB30, 0xB32, 0xB33, 0xB35, 0xB39, 0xB3D, 0xB3D, 0xB5C, 0xB5D, 0xB5F, 0xB61, 0xB66,
0xB6F, 0xB71, 0xB77, 0xB83, 0xB83, 0xB85, 0xB8A, 0xB8E, 0xB90, 0xB92, 0xB95, 0xB99, 0xB9A, 0xB9C, 0xB9C, 0xB9E,
0xB9F, 0xBA3, 0xBA4, 0xBA8, 0xBAA, 0xBAE, 0xBB9, 0xBD0, 0xBD0, 0xBE6, 0xBF2, 0xC05, 0xC0C, 0xC0E, 0xC10, 0xC12,
0xC28, 0xC2A, 0xC39, 0xC3D, 0xC3D, 0xC58, 0xC5A, 0xC5D, 0xC5D, 0xC60, 0xC61, 0xC66, 0xC6F, 0xC78, 0xC7E, 0xC80,
0xC80, 0xC85, 0xC8C, 0xC8E, 0xC90, 0xC92, 0xCA8, 0xCAA, 0xCB3, 0xCB5, 0xCB9, 0xCBD, 0xCBD, 0xCDD, 0xCDE, 0xCE0,
0xCE1, 0xCE6, 0xCEF, 0xCF1, 0xCF2, 0xD04, 0xD0C, 0xD0E, 0xD10, 0xD12, 0xD3A, 0xD3D, 0xD3D, 0xD4E, 0xD4E, 0xD54,
0xD56, 0xD58, 0xD61, 0xD66, 0xD78, 0xD7A, 0xD7F, 0xD85, 0xD96, 0xD9A, 0xDB1, 0xDB3, 0xDBB, 0xDBD, 0xDBD, 0xDC0,
0xDC6, 0xDE6, 0xDEF, 0xE01, 0xE30, 0xE32, 0xE33, 0xE40, 0xE46, 0xE50, 0xE59, 0xE81, 0xE82, 0xE84, 0xE84, 0xE86,
0xE8A, 0xE8C, 0xEA3, 0xEA5, 0xEA5, 0xEA7, 0xEB0, 0xEB2, 0xEB3, 0xEBD, 0xEBD, 0xEC0, 0xEC4, 0xEC6, 0xEC6, 0xED0,
0xED9, 0xEDC, 0xEDF, 0xF00, 0xF00, 0xF20, 0xF33, 0xF40, 0xF47, 0xF49, 0xF6C, 0xF88, 0xF8C, 0x1000, 0x102A,
0x103F, 0x1049, 0x1050, 0x1055, 0x105A, 0x105D, 0x1061, 0x1061, 0x1065, 0x1066, 0x106E, 0x1070, 0x1075, 0x1081,
0x108E, 0x108E, 0x1090, 0x1099, 0x10A0, 0x10C5, 0x10C7, 0x10C7, 0x10CD, 0x10CD, 0x10D0, 0x10FA, 0x10FC, 0x1248,
0x124A, 0x124D, 0x1250, 0x1256, 0x1258, 0x1258, 0x125A, 0x125D, 0x1260, 0x1288, 0x128A, 0x128D, 0x1290, 0x12B0,
0x12B2, 0x12B5, 0x12B8, 0x12BE, 0x12C0, 0x12C0, 0x12C2, 0x12C5, 0x12C8, 0x12D6, 0x12D8, 0x1310, 0x1312, 0x1315,
0x1318, 0x135A, 0x1369, 0x137C, 0x1380, 0x138F, 0x13A0, 0x13F5, 0x13F8, 0x13FD, 0x1401, 0x166C, 0x166F, 0x167F,
0x1681, 0x169A, 0x16A0, 0x16EA, 0x16EE, 0x16F8, 0x1700, 0x1711, 0x171F, 0x1731, 0x1740, 0x1751, 0x1760, 0x176C,
0x176E, 0x1770, 0x1780, 0x17B3, 0x17D7, 0x17D7, 0x17DC, 0x17DC, 0x17E0, 0x17E9, 0x17F0, 0x17F9, 0x1810, 0x1819,
0x1820, 0x1878, 0x1880, 0x1884, 0x1887, 0x18A8, 0x18AA, 0x18AA, 0x18B0, 0x18F5, 0x1900, 0x191E, 0x1946, 0x196D,
0x1970, 0x1974, 0x1980, 0x19AB, 0x19B0, 0x19C9, 0x19D0, 0x19DA, 0x1A00, 0x1A16, 0x1A20, 0x1A54, 0x1A80, 0x1A89,
0x1A90, 0x1A99, 0x1AA7, 0x1AA7, 0x1B05, 0x1B33, 0x1B45, 0x1B4C, 0x1B50, 0x1B59, 0x1B83, 0x1BA0, 0x1BAE, 0x1BE5,
0x1C00, 0x1C23, 0x1C40, 0x1C49, 0x1C4D, 0x1C7D, 0x1C80, 0x1C8A, 0x1C90, 0x1CBA, 0x1CBD, 0x1CBF, 0x1CE9, 0x1CEC,
0x1CEE, 0x1CF3, 0x1CF5, 0x1CF6, 0x1CFA, 0x1CFA, 0x1D00, 0x1DBF, 0x1E00, 0x1F15, 0x1F18, 0x1F1D, 0x1F20, 0x1F45,
0x1F48, 0x1F4D, 0x1F50, 0x1F57, 0x1F59, 0x1F59, 0x1F5B, 0x1F5B, 0x1F5D, 0x1F5D, 0x1F5F, 0x1F7D, 0x1F80, 0x1FB4,
0x1FB6, 0x1FBC, 0x1FBE, 0x1FBE, 0x1FC2, 0x1FC4, 0x1FC6, 0x1FCC, 0x1FD0, 0x1FD3, 0x1FD6, 0x1FDB, 0x1FE0, 0x1FEC,
0x1FF2, 0x1FF4, 0x1FF6, 0x1FFC, 0x2070, 0x2071, 0x2074, 0x2079, 0x207F, 0x2089, 0x2090, 0x209C, 0x2102, 0x2102,
0x2107, 0x2107, 0x210A, 0x2113, 0x2115, 0x2115, 0x2119, 0x211D, 0x2124, 0x2124, 0x2126, 0x2126, 0x2128, 0x2128,
0x212A, 0x212D, 0x212F, 0x2139, 0x213C, 0x213F, 0x2145, 0x2149, 0x214E, 0x214E, 0x2150, 0x2189, 0x2460, 0x249B,
0x24EA, 0x24FF, 0x2776, 0x2793, 0x2C00, 0x2CE4, 0x2CEB, 0x2CEE, 0x2CF2, 0x2CF3, 0x2CFD, 0x2CFD, 0x2D00, 0x2D25,
0x2D27, 0x2D27, 0x2D2D, 0x2D2D, 0x2D30, 0x2D67, 0x2D6F, 0x2D6F, 0x2D80, 0x2D96, 0x2DA0, 0x2DA6, 0x2DA8, 0x2DAE,
0x2DB0, 0x2DB6, 0x2DB8, 0x2DBE, 0x2DC0, 0x2DC6, 0x2DC8, 0x2DCE, 0x2DD0, 0x2DD6, 0x2DD8, 0x2DDE, 0x2E2F, 0x2E2F,
0x3005, 0x3007, 0x3021, 0x3029, 0x3031, 0x3035, 0x3038, 0x303C, 0x3041, 0x3096, 0x309D, 0x309F, 0x30A1, 0x30FA,
0x30FC, 0x30FF, 0x3105, 0x312F, 0x3131, 0x318E, 0x3192, 0x3195, 0x31A0, 0x31BF, 0x31F0, 0x31FF, 0x3220, 0x3229,
0x3248, 0x324F, 0x3251, 0x325F, 0x3280, 0x3289, 0x32B1, 0x32BF, 0x3400, 0x4DBF, 0x4E00, 0xA48C, 0xA4D0, 0xA4FD,
0xA500, 0xA60C, 0xA610, 0xA62B, 0xA640, 0xA66E, 0xA67F, 0xA69D, 0xA6A0, 0xA6EF, 0xA717, 0xA71F, 0xA722, 0xA788,
0xA78B, 0xA7CD, 0xA7D0, 0xA7D1, 0xA7D3, 0xA7D3, 0xA7D5, 0xA7DC, 0xA7F2, 0xA801, 0xA803, 0xA805, 0xA807, 0xA80A,
0xA80C, 0xA822, 0xA830, 0xA835, 0xA840, 0xA873, 0xA882, 0xA8B3, 0xA8D0, 0xA8D9, 0xA8F2, 0xA8F7, 0xA8FB, 0xA8FB,
0xA8FD, 0xA8FE, 0xA900, 0xA925, 0xA930, 0xA946, 0xA960, 0xA97C, 0xA984, 0xA9B2, 0xA9CF, 0xA9D9, 0xA9E0, 0xA9E4,
0xA9E6, 0xA9FE, 0xAA00, 0xAA28, 0xAA40, 0xAA42, 0xAA44, 0xAA4B, 0xAA50, 0xAA59, 0xAA60, 0xAA76, 0xAA7A, 0xAA7A,
0xAA7E, 0xAAAF, 0xAAB1, 0xAAB1, 0xAAB5, 0xAAB6, 0xAAB9, 0xAABD, 0xAAC0, 0xAAC0, 0xAAC2, 0xAAC2, 0xAADB, 0xAADD,
0xAAE0, 0xAAEA, 0xAAF2, 0xAAF4, 0xAB01, 0xAB06, 0xAB09, 0xAB0E, 0xAB11, 0xAB16, 0xAB20, 0xAB26, 0xAB28, 0xAB2E,
0xAB30, 0xAB5A, 0xAB5C, 0xAB69, 0xAB70, 0xABE2, 0xABF0, 0xABF9, 0xAC00, 0xD7A3, 0xD7B0, 0xD7C6, 0xD7CB, 0xD7FB,
0xF900, 0xFA6D, 0xFA70, 0xFAD9, 0xFB00, 0xFB06, 0xFB13, 0xFB17, 0xFB1D, 0xFB1D, 0xFB1F, 0xFB28, 0xFB2A, 0xFB36,
0xFB38, 0xFB3C, 0xFB3E, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFBB1, 0xFBD3, 0xFD3D, 0xFD50, 0xFD8F,
0xFD92, 0xFDC7, 0xFDF0, 0xFDFB, 0xFE70, 0xFE74, 0xFE76, 0xFEFC, 0xFF10, 0xFF19, 0xFF21, 0xFF3A, 0xFF41, 0xFF5A,
0xFF66, 0xFFBE, 0xFFC2, 0xFFC7, 0xFFCA, 0xFFCF, 0xFFD2, 0xFFD7, 0xFFDA, 0xFFDC, 0x10000, 0x1000B, 0x1000D,
0x10026, 0x10028, 0x1003A, 0x1003C, 0x1003D, 0x1003F, 0x1004D, 0x10050, 0x1005D, 0x10080, 0x100FA, 0x10107,
0x10133, 0x10140, 0x10178, 0x1018A, 0x1018B, 0x10280, 0x1029C, 0x102A0, 0x102D0, 0x102E1, 0x102FB, 0x10300,
0x10323, 0x1032D, 0x1034A, 0x10350, 0x10375, 0x10380, 0x1039D, 0x103A0, 0x103C3, 0x103C8, 0x103CF, 0x103D1,
0x103D5, 0x10400, 0x1049D, 0x104A0, 0x104A9, 0x104B0, 0x104D3, 0x104D8, 0x104FB, 0x10500, 0x10527, 0x10530,
0x10563, 0x10570, 0x1057A, 0x1057C, 0x1058A, 0x1058C, 0x10592, 0x10594, 0x10595, 0x10597, 0x105A1, 0x105A3,
0x105B1, 0x105B3, 0x105B9, 0x105BB, 0x105BC, 0x105C0, 0x105F3, 0x10600, 0x10736, 0x10740, 0x10755, 0x10760,
0x10767, 0x10780, 0x10785, 0x10787, 0x107B0, 0x107B2, 0x107BA, 0x10800, 0x10805, 0x10808, 0x10808, 0x1080A,
0x10835, 0x10837, 0x10838, 0x1083C, 0x1083C, 0x1083F, 0x10855, 0x10858, 0x10876, 0x10879, 0x1089E, 0x108A7,
0x108AF, 0x108E0, 0x108F2, 0x108F4, 0x108F5, 0x108FB, 0x1091B, 0x10920, 0x10939, 0x10980, 0x109B7, 0x109BC,
0x109CF, 0x109D2, 0x10A00, 0x10A10, 0x10A13, 0x10A15, 0x10A17, 0x10A19, 0x10A35, 0x10A40, 0x10A48, 0x10A60,
0x10A7E, 0x10A80, 0x10A9F, 0x10AC0, 0x10AC7, 0x10AC9, 0x10AE4, 0x10AEB, 0x10AEF, 0x10B00, 0x10B35, 0x10B40,
0x10B55, 0x10B58, 0x10B72, 0x10B78, 0x10B91, 0x10BA9, 0x10BAF, 0x10C00, 0x10C48, 0x10C80, 0x10CB2, 0x10CC0,
0x10CF2, 0x10CFA, 0x10D23, 0x10D30, 0x10D39, 0x10D40, 0x10D65, 0x10D6F, 0x10D85, 0x10E60, 0x10E7E, 0x10E80,
0x10EA9, 0x10EB0, 0x10EB1, 0x10EC2, 0x10EC4, 0x10F00, 0x10F27, 0x10F30, 0x10F45, 0x10F51, 0x10F54, 0x10F70,
0x10F81, 0x10FB0, 0x10FCB, 0x10FE0, 0x10FF6, 0x11003, 0x11037, 0x11052, 0x1106F, 0x11071, 0x11072, 0x11075,
0x11075, 0x11083, 0x110AF, 0x110D0, 0x110E8, 0x110F0, 0x110F9, 0x11103, 0x11126, 0x11136, 0x1113F, 0x11144,
0x11144, 0x11147, 0x11147, 0x11150, 0x11172, 0x11176, 0x11176, 0x11183, 0x111B2, 0x111C1, 0x111C4, 0x111D0,
0x111DA, 0x111DC, 0x111DC, 0x111E1, 0x111F4, 0x11200, 0x11211, 0x11213, 0x1122B, 0x1123F, 0x11240, 0x11280,
0x11286, 0x11288, 0x11288, 0x1128A, 0x1128D, 0x1128F, 0x1129D, 0x1129F, 0x112A8, 0x112B0, 0x112DE, 0x112F0,
0x112F9, 0x11305, 0x1130C, 0x1130F, 0x11310, 0x11313, 0x11328, 0x1132A, 0x11330, 0x11332, 0x11333, 0x11335,
0x11339, 0x1133D, 0x1133D, 0x11350, 0x11350, 0x1135D, 0x11361, 0x11380, 0x11389, 0x1138B, 0x1138B, 0x1138E,
0x1138E, 0x11390, 0x113B5, 0x113B7, 0x113B7, 0x113D1, 0x113D1, 0x113D3, 0x113D3, 0x11400, 0x11434, 0x11447,
0x1144A, 0x11450, 0x11459, 0x1145F, 0x11461, 0x11480, 0x114AF, 0x114C4, 0x114C5, 0x114C7, 0x114C7, 0x114D0,
0x114D9, 0x11580, 0x115AE, 0x115D8, 0x115DB, 0x11600, 0x1162F, 0x11644, 0x11644, 0x11650, 0x11659, 0x11680,
0x116AA, 0x116B8, 0x116B8, 0x116C0, 0x116C9, 0x116D0, 0x116E3, 0x11700, 0x1171A, 0x11730, 0x1173B, 0x11740,
0x11746, 0x11800, 0x1182B, 0x118A0, 0x118F2, 0x118FF, 0x11906, 0x11909, 0x11909, 0x1190C, 0x11913, 0x11915,
0x11916, 0x11918, 0x1192F, 0x1193F, 0x1193F, 0x11941, 0x11941, 0x11950, 0x11959, 0x119A0, 0x119A7, 0x119AA,
0x119D0, 0x119E1, 0x119E1, 0x119E3, 0x119E3, 0x11A00, 0x11A00, 0x11A0B, 0x11A32, 0x11A3A, 0x11A3A, 0x11A50,
0x11A50, 0x11A5C, 0x11A89, 0x11A9D, 0x11A9D, 0x11AB0, 0x11AF8, 0x11BC0, 0x11BE0, 0x11BF0, 0x11BF9, 0x11C00,
0x11C08, 0x11C0A, 0x11C2E, 0x11C40, 0x11C40, 0x11C50, 0x11C6C, 0x11C72, 0x11C8F, 0x11D00, 0x11D06, 0x11D08,
0x11D09, 0x11D0B, 0x11D30, 0x11D46, 0x11D46, 0x11D50, 0x11D59, 0x11D60, 0x11D65, 0x11D67, 0x11D68, 0x11D6A,
0x11D89, 0x11D98, 0x11D98, 0x11DA0, 0x11DA9, 0x11EE0, 0x11EF2, 0x11F02, 0x11F02, 0x11F04, 0x11F10, 0x11F12,
0x11F33, 0x11F50, 0x11F59, 0x11FB0, 0x11FB0, 0x11FC0, 0x11FD4, 0x12000, 0x12399, 0x12400, 0x1246E, 0x12480,
0x12543, 0x12F90, 0x12FF0, 0x13000, 0x1342F, 0x13441, 0x13446, 0x13460, 0x143FA, 0x14400, 0x14646, 0x16100,
0x1611D, 0x16130, 0x16139, 0x16800, 0x16A38, 0x16A40, 0x16A5E, 0x16A60, 0x16A69, 0x16A70, 0x16ABE, 0x16AC0,
0x16AC9, 0x16AD0, 0x16AED, 0x16B00, 0x16B2F, 0x16B40, 0x16B43, 0x16B50, 0x16B59, 0x16B5B, 0x16B61, 0x16B63,
0x16B77, 0x16B7D, 0x16B8F, 0x16D40, 0x16D6C, 0x16D70, 0x16D79, 0x16E40, 0x16E96, 0x16F00, 0x16F4A, 0x16F50,
0x16F50, 0x16F93, 0x16F9F, 0x16FE0, 0x16FE1, 0x16FE3, 0x16FE3, 0x17000, 0x187F7, 0x18800, 0x18CD5, 0x18CFF,
0x18D08, 0x1AFF0, 0x1AFF3, 0x1AFF5, 0x1AFFB, 0x1AFFD, 0x1AFFE, 0x1B000, 0x1B122, 0x1B132, 0x1B132, 0x1B150,
0x1B152, 0x1B155, 0x1B155, 0x1B164, 0x1B167, 0x1B170, 0x1B2FB, 0x1BC00, 0x1BC6A, 0x1BC70, 0x1BC7C, 0x1BC80,
0x1BC88, 0x1BC90, 0x1BC99, 0x1CCF0, 0x1CCF9, 0x1D2C0, 0x1D2D3, 0x1D2E0, 0x1D2F3, 0x1D360, 0x1D378, 0x1D400,
0x1D454, 0x1D456, 0x1D49C, 0x1D49E, 0x1D49F, 0x1D4A2, 0x1D4A2, 0x1D4A5, 0x1D4A6, 0x1D4A9, 0x1D4AC, 0x1D4AE,
0x1D4B9, 0x1D4BB, 0x1D4BB, 0x1D4BD, 0x1D4C3, 0x1D4C5, 0x1D505, 0x1D507, 0x1D50A, 0x1D50D, 0x1D514, 0x1D516,
0x1D51C, 0x1D51E, 0x1D539, 0x1D53B, 0x1D53E, 0x1D540, 0x1D544, 0x1D546, 0x1D546, 0x1D54A, 0x1D550, 0x1D552,
0x1D6A5, 0x1D6A8, 0x1D6C0, 0x1D6C2, 0x1D6DA, 0x1D6DC, 0x1D6FA, 0x1D6FC, 0x1D714, 0x1D716, 0x1D734, 0x1D736,
0x1D74E, 0x1D750, 0x1D76E, 0x1D770, 0x1D788, 0x1D78A, 0x1D7A8, 0x1D7AA, 0x1D7C2, 0x1D7C4, 0x1D7CB, 0x1D7CE,
0x1D7FF, 0x1DF00, 0x1DF1E, 0x1DF25, 0x1DF2A, 0x1E030, 0x1E06D, 0x1E100, 0x1E12C, 0x1E137, 0x1E13D, 0x1E140,
0x1E149, 0x1E14E, 0x1E14E, 0x1E290, 0x1E2AD, 0x1E2C0, 0x1E2EB, 0x1E2F0, 0x1E2F9, 0x1E4D0, 0x1E4EB, 0x1E4F0,
0x1E4F9, 0x1E5D0, 0x1E5ED, 0x1E5F0, 0x1E5FA, 0x1E7E0, 0x1E7E6, 0x1E7E8, 0x1E7EB, 0x1E7ED, 0x1E7EE, 0x1E7F0,
0x1E7FE, 0x1E800, 0x1E8C4, 0x1E8C7, 0x1E8CF, 0x1E900, 0x1E943, 0x1E94B, 0x1E94B, 0x1E950, 0x1E959, 0x1EC71,
0x1ECAB, 0x1ECAD, 0x1ECAF, 0x1ECB1, 0x1ECB4, 0x1ED01, 0x1ED2D, 0x1ED2F, 0x1ED3D, 0x1EE00, 0x1EE03, 0x1EE05,
0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE24, 0x1EE27, 0x1EE27, 0x1EE29, 0x1EE32, 0x1EE34, 0x1EE37, 0x1EE39,
0x1EE39, 0x1EE3B, 0x1EE3B, 0x1EE42, 0x1EE42, 0x1EE47, 0x1EE47, 0x1EE49, 0x1EE49, 0x1EE4B, 0x1EE4B, 0x1EE4D,
0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE54, 0x1EE57, 0x1EE57, 0x1EE59, 0x1EE59, 0x1EE5B, 0x1EE5B, 0x1EE5D,
0x1EE5D, 0x1EE5F, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE64, 0x1EE67, 0x1EE6A, 0x1EE6C, 0x1EE72, 0x1EE74,
0x1EE77, 0x1EE79, 0x1EE7C, 0x1EE7E, 0x1EE7E, 0x1EE80, 0x1EE89, 0x1EE8B, 0x1EE9B, 0x1EEA1, 0x1EEA3, 0x1EEA5,
0x1EEA9, 0x1EEAB, 0x1EEBB, 0x1F100, 0x1F10C, 0x1FBF0, 0x1FBF9, 0x20000, 0x2A6DF, 0x2A700, 0x2B739, 0x2B740,
0x2B81D, 0x2B820, 0x2CEA1, 0x2CEB0, 0x2EBE0, 0x2EBF0, 0x2EE5D, 0x2F800, 0x2FA1D, 0x30000, 0x3134A, 0x31350,
0x323AF,
)
internal val DEFAULT_IGNORABLE: IntArray = intArrayOf(
0xAD, 0xAD, 0x34F, 0x34F, 0x61C, 0x61C, 0x115F, 0x1160, 0x17B4, 0x17B5, 0x180B, 0x180F, 0x200B, 0x200F, 0x202A,
0x202E, 0x2060, 0x206F, 0x3164, 0x3164, 0xFE00, 0xFE0F, 0xFEFF, 0xFEFF, 0xFFA0, 0xFFA0, 0xFFF0, 0xFFF8, 0x1BCA0,
0x1BCA3, 0x1D173, 0x1D17A, 0xE0000, 0xE0FFF,
)

View file

@ -0,0 +1,286 @@
package org.gamecult.cultmesh
// The write receipt (contracts/cultnet/interop/write-receipt.md): the two frames, their strict decode, the dedupe
// content hash, the hello capability test and the client settle rules. Mirrors packages/cultnet-ts (contracts.ts,
// write-tracker.ts) and packages/cultnet-rs (write_content_hash). The replay of write-receipt-vectors.json lives in
// WriteReceiptVectors.kt. Server rules (dedupe, limits, blank fields) are not a decoder's business and are not here.
import java.io.IOException
import java.security.MessageDigest
const val WRITE_ADMITTED_VERSION = "cultnet.write_admitted.v0"
const val ERROR_V1_VERSION = "cultnet.error.v1"
const val ERROR_V0_VERSION = "cultnet.error.v0"
/** A connection is receipt-capable only when its hello lists both frames. */
val CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS: List<String> = listOf(WRITE_ADMITTED_VERSION, ERROR_V1_VERSION)
const val RECEIPT_RESULT_WINDOW_MS = 5000L
const val LEGACY_RESULT_WINDOW_MS = 500L
fun resultWindowMs(serverAdvertisesReceipts: Boolean): Long =
if (serverAdvertisesReceipts) RECEIPT_RESULT_WINDOW_MS else LEGACY_RESULT_WINDOW_MS
/** The closed refusal-code set of error.v0; error.v1 adds `limit_reached`. */
val CULTNET_ERROR_V0_CODES: Set<String> = setOf(
"selection_invalid", "cursor_stale", "cursor_invalid", "reference_outside_target", "variant_unsupported",
"unowned_schema", "write_not_authorized", "unsupported_schema_version", "message_invalid",
)
val CULTNET_ERROR_V1_CODES: Set<String> = CULTNET_ERROR_V0_CODES + "limit_reached"
fun helloAdvertisesWriteReceipts(hello: CultNetMessage): Boolean {
val versions = hello.body["supportedMessageVersions"] as? List<*> ?: return false
return CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS.all { it in versions }
}
data class CultNetWriteAdmitted(val messageId: String, val operation: String, val schemaId: String, val recordKey: String) {
fun toMessage() = CultNetMessage(
WRITE_ADMITTED_VERSION,
linkedMapOf("messageId" to messageId, "operation" to operation, "schemaId" to schemaId, "recordKey" to recordKey),
)
}
data class CultNetErrorDetails(val field: String?, val value: String?, val asOf: Long?, val current: Long?)
/** error.v0 (`messageId` always null, `version` 0) or error.v1 (`version` 1). */
data class CultNetErrorFrame(
val version: Int,
val error: String,
val routingHint: Map<String, Any?>?,
val code: String?,
val details: CultNetErrorDetails?,
val messageId: String?,
) {
fun toMessage(): CultNetMessage {
val body = linkedMapOf<String, Any?>(
"error" to error,
"routingHint" to routingHint,
"code" to code,
"details" to details?.let {
linkedMapOf("field" to it.field, "value" to it.value, "asOf" to it.asOf, "current" to it.current)
},
)
if (version == 1) body["messageId"] = messageId
return CultNetMessage(if (version == 1) ERROR_V1_VERSION else ERROR_V0_VERSION, body)
}
}
/**
* Strict decode of a write_admitted.v0 message against its closed schema: exactly five keys, a non-empty string each,
* operation put|delete.
*/
fun decodeWriteAdmitted(message: CultNetMessage): CultNetWriteAdmitted {
if (message.schemaVersion != WRITE_ADMITTED_VERSION) throw IOException("not a $WRITE_ADMITTED_VERSION message")
closedKeys(message, setOf("messageId", "operation", "schemaId", "recordKey"))
val operation = nonEmpty(message, "operation")
if (operation != "put" && operation != "delete") throw IOException("operation must be put or delete")
return CultNetWriteAdmitted(admittedMessageId(message), operation, nonEmpty(message, "schemaId"), nonEmpty(message, "recordKey"))
}
// write-receipt.md: a letter (Lu Ll Lt Lm Lo) or number (Nd Nl No) somewhere, no Default_Ignorable code point anywhere, as of
// Unicode 16.0, compared raw (never trimmed). The tables are embedded (UnicodeMessageIdTables.kt, generated by
// scripts/gen-unicode-messageid-tables.py), not the JDK's, so the running JVM's Unicode version changes no result; the other
// four runtimes embed the same generated tables.
private fun inRanges(ranges: IntArray, point: Int): Boolean {
var low = 0
var high = ranges.size / 2 - 1
while (low <= high) {
val mid = (low + high) ushr 1
when {
point < ranges[2 * mid] -> high = mid - 1
point > ranges[2 * mid + 1] -> low = mid + 1
else -> return true
}
}
return false
}
private fun admittedMessageId(message: CultNetMessage): String {
val id = nonEmpty(message, "messageId")
var hasLetterOrNumber = false
id.codePoints().forEach { cp ->
if (inRanges(DEFAULT_IGNORABLE, cp)) throw IOException("messageId holds a Default_Ignorable code point")
if (inRanges(LETTER_OR_NUMBER, cp)) hasLetterOrNumber = true
}
if (!hasLetterOrNumber) throw IOException("messageId must contain a letter or number")
return id
}
/** Strict decode of error.v0 (no messageId, no limit_reached) or error.v1 (messageId required, string or nil, never empty). */
fun decodeErrorFrame(message: CultNetMessage): CultNetErrorFrame {
val version = when (message.schemaVersion) {
ERROR_V1_VERSION -> 1
ERROR_V0_VERSION -> 0
else -> throw IOException("not an error message")
}
closedKeys(message, setOf("error", "routingHint", "code", "details") + if (version == 1) setOf("messageId") else emptySet())
val error = nonEmpty(message, "error")
val codeValue = message.body["code"]
if (codeValue != null && (codeValue !is String || codeValue !in (if (version == 1) CULTNET_ERROR_V1_CODES else CULTNET_ERROR_V0_CODES))) {
throw IOException("unknown error code")
}
var messageId: String? = null
if (version == 1) {
val id = message.body["messageId"]
if (id != null && (id !is String || id.isEmpty())) throw IOException("messageId must be a non-empty string or nil")
messageId = id as String?
}
return CultNetErrorFrame(version, error, routingHintOf(message.body["routingHint"]), codeValue as String?, detailsOf(message.body["details"]), messageId)
}
private fun closedKeys(message: CultNetMessage, required: Set<String>) {
if (!message.body.keys.containsAll(required)) throw IOException("${message.schemaVersion} is missing ${required - message.body.keys}")
val unknown = message.body.keys - required
if (unknown.isNotEmpty()) throw IOException("${message.schemaVersion} carries unknown keys $unknown")
}
private fun nonEmpty(message: CultNetMessage, key: String): String {
val value = message.body[key]
if (value !is String || value.isEmpty()) throw IOException("$key must be a non-empty string")
return value
}
private fun routingHintOf(value: Any?): Map<String, Any?>? {
if (value == null) return null
if (value !is Map<*, *> || value.keys != setOf("shard", "reason")) throw IOException("routingHint must be nil or {shard, reason}")
if (value["shard"] != null && value["shard"] !is Map<*, *>) throw IOException("routingHint.shard must be an object or nil")
if (value["reason"] !is String) throw IOException("routingHint.reason must be a string")
@Suppress("UNCHECKED_CAST")
return value as Map<String, Any?>
}
private fun detailsOf(value: Any?): CultNetErrorDetails? {
if (value == null) return null
if (value !is Map<*, *> || value.keys != setOf("field", "value", "asOf", "current")) {
throw IOException("details must be nil or {field, value, asOf, current}")
}
fun text(key: String): String? = value[key].let { if (it == null || it is String) it as String? else throw IOException("details.$key must be a string or nil") }
fun cursor(key: String): Long? = value[key].let {
if (it == null) null else if (it is Long && it >= 0) it else throw IOException("details.$key must be a non-negative integer or nil")
}
return CultNetErrorDetails(text("field"), text("value"), cursor("asOf"), cursor("current"))
}
/** sha256 of the MessagePack array [operation, schemaId, recordKey, payload]: payload a bin for a put, nil for a delete. Lowercase hex. */
fun writeContentHash(operation: String, schemaId: String, recordKey: String, payload: ByteArray?): String {
val writer = MessagePackWriter().array(4).string(operation).string(schemaId).string(recordKey)
if (payload == null) writer.nil() else writer.binary(payload)
return MessageDigest.getInstance("SHA-256").digest(writer.toByteArray()).joinToString("") { "%02x".format(it) }
}
/** Why nothing settled a write. */
enum class WriteUnconfirmedReason(val wire: String) { WINDOW_ELAPSED("window_elapsed"), SESSION_ENDED("session_ended"), LOCAL_SEND_FAILED("local_send_failed") }
/** What a late answer is recorded as on a write that already settled unconfirmed. */
enum class WriteRecorded(val wire: String) { ADMITTED_LATE("admitted_late"), REFUSED_LATE("refused_late") }
/** What the caller was told. Settled once; never changed by a later frame. */
sealed class WriteSettlement {
object Admitted : WriteSettlement()
data class Refused(val code: String?, val error: String, val response: CultNetErrorFrame) : WriteSettlement()
data class Unconfirmed(val reason: WriteUnconfirmedReason) : WriteSettlement()
}
/**
* The client half of the receipt rules: a pure state machine with an abstract clock, one decision, how each sent write
* settles. Transport, timers and decoding belong to the caller; `frame` takes a message and decodes it strictly.
*/
class WriteTracker(private val windowMs: Long, private val onSettle: (String, WriteSettlement) -> Unit = { _, _ -> }) {
private class Entry(val sentAtMs: Long) {
var settlement: WriteSettlement? = null
var recorded: WriteRecorded? = null
}
private val writes = linkedMapOf<String, Entry>()
private var ended = false
/** Registers a write sent at [atMs]. Re-sending a known id is the same write and does not restart its window. */
fun send(messageId: String, atMs: Long) {
tick(atMs)
if (messageId in writes) return
val entry = Entry(atMs)
writes[messageId] = entry
// On a session that already ended nothing can answer this write.
if (ended) settle(messageId, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.SESSION_ENDED))
}
/** Feeds one received message. Only write_admitted, error.v1 and error.v0 answer; anything else is ignored. */
fun frame(message: CultNetMessage, atMs: Long) {
tick(atMs)
when (message.schemaVersion) {
WRITE_ADMITTED_VERSION -> {
answer(decodeWriteAdmitted(message).messageId, WriteSettlement.Admitted, WriteRecorded.ADMITTED_LATE)
return
}
ERROR_V1_VERSION, ERROR_V0_VERSION -> {
val error = decodeErrorFrame(message)
val refusal = WriteSettlement.Refused(error.code, error.error, error)
if (error.messageId != null) {
answer(error.messageId, refusal, WriteRecorded.REFUSED_LATE)
return
}
// An error that names no write is attributable only when exactly one write is unanswered.
val unanswered = writes.filterValues { it.settlement == null }
if (unanswered.size == 1) settle(unanswered.keys.first(), unanswered.values.first(), refusal)
}
else -> return
}
}
/** Every unanswered write whose window, counted from its own send, has run settles unconfirmed. */
fun tick(atMs: Long) {
for ((id, entry) in writes) {
if (entry.settlement == null && atMs - entry.sentAtMs >= windowMs) settle(id, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.WINDOW_ELAPSED))
}
}
/** The session ended: every unanswered write settles unconfirmed, and so does any write sent afterwards. */
fun sessionEnd(atMs: Long) {
tick(atMs)
ended = true
for ((id, entry) in writes) if (entry.settlement == null) settle(id, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.SESSION_ENDED))
}
/** This client's own send of [messageId] failed: that write settles unconfirmed; the others are untouched. */
fun sendFailed(messageId: String, atMs: Long) {
val entry = writes[messageId]
if (entry != null && entry.settlement == null) settle(messageId, entry, WriteSettlement.Unconfirmed(WriteUnconfirmedReason.LOCAL_SEND_FAILED))
tick(atMs)
}
/** The settlement told to the caller, or null while unanswered or unknown. */
fun settlement(messageId: String): WriteSettlement? = writes[messageId]?.settlement
/** The late answer recorded on an unconfirmed write. */
fun recorded(messageId: String): WriteRecorded? = writes[messageId]?.recorded
private fun answer(messageId: String, settlement: WriteSettlement, late: WriteRecorded) {
val entry = writes[messageId] ?: return // names a write that is not in flight: settles nothing
val current = entry.settlement
if (current == null) settle(messageId, entry, settlement)
else if (current is WriteSettlement.Unconfirmed && entry.recorded == null) entry.recorded = late
}
private fun settle(messageId: String, entry: Entry, settlement: WriteSettlement) {
entry.settlement = settlement
onSettle(messageId, settlement)
}
}
/** Unicode White_Space (PropList), the one definition of "blank" in write-receipt.md rule 5; Kotlin's own isBlank takes U+001C to U+001F. */
private val WHITE_SPACE_CODE_POINTS: Set<Int> = (0x0009..0x000D).toSet() + 0x0020 + 0x0085 + 0x00A0 + 0x1680 +
(0x2000..0x200A).toSet() + 0x2028 + 0x2029 + 0x202F + 0x205F + 0x3000
/** True for null, empty, or only White_Space code points. */
fun isBlankText(text: String?): Boolean = text == null || text.codePoints().allMatch { it in WHITE_SPACE_CODE_POINTS }
/** Self-test: blank is White_Space, not Kotlin's isBlank (rule 5): U+001C to U+001F name something, U+00A0 and U+0085 do not. */
fun rawDocumentRecordDropsOnlyWhiteSpaceSourceIds() {
fun wireKeys(id: String) = CultNetRawDocumentRecord("note.v0", "note:1", "2026-11-08T00:00:00Z", payload = byteArrayOf(1), sourceRuntimeId = id, sourceAgentId = id, sourceRole = id).toWireMap().keys
for (blank in listOf("", "\u0085", "\u00a0\u2003", "\u3000", "\t\r\n ")) {
check(isBlankText(blank) && "sourceRuntimeId" !in wireKeys(blank)) { "blank ${blank.map { it.code }} must be dropped" }
}
for (named in listOf("\u001c", "\u001f", "\u200b", "\ufeff", "\u180e", "a")) {
check(!isBlankText(named) && "sourceRuntimeId" in wireKeys(named) && "sourceRole" in wireKeys(named)) { "${named.map { it.code }} names something and must be kept" }
}
}

View file

@ -0,0 +1,310 @@
package org.gamecult.cultmesh
// Replays contracts/cultnet/interop/write-receipt-vectors.json against this runtime: constants, contentHash, every
// `wire` frame (decode to the vector's fields, re-encode to its bytes), every `schemaInvalid` frame (must be refused),
// and every `scenarios` event replay through WriteTracker. `dedupe` and `blankFields` are server inputs and are not
// run here. Mode: `java -cp ... org.gamecult.cultmesh.CultMeshKt write-receipt-vectors <vectors.json>`.
import java.io.File
import java.io.IOException
// The event actions scenarios.semantics names; anything else is refused, not skipped.
private val EVENT_KEYS = listOf("send", "frame", "tick", "sessionEnd", "sendFailed", "transportAck")
fun replayWriteReceiptVectors(path: String): Boolean {
@Suppress("UNCHECKED_CAST")
val vectors = JsonReader(File(path).readText(Charsets.UTF_8)).readDocument() as Map<String, Any?>
val results = linkedMapOf<String, List<String>>()
fun check(name: String, run: () -> List<String>) {
results[name] = try { run() } catch (e: Throwable) { listOf("threw: $e") }
}
val constants = obj(vectors["constants"])
check("constants") {
listOfNotNull(
"RECEIPT window".takeIf { constants["RECEIPT_RESULT_WINDOW_MS"] != RECEIPT_RESULT_WINDOW_MS },
"LEGACY window".takeIf { constants["LEGACY_RESULT_WINDOW_MS"] != LEGACY_RESULT_WINDOW_MS },
)
}
for (case in list(obj(vectors["contentHash"])["cases"])) {
val c = obj(case)
check("contentHash/${c["name"]}") {
val got = writeContentHash(c["operation"] as String, c["schemaId"] as String, c["recordKey"] as String, (c["payloadHex"] as String?)?.let(::unhex))
if (got == c["sha256"]) emptyList() else listOf("$got != ${c["sha256"]}")
}
}
for (case in list(vectors["wire"])) {
val c = obj(case)
check("wire/${c["name"]}") {
val bytes = unhex(c["messagePackHex"] as String)
val problems = mutableListOf<String>()
val message = decodeReceiptFrame(parseCultNetMessage(bytes))
if (message.toWireMap() != c["message"]) problems += "decoded ${message.toWireMap()} != ${c["message"]}"
val again = message.toBytes().joinToString("") { "%02X".format(it) }
if (again != (c["messagePackHex"] as String).uppercase()) problems += "re-encoded bytes $again != captured ${c["messagePackHex"]}"
problems
}
}
// admittedMessageId: a write_admitted messageId needs a letter or number and no Default_Ignorable code point, compared
// raw. The frame is built with this runtime's own encoder; a case with `wireHex` (the lone surrogate, invalid UTF-8)
// supplies the whole frame.
for (case in list(obj(vectors["admittedMessageId"])["cases"])) {
val c = obj(case)
check("admittedMessageId/${c["name"]}") {
val id = list(c["codePoints"]).joinToString("") { String(Character.toChars((it as String).toInt(16))) }.repeat(((c["repeat"] as Long?) ?: 1L).toInt())
val bytes = (c["wireHex"] as String?)?.let(::unhex) ?: MessagePackWriter().value(linkedMapOf(
"schemaVersion" to WRITE_ADMITTED_VERSION, "messageId" to id, "operation" to "put", "schemaId" to "note.v0", "recordKey" to "note:1",
)).toByteArray()
val decoded = try { decodeReceiptFrame(parseCultNetMessage(bytes)) } catch (_: IOException) { null }
when {
c["expect"] == "refuse" -> if (decoded == null) emptyList() else listOf("accepted an id that must be refused (${c["why"]})")
decoded == null -> listOf("refused an id that must be accepted (${c["why"]})")
decoded.toWireMap()["messageId"] != id -> listOf("id not echoed raw: ${decoded.toWireMap()["messageId"]}")
else -> emptyList()
}
}
}
// The generated ranges file is the independent copy of the embedded tables: first, last and the points either side of every
// range, so deleting or narrowing any range fails here.
check("unicodeTableRanges") {
@Suppress("UNCHECKED_CAST")
val ranges = JsonReader(File(File(path).parentFile, "write-admitted-message-id-ranges.json").readText(Charsets.UTF_8)).readDocument() as Map<String, Any?>
fun pairs(key: String) = list(ranges[key]).map { list(it).map { n -> (n as Long).toInt() } }
val letters = pairs("letterOrNumber")
val ignorable = pairs("defaultIgnorable")
val problems = mutableListOf<String>()
if (letters.size <= 700 || ignorable.size != 17) problems += "ranges file holds ${letters.size} and ${ignorable.size} ranges"
fun accepted(id: String): Boolean = try {
decodeReceiptFrame(parseCultNetMessage(MessagePackWriter().value(linkedMapOf(
"schemaVersion" to WRITE_ADMITTED_VERSION, "messageId" to id, "operation" to "put", "schemaId" to "note.v0", "recordKey" to "note:1",
)).toByteArray()))
true
} catch (_: IOException) { false }
for ((low, high) in letters) for ((point, want) in listOf(low to true, high to true, low - 1 to false, high + 1 to false)) {
if (accepted(String(Character.toChars(point))) != want) problems += "U+${point.toString(16)} alone should be ${if (want) "accepted" else "refused"}"
}
for ((low, high) in ignorable) for ((point, want) in listOf(low to false, high to false, low - 1 to true, high + 1 to true)) {
if (accepted("a" + String(Character.toChars(point))) != want) problems += "a + U+${point.toString(16)} should be ${if (want) "accepted" else "refused"}"
}
problems
}
// A document payload string with a lone surrogate (ED A0 80) is not a write_admitted id: the shared MessagePack reader keeps
// reading it. Strictness is scoped to the write_admitted frame, never to the reader.
check("documentPayloadStringWithLoneSurrogateStillDecodes") {
val text = MessagePackReader(unhex("A3EDA080")).readString()
if (text.isNotEmpty()) emptyList() else listOf("decoded to an empty string")
}
// admittedMessageIdDuplicates: Kotlin decodes the frame to a map, so it cannot see a repeated key: it judges the last one.
for (case in list(obj(vectors["admittedMessageIdDuplicates"])["cases"])) {
val c = obj(case)
check("admittedMessageIdDuplicates/${c["name"]}") {
val decoded = try { decodeReceiptFrame(parseCultNetMessage(unhex(c["wireHex"] as String))) } catch (_: IOException) { null }
when {
c["lastKeyWins"] == "refuse" -> if (decoded == null) emptyList() else listOf("accepted a frame whose last messageId key is invalid")
decoded == null -> listOf("refused a frame whose last messageId key is valid")
decoded.toWireMap()["messageId"] != c["lastKeyWinsEcho"] -> listOf("echoed ${decoded.toWireMap()["messageId"]}, wanted ${c["lastKeyWinsEcho"]}")
else -> emptyList()
}
}
}
for (case in list(vectors["schemaInvalid"])) {
val c = obj(case)
check("schemaInvalid/${c["name"]}") {
try {
decodeReceiptFrame(parseCultNetMessage(unhex(c["messagePackHex"] as String)))
listOf("accepted a frame that must be refused (${c["why"]})")
} catch (_: IOException) {
emptyList()
}
}
}
// Not a vector: `limit_reached` is in error.v1's enum only (write-receipt.md), as the TS and Rust suites also pin.
check("error_v0_refuses_the_v1_only_limit_reached_code") {
val body = linkedMapOf<String, Any?>("error" to "x", "routingHint" to null, "code" to "limit_reached", "details" to null)
val v1 = decodeErrorFrame(CultNetMessage(ERROR_V1_VERSION, body + ("messageId" to null))).code
try {
decodeErrorFrame(CultNetMessage(ERROR_V0_VERSION, body))
listOf("error.v0 accepted limit_reached")
} catch (_: IOException) {
if (v1 == "limit_reached") emptyList() else listOf("error.v1 lost limit_reached")
}
}
for (case in list(obj(vectors["scenarios"])["cases"])) {
val scenario = obj(case)
check("scenario/${scenario["name"]}") {
val problems = mutableListOf<String>()
// The fake server states its capability the only way a real one does: in its hello.
val hello = cultNetHello(
"fake-server", "fake",
supportedMessageVersions = if (scenario["server"] == "receipt") CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS else emptyList(),
)
val windowMs = resultWindowMs(helloAdvertisesWriteReceipts(hello))
if (windowMs != constants[scenario["window"] as String]) problems += "window $windowMs != ${scenario["window"]}"
val told = linkedMapOf<String, WriteSettlement>()
val tracker = WriteTracker(windowMs) { id, settlement ->
if (id in told) problems += "$id settled twice"
told[id] = settlement
}
for (event in list(scenario["events"]).map(::obj).sortedBy { it["atMs"] as Long }) {
val at = event["atMs"] as Long
val actions = event.keys - "atMs"
if (actions.size != 1 || actions.first() !in EVENT_KEYS) { problems += "event at $at has keys $actions, wanted atMs and exactly one of $EVENT_KEYS"; continue }
when {
"send" in event -> tracker.send(event["send"] as String, at)
// A frame reaches the client as bytes: the fake server encodes it, the client decodes it.
"frame" in event -> tracker.frame(parseCultNetMessage(MessagePackWriter().value(event["frame"]).toByteArray()), at)
"tick" in event -> tracker.tick(at)
"sessionEnd" in event -> tracker.sessionEnd(at)
"sendFailed" in event -> tracker.sendFailed(event["sendFailed"] as String, at)
// transportAck: delivery is not an answer; the tracker has no such input and must not need one.
}
}
val expect = obj(scenario["expect"])
for ((id, wantAny) in expect) {
val want = obj(wantAny)
val got = told[id]
if (got == null) { problems += "$id: never settled, wanted ${want["outcome"]}"; continue }
val (outcome, code, reason) = when (got) {
is WriteSettlement.Admitted -> Triple("admitted", null, null)
is WriteSettlement.Refused -> Triple("refused", got.code, null)
is WriteSettlement.Unconfirmed -> Triple("unconfirmed", null, got.reason.wire)
}
if (outcome != want["outcome"]) problems += "$id: told $outcome, wanted ${want["outcome"]}"
if ("code" in want && code != want["code"]) problems += "$id: code $code, wanted ${want["code"]}"
if ("reason" in want && reason != want["reason"]) problems += "$id: reason $reason, wanted ${want["reason"]}"
if (tracker.recorded(id)?.wire != want["recorded"]) problems += "$id: recorded ${tracker.recorded(id)?.wire}, wanted ${want["recorded"]}"
}
for (id in told.keys) if (id !in expect) problems += "$id: settled but the scenario expects nothing for it"
problems
}
}
// A runner that read fewer vectors than the file declares has silently skipped some.
check("counts") {
val declared = obj(vectors["counts"])
fun ran(prefix: String) = results.keys.count { it.startsWith(prefix) }
val loaded = mapOf(
"wire" to list(vectors["wire"]).size, "schemaInvalid" to list(vectors["schemaInvalid"]).size,
"contentHashCases" to list(obj(vectors["contentHash"])["cases"]).size, "scenarioCases" to list(obj(vectors["scenarios"])["cases"]).size,
"admittedMessageIdCases" to list(obj(vectors["admittedMessageId"])["cases"]).size,
)
val executed = mapOf("wire" to ran("wire/"), "schemaInvalid" to ran("schemaInvalid/"), "contentHashCases" to ran("contentHash/"), "scenarioCases" to ran("scenario/"), "admittedMessageIdCases" to ran("admittedMessageId/"))
loaded.keys.filter { loaded[it] != (declared[it] as Long).toInt() || executed[it] != loaded[it] }
.map { "$it: declared ${declared[it]}, loaded ${loaded[it]}, ran ${executed[it]}" }
}
for ((name, problems) in results) {
println(if (problems.isEmpty()) "PASS $name" else "FAIL $name")
problems.forEach { println(" $it") }
}
val failed = results.values.count { it.isNotEmpty() }
println("${results.size - failed}/${results.size} passed")
return failed == 0
}
/** Strict decode of whichever receipt-family frame this is, returned as the message its typed form encodes; anything else is refused. */
private fun decodeReceiptFrame(message: CultNetMessage): CultNetMessage = when (message.schemaVersion) {
WRITE_ADMITTED_VERSION -> decodeWriteAdmitted(message).toMessage()
ERROR_V1_VERSION, ERROR_V0_VERSION -> decodeErrorFrame(message).toMessage()
else -> throw IOException("not a receipt frame: ${message.schemaVersion}")
}
@Suppress("UNCHECKED_CAST")
private fun obj(value: Any?): Map<String, Any?> = value as Map<String, Any?>
private fun list(value: Any?): List<Any?> = value as List<Any?>
private fun unhex(text: String): ByteArray = ByteArray(text.length / 2) { text.substring(it * 2, it * 2 + 2).toInt(16).toByte() }
/** A small JSON reader for the vector file: objects, arrays, strings, integers, true/false/null. */
private class JsonReader(private val text: String) {
private var at = 0
fun readDocument(): Any? = readValue().also { skipSpace(); if (at != text.length) throw IOException("trailing JSON") }
private fun skipSpace() { while (at < text.length && text[at] in " \t\r\n") at++ }
private fun readValue(): Any? {
skipSpace()
return when (val c = text[at]) {
'{' -> {
at++
val map = linkedMapOf<String, Any?>()
skipSpace()
if (text[at] == '}') { at++; return map }
do {
skipSpace()
val key = readString()
skipSpace(); expect(':')
map[key] = readValue()
skipSpace()
} while (closes('}'))
map
}
'[' -> {
at++
val items = mutableListOf<Any?>()
skipSpace()
if (text[at] == ']') { at++; return items }
do {
items += readValue()
skipSpace()
} while (closes(']'))
items
}
'"' -> readString()
't' -> literal("true", true)
'f' -> literal("false", false)
'n' -> literal("null", null)
else -> {
if (c != '-' && !c.isDigit()) throw IOException("unexpected '$c' at $at")
val start = at++
while (at < text.length && text[at].isDigit()) at++
text.substring(start, at).toLong()
}
}
}
/** After an element: false when [close] ends the container, true after a comma. */
private fun closes(close: Char): Boolean {
val c = text[at++]
if (c == close) return false
if (c != ',') throw IOException("expected , or $close at ${at - 1}")
return true
}
private fun literal(word: String, value: Any?): Any? {
if (!text.startsWith(word, at)) throw IOException("bad literal at $at")
at += word.length
return value
}
private fun expect(c: Char) { if (text[at++] != c) throw IOException("expected $c at ${at - 1}") }
private fun readString(): String {
expect('"')
val out = StringBuilder()
while (true) {
val c = text[at++]
when (c) {
'"' -> return out.toString()
'\\' -> when (val e = text[at++]) {
'n' -> out.append('\n'); 't' -> out.append('\t'); 'r' -> out.append('\r')
'b' -> out.append('\b'); 'f' -> out.append('\u000c')
'u' -> { out.append(text.substring(at, at + 4).toInt(16).toChar()); at += 4 }
'"', '\\', '/' -> out.append(e)
else -> throw IOException("bad escape \\$e")
}
else -> out.append(c)
}
}
}
}

View file

@ -7,7 +7,7 @@ game sessions with prediction reconciliation, committed simulation facts, the
local TCP/RUDP server, and a package daemon. local TCP/RUDP server, and a package daemon.
It depends on `cultcache-py` and `cultnet-py`, mirroring `cultmesh-rs` and It depends on `cultcache-py` and `cultnet-py`, mirroring `cultmesh-rs` and
`cultmesh-ts`. The Verse catalog, peer exchange, authority lease, stream `@gamecult/cultmesh-ts`. The Verse catalog, peer exchange, authority lease, stream
negotiation, and simulation fact contracts are defined in negotiation, and simulation fact contracts are defined in
`cultnet_py.cultmesh_contracts` and re-exported here. `cultnet_py.cultmesh_contracts` and re-exported here.
@ -122,6 +122,33 @@ server = CultMesh.serve_node(
) )
``` ```
## Peer writes
**Breaking (0.x):** a served node refuses every peer `document_put_raw` and `document_delete` unless a write
authority grants it, mirroring C# `ICultNetRemoteWriteAuthority`. Before this, any connected peer could overwrite
or delete the node's documents. The refusal is a typed `cultnet.error.v0` with code `write_not_authorized` and the
record key in `details`; an authority that raises, or returns no decision, refuses too.
Known residual: ungranted peers can still distinguish registered from unregistered schemas by timing (the node resolves the
schema before the gate so the authority sees the canonical id); the refusal itself is identical.
```python
from cultmesh_py import CultMeshGrantAllWrites, CultMeshRemoteWriteDecision, CultMeshRemoteWriteRequest
class OwnKeysOnly:
def decide(self, request: CultMeshRemoteWriteRequest) -> CultMeshRemoteWriteDecision:
if request.record_key.startswith("input:python:"):
return CultMeshRemoteWriteDecision.grant()
return CultMeshRemoteWriteDecision.refuse("not your key")
server = CultMesh.serve_node(node, write_authority=OwnKeysOnly())
```
The request carries the peer (`endpoint`, `transport`), the operation, the canonical schema id the node
resolved (never the alias the peer sent), the record key and the shard id and epoch as sent. `session.serve(...)`
takes the same `write_authority`. A host that already authenticates its peers, or a test rig, opts in to
`CultMeshGrantAllWrites()`; the daemon's equivalent is `--allow-peer-writes`. Without it the daemon is read-only to peers.
The same local server can be launched as a package daemon when another runtime The same local server can be launched as a package daemon when another runtime
or operator process needs a CultNet endpoint without embedding Python glue: or operator process needs a CultNet endpoint without embedding Python glue:

View file

@ -39,6 +39,14 @@ from .simulation import (
CultMeshSimulationFactCommitter, CultMeshSimulationFactCommitter,
simulation_fact_document, simulation_fact_document,
) )
from .write_authority import (
CultMeshGrantAllWrites,
CultMeshRemoteWriteAuthority,
CultMeshRemoteWriteDecision,
CultMeshRemoteWriteOperation,
CultMeshRemoteWriteRequest,
CultMeshServerPeer,
)
from cultnet_py.cultmesh_contracts import ( from cultnet_py.cultmesh_contracts import (
PEER_EXCHANGE_REQUEST, PEER_EXCHANGE_REQUEST,
PEER_EXCHANGE_RESPONSE, PEER_EXCHANGE_RESPONSE,
@ -89,6 +97,12 @@ __all__ = [
"CultMeshSimulationFact", "CultMeshSimulationFact",
"CultMeshSimulationFactCommit", "CultMeshSimulationFactCommit",
"CultMeshSimulationFactCommitter", "CultMeshSimulationFactCommitter",
"CultMeshGrantAllWrites",
"CultMeshRemoteWriteAuthority",
"CultMeshRemoteWriteDecision",
"CultMeshRemoteWriteOperation",
"CultMeshRemoteWriteRequest",
"CultMeshServerPeer",
"CultMeshAuthorityLease", "CultMeshAuthorityLease",
"CultMeshAuthorityLeaseCatalog", "CultMeshAuthorityLeaseCatalog",
"CultMeshHmacAuthorityLeaseVerifier", "CultMeshHmacAuthorityLeaseVerifier",

View file

@ -13,6 +13,7 @@ from cultnet_py import CultNetSimulationConsensusOptions, CultNetSimulationObser
from .facade import CultMesh from .facade import CultMesh
from .server import CultMeshLocalServer from .server import CultMeshLocalServer
from .write_authority import CultMeshGrantAllWrites
from cultnet_py.cultmesh_contracts import ( from cultnet_py.cultmesh_contracts import (
CultMeshPeerCard, CultMeshPeerCard,
CultMeshPeerCatalog, CultMeshPeerCatalog,
@ -53,6 +54,7 @@ def main(argv: list[str] | None = None) -> int:
parser.add_argument("--simulation-quorum-ratio", type=float, default=0.5) parser.add_argument("--simulation-quorum-ratio", type=float, default=0.5)
parser.add_argument("--verse-id") parser.add_argument("--verse-id")
parser.add_argument("--verse-display-name") parser.add_argument("--verse-display-name")
parser.add_argument("--allow-peer-writes", action="store_true", help="grant every connected peer put and delete; without it peer writes are refused")
parser.add_argument("--role", action="append", dest="roles") parser.add_argument("--role", action="append", dest="roles")
args = parser.parse_args(argv) args = parser.parse_args(argv)
@ -117,6 +119,7 @@ def start_server(args: argparse.Namespace, parser: argparse.ArgumentParser) -> C
display_name=args.display_name, display_name=args.display_name,
max_snapshot_documents=args.max_snapshot_documents, max_snapshot_documents=args.max_snapshot_documents,
max_snapshot_bytes=args.max_snapshot_bytes, max_snapshot_bytes=args.max_snapshot_bytes,
write_authority=CultMeshGrantAllWrites() if args.allow_peer_writes else None,
) )
except ValueError as error: except ValueError as error:
# The server owns its option rules; a limit it refuses is a usage error, not a crash. # The server owns its option rules; a limit it refuses is a usage error, not a crash.

View file

@ -35,6 +35,7 @@ from .node import (
from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer from .server import CULTMESH_RUDP_DEFAULT_MAX_FRAGMENT_BYTES, CultMeshLocalServer
from .session import CultMeshGameSession, CultMeshGameSessionOptions from .session import CultMeshGameSession, CultMeshGameSessionOptions
from .simulation import CultMeshSimulationFactCommitter from .simulation import CultMeshSimulationFactCommitter
from .write_authority import CultMeshRemoteWriteAuthority
from cultnet_py.cultmesh_contracts import ( from cultnet_py.cultmesh_contracts import (
AuthorityLeaseVerifier, AuthorityLeaseVerifier,
CultMeshAuthorityLeaseCatalog, CultMeshAuthorityLeaseCatalog,
@ -400,6 +401,7 @@ class CultMesh:
verse_catalog: CultMeshVerseCatalog | None = None, verse_catalog: CultMeshVerseCatalog | None = None,
peer_catalog: CultMeshPeerCatalog | None = None, peer_catalog: CultMeshPeerCatalog | None = None,
observation_hub: CultNetSimulationObservationHub | None = None, observation_hub: CultNetSimulationObservationHub | None = None,
write_authority: CultMeshRemoteWriteAuthority | None = None,
host: str = "127.0.0.1", host: str = "127.0.0.1",
port: int = 0, port: int = 0,
display_name: str | None = None, display_name: str | None = None,
@ -416,6 +418,7 @@ class CultMesh:
verse_catalog=verse_catalog or CultMeshVerseCatalog(), verse_catalog=verse_catalog or CultMeshVerseCatalog(),
peer_catalog=peer_catalog or CultMeshPeerCatalog(), peer_catalog=peer_catalog or CultMeshPeerCatalog(),
observation_hub=observation_hub, observation_hub=observation_hub,
write_authority=write_authority,
host=host, host=host,
port=port, port=port,
display_name=display_name, display_name=display_name,

View file

@ -650,6 +650,29 @@ class CultMeshDatabase:
self._append_shard_log_delete(message) self._append_shard_log_delete(message)
return message return message
def raw_put_target(self, message: dict[str, Any]) -> tuple[str, str] | None:
"""The canonical schema id and record key a raw put would write, or None when it would not apply."""
document_record = message.get("document")
# Only a document of the wire shape is resolved, so an ungranted peer's payload is never
# converted or allocated here: a malformed one is the store's refusal, after the authority.
if (
not isinstance(document_record, dict)
or not isinstance(document_record.get("recordKey"), str)
or not isinstance(document_record.get("payload"), (bytes, bytearray, memoryview))
):
return None
try:
prepared = self._raw_put_envelope(message)
except Exception: # noqa: BLE001 - any other malformed shape
return None
return None if prepared is None else (prepared[0].catalog_entry().schema_id, prepared[1].key)
def raw_delete_target(self, message: dict[str, Any]) -> tuple[str, str] | None:
"""The canonical schema id and record key a raw delete names, or None when its schema is not registered."""
document = self._document_for_schema(str(message.get("schemaId") or ""))
record_key = str(message.get("recordKey") or "")
return None if document is None or not record_key else (document.catalog_entry().schema_id, record_key)
def apply_raw_put_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None: def apply_raw_put_message(self, message: dict[str, Any]) -> CultMeshDatabaseChange | None:
prepared = self._raw_put_envelope(message) prepared = self._raw_put_envelope(message)
if prepared is None: if prepared is None:

View file

@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import errno
import logging import logging
import socket import socket
import threading import threading
@ -10,6 +11,8 @@ from typing import Any
import msgpack import msgpack
from cultnet_py import ( from cultnet_py import (
error_message,
message_invalid_error,
unsupported_schema_version_error, unsupported_schema_version_error,
CultNetRawSnapshotResponse, CultNetRawSnapshotResponse,
CultNetSimulationObservationHub, CultNetSimulationObservationHub,
@ -28,6 +31,12 @@ from cultnet_py import (
) )
from .node import CultMeshNode from .node import CultMeshNode
from .write_authority import (
CultMeshRemoteWriteAuthority,
CultMeshRemoteWriteOperation,
CultMeshRemoteWriteRequest,
CultMeshServerPeer,
)
# The shortest message id this server answers a snapshot request under. It takes a # The shortest message id this server answers a snapshot request under. It takes a
# request's messageId as given, an empty one included, so no response it sends is smaller. # request's messageId as given, an empty one included, so no response it sends is smaller.
@ -51,6 +60,17 @@ from cultnet_py.cultmesh_contracts import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
# How many consecutive refused frames of one kind a RUDP session may send before it is ended: undecodable
# frames (reset by any frame that decodes) and deletes the write authority refuses (reset by any decoded
# frame that is not a refused delete). Fewer are answered with a typed refusal and the session is kept; the
# frame that reaches this number is answered too, then the session ends. The same number is the cap in every
# runtime.
MAX_CONSECUTIVE_REFUSED_FRAMES = 8
# How long a session whose capped frame was answered waits for the peer to acknowledge the answer before it ends anyway.
_RUDP_CAPPED_ANSWER_GRACE_MS = 2000
_EPHEMERAL_PAIR_ATTEMPTS = 64
class _ReplyUnqueueable(Exception): class _ReplyUnqueueable(Exception):
"""A reply the peer's reliable queue cannot take. The peer's session ends, and the peer is """A reply the peer's reliable queue cannot take. The peer's session ends, and the peer is
@ -80,6 +100,10 @@ class _DatabaseSubscription:
class _RudpPeerConnection: class _RudpPeerConnection:
session: CultNetRudpSession session: CultNetRudpSession
subscriptions: dict[str, _DatabaseSubscription] = field(default_factory=dict) subscriptions: dict[str, _DatabaseSubscription] = field(default_factory=dict)
undecodable_frames_in_a_row: int = 0
refused_deletes_in_a_row: int = 0
# Set once the peer's capped frame has been answered: the session ends when the answers are acknowledged.
ending_deadline_ms: int | None = None
@dataclass @dataclass
@ -88,6 +112,9 @@ class CultMeshLocalServer:
verse_catalog: CultMeshVerseCatalog = field(default_factory=CultMeshVerseCatalog) verse_catalog: CultMeshVerseCatalog = field(default_factory=CultMeshVerseCatalog)
peer_catalog: CultMeshPeerCatalog = field(default_factory=CultMeshPeerCatalog) peer_catalog: CultMeshPeerCatalog = field(default_factory=CultMeshPeerCatalog)
observation_hub: CultNetSimulationObservationHub | None = None observation_hub: CultNetSimulationObservationHub | None = None
# Asked once per peer put and delete. None refuses every one of them (write_not_authorized); a node's own
# writes never come through here.
write_authority: CultMeshRemoteWriteAuthority | None = None
host: str = "127.0.0.1" host: str = "127.0.0.1"
port: int = 0 port: int = 0
display_name: str | None = None display_name: str | None = None
@ -158,26 +185,49 @@ class CultMeshLocalServer:
def start(self) -> "CultMeshLocalServer": def start(self) -> "CultMeshLocalServer":
if self._socket is not None: if self._socket is not None:
return self return self
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server, rudp_socket = self._bind_sockets()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((self.host, self.port))
server.listen()
server.settimeout(0.2) server.settimeout(0.2)
self._socket = server self._socket = server
self.port = int(server.getsockname()[1]) self.port = int(server.getsockname()[1])
self._stop.clear() self._stop.clear()
self._thread = threading.Thread(target=self._accept_loop, daemon=True) self._thread = threading.Thread(target=self._accept_loop, daemon=True)
self._thread.start() self._thread.start()
if self.enable_rudp: if rudp_socket is not None:
rudp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rudp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
rudp_socket.bind((self.host, self.port))
rudp_socket.settimeout(0.02) rudp_socket.settimeout(0.02)
self._rudp_socket = rudp_socket self._rudp_socket = rudp_socket
self._rudp_thread = threading.Thread(target=self._rudp_loop, daemon=True) self._rudp_thread = threading.Thread(target=self._rudp_loop, daemon=True)
self._rudp_thread.start() self._rudp_thread.start()
return self return self
def _bind_sockets(self) -> tuple[socket.socket, socket.socket | None]:
"""The listening TCP socket and, when RUDP is on, the UDP socket on the same port number.
An explicit port is bound as asked and a failure is the caller's. Port 0 asks for any free port, and the
kernel picks the TCP one without knowing whether another process holds that number for UDP, so a
UDP collision retries with a fresh TCP port instead of failing the start. Both sockets are bound
before any thread starts, so a failed start leaves nothing running or open.
"""
attempts = _EPHEMERAL_PAIR_ATTEMPTS if self.port == 0 and self.enable_rudp else 1
for attempt in range(attempts):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
rudp_socket = None
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((self.host, self.port))
server.listen()
if self.enable_rudp:
rudp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rudp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
rudp_socket.bind((self.host, int(server.getsockname()[1])))
return server, rudp_socket
except OSError as error:
server.close()
if rudp_socket is not None:
rudp_socket.close()
if error.errno != errno.EADDRINUSE or attempt == attempts - 1:
raise
raise AssertionError("unreachable")
def stop(self) -> None: def stop(self) -> None:
self._stop.set() self._stop.set()
if self._rudp_socket is not None: if self._rudp_socket is not None:
@ -238,14 +288,15 @@ class CultMeshLocalServer:
if server is None: if server is None:
return return
try: try:
client, _ = server.accept() client, address = server.accept()
except TimeoutError: except TimeoutError:
continue continue
except OSError: except OSError:
return return
threading.Thread(target=self._handle_connection, args=(client,), daemon=True).start() peer = CultMeshServerPeer(f"{address[0]}:{address[1]}", "tcp")
threading.Thread(target=self._handle_connection, args=(client, peer), daemon=True).start()
def _handle_connection(self, client: socket.socket) -> None: def _handle_connection(self, client: socket.socket, peer: CultMeshServerPeer) -> None:
with client: with client:
stream = client.makefile("rwb") stream = client.makefile("rwb")
transport = TcpFramedTransportConnection( transport = TcpFramedTransportConnection(
@ -267,7 +318,7 @@ class CultMeshLocalServer:
if not isinstance(message, dict): if not isinstance(message, dict):
continue continue
try: try:
responses = self._handle_connection_message(message, subscriptions) responses = self._handle_connection_message(message, subscriptions, peer=peer)
except Exception as error: # noqa: BLE001 - one message never ends the connection except Exception as error: # noqa: BLE001 - one message never ends the connection
# Whatever a peer's message makes the handling raise is that peer's failure: # Whatever a peer's message makes the handling raise is that peer's failure:
# it is refused with fixed text and the connection serves on. The log names # it is refused with fixed text and the connection serves on. The log names
@ -309,6 +360,7 @@ class CultMeshLocalServer:
if packet.connection_id != self.rudp_connection_id: if packet.connection_id != self.rudp_connection_id:
continue continue
self._end_answered_peers(rudp_socket, peers)
now_ms = _now_ms() now_ms = _now_ms()
peer = peers.get(remote_addr) peer = peers.get(remote_addr)
if packet.packet_type == CultNetRudpPacketType.CONNECT: if packet.packet_type == CultNetRudpPacketType.CONNECT:
@ -357,13 +409,31 @@ class CultMeshLocalServer:
for delivered in result.delivered: for delivered in result.delivered:
if delivered.channel_id != "schema": if delivered.channel_id != "schema":
continue continue
if peer.ending_deadline_ms is not None:
# The capped frame was answered; nothing after it is served while the answer is delivered.
break
try: try:
message = msgpack.unpackb(delivered.payload, raw=False) message = msgpack.unpackb(delivered.payload, raw=False)
except (msgpack.ExtraData, msgpack.FormatError, msgpack.StackError, ValueError): except (msgpack.ExtraData, msgpack.FormatError, msgpack.StackError, ValueError):
continue message = None
if not isinstance(message, dict): if isinstance(message, dict):
continue peer.undecodable_frames_in_a_row = 0
responses = self._handle_connection_message(message, peer.subscriptions, over_rudp=True) responses = self._handle_connection_message(
message,
peer.subscriptions,
over_rudp=True,
peer=CultMeshServerPeer(f"{remote_addr[0]}:{remote_addr[1]}", "rudp"),
)
refused_delete = message.get("schemaVersion") == "cultnet.document_delete.v0" and any(
response.get("code") == "write_not_authorized" for response in responses
)
peer.refused_deletes_in_a_row = peer.refused_deletes_in_a_row + 1 if refused_delete else 0
refused, run = refused_delete, peer.refused_deletes_in_a_row
else:
# A frame that is no CultNet message is answered, not dropped, and the session kept.
peer.undecodable_frames_in_a_row += 1
refused, run = True, peer.undecodable_frames_in_a_row
responses = [self._message_invalid({}, "message", "CultMesh RUDP server could not read the message.")]
for response in responses: for response in responses:
if unsendable is None: if unsendable is None:
unsendable = self._send_rudp_schema_frame( unsendable = self._send_rudp_schema_frame(
@ -373,6 +443,11 @@ class CultMeshLocalServer:
msgpack.packb(response, use_bin_type=True), msgpack.packb(response, use_bin_type=True),
message_id=str(response.get("messageId") or ""), message_id=str(response.get("messageId") or ""),
) )
if refused and run >= MAX_CONSECUTIVE_REFUSED_FRAMES:
# The capped frame is answered like any other, reliably. The session ends once the peer
# has acknowledged every answer (or the grace runs out): see _end_answered_peers.
peer.ending_deadline_ms = now_ms + _RUDP_CAPPED_ANSWER_GRACE_MS
break
except Exception as error: # noqa: BLE001 - one peer's message never ends the thread except Exception as error: # noqa: BLE001 - one peer's message never ends the thread
# Whatever a peer's message makes the handling raise is that peer's failure. # Whatever a peer's message makes the handling raise is that peer's failure.
# The session recorded the frame's sequence, so it cannot be kept: a retransmit # The session recorded the frame's sequence, so it cannot be kept: a retransmit
@ -403,11 +478,26 @@ class CultMeshLocalServer:
if unsendable is not None: if unsendable is not None:
self._end_unsendable_peer(rudp_socket, peers, remote_addr, unsendable) self._end_unsendable_peer(rudp_socket, peers, remote_addr, unsendable)
def _end_answered_peers(
self,
rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection],
) -> None:
"""Ends each session whose capped frame was answered once the peer has acknowledged every answer (a lost
answer is resent first), or when the grace has run out."""
now_ms = _now_ms()
for remote_addr, peer in list(peers.items()):
if peer.ending_deadline_ms is None:
continue
if peer.session.outstanding_reliable_packet_count == 0 or now_ms >= peer.ending_deadline_ms:
self._end_refused_peer(rudp_socket, peers, remote_addr)
def _poll_rudp_resends( def _poll_rudp_resends(
self, self,
rudp_socket: socket.socket, rudp_socket: socket.socket,
peers: dict[tuple[str, int], _RudpPeerConnection], peers: dict[tuple[str, int], _RudpPeerConnection],
) -> None: ) -> None:
self._end_answered_peers(rudp_socket, peers)
now_ms = _now_ms() now_ms = _now_ms()
for remote_addr, peer in list(peers.items()): for remote_addr, peer in list(peers.items()):
for packet in peer.session.due_resends(now_ms): for packet in peer.session.due_resends(now_ms):
@ -519,6 +609,7 @@ class CultMeshLocalServer:
subscriptions: dict[str, _DatabaseSubscription], subscriptions: dict[str, _DatabaseSubscription],
*, *,
over_rudp: bool = False, over_rudp: bool = False,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
schema_version = message.get("schemaVersion") schema_version = message.get("schemaVersion")
if schema_version == "cultnet.database_subscribe.v0": if schema_version == "cultnet.database_subscribe.v0":
@ -542,9 +633,9 @@ class CultMeshLocalServer:
subscriptions.pop(str(message.get("subscriptionId") or ""), None) subscriptions.pop(str(message.get("subscriptionId") or ""), None)
return [] return []
if schema_version == "cultnet.document_put_raw.v0": if schema_version == "cultnet.document_put_raw.v0":
return self._handle_raw_put(message, subscriptions, over_rudp=over_rudp) return self._handle_raw_put(message, subscriptions, over_rudp=over_rudp, peer=peer)
if schema_version == "cultnet.document_delete.v0": if schema_version == "cultnet.document_delete.v0":
return self._handle_raw_delete(message, subscriptions) return self._handle_raw_delete(message, subscriptions, peer=peer)
if schema_version == "cultnet.simulation_observation.v0": if schema_version == "cultnet.simulation_observation.v0":
return self._candidate_responses(message) return self._candidate_responses(message)
response = self.handle_message(message) response = self.handle_message(message)
@ -556,14 +647,27 @@ class CultMeshLocalServer:
subscriptions: dict[str, _DatabaseSubscription], subscriptions: dict[str, _DatabaseSubscription],
*, *,
over_rudp: bool = False, over_rudp: bool = False,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
document_record = message.get("document") document_record = message.get("document")
if not isinstance(document_record, dict): if not isinstance(document_record, dict):
return [self._error_response( return [self._message_invalid(message, "document", "Raw put messages must contain a document map.")]
"Raw put messages must contain a document map.", malformed_shard = self._malformed_shard_fields(message)
message_id=str(message.get("messageId") or ""), if malformed_shard is not None:
code="malformed_document_put", return [malformed_shard]
)] # Refusal precedes every other judgment of the put. The node resolves the schema first, because the
# authority must be asked about the canonical schema id (a payload-inferred alias included), as C#
# does; only a payload of the wire shape is resolved, so nothing of an ungranted peer's is
# allocated. A put the node cannot resolve is asked about under the ids as sent. Residual: the
# refusal is the same either way, but an ungranted peer can still tell registered from unregistered
# schemas by timing.
target = self.node.database.raw_put_target(message) or (
str(document_record.get("schemaId") or ""),
str(document_record.get("recordKey") or ""),
)
refusal = self._refuse_unauthorized_write(peer, CultMeshRemoteWriteOperation.PUT, target, message)
if refusal is not None:
return [refusal]
unservable = self._unservable_put(message, over_rudp=over_rudp) unservable = self._unservable_put(message, over_rudp=over_rudp)
if unservable is not None: if unservable is not None:
return [unservable] return [unservable]
@ -575,11 +679,7 @@ class CultMeshLocalServer:
# raises. It is refused to the peer that sent it; no thread and no other peer is # raises. It is refused to the peer that sent it; no thread and no other peer is
# affected. Neither the refusal nor the log quotes the error, which can quote the put. # affected. Neither the refusal nor the log quotes the error, which can quote the put.
_LOGGER.warning("CultMesh server refused a raw put the store could not take (%s).", type(error).__name__) _LOGGER.warning("CultMesh server refused a raw put the store could not take (%s).", type(error).__name__)
return [self._error_response( return [self._message_invalid(message, "document", "Raw put document could not be stored.")]
"Raw put document could not be stored.",
message_id=str(message.get("messageId") or ""),
code="malformed_document_put",
)]
if change is None: if change is None:
return [self._error_response( return [self._error_response(
"Raw put message did not apply to a registered document.", "Raw put message did not apply to a registered document.",
@ -598,15 +698,22 @@ class CultMeshLocalServer:
self, self,
message: dict[str, Any], message: dict[str, Any],
subscriptions: dict[str, _DatabaseSubscription], subscriptions: dict[str, _DatabaseSubscription],
*,
peer: CultMeshServerPeer | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
schema_id = str(message.get("schemaId") or "") schema_id = str(message.get("schemaId") or "")
record_key = str(message.get("recordKey") or "") record_key = str(message.get("recordKey") or "")
if not schema_id or not record_key: if not schema_id or not record_key:
return [self._error_response( return [self._message_invalid(
"Raw delete messages must contain schemaId and recordKey.", message, "schemaId" if not schema_id else "recordKey", "Raw delete messages must contain schemaId and recordKey.",
message_id=str(message.get("messageId") or ""),
code="malformed_document_delete",
)] )]
malformed_shard = self._malformed_shard_fields(message)
if malformed_shard is not None:
return [malformed_shard]
target = self.node.database.raw_delete_target(message) or (schema_id, record_key)
refusal = self._refuse_unauthorized_write(peer, CultMeshRemoteWriteOperation.DELETE, target, message)
if refusal is not None:
return [refusal]
change = self.node.database.apply_raw_delete_message(message) change = self.node.database.apply_raw_delete_message(message)
if change is None: if change is None:
return [self._error_response( return [self._error_response(
@ -616,6 +723,70 @@ class CultMeshLocalServer:
)] )]
return self._database_delete_notifications(message, subscriptions, resolved_schema_id=change.schema_id) return self._database_delete_notifications(message, subscriptions, resolved_schema_id=change.schema_id)
def _message_invalid(self, message: dict[str, Any], field: str, reason: str) -> dict[str, Any]:
"""The typed `message_invalid` refusal naming the request field at fault, under the request's messageId."""
response = message_invalid_error(field, reason).to_wire()
response["messageId"] = str(message.get("messageId") or "")
return response
def _malformed_shard_fields(self, message: dict[str, Any]) -> dict[str, Any] | None:
"""The protocol error for a shardId that is not a string or a shardEpoch that is not an int (a bool is
not), else None. It precedes the gate, so the authority only ever judges a write whose shard it can
read, and the store never files a write under a shard the authority did not see."""
shard_id = message.get("shardId")
shard_epoch = message.get("shardEpoch")
if (shard_id is None or isinstance(shard_id, str)) and (
shard_epoch is None or (isinstance(shard_epoch, int) and not isinstance(shard_epoch, bool))
):
return None
return self._message_invalid(
message,
"shardId" if not (shard_id is None or isinstance(shard_id, str)) else "shardEpoch",
"shardId must be a string and shardEpoch an integer.",
)
def _refuse_unauthorized_write(
self,
peer: CultMeshServerPeer | None,
operation: CultMeshRemoteWriteOperation,
target: tuple[str, str],
message: dict[str, Any],
) -> dict[str, Any] | None:
"""None when the write may proceed, else the typed refusal for the sending peer.
No authority configured refuses; an authority that raises refuses too (fail closed) and is logged.
"""
schema_id, record_key = target
reason: str | None
authority = self.write_authority
if authority is None:
reason = "no remote write authority is configured"
else:
request = CultMeshRemoteWriteRequest(
peer=peer or CultMeshServerPeer("", "unknown"),
operation=operation,
schema_id=schema_id,
record_key=record_key,
shard_id=message.get("shardId"),
shard_epoch=message.get("shardEpoch"),
)
try:
decision = authority.decide(request)
except Exception as error: # noqa: BLE001 - a failing authority refuses
_LOGGER.error("CultMesh remote write authority failed (%s); the write was refused.", type(error).__name__)
decision = None
reason = "the write authority failed"
else:
reason = getattr(decision, "reason", None)
if decision is not None and getattr(decision, "is_granted", False) is True:
return None
_LOGGER.warning("CultMesh %s of %s refused: write not authorized.", operation.value, schema_id)
return error_message(
f"write_not_authorized: {reason}" if reason and reason.strip() else "write_not_authorized",
code="write_not_authorized",
details={"field": "recordKey", "value": record_key},
).to_wire()
def _database_change_notifications( def _database_change_notifications(
self, self,
message: dict[str, Any], message: dict[str, Any],
@ -803,11 +974,7 @@ class CultMeshLocalServer:
and isinstance(document_record.get("recordKey"), str) and isinstance(document_record.get("recordKey"), str)
and isinstance(document_record.get("payload"), (bytes, bytearray)) and isinstance(document_record.get("payload"), (bytes, bytearray))
): ):
return self._error_response( return self._message_invalid(message, "document", "Raw put documents must carry a string recordKey and a binary payload.")
"Raw put documents must carry a string recordKey and a binary payload.",
message_id=str(message.get("messageId") or ""),
code="malformed_document_put",
)
if self.max_snapshot_bytes is None and not over_rudp: if self.max_snapshot_bytes is None and not over_rudp:
return None return None
alone = self.node.database.raw_put_served_alone(message, message_id=_SHORTEST_SERVED_MESSAGE_ID) alone = self.node.database.raw_put_served_alone(message, message_id=_SHORTEST_SERVED_MESSAGE_ID)

View file

@ -27,6 +27,7 @@ from cultnet_py.cultmesh_contracts import CultMeshAuthorityLeaseCatalog, CultMes
if TYPE_CHECKING: if TYPE_CHECKING:
from .server import CultMeshLocalServer from .server import CultMeshLocalServer
from .write_authority import CultMeshRemoteWriteAuthority
@dataclass(frozen=True) @dataclass(frozen=True)
@ -83,6 +84,7 @@ class CultMeshGameSession:
def serve( def serve(
self, self,
*, *,
write_authority: CultMeshRemoteWriteAuthority | None = None,
host: str = "127.0.0.1", host: str = "127.0.0.1",
port: int = 0, port: int = 0,
display_name: str | None = None, display_name: str | None = None,
@ -96,6 +98,7 @@ class CultMeshGameSession:
verse_catalog=self.verse_catalog if self._serve_verse_discovery else CultMeshVerseCatalog(), verse_catalog=self.verse_catalog if self._serve_verse_discovery else CultMeshVerseCatalog(),
peer_catalog=self.peer_catalog if self._serve_peer_exchange else CultMeshPeerCatalog(), peer_catalog=self.peer_catalog if self._serve_peer_exchange else CultMeshPeerCatalog(),
observation_hub=self.observation_hub if self._serve_simulation_observations else None, observation_hub=self.observation_hub if self._serve_simulation_observations else None,
write_authority=write_authority,
host=host, host=host,
port=port, port=port,
display_name=display_name, display_name=display_name,

View file

@ -0,0 +1,66 @@
"""The one question a CultMesh server asks before it applies a peer's write.
Mirrors C# ``ICultNetRemoteWriteAuthority``: a server with no authority refuses every peer put and
delete, so serving a node never lets a connected peer overwrite its documents by default.
"""
from __future__ import annotations
from dataclasses import dataclass
from enum import Enum
from typing import Protocol
class CultMeshRemoteWriteOperation(Enum):
PUT = "put"
DELETE = "delete"
@dataclass(frozen=True)
class CultMeshServerPeer:
"""The connection a write arrived on: its endpoint and transport, nothing the peer claimed."""
endpoint: str
transport: str
@dataclass(frozen=True)
class CultMeshRemoteWriteRequest:
"""One peer write as the authority sees it.
``schema_id`` is the canonical id the node resolved for the write, never an alias the peer sent.
``shard_id`` and ``shard_epoch`` are as the peer sent them.
"""
peer: CultMeshServerPeer
operation: CultMeshRemoteWriteOperation
schema_id: str
record_key: str
shard_id: str | None = None
shard_epoch: int | None = None
@dataclass(frozen=True)
class CultMeshRemoteWriteDecision:
is_granted: bool
reason: str | None = None
@staticmethod
def grant() -> CultMeshRemoteWriteDecision:
return CultMeshRemoteWriteDecision(True)
@staticmethod
def refuse(reason: str | None = None) -> CultMeshRemoteWriteDecision:
return CultMeshRemoteWriteDecision(False, reason)
class CultMeshRemoteWriteAuthority(Protocol):
def decide(self, request: CultMeshRemoteWriteRequest) -> CultMeshRemoteWriteDecision: ...
class CultMeshGrantAllWrites:
"""Grants every peer write. For a host that has already authenticated its peers (or a test rig); it is
an explicit choice because serving without an authority refuses writes."""
def decide(self, request: CultMeshRemoteWriteRequest) -> CultMeshRemoteWriteDecision:
return CultMeshRemoteWriteDecision.grant()

View file

@ -0,0 +1,52 @@
"""Heimdall's invariant: no client treats a reliable-transport ack as write admission. A put completes only on
its result frame (write_not_authorized, or the success reply).
The Python write path is a subscription over RUDP: `send` queues the put, `read_next` returns the result frame
and raises the peer's refusal. The server here refuses the put; its reliable ack of the put arrives (the test
waits for it) and the client still reports the refusal, never success. The transport's `receive` yields data
frames only, so the order of the ack against the refusal cannot change what `read_next` reports.
"""
from __future__ import annotations
import unittest
from cultcache_py import define_database_entry_type
from cultmesh_py import CultMesh, create_node
from cultmesh_py.server import CultMeshLocalServer
from cultnet_py import CultNetDatabaseSubscription, CultNetPeerError, create_rudp_schema_transport
from test_remote_write_authority import KEY_A, NOTE, SCHEMA_ID, put_of
class ClientWriteCompletionTests(unittest.TestCase):
def test_a_put_the_server_refused_is_reported_refused_after_its_ack_arrived(self) -> None:
node = create_node(runtime_id="completion-server")
node.database.register_document(NOTE)
server = CultMeshLocalServer(node=node, port=0, write_authority=None)
server.start()
try:
subscription = CultNetDatabaseSubscription(
host="127.0.0.1",
port=server.port,
timeout_seconds=4.0,
subscription_id="completion",
schema_ids=[SCHEMA_ID],
include_snapshot=False,
create_transport=lambda: create_rudp_schema_transport(
host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, timeout_seconds=4.0
),
)
with subscription as sub:
sub.send(put_of(KEY_A, "peer"))
sub._transport.flush_reliable(2.0) # the put's reliable ack has arrived
with self.assertRaises(CultNetPeerError) as raised:
sub.read_next()
finally:
server.stop()
self.assertEqual(raised.exception.response["code"], "write_not_authorized")
self.assertIsNone(server.node.cache.get(NOTE, KEY_A))
if __name__ == "__main__":
unittest.main()

View file

@ -24,7 +24,9 @@ from cultcache_py import (
define_document_type, define_document_type,
) )
from cultcache_py.interop import INTEROP_SCHEMA_VERSION, interop_note_document from cultcache_py.interop import INTEROP_SCHEMA_VERSION, interop_note_document
from cultmesh_py.server import MAX_CONSECUTIVE_REFUSED_FRAMES
from cultmesh_py.verify import verify from cultmesh_py.verify import verify
from cultmesh_py.write_authority import CultMeshRemoteWriteDecision
from cultnet_py import ( from cultnet_py import (
compute_simulation_claim_hash, compute_simulation_claim_hash,
CultNetClientAuthorityScope, CultNetClientAuthorityScope,
@ -68,7 +70,7 @@ from cultnet_py import (
snapshot_request, snapshot_request,
) )
from cultnet_py.cultmesh_contracts import VERSE_CATALOG_REQUEST from cultnet_py.cultmesh_contracts import VERSE_CATALOG_REQUEST
from cultmesh_py import create_node from cultmesh_py import CultMeshGrantAllWrites, create_node
from cultmesh_py import ( from cultmesh_py import (
CultMesh, CultMesh,
CultMeshDatabase, CultMeshDatabase,
@ -1631,7 +1633,7 @@ class CultMeshTests(unittest.TestCase):
) )
primary = CultMesh.create_node(runtime_id="forward-primary") primary = CultMesh.create_node(runtime_id="forward-primary")
primary.database.register_document(document) primary.database.register_document(document)
server = CultMesh.serve_node(primary) server = CultMesh.serve_node(primary, write_authority=CultMeshGrantAllWrites())
try: try:
shard = CultNetShardDescriptor( shard = CultNetShardDescriptor(
shard_id="forward", shard_id="forward",
@ -3015,7 +3017,7 @@ class CultMeshTests(unittest.TestCase):
source.database.put_raw_message(document, "note:live", CanonicalNote("initial")) source.database.put_raw_message(document, "note:live", CanonicalNote("initial"))
target = CultMesh.create_node(runtime_id="subscription-alias-target") target = CultMesh.create_node(runtime_id="subscription-alias-target")
target.database.register_document(document) target.database.register_document(document)
server = CultMesh.serve_node(source) server = CultMesh.serve_node(source, write_authority=CultMeshGrantAllWrites())
try: try:
raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0) raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with CultMesh.subscribe_document(target, raw_client, alias, "note:live") as subscription: with CultMesh.subscribe_document(target, raw_client, alias, "note:live") as subscription:
@ -3533,6 +3535,7 @@ class CultMeshTests(unittest.TestCase):
sys.executable, sys.executable,
"-m", "-m",
"cultmesh_py.daemon", "cultmesh_py.daemon",
"--allow-peer-writes",
"--runtime-id", "--runtime-id",
"live-daemon-peer", "live-daemon-peer",
"--port", "--port",
@ -3723,6 +3726,7 @@ class CultMeshTests(unittest.TestCase):
sys.executable, sys.executable,
"-m", "-m",
"cultmesh_py.daemon", "cultmesh_py.daemon",
"--allow-peer-writes",
"--runtime-id", "--runtime-id",
"forwarder-daemon-peer", "forwarder-daemon-peer",
"--port", "--port",
@ -3998,6 +4002,7 @@ class CultMeshTests(unittest.TestCase):
server = CultMesh.serve_node( server = CultMesh.serve_node(
node, node,
verse_catalog=verses, verse_catalog=verses,
write_authority=CultMeshGrantAllWrites(),
peer_catalog=peers, peer_catalog=peers,
observation_hub=observation_hub, observation_hub=observation_hub,
display_name="Mesh Server", display_name="Mesh Server",
@ -4274,7 +4279,7 @@ class CultMeshTests(unittest.TestCase):
node = CultMesh.create_node(runtime_id="mesh-alias-sub-server") node = CultMesh.create_node(runtime_id="mesh-alias-sub-server")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0) raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with raw_client.subscribe_database( with raw_client.subscribe_database(
@ -4323,7 +4328,7 @@ class CultMeshTests(unittest.TestCase):
shard_epoch=1, shard_epoch=1,
) )
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0) raw_client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with raw_client.subscribe_database( with raw_client.subscribe_database(
@ -4420,7 +4425,7 @@ class CultMeshTests(unittest.TestCase):
def served_alone_bytes(key: str, body_length: int) -> int: def served_alone_bytes(key: str, body_length: int) -> int:
node = CultMesh.create_node(runtime_id="mesh-served-bound-probe") node = CultMesh.create_node(runtime_id="mesh-served-bound-probe")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node, enable_rudp=False) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites(), enable_rudp=False)
try: try:
response, payload = exchange(server, put("probe", key, body_length), empty_id_snapshot) response, payload = exchange(server, put("probe", key, body_length), empty_id_snapshot)
finally: finally:
@ -4434,7 +4439,7 @@ class CultMeshTests(unittest.TestCase):
node = CultMesh.create_node(runtime_id="mesh-served-bound") node = CultMesh.create_node(runtime_id="mesh-served-bound")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node, max_snapshot_bytes=limit, enable_rudp=False) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites(), max_snapshot_bytes=limit, enable_rudp=False)
try: try:
refused, _ = exchange(server, put("put-over", "note:over", 101)) refused, _ = exchange(server, put("put-over", "note:over", 101))
stored_after_refusal = node.database.get(document, "note:over") stored_after_refusal = node.database.get(document, "note:over")
@ -4498,7 +4503,7 @@ class CultMeshTests(unittest.TestCase):
document = self._rudp_bound_note() document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-large") node = CultMesh.create_node(runtime_id="mesh-rudp-large")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
served, payload = self._rudp_exchange( served, payload = self._rudp_exchange(
server, server,
@ -4524,7 +4529,7 @@ class CultMeshTests(unittest.TestCase):
def served_alone_bytes(body_length: int) -> int: def served_alone_bytes(body_length: int) -> int:
node = CultMesh.create_node(runtime_id="mesh-rudp-bound-probe") node = CultMesh.create_node(runtime_id="mesh-rudp-bound-probe")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
_, payload = self._rudp_exchange( _, payload = self._rudp_exchange(
server, self._rudp_note_put(document, "probe", key, body_length), server, self._rudp_note_put(document, "probe", key, body_length),
@ -4554,7 +4559,7 @@ class CultMeshTests(unittest.TestCase):
node = CultMesh.create_node(runtime_id="mesh-rudp-bound") node = CultMesh.create_node(runtime_id="mesh-rudp-bound")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites(), rudp_max_fragment_bytes=100, rudp_max_pending_reliable_packets=8)
try: try:
refusals = [ refusals = [
self._rudp_exchange(server, self._rudp_note_put(document, f"put-{served}", "note:q", body_for(served)))[0] self._rudp_exchange(server, self._rudp_note_put(document, f"put-{served}", "note:q", body_for(served)))[0]
@ -4792,7 +4797,7 @@ class CultMeshTests(unittest.TestCase):
body_for = self._rudp_body_for(document, "note:w") body_for = self._rudp_body_for(document, "note:w")
node = CultMesh.create_node(runtime_id="mesh-rudp-wide") node = CultMesh.create_node(runtime_id="mesh-rudp-wide")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node, rudp_max_fragment_bytes=1) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites(), rudp_max_fragment_bytes=1)
try: try:
transport = create_rudp_schema_transport( transport = create_rudp_schema_transport(
host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id,
@ -4857,7 +4862,7 @@ class CultMeshTests(unittest.TestCase):
document = self._rudp_bound_note() document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-malformed") node = CultMesh.create_node(runtime_id="mesh-rudp-malformed")
node.database.register_document(document) node.database.register_document(document)
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
refusals = [] refusals = []
for field_name, value in ( for field_name, value in (
@ -4880,11 +4885,146 @@ class CultMeshTests(unittest.TestCase):
for message_id, refusal in refusals: for message_id, refusal in refusals:
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id) self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id)
self.assertEqual(refusal["messageId"], message_id) self.assertEqual(refusal["messageId"], message_id)
self.assertEqual(refusal["code"], "malformed_document_put", message_id) self.assertEqual(refusal["code"], "message_invalid", message_id)
self.assertEqual(refusal["details"]["field"], "document", message_id)
self.assertEqual(after["messageId"], "after") self.assertEqual(after["messageId"], "after")
self.assertEqual(after["documents"], []) self.assertEqual(after["documents"], [])
self.assertTrue(alive) self.assertTrue(alive)
def _rudp_open(self, server: Any) -> Any:
return create_rudp_schema_transport(
host="127.0.0.1",
port=server.port,
connection_id=server.rudp_connection_id,
timeout_seconds=4.0,
max_fragment_bytes=1200,
)
def _rudp_answer(self, transport: Any, payload: bytes) -> dict[str, Any]:
transport.send("schema", payload)
return msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
def _assert_rudp_session_ended(self, transport: Any, server: Any) -> None:
transport.send("schema", msgpack.packb(snapshot_request(message_id="after-cap").to_wire(), use_bin_type=True))
with self.assertRaises(Exception):
transport.receive(timeout_seconds=1.0)
self.assertTrue(server._rudp_thread.is_alive())
def test_cultmesh_local_server_answers_unreadable_frames_and_ends_the_session_at_eight_in_a_row(self) -> None:
# An undecodable frame (not a msgpack map) is answered message_invalid and the session kept;
# eight in a row end it (the eighth is answered too); any decoded frame resets the run.
self.assertEqual(MAX_CONSECUTIVE_REFUSED_FRAMES, 8)
node = CultMesh.create_node(runtime_id="mesh-rudp-unreadable")
server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
garbage = b"\xc1"
snapshot = msgpack.packb(snapshot_request(message_id="ok").to_wire(), use_bin_type=True)
transport = self._rudp_open(server)
try:
for _ in range(2):
for _ in range(MAX_CONSECUTIVE_REFUSED_FRAMES - 1):
reply = self._rudp_answer(transport, garbage)
self.assertEqual(reply["code"], "message_invalid")
self.assertEqual(reply["details"]["field"], "message")
self.assertEqual(self._rudp_answer(transport, snapshot)["messageId"], "ok")
for _ in range(MAX_CONSECUTIVE_REFUSED_FRAMES - 1):
self._rudp_answer(transport, garbage)
transport.send("schema", garbage)
eighth = msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
self.assertEqual(eighth["code"], "message_invalid")
self._assert_rudp_session_ended(transport, server)
finally:
transport.close()
server.stop()
def test_cultmesh_local_server_resends_a_lost_capped_answer_before_it_ends_the_session(self) -> None:
# The eighth refusal is answered reliably: the datagram carrying it is lost on the wire, and the
# peer still gets the answer (by resend) before the goodbye. An unreliable final answer, or a
# goodbye sent at once, would leave the peer without it.
node = CultMesh.create_node(runtime_id="mesh-rudp-lost-answer")
server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
send = server._send_rudp_packet
dropped: list[Any] = []
armed = threading.Event()
def lossy(rudp_socket: Any, remote_addr: Any, packet: Any) -> Any:
if armed.is_set() and not dropped and packet.packet_type == CultNetRudpPacketType.DATA and b"message_invalid" in (packet.payload or b""):
dropped.append(packet)
return None
return send(rudp_socket, remote_addr, packet)
server._send_rudp_packet = lossy
transport = self._rudp_open(server)
try:
for _ in range(MAX_CONSECUTIVE_REFUSED_FRAMES - 1):
self._rudp_answer(transport, b"\xc1")
armed.set()
reply = self._rudp_answer(transport, b"\xc1")
self.assertEqual(len(dropped), 1, "fixture: the first transmission of the last answer was lost")
self.assertEqual(reply["code"], "message_invalid")
self._assert_rudp_session_ended(transport, server)
finally:
transport.close()
server.stop()
def test_cultmesh_local_server_serves_nothing_after_the_capped_frame(self) -> None:
node = CultMesh.create_node(runtime_id="mesh-rudp-after-cap")
server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
transport = self._rudp_open(server)
try:
for _ in range(MAX_CONSECUTIVE_REFUSED_FRAMES - 1):
self._rudp_answer(transport, b"\xc1")
transport.send("schema", b"\xc1")
transport.send("schema", msgpack.packb(snapshot_request(message_id="behind-the-cap").to_wire(), use_bin_type=True))
first = msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
self.assertEqual(first["code"], "message_invalid")
with self.assertRaises(Exception):
transport.receive(timeout_seconds=1.0)
finally:
transport.close()
server.stop()
def test_cultmesh_local_server_ends_the_session_at_eight_refused_deletes_in_a_row(self) -> None:
class GrantOnlyKeyB:
def decide(self, request: Any) -> Any:
return CultMeshRemoteWriteDecision.grant() if request.record_key == "note:b" else CultMeshRemoteWriteDecision.refuse("no")
document = self._rudp_bound_note()
node = CultMesh.create_node(runtime_id="mesh-rudp-deletes")
node.database.register_document(document)
server = CultMesh.serve_node(node, write_authority=GrantOnlyKeyB())
def delete(key: str) -> bytes:
return msgpack.packb({
"schemaVersion": "cultnet.document_delete.v0",
"messageId": f"del-{key}",
"schemaId": document.schema_id,
"recordKey": key,
}, use_bin_type=True)
snapshot = msgpack.packb(snapshot_request(message_id="ok").to_wire(), use_bin_type=True)
transport = self._rudp_open(server)
try:
def refused_run(count: int) -> None:
for _ in range(count):
reply = self._rudp_answer(transport, delete("note:a"))
self.assertEqual(reply["code"], "write_not_authorized")
self.assertEqual(reply["details"]["value"], "note:a")
refused_run(MAX_CONSECUTIVE_REFUSED_FRAMES - 1)
# A granted delete resets the run (nothing is stored under it, so the store answers that).
self.assertEqual(self._rudp_answer(transport, delete("note:b"))["code"], "unregistered_document_delete")
refused_run(MAX_CONSECUTIVE_REFUSED_FRAMES - 1)
# So does any decoded non-delete frame.
self.assertEqual(self._rudp_answer(transport, snapshot)["messageId"], "ok")
refused_run(MAX_CONSECUTIVE_REFUSED_FRAMES - 1)
transport.send("schema", delete("note:a"))
eighth = msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
self.assertEqual(eighth["code"], "write_not_authorized")
self._assert_rudp_session_ended(transport, server)
finally:
transport.close()
server.stop()
def test_cultmesh_local_server_refuses_a_put_its_store_cannot_take_and_serves_on(self) -> None: def test_cultmesh_local_server_refuses_a_put_its_store_cannot_take_and_serves_on(self) -> None:
# Well-formed puts the store refuses: a blank key, a payload that is not MessagePack, a # Well-formed puts the store refuses: a blank key, a payload that is not MessagePack, a
# payload its schema cannot decode, a global document under another key. Each is refused # payload its schema cannot decode, a global document under another key. Each is refused
@ -4917,7 +5057,7 @@ class CultMeshTests(unittest.TestCase):
node = CultMesh.create_node(runtime_id="mesh-unstorable-put") node = CultMesh.create_node(runtime_id="mesh-unstorable-put")
node.database.register_document(document) node.database.register_document(document)
node.database.register_document(global_document) node.database.register_document(global_document)
server = CultMesh.serve_node(node) server = CultMesh.serve_node(node, write_authority=CultMeshGrantAllWrites())
try: try:
rudp_refusals = [(put["messageId"], self._rudp_exchange(server, put)[0]) for put in cases()] rudp_refusals = [(put["messageId"], self._rudp_exchange(server, put)[0]) for put in cases()]
rudp_after, _ = self._rudp_exchange(server, hello(runtime_id="rudp-after").to_wire()) rudp_after, _ = self._rudp_exchange(server, hello(runtime_id="rudp-after").to_wire())
@ -4939,7 +5079,8 @@ class CultMeshTests(unittest.TestCase):
for message_id, refusal in rudp_refusals + tcp_refusals: for message_id, refusal in rudp_refusals + tcp_refusals:
self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id) self.assertEqual(refusal["schemaVersion"], "cultnet.error.v0", message_id)
self.assertEqual(refusal["messageId"], message_id) self.assertEqual(refusal["messageId"], message_id)
self.assertEqual(refusal["code"], "malformed_document_put", message_id) self.assertEqual(refusal["code"], "message_invalid", message_id)
self.assertEqual(refusal["details"]["field"], "document", message_id)
self.assertNotIn("note:ok", refusal["error"], message_id) self.assertNotIn("note:ok", refusal["error"], message_id)
self.assertEqual(len(tcp_refusals), 5) self.assertEqual(len(tcp_refusals), 5)
self.assertEqual(rudp_after["schemaVersion"], "cultnet.hello.v0") self.assertEqual(rudp_after["schemaVersion"], "cultnet.hello.v0")
@ -5053,9 +5194,11 @@ class CultMeshTests(unittest.TestCase):
self.assertEqual(unsupported["details"]["value"], "cultnet.nope.v0") self.assertEqual(unsupported["details"]["value"], "cultnet.nope.v0")
self.assertIn("unsupported_schema_version", unsupported["error"]) self.assertIn("unsupported_schema_version", unsupported["error"])
self.assertEqual(malformed_put["messageId"], "bad-put") self.assertEqual(malformed_put["messageId"], "bad-put")
self.assertEqual(malformed_put["code"], "malformed_document_put") self.assertEqual(malformed_put["code"], "message_invalid")
self.assertEqual(malformed_put["details"]["field"], "document")
self.assertEqual(malformed_delete["messageId"], "bad-delete") self.assertEqual(malformed_delete["messageId"], "bad-delete")
self.assertEqual(malformed_delete["code"], "malformed_document_delete") self.assertEqual(malformed_delete["code"], "message_invalid")
self.assertEqual(malformed_delete["details"]["field"], "recordKey")
self.assertEqual(unsupported_v1["code"], "unsupported_schema_version") self.assertEqual(unsupported_v1["code"], "unsupported_schema_version")
self.assertEqual(unsupported_v1["details"]["value"], "cultnet.snapshot_request.v1") self.assertEqual(unsupported_v1["details"]["value"], "cultnet.snapshot_request.v1")

View file

@ -0,0 +1,338 @@
"""A peer's put or delete is applied only when the server's write authority grants it.
Ports the behaviours of C# RemoteWriteAuthorityTests. The C# forwarding behaviour (a refused write is never
forwarded) has no counterpart: this server does not forward non-primary writes. The handlers are reached with
the peer the connection loop would pass, and one test drives the same path over a real TCP connection.
"""
from __future__ import annotations
import json
import unittest
from pathlib import Path
from typing import Any
import msgpack
from cultcache_py import define_database_entry_type
from cultmesh_py import (
CultMesh,
CultMeshGrantAllWrites,
CultMeshRemoteWriteDecision,
CultMeshRemoteWriteOperation,
CultMeshRemoteWriteRequest,
CultMeshServerPeer,
create_node,
)
from cultmesh_py.server import CultMeshLocalServer
from cultnet_py import CultNetPeerError, create_rudp_schema_transport, document_delete, document_put_raw, error_message
SCHEMA_ID = "sha256:authority-note"
ALIAS = "runtime.generated.authority-note.ui.42"
SHARD_ID = "authority-shard"
KEY_A = "tests:authority:a"
KEY_B = "tests:authority:b"
PEER = CultMeshServerPeer("127.0.0.1:50000", "tcp")
_REPO = Path(__file__).resolve().parents[3]
_VECTORS = json.loads((_REPO / "contracts/cultnet/interop/error-vectors.json").read_text(encoding="utf-8"))["vectors"]
NOTE = define_database_entry_type(
"tests.authority_note",
[("schema_version", 0), ("text", 1)],
schema_id=SCHEMA_ID,
schema_name="tests.authority_note",
schema_version="tests.authority_note.v1",
)
class Recording:
def __init__(self, decide: Any) -> None:
self._decide = decide
self.requests: list[CultMeshRemoteWriteRequest] = []
def decide(self, request: CultMeshRemoteWriteRequest) -> Any:
self.requests.append(request)
return self._decide(request)
def put_of(key: str, text: str, *, schema_id: str = SCHEMA_ID) -> dict[str, Any]:
return document_put_raw(
message_id="wire",
key=key,
schema_id=schema_id,
stored_at="2026-11-07T00:00:00Z",
payload=NOTE.encode_payload({"schema_version": "tests.authority_note.v1", "text": text}),
shard_id=SHARD_ID,
shard_epoch=1,
).to_wire()
def delete_of(key: str, *, schema_id: str = SCHEMA_ID) -> dict[str, Any]:
return document_delete(
message_id="wire-delete", schema_id=schema_id, record_key=key, shard_id=SHARD_ID, shard_epoch=1
).to_wire()
class RemoteWriteAuthorityTests(unittest.TestCase):
def build(self, authority: Any = None) -> CultMeshLocalServer:
node = create_node(runtime_id="authority-server")
node.database.register_document(NOTE)
return CultMeshLocalServer(node=node, port=0, write_authority=authority)
def text_of(self, server: CultMeshLocalServer, key: str) -> str | None:
value = server.node.cache.get(NOTE, key)
return None if value is None else value["text"]
def send(self, server: CultMeshLocalServer, message: dict[str, Any]) -> list[dict[str, Any]]:
subscriptions: dict[str, Any] = {}
return server._handle_connection_message(message, subscriptions, peer=PEER)
def assert_refused(self, replies: list[dict[str, Any]], key: str, *, error: str | None = None) -> None:
self.assertEqual(len(replies), 1)
reply = replies[0]
self.assertEqual(reply["schemaVersion"], "cultnet.error.v0")
self.assertEqual(reply["code"], "write_not_authorized")
self.assertTrue(reply["error"].startswith("write_not_authorized"))
self.assertEqual(reply["details"]["field"], "recordKey")
self.assertEqual(reply["details"]["value"], key)
if error is not None:
self.assertEqual(reply["error"], error)
def seed(self, server: CultMeshLocalServer, key: str, text: str) -> None:
# The host writes its own record through its own door, which asks no remote authority.
self.assertEqual(server.node.database.apply_raw_put_message(put_of(key, text)).change_kind, "added")
def test_with_no_authority_a_peers_put_and_delete_are_refused_and_change_nothing(self) -> None:
server = self.build(None)
self.seed(server, KEY_A, "server")
with self.assertLogs("cultmesh_py.server", level="WARNING") as logs:
self.assert_refused(self.send(server, put_of(KEY_A, "peer")), KEY_A)
self.assert_refused(self.send(server, delete_of(KEY_A)), KEY_A)
self.assert_refused(self.send(server, put_of(KEY_B, "peer")), KEY_B)
self.assertEqual(self.text_of(server, KEY_A), "server")
self.assertIsNone(self.text_of(server, KEY_B))
self.assertEqual(sum("write not authorized" in line for line in logs.output), 3)
def test_a_refusal_publishes_no_change_to_a_subscriber(self) -> None:
server = self.build(None)
server.start()
try:
client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with client.subscribe_database(subscription_id="s", schema_ids=[SCHEMA_ID], include_snapshot=False) as sub:
with self.assertRaises(CultNetPeerError) as raised:
sub.send(put_of(KEY_A, "peer"))
sub.read_next()
finally:
server.stop()
self.assertEqual(raised.exception.response["code"], "write_not_authorized")
self.assertIsNone(self.text_of(server, KEY_A))
def test_a_granted_put_and_delete_commit_and_the_authority_saw_this_peer(self) -> None:
authority = Recording(lambda _: CultMeshRemoteWriteDecision.grant())
server = self.build(authority)
put_replies = self.send(server, put_of(KEY_A, "peer"))
self.assertEqual(self.text_of(server, KEY_A), "peer")
self.assertEqual(put_replies, [])
self.send(server, delete_of(KEY_A))
self.assertIsNone(self.text_of(server, KEY_A))
self.assertEqual(len(authority.requests), 2)
self.assertTrue(all(request.peer is PEER for request in authority.requests))
def test_the_request_carries_the_resolved_write_and_scoped_grants_refuse_their_neighbours(self) -> None:
authority = Recording(
lambda request: CultMeshRemoteWriteDecision.grant()
if request.operation is CultMeshRemoteWriteOperation.PUT and request.record_key == KEY_A
else CultMeshRemoteWriteDecision.refuse("scoped")
)
server = self.build(authority)
self.seed(server, KEY_A, "server")
self.send(server, put_of(KEY_A, "aliased", schema_id=ALIAS))
request = authority.requests[0]
self.assertEqual(request.schema_id, SCHEMA_ID, "the authority sees the canonical id, not the alias as sent")
self.assertIs(request.operation, CultMeshRemoteWriteOperation.PUT)
self.assertEqual(request.record_key, KEY_A)
self.assertEqual(request.shard_id, SHARD_ID)
self.assertEqual(request.shard_epoch, 1)
self.assertEqual(self.text_of(server, KEY_A), "aliased")
self.assert_refused(self.send(server, put_of(KEY_B, "other-key")), KEY_B)
self.assert_refused(self.send(server, delete_of(KEY_A)), KEY_A)
self.assertIsNone(self.text_of(server, KEY_B), "a grant scoped to key a refuses key b")
self.assertEqual(self.text_of(server, KEY_A), "aliased", "a grant scoped to put refuses delete")
self.assertIs(authority.requests[-1].operation, CultMeshRemoteWriteOperation.DELETE)
self.assertEqual(authority.requests[-1].schema_id, SCHEMA_ID)
def test_refusal_precedes_every_other_judgment_of_the_put(self) -> None:
refusing = self.build(None)
unowned = put_of("unrelated:authority", "x", schema_id="sha256:nobody-owns-this")
unowned["document"]["payload"] = msgpack.packb(["nobody.owns.this.v1", "x"], use_bin_type=True)
self.assert_refused(self.send(refusing, unowned), "unrelated:authority")
blank_key = put_of("", "x")
self.assert_refused(self.send(refusing, blank_key), "")
granting = self.build(Recording(lambda _: CultMeshRemoteWriteDecision.grant()))
reply = self.send(granting, unowned)
self.assertEqual(reply[0]["code"], "unregistered_document_put", "a granted put still meets the store's refusal")
def test_an_authority_that_raises_refuses_and_is_logged_as_an_error(self) -> None:
def explode(_: Any) -> Any:
raise RuntimeError("authority exploded")
server = self.build(Recording(explode))
self.seed(server, KEY_A, "server")
with self.assertLogs("cultmesh_py.server", level="ERROR") as logs:
self.assert_refused(self.send(server, put_of(KEY_A, "peer")), KEY_A)
self.assert_refused(self.send(server, delete_of(KEY_A)), KEY_A)
self.assertEqual(self.text_of(server, KEY_A), "server", "fail closed")
self.assertTrue(any("RuntimeError" in line for line in logs.output))
def test_a_refusal_with_no_reason_still_says_why(self) -> None:
server = self.build(Recording(lambda _: CultMeshRemoteWriteDecision.refuse()))
self.assert_refused(self.send(server, put_of(KEY_A, "peer")), KEY_A, error="write_not_authorized")
def test_the_refusal_names_the_key_and_the_code_in_the_pinned_bytes(self) -> None:
vector = next(v for v in _VECTORS if v["name"] == "write_not_authorized")
message = error_message(
"write_not_authorized: not granted",
code="write_not_authorized",
details={"field": "recordKey", "value": "some:key"},
)
self.assertEqual(message.to_bytes(), bytes.fromhex(vector["messagePackHex"]))
server = self.build(Recording(lambda _: CultMeshRemoteWriteDecision.refuse("not granted")))
reply = self.send(server, put_of("some:key", "peer"))[0]
self.assertEqual(msgpack.packb(reply, use_bin_type=True), bytes.fromhex(vector["messagePackHex"]))
def test_the_peer_receives_the_typed_refusal_over_tcp_and_a_grant_sends_nothing_back(self) -> None:
authority = Recording(
lambda request: CultMeshRemoteWriteDecision.grant()
if request.record_key == KEY_A
else CultMeshRemoteWriteDecision.refuse("only a")
)
server = self.build(authority)
server.start()
try:
client = CultMesh.create_client("127.0.0.1", server.port, timeout_seconds=2.0)
with client.subscribe_database(subscription_id="s", schema_ids=[SCHEMA_ID], include_snapshot=False) as sub:
sub.send(put_of(KEY_A, "peer"))
self.assertEqual(sub.read_next_change().record_key, KEY_A, "the granted write was answered by its change, not an error")
sub.send(put_of(KEY_B, "peer"))
with self.assertRaises(CultNetPeerError) as raised:
sub.read_next()
finally:
server.stop()
reply = raised.exception.response
self.assertEqual(reply["error"], "write_not_authorized: only a")
self.assertEqual(reply["details"]["value"], KEY_B)
self.assertTrue(authority.requests[0].peer.endpoint.startswith("127.0.0.1:"))
self.assertEqual(authority.requests[0].peer.transport, "tcp")
self.assertEqual(self.text_of(server, KEY_A), "peer")
self.assertIsNone(self.text_of(server, KEY_B))
def test_a_delete_sent_under_a_schema_alias_asks_the_authority_with_the_canonical_id(self) -> None:
authority = Recording(lambda _: CultMeshRemoteWriteDecision.grant())
server = self.build(authority)
self.seed(server, KEY_A, "server")
self.send(server, delete_of(KEY_A, schema_id="tests.authority_note.v1"))
request = authority.requests[0]
self.assertIs(request.operation, CultMeshRemoteWriteOperation.DELETE)
self.assertEqual(request.schema_id, SCHEMA_ID)
self.assertIsNone(self.text_of(server, KEY_A), "the aliased delete was granted and applied")
def test_a_missing_decision_refuses_put_and_delete(self) -> None:
server = self.build(Recording(lambda _: None))
self.seed(server, KEY_A, "server")
self.assert_refused(self.send(server, put_of(KEY_A, "peer")), KEY_A)
self.assert_refused(self.send(server, delete_of(KEY_A)), KEY_A)
self.assert_refused(self.send(server, put_of(KEY_B, "peer")), KEY_B)
self.assertEqual(self.text_of(server, KEY_A), "server")
self.assertIsNone(self.text_of(server, KEY_B))
def test_a_peer_over_rudp_is_refused_with_its_rudp_endpoint_and_the_server_serves_on(self) -> None:
authority = Recording(lambda _: CultMeshRemoteWriteDecision.refuse("rudp no"))
server = self.build(authority)
server.start()
try:
transport = create_rudp_schema_transport(
host="127.0.0.1", port=server.port, connection_id=server.rudp_connection_id, timeout_seconds=4.0
)
try:
transport.send("schema", msgpack.packb(put_of(KEY_A, "peer"), use_bin_type=True))
reply = msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
transport.send("schema", msgpack.packb(delete_of(KEY_A), use_bin_type=True))
delete_reply = msgpack.unpackb(transport.receive(timeout_seconds=4.0).payload, raw=False)
finally:
transport.close()
finally:
server.stop()
self.assertEqual(reply["error"], "write_not_authorized: rudp no")
self.assertEqual(delete_reply["code"], "write_not_authorized")
self.assertEqual([r.peer.transport for r in authority.requests], ["rudp", "rudp"])
self.assertTrue(all(r.peer.endpoint.startswith("127.0.0.1:") for r in authority.requests))
self.assertIsNone(self.text_of(server, KEY_A))
def test_a_put_with_an_absurd_payload_is_refused_by_the_gate_not_crashed_on(self) -> None:
server = self.build(None)
absurd = put_of(KEY_A, "x")
absurd["document"]["payload"] = 2**70
self.assert_refused(self.send(server, absurd), KEY_A)
def test_an_ungranted_peers_huge_payload_is_refused_without_allocating_it(self) -> None:
import tracemalloc
server = self.build(None)
huge = put_of(KEY_A, "x")
huge["document"]["payload"] = 10**9 # bytes(10**9) would allocate a gigabyte
tracemalloc.start()
try:
replies = self.send(server, huge)
_, peak = tracemalloc.get_traced_memory()
finally:
tracemalloc.stop()
self.assert_refused(replies, KEY_A)
self.assertLess(peak, 10_000_000)
def test_wrong_typed_shard_fields_are_refused_before_the_gate_and_write_nothing(self) -> None:
authority = Recording(lambda _: CultMeshRemoteWriteDecision.grant())
server = self.build(authority)
self.seed(server, KEY_B, "server")
shards_before = server.node.database.shard_ids()
for field, value in (("shardId", {"not": "a string"}), ("shardId", 5), ("shardEpoch", "7"), ("shardEpoch", True), ("shardEpoch", 1.5)):
for operation in ("put", "delete"):
with self.subTest(field=field, value=value, operation=operation):
message = put_of(KEY_A, "x") if operation == "put" else delete_of(KEY_B)
message[field] = value
replies = self.send(server, message)
self.assertEqual([(reply["code"], reply["details"]["field"]) for reply in replies], [("message_invalid", field)])
self.assertEqual(authority.requests, [], "the authority was never asked")
self.assertIsNone(self.text_of(server, KEY_A), "nothing was written")
self.assertEqual(self.text_of(server, KEY_B), "server", "nothing was deleted")
self.assertEqual(server.node.database.shard_ids(), shards_before, "no shard or log entry was filed")
def test_well_typed_shard_fields_reach_the_authority_as_sent(self) -> None:
authority = Recording(lambda _: CultMeshRemoteWriteDecision.grant())
server = self.build(authority)
self.send(server, put_of(KEY_A, "x"))
self.assertEqual((authority.requests[0].shard_id, authority.requests[0].shard_epoch), (SHARD_ID, 1))
def test_grant_all_is_an_explicit_choice_that_grants_every_write(self) -> None:
server = self.build(CultMeshGrantAllWrites())
self.send(server, put_of(KEY_A, "peer"))
self.assertEqual(self.text_of(server, KEY_A), "peer")
if __name__ == "__main__":
unittest.main()

View file

@ -10,7 +10,7 @@ from dataclasses import dataclass
import msgpack import msgpack
from cultcache_py import define_database_entry_type from cultcache_py import define_database_entry_type
from cultmesh_py import create_node from cultmesh_py import CultMeshGrantAllWrites, create_node
from cultmesh_py.server import CultMeshLocalServer from cultmesh_py.server import CultMeshLocalServer
from cultnet_py import ( from cultnet_py import (
CultNetRudpSendOptions, CultNetRudpSendOptions,
@ -49,7 +49,7 @@ class RudpServerGenerationTests(unittest.TestCase):
node = create_node(runtime_id="rudp-generation") node = create_node(runtime_id="rudp-generation")
node.database.register_document(NOTE) node.database.register_document(NOTE)
# Replies stay whole datagrams here, so each server packet the pump reads is one message. # Replies stay whole datagrams here, so each server packet the pump reads is one message.
self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID, rudp_max_fragment_bytes=60_000) self.server = CultMeshLocalServer(node=node, rudp_connection_id=CONNECTION_ID, rudp_max_fragment_bytes=60_000, write_authority=CultMeshGrantAllWrites())
self.server.start() self.server.start()
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.bind(("127.0.0.1", 0)) self.sock.bind(("127.0.0.1", 0))

View file

@ -0,0 +1,69 @@
"""A server asked for any port finds a TCP+UDP pair; one asked for a port gets that port or an honest failure."""
from __future__ import annotations
import errno
import socket
import threading
import unittest
from unittest.mock import patch
from cultmesh_py import create_node
from cultmesh_py.server import CultMeshLocalServer
def server(**kwargs) -> CultMeshLocalServer:
return CultMeshLocalServer(node=create_node(runtime_id="bind-test"), host="127.0.0.1", **kwargs)
class ServerBindTests(unittest.TestCase):
def test_port_zero_retries_with_a_fresh_port_when_another_process_holds_the_udp_number(self) -> None:
real_bind = socket.socket.bind
refused: list[int] = []
def bind(sock: socket.socket, address) -> None:
# The first two UDP binds find the number taken, as a UDP listener of another process would.
if sock.type == socket.SOCK_DGRAM and len(refused) < 2:
refused.append(address[1])
raise OSError(errno.EADDRINUSE, "Address already in use")
real_bind(sock, address)
with patch.object(socket.socket, "bind", bind):
started = server().start()
try:
self.assertEqual(len(refused), 2)
self.assertNotIn(started.port, refused[:1], "the retry used a fresh TCP port")
probe = socket.create_connection(("127.0.0.1", started.port), timeout=2.0)
probe.close()
finally:
started.stop()
def test_an_explicit_port_whose_udp_number_is_taken_fails_and_leaves_nothing_running(self) -> None:
holder = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
holder.bind(("127.0.0.1", 0))
port = holder.getsockname()[1]
free = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
free.bind(("127.0.0.1", port)) # the TCP number is free: only the UDP one is taken
finally:
free.close()
threads_before = threading.active_count()
try:
failing = server(port=port)
with self.assertRaises(OSError) as raised:
failing.start()
self.assertEqual(raised.exception.errno, errno.EADDRINUSE)
self.assertIsNone(failing._socket)
self.assertEqual(threading.active_count(), threads_before, "no accept thread was left running")
# The TCP number was released, not left listening.
free = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
free.bind(("127.0.0.1", port))
finally:
free.close()
finally:
holder.close()
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,77 @@
//! The real Rust RUDP document server on an ephemeral loopback port, for the cross-runtime write-receipt interop
//! harness (packages/cultmesh-ts/test/interop/write-receipt-interop.test.ts). It is the production server with a
//! recording sink and nothing else: stdout carries one JSON line per fact the harness asserts on, and the server runs
//! until stdin closes.
//!
//! {"event":"listening","port":N}
//! {"event":"applied","op":"put","messageId":"...","schemaId":"...","recordKey":"..."}
//!
//! Record keys that start with `refuse:` are refused by the sink (authorize and commit), which is how the harness
//! asks for a refused write.
use anyhow::Result;
use cultmesh_rs::{
CultMeshRudpDocumentServer, CultMeshRudpRawDocumentReceipt, CultMeshRudpRawDocumentSink,
CultMeshRudpSnapshotQuery, CultMeshSystemClock,
};
use cultnet_rs::CultNetRawDocumentRecord;
use serde_json::json;
use std::io::Read;
use std::net::UdpSocket;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
const REFUSED_PREFIX: &str = "refuse:";
struct RecordingSink;
impl CultMeshRudpRawDocumentSink for RecordingSink {
fn authorize_raw_document(&mut self, receipt: &CultMeshRudpRawDocumentReceipt) -> Result<()> {
if receipt.document.record_key.starts_with(REFUSED_PREFIX) {
anyhow::bail!("not authorized");
}
Ok(())
}
fn accept_raw_document(&mut self, receipt: CultMeshRudpRawDocumentReceipt) -> Result<()> {
if receipt.document.record_key.starts_with(REFUSED_PREFIX) {
anyhow::bail!("not authorized");
}
println!(
"{}",
json!({
"event": "applied",
"op": "put",
"messageId": receipt.message_id,
"schemaId": receipt.document.schema_id,
"recordKey": receipt.document.record_key,
})
);
Ok(())
}
}
fn main() -> Result<()> {
let source = |_: &CultMeshRudpSnapshotQuery| -> Result<Vec<CultNetRawDocumentRecord>> { Ok(Vec::new()) };
let mut server = CultMeshRudpDocumentServer::new(
UdpSocket::bind("127.0.0.1:0")?,
RecordingSink,
source,
CultMeshSystemClock::default(),
Default::default(),
)?;
println!("{}", json!({ "event": "listening", "port": server.local_addr()?.port() }));
let stop = Arc::new(AtomicBool::new(false));
let watcher = Arc::clone(&stop);
thread::spawn(move || {
let mut sink = Vec::new();
let _ = std::io::stdin().read_to_end(&mut sink);
watcher.store(true, Ordering::SeqCst);
});
while !stop.load(Ordering::SeqCst) {
server.poll_once()?;
thread::sleep(Duration::from_millis(1));
}
Ok(())
}

View file

@ -82,7 +82,10 @@ pub struct CultMeshRudpDocumentPublishOptions {
pub target: SocketAddr, pub target: SocketAddr,
pub runtime_id: String, pub runtime_id: String,
pub connect_timeout: Duration, pub connect_timeout: Duration,
/// How long the acknowledgement of every put may take.
pub flush_timeout: Duration, pub flush_timeout: Duration,
/// How long after the acknowledgement a refusal may still arrive; a success frame ends the wait early.
pub result_window: Duration,
pub poll_interval: Duration, pub poll_interval: Duration,
pub resend_delay_ms: u64, pub resend_delay_ms: u64,
pub source_agent_id: Option<String>, pub source_agent_id: Option<String>,
@ -149,6 +152,7 @@ impl Default for CultMeshRudpDocumentPublishOptions {
runtime_id: "cultmesh-rudp-document-publisher".to_string(), runtime_id: "cultmesh-rudp-document-publisher".to_string(),
connect_timeout: Duration::from_secs(3), connect_timeout: Duration::from_secs(3),
flush_timeout: Duration::from_millis(300), flush_timeout: Duration::from_millis(300),
result_window: Duration::from_millis(500),
poll_interval: Duration::from_millis(10), poll_interval: Duration::from_millis(10),
resend_delay_ms: 50, resend_delay_ms: 50,
source_agent_id: None, source_agent_id: None,
@ -865,6 +869,7 @@ pub fn request_raw_snapshot_from_rudp_catalog(
/// fixed refusals a CultMesh catalog sends; any other text could carry /// fixed refusals a CultMesh catalog sends; any other text could carry
/// anything, so it is left out. /// anything, so it is left out.
fn recognised_refusal(text: &str) -> String { fn recognised_refusal(text: &str) -> String {
let text = text.strip_prefix("write_not_authorized: ").unwrap_or(text);
if REFUSAL_TEXTS.contains(&text) { if REFUSAL_TEXTS.contains(&text) {
format!(": {text}") format!(": {text}")
} else { } else {
@ -881,77 +886,30 @@ fn unix_millis() -> u128 {
/// Publish one raw CultNet schema message to a RUDP catalog. /// Publish one raw CultNet schema message to a RUDP catalog.
/// ///
/// Each call owns a fresh connection epoch and returns only after the catalog /// A put completes on the catalog's result frame, never on the transport
/// acknowledges reliable application admission. Against a Rust CultMesh /// acknowledgement: an ack proves delivery, not admission. A refusal (a
/// catalog, which never acknowledges a message it refuses, a refusal is /// `cultnet.error.v0` frame) returns an error in either order against the ack,
/// returned as an error, naming the refusal when it is one of the fixed texts /// naming the refusal when it is one of the fixed texts a catalog sends. A
/// such a catalog sends. A catalog that acknowledges a message on receipt and /// catalog that admits a put sends no success frame, so after the ack the call
/// refuses it afterwards (the TypeScript document server does) is reported as /// waits `result_window` for a refusal and reports the put as admitted when
/// having admitted it: the acknowledgement arrives first. /// none comes (interim until the catalog sends a success frame; a success
/// frame ends the wait early). Each call owns a fresh connection epoch.
pub fn publish_cultnet_message_to_rudp_catalog( pub fn publish_cultnet_message_to_rudp_catalog(
message: &cultnet_rs::CultNetMessage, message: &cultnet_rs::CultNetMessage,
options: CultMeshRudpDocumentPublishOptions, options: CultMeshRudpDocumentPublishOptions,
) -> Result<()> { ) -> Result<()> {
if options.runtime_id.trim().is_empty() { publish_cultnet_messages_to_rudp_catalog(std::slice::from_ref(message), options)
anyhow::bail!("runtime_id must be non-empty");
}
let mut client = connect_rudp_client(
options.target,
&options.runtime_id,
options.connect_timeout,
options.poll_interval,
options.resend_delay_ms,
"cultmesh-rudp-document-publisher",
)?;
let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?;
let receipt = client.send_reliable("schema", payload)?;
let flush_deadline = Instant::now() + options.flush_timeout;
while Instant::now() < flush_deadline {
if let Some(frame) = client.receive_once()? {
if frame.channel_id == "schema" {
if let Ok(cultnet_rs::CultNetMessage::Error { error, .. }) =
decode_cultnet_message_from_slice(
&frame.payload,
CultNetWireContract::CultNetSchemaV0,
)
{
let _ = client.disconnect(b"document-refused".to_vec());
anyhow::bail!(
"CultMesh RUDP catalog {} refused the put{}",
options.target,
recognised_refusal(&error)
);
}
}
}
match client.reliable_send_status(&receipt) {
cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged => {
let _ = client.disconnect(b"document-acknowledged".to_vec());
return Ok(());
}
cultnet_rs::CultNetRudpReliableSendStatus::Invalidated => {
anyhow::bail!("CultMesh RUDP document receipt was invalidated")
}
cultnet_rs::CultNetRudpReliableSendStatus::Pending => {}
}
client.poll_resends()?;
thread::sleep(options.poll_interval);
}
let _ = client.disconnect(b"document-unacknowledged".to_vec());
anyhow::bail!(
"timed out waiting for reliable acknowledgement from CultMesh RUDP catalog {}",
options.target
)
} }
/// Publish a batch of raw CultNet schema messages to a RUDP catalog. /// Publish a batch of raw CultNet schema messages to a RUDP catalog on one
/// connection.
/// ///
/// Unlike [`publish_cultnet_message_to_rudp_catalog`], which polls for /// Completes under the same rule as [`publish_cultnet_message_to_rudp_catalog`]:
/// per-message application-level acknowledgement, this sends every message on /// every message acknowledged, then no refusal frame within `result_window`
/// one connection and waits only for a transport-level `flush_reliable`. It /// (or one success frame per message). A refusal of any message in the batch
/// trades per-receipt confirmation for batch throughput; callers that need a /// fails the whole call; the batch cannot hide it. The catalog's answers do not
/// stronger delivery guarantee should use the singular publish path instead. /// name the message they answer, so a failed batch does not say which message
/// was refused or whether the others were admitted.
pub fn publish_cultnet_messages_to_rudp_catalog( pub fn publish_cultnet_messages_to_rudp_catalog(
messages: &[cultnet_rs::CultNetMessage], messages: &[cultnet_rs::CultNetMessage],
options: CultMeshRudpDocumentPublishOptions, options: CultMeshRudpDocumentPublishOptions,
@ -968,11 +926,62 @@ pub fn publish_cultnet_messages_to_rudp_catalog(
"cultmesh-rudp-document-publisher", "cultmesh-rudp-document-publisher",
)?; )?;
let mut receipts = Vec::with_capacity(messages.len());
for message in messages { for message in messages {
let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?; let payload = encode_cultnet_message_to_vec(message, CultNetWireContract::CultNetSchemaV0)?;
client.send("schema", payload)?; receipts.push(client.send_reliable("schema", payload)?);
}
let ack_deadline = Instant::now() + options.flush_timeout;
let mut acknowledged_at: Option<Instant> = None;
let mut successes = 0;
loop {
while let Some(frame) = client.receive_once()? {
if frame.channel_id != "schema" {
continue;
}
match decode_cultnet_message_from_slice(&frame.payload, CultNetWireContract::CultNetSchemaV0) {
Ok(cultnet_rs::CultNetMessage::Error { error, .. }) => {
let _ = client.disconnect(b"document-refused".to_vec());
anyhow::bail!(
"CultMesh RUDP catalog {} refused the put{}",
options.target,
recognised_refusal(&error)
);
}
Ok(_) => successes += 1,
Err(_) => {}
}
}
if acknowledged_at.is_none() {
let mut all_acknowledged = true;
for receipt in &receipts {
match client.reliable_send_status(receipt) {
cultnet_rs::CultNetRudpReliableSendStatus::Acknowledged => {}
cultnet_rs::CultNetRudpReliableSendStatus::Invalidated => {
anyhow::bail!("CultMesh RUDP document receipt was invalidated")
}
cultnet_rs::CultNetRudpReliableSendStatus::Pending => all_acknowledged = false,
}
}
if all_acknowledged {
acknowledged_at = Some(Instant::now());
} else if Instant::now() >= ack_deadline {
let _ = client.disconnect(b"document-unacknowledged".to_vec());
anyhow::bail!(
"timed out waiting for reliable acknowledgement from CultMesh RUDP catalog {}",
options.target
)
}
}
if let Some(acknowledged_at) = acknowledged_at {
if successes >= messages.len() || acknowledged_at.elapsed() >= options.result_window {
let _ = client.disconnect(b"document-completed".to_vec());
return Ok(());
}
}
client.poll_resends()?;
thread::sleep(options.poll_interval);
} }
client.flush_reliable(options.flush_timeout)
} }
fn connect_rudp_client( fn connect_rudp_client(
@ -1450,6 +1459,141 @@ mod tests {
Ok((target, stop, catalog)) Ok((target, stop, catalog))
} }
/// A catalog that acknowledges every reliable message it receives and refuses it with a typed
/// write_not_authorized, the acknowledgement either before the refusal or after it (the second packet
/// follows the first by 100 ms). The refusal carries no acknowledgement of its own.
/// What the stub catalog sends for a put, and in which order against the transport ack.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CatalogReply {
RefusalThenAck,
AckThenRefusal,
AckThenSuccess,
}
fn acknowledging_refusing_catalog(
reply: CatalogReply,
) -> Result<(
SocketAddr,
std::sync::Arc<std::sync::atomic::AtomicBool>,
thread::JoinHandle<Result<()>>,
)> {
use cultnet_rs::{
CultNetRudpPacketType, CultNetRudpSendOptions, CultNetRudpSession,
CultNetRudpSessionOptions, decode_rudp_packet, encode_rudp_packet,
};
let socket = UdpSocket::bind("127.0.0.1:0")?;
socket.set_read_timeout(Some(Duration::from_millis(5)))?;
let target = socket.local_addr()?;
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let catalog_stop = stop.clone();
let catalog = thread::spawn(move || -> Result<()> {
let mut session: Option<CultNetRudpSession> = None;
let mut wire = vec![0_u8; 65_535];
while !catalog_stop.load(std::sync::atomic::Ordering::SeqCst) {
let Ok((bytes, peer)) = socket.recv_from(&mut wire) else {
continue;
};
let Ok(packet) = decode_rudp_packet(&wire[..bytes]) else {
continue;
};
if packet.packet_type == CultNetRudpPacketType::Connect {
let mut accepted = CultNetRudpSession::new(CultNetRudpSessionOptions {
connection_id: packet.connection_id,
initial_sequence: None,
resend_delay_ms: 10_000,
max_pending_reliable_packets: Some(64),
});
let accept = accepted.accept_connect(&packet, 0, Vec::new())?;
socket.send_to(&encode_rudp_packet(&accept)?, peer)?;
session = Some(accepted);
continue;
}
let Some(session) = session.as_mut() else {
continue;
};
let Ok(received) = session.receive(&packet, 1) else {
continue;
};
if !packet.reliable || received.delivered.is_empty() {
continue;
}
let ack = session.create_ack_for_received(packet.sequence);
let refusal = encode_cultnet_message_to_vec(
&if reply == CatalogReply::AckThenSuccess {
cultnet_rs::CultNetMessage::SnapshotResponseRaw {
message_id: "completion".into(),
documents: Vec::new(),
}
} else {
cultnet_rs::CultNetMessage::Error {
error: "write_not_authorized: the catalog refused the document".into(),
code: Some(cultnet_rs::CultNetErrorCode::WriteNotAuthorized),
details: None,
}
},
CultNetWireContract::CultNetSchemaV0,
)?;
let options = CultNetRudpSendOptions {
reliable: false,
ordered: false,
sequenced: false,
now_ms: 2,
reliable_expire_after_ms: None,
};
let mut refusals = session.send_many("schema", refusal, options, Some(1200))?;
for refusal in &mut refusals {
refusal.ack = 0;
refusal.ack_mask = 0;
}
let send_refusals = |socket: &UdpSocket| -> Result<()> {
for refusal in &refusals {
socket.send_to(&encode_rudp_packet(refusal)?, peer)?;
}
Ok(())
};
if reply == CatalogReply::RefusalThenAck {
send_refusals(&socket)?;
thread::sleep(Duration::from_millis(100));
socket.send_to(&encode_rudp_packet(&ack)?, peer)?;
} else {
socket.send_to(&encode_rudp_packet(&ack)?, peer)?;
thread::sleep(Duration::from_millis(100));
send_refusals(&socket)?;
}
}
Ok(())
});
Ok((target, stop, catalog))
}
fn publish_options(target: SocketAddr) -> CultMeshRudpDocumentPublishOptions {
CultMeshRudpDocumentPublishOptions {
target,
connect_timeout: Duration::from_secs(2),
flush_timeout: Duration::from_secs(3),
poll_interval: Duration::from_millis(2),
resend_delay_ms: 5,
..CultMeshRudpDocumentPublishOptions::default()
}
}
fn refused_note() -> cultnet_rs::CultNetMessage {
cultnet_rs::CultNetMessage::DocumentPutRaw {
message_id: "completion".into(),
document: cultnet_rs::CultNetRawDocumentRecord {
schema_id: "cultmesh.test.raw.v0".into(),
record_key: "tests:completion:a".into(),
stored_at: "2026-11-08T00:00:00Z".into(),
payload_encoding: cultnet_rs::CultNetRawPayloadEncoding::Messagepack,
payload: vec![0xc0],
source_runtime_id: None,
source_agent_id: None,
source_role: None,
tags: None,
},
}
}
/// A catalog's refusal text is quoted only when it is one of the fixed /// A catalog's refusal text is quoted only when it is one of the fixed
/// refusals a CultMesh catalog sends. Any other text, which could carry /// refusals a CultMesh catalog sends. Any other text, which could carry
/// anything, stays out of the publisher's error. /// anything, stays out of the publisher's error.
@ -1900,4 +2044,63 @@ mod tests {
assert_eq!(lease.bytes(), &[1, 2, 3]); assert_eq!(lease.bytes(), &[1, 2, 3]);
Ok(()) Ok(())
} }
// Heimdall's invariant: no client treats a reliable-transport ack as write admission. The catalog here
// acknowledges the put and refuses it, the refusal arriving before or after the ack.
#[test]
fn a_publish_whose_refusal_arrives_before_the_ack_is_refused() -> Result<()> {
let (target, stop, catalog) = acknowledging_refusing_catalog(CatalogReply::RefusalThenAck)?;
let result = publish_cultnet_message_to_rudp_catalog(&refused_note(), publish_options(target));
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
let error = result.expect_err("a refused put is never reported as admitted");
assert!(error.to_string().contains("refused the put"), "{error:#}");
Ok(())
}
#[test]
fn a_publish_whose_ack_arrives_before_the_refusal_is_refused() -> Result<()> {
let (target, stop, catalog) = acknowledging_refusing_catalog(CatalogReply::AckThenRefusal)?;
let result = publish_cultnet_message_to_rudp_catalog(&refused_note(), publish_options(target));
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
let error = result.expect_err("a refused put is never reported as admitted");
assert!(error.to_string().contains("refused the put"), "{error:#}");
Ok(())
}
#[test]
fn a_batch_publish_is_not_complete_on_the_ack_of_refused_puts() -> Result<()> {
for reply in [CatalogReply::AckThenRefusal, CatalogReply::RefusalThenAck] {
let (target, stop, catalog) = acknowledging_refusing_catalog(reply)?;
let result = publish_cultnet_messages_to_rudp_catalog(&[refused_note()], publish_options(target));
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
assert!(result.is_err(), "a refused put was reported as published");
}
Ok(())
}
#[test]
fn a_success_frame_completes_the_publish_without_waiting_out_the_result_window() -> Result<()> {
for batch in [false, true] {
let (target, stop, catalog) = acknowledging_refusing_catalog(CatalogReply::AckThenSuccess)?;
let options = CultMeshRudpDocumentPublishOptions {
result_window: Duration::from_secs(30),
..publish_options(target)
};
let started = Instant::now();
let result = if batch {
publish_cultnet_messages_to_rudp_catalog(&[refused_note()], options)
} else {
publish_cultnet_message_to_rudp_catalog(&refused_note(), options)
};
stop.store(true, std::sync::atomic::Ordering::SeqCst);
catalog.join().expect("catalog thread should not panic")?;
result?;
assert!(started.elapsed() < Duration::from_secs(10), "batch={batch}: waited out the window");
}
Ok(())
}
} }

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,27 @@
# Changelog # Changelog
All notable changes to `cultmesh-ts` are recorded here, following All notable changes to `@gamecult/cultmesh-ts` are recorded here, following
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/). [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased ## Unreleased
### Added
- `publishRudpDocumentOnce` takes `writeReceipts: true`: it sends a hello listing `cultnet.write_admitted.v0` and `cultnet.error.v1` and, against a server that lists both back, resolves only on that write's `write_admitted`, rejects with `CultMeshRudpWriteRefusedError` (now also carrying an `error.v1`) on its refusal and with the new `CultMeshRudpWriteUnconfirmedError` (`reason`: `window_elapsed` after 5000 ms, `session_ended`, or `local_send_failed`) when nothing settles it. Without the option, or against a server that did not advertise, there is no hello and the window is 500 ms; a put nothing settled in it is unconfirmed too, no longer "published" (**behaviour change**: a server that applies a put but answers nothing now yields `CultMeshRudpWriteUnconfirmedError`, as the spec requires). A legacy server's echo of the put's id is not admission: only `write_admitted` is. The flush that sends the put is bounded by the result window, and a send not acknowledged by then is `local_send_failed`. `resultWindowMs` overrides either window. `publishRudpDocumentAndWaitForReceipt` is not changed.
### Breaking ### Breaking
- `publishRudpDocumentOnce` no longer treats a window with no refusal as published: a put nothing settled in its result window (500 ms, or 5000 ms against a receipt-capable server) rejects `CultMeshRudpWriteUnconfirmedError`, and a legacy server's echo of the put's id is not admission. It now resolves `"admitted"` (only on a `write_admitted`) or `"sent"`. **Migration:** a caller whose server cannot answer a write yet (for example Odin, until it is receipt-capable) passes `sendOnly: true` per call and treats `"sent"` as "sent", never as admitted. Receipts stay opt-in (`writeReceipts: true`); neither mode is the default.
- The package is renamed `cultmesh-ts` to `@gamecult/cultmesh-ts` (the repo already scopes `@gamecult/cultcache-ts`), so the unscoped name cannot be claimed by someone else. Import from `@gamecult/cultmesh-ts` and its subpaths; the API is unchanged. Depends on `@gamecult/cultnet-ts`.
- `asSchemaAlias` is removed from `CultMeshDocumentHandle`, `CultMeshCollectionHandle` and their bound forms. Read the handle by the schema you mean. - `asSchemaAlias` is removed from `CultMeshDocumentHandle`, `CultMeshCollectionHandle` and their bound forms. Read the handle by the schema you mean.
- `CultMeshDocumentCatalog` (`document`, `tryDocument`, `latest`, `replace`, `submitPrediction`, `authoritativeWriter`, `predictionWriter`, `watch`) and `CultMeshCollectionCatalog` (`collection`, `tryCollection`, `latest`, `watchChanges`) take `<TDocument = never, TSchema>` and yield `CultMeshCatalogValue<TDocument, TSchema>`: an explicit type argument wins, a CultCache document definition names its own value type, and a bare schema descriptor yields `unknown`. A value type is no longer inferred from a value or an expected result. The `parse` option is removed from these calls, and a lookup by type answers with that type's handle or none, not an alias of a compatible schema. - `CultMeshDocumentCatalog` (`document`, `tryDocument`, `latest`, `replace`, `submitPrediction`, `authoritativeWriter`, `predictionWriter`, `watch`) and `CultMeshCollectionCatalog` (`collection`, `tryCollection`, `latest`, `watchChanges`) take `<TDocument = never, TSchema>` and yield `CultMeshCatalogValue<TDocument, TSchema>`: an explicit type argument wins, a CultCache document definition names its own value type, and a bare schema descriptor yields `unknown`. A value type is no longer inferred from a value or an expected result. The `parse` option is removed from these calls, and a lookup by type answers with that type's handle or none, not an alias of a compatible schema.
- `createRudpDocumentServer` takes `writeAuthorityTimeoutMs` (default `CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_DECIDE_TIMEOUT_MS`, 5000; a value outside 1..2147483647 throws `RangeError`): a write authority whose `decide()` has not settled by then refuses the write like one that throws (`write_not_authorized`, and `onError` hears of it), so a hung authority no longer holds up the session's later frames.
- `createRudpDocumentServer` refuses every peer put and delete unless it is given a `writeAuthority`. A refused write is answered with the typed `write_not_authorized` naming the record key (the bytes pinned in `error-vectors.json`), and `onDocumentPutRaw` is never called; pass `writeAuthority: new CultMeshGrantAllWrites()` to keep the old accept-everything behaviour. The authority is asked before the put is sized or decoded and before any handler runs, with the canonical schema id and the peer's address (the schema id is resolved to its canonical form first, which is the timing residual below); one that throws, rejects or answers anything but `granted: true` refuses. A frame the server cannot read is judged as the write it looks like (a put when it does not decode at all), so an ungranted peer gets `write_not_authorized` for it too; a granted peer gets `onError` and a typed `message_invalid` refusal (`details.field` is `message`). A put carrying a wrong-typed `shardId` or `shardEpoch` is judged with null shard fields and, once granted, refused with `message_invalid` naming that field. A refusal's record key and reason are clipped (64 and 96 UTF-8 bytes) so the refusal is at most 309 bytes; a `maxPayloadBytes` below that cannot carry it, and the peer then hears nothing (the failure goes to `onError`). Residual: ungranted peers can still distinguish registered from unregistered schemas by timing. A peer `document_delete` now reaches the new `onDocumentDeleteRaw` once granted (without it, a text refusal) instead of the unsupported-request error.
- Adding a document or collection to a catalog under a schema id or schema name another type already holds is refused with `SchemaConflictError`. - Adding a document or collection to a catalog under a schema id or schema name another type already holds is refused with `SchemaConflictError`.
### Added ### Added
- `createRudpDocumentServer` ends a session after `CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES` (8) consecutive undecodable frames or consecutive deletes the write authority refuses; fewer are answered and the session is kept. Any decoded frame resets the undecodable run, any decoded non-refused-delete frame resets the delete run. The same cap holds in every runtime.
- `CultMeshCatalogValue<TDocument, TSchema>`, exported. - `CultMeshCatalogValue<TDocument, TSchema>`, exported.
- `documentById` and `tryDocumentById` on `CultMeshDocumentCatalog`, which address one document by its document id when a catalog holds several documents of one type. - `documentById` and `tryDocumentById` on `CultMeshDocumentCatalog`, which address one document by its document id when a catalog holds several documents of one type.

View file

@ -1,6 +1,6 @@
# CultMesh TS # CultMesh TS
`cultmesh-ts` is the TypeScript projection of CultMesh contracts for local `@gamecult/cultmesh-ts` is the TypeScript projection of CultMesh contracts for local
tools and browser-adjacent runtimes. The C# `GameCult.Mesh` package owns the tools and browser-adjacent runtimes. The C# `GameCult.Mesh` package owns the
native CultMesh stream implementation used by Mimir and Fensalir; this package native CultMesh stream implementation used by Mimir and Fensalir; this package
mirrors the typed declaration and negotiation shapes without owning the hot mirrors the typed declaration and negotiation shapes without owning the hot
@ -21,7 +21,7 @@ WASM route. Runtime code can ask for a whole XY rect, then adapt it to the
current wire schema at the edge: current wire schema at the edge:
```ts ```ts
import { CultMesh } from "cultmesh-ts"; import { CultMesh } from "@gamecult/cultmesh-ts";
const viewport = CultMesh.rectFromBounds(-500, -300, 500, 300); const viewport = CultMesh.rectFromBounds(-500, -300, 500, 300);
const request = CultMesh.viewportRequest(viewport, [3, 8]); const request = CultMesh.viewportRequest(viewport, [3, 8]);
@ -215,7 +215,7 @@ const stopFeed = viewportFeed.watch(request, "browser-starfire", render);
``` ```
```ts ```ts
import { CultMesh } from "cultmesh-ts"; import { CultMesh } from "@gamecult/cultmesh-ts";
const verses = CultMesh.createVerseCatalog<{ verseId: string; label: string }>(); const verses = CultMesh.createVerseCatalog<{ verseId: string; label: string }>();
const stopWatching = verses.watch((verse) => { const stopWatching = verses.watch((verse) => {
@ -274,7 +274,7 @@ const noteShards = shards.list({
}); });
``` ```
Schema and shard catalog factories delegate to `cultnet-ts`; the branded Schema and shard catalog factories delegate to `@gamecult/cultnet-ts`; the branded
`CultMesh` entrypoint does not create a second owner for schema discovery or `CultMesh` entrypoint does not create a second owner for schema discovery or
topology truth. topology truth.
@ -290,7 +290,7 @@ command transactions; the injected transport owns CultNet wire details.
import { import {
CultMeshProviderRudpTransport, CultMeshProviderRudpTransport,
CultMeshProviderSession, CultMeshProviderSession,
} from "cultmesh-ts"; } from "@gamecult/cultmesh-ts";
const odinTransport = new CultMeshProviderRudpTransport({ const odinTransport = new CultMeshProviderRudpTransport({
endpoint: "rudp://127.0.0.1:17871", endpoint: "rudp://127.0.0.1:17871",
@ -345,9 +345,11 @@ evidence for the requested provider identity.
## RUDP Helpers ## RUDP Helpers
`createRudpDocumentServer` refuses every peer put and delete unless given a `writeAuthority` (`new CultMeshGrantAllWrites()` accepts all). The authority is asked before a write's payload is sized or decoded and before any handler runs, and a refusal is the typed `write_not_authorized`. Residual: ungranted peers can still distinguish registered from unregistered schemas by timing.
Node runtimes can build the shared CultNet reliable-UDP transport from the Node runtimes can build the shared CultNet reliable-UDP transport from the
branded CultMesh entrypoint while the transport semantics stay owned by branded CultMesh entrypoint while the transport semantics stay owned by
`cultnet-ts`: `@gamecult/cultnet-ts`:
```ts ```ts
const server = await CultMesh.createRudpServer("ts-server", 0x1020_3040); const server = await CultMesh.createRudpServer("ts-server", 0x1020_3040);
@ -472,7 +474,7 @@ The split is deliberate:
The mirrored API shape is `CultMeshStreamCatalog`: The mirrored API shape is `CultMeshStreamCatalog`:
```ts ```ts
import { CultMesh } from "cultmesh-ts"; import { CultMesh } from "@gamecult/cultmesh-ts";
const streams = CultMesh.createStreamCatalog(); const streams = CultMesh.createStreamCatalog();
const stopWatchingStreams = streams.watch((stream) => { const stopWatchingStreams = streams.watch((stream) => {
@ -533,7 +535,7 @@ nonlocal fallback.
## Content Chunks over HTTP(S) ## Content Chunks over HTTP(S)
`cultmesh-ts/content` answers the C# HTTPS connector's request, `GET` or `HEAD` `@gamecult/cultmesh-ts/content` answers the C# HTTPS connector's request, `GET` or `HEAD`
`<mount>?chunkHash=<hex>&recordKey=<key>`. The mount path is the host's; the `<mount>?chunkHash=<hex>&recordKey=<key>`. The mount path is the host's; the
handler reads only the query. Every chunk is hashed against its name before a handler reads only the query. Every chunk is hashed against its name before a
byte is sent, so a corrupt or swapped file answers 500 and never leaves the byte is sent, so a corrupt or swapped file answers 500 and never leaves the
@ -550,7 +552,7 @@ host store may reuse its buffer). `onServerFault` reports every 500 (`hash-misma
```ts ```ts
import { readFileSync } from "node:fs"; import { readFileSync } from "node:fs";
import { createServer } from "node:https"; import { createServer } from "node:https";
import { createContentChunkHandler, createDirectoryChunkStore, toNodeListener } from "cultmesh-ts/content"; import { createContentChunkHandler, createDirectoryChunkStore, toNodeListener } from "@gamecult/cultmesh-ts/content";
const handler = createContentChunkHandler(createDirectoryChunkStore("/srv/content"), { const handler = createContentChunkHandler(createDirectoryChunkStore("/srv/content"), {
onServerFault: fault => console.error("chunk fault", fault.kind, fault.chunkHash), onServerFault: fault => console.error("chunk fault", fault.kind, fault.chunkHash),

View file

@ -1,5 +1,5 @@
{ {
"name": "cultmesh-ts", "name": "@gamecult/cultmesh-ts",
"version": "0.2.0", "version": "0.2.0",
"description": "CultMesh local typed state and mesh catalog primitives for TypeScript runtimes.", "description": "CultMesh local typed state and mesh catalog primitives for TypeScript runtimes.",
"main": "dist/index.js", "main": "dist/index.js",
@ -24,7 +24,8 @@
"build": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json", "build": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json",
"prepack": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json", "prepack": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json",
"typecheck": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json --pretty false", "typecheck": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json --pretty false",
"test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --expose-gc --test dist-test/test/*.test.js" "test": "node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --expose-gc --test dist-test/test/*.test.js",
"test:interop": "npm --prefix ../.. run build --workspace @gamecult/cultcache-ts --workspace @gamecult/cultnet-ts && node ../../node_modules/typescript/bin/tsc -p tsconfig.json && node ../../node_modules/typescript/bin/tsc -p tsconfig.test.json && node --test --test-force-exit dist-test/test/interop/write-receipt-interop.test.js"
}, },
"keywords": [ "keywords": [
"cultmesh", "cultmesh",
@ -48,8 +49,8 @@
"node": ">=20" "node": ">=20"
}, },
"dependencies": { "dependencies": {
"@gamecult/cultcache-ts": "^0.14.0", "@gamecult/cultcache-ts": "^0.15.0",
"cultnet-ts": "^0.3.0", "@gamecult/cultnet-ts": "^0.3.0",
"koffi": "3.3.0" "koffi": "3.3.0"
}, },
"devDependencies": { "devDependencies": {

View file

@ -2,7 +2,7 @@ import { constants } from "node:fs";
import { open } from "node:fs/promises"; import { open } from "node:fs/promises";
import type { IncomingMessage, ServerResponse } from "node:http"; import type { IncomingMessage, ServerResponse } from "node:http";
import { join } from "node:path"; import { join } from "node:path";
import { DEFAULT_CHUNK_SIZE_BYTES, EMPTY_SHA256, chunkRecordKey, isNullOrWhiteSpaceCSharp, parseSha256Hex, sha256Hex } from "cultnet-ts/content"; import { DEFAULT_CHUNK_SIZE_BYTES, EMPTY_SHA256, chunkRecordKey, isNullOrWhiteSpaceCSharp, parseSha256Hex, sha256Hex } from "@gamecult/cultnet-ts/content";
/** What the provider reads of a request. The path and the headers are never read: the route is the query alone. */ /** What the provider reads of a request. The path and the headers are never read: the route is the query alone. */
export interface ContentChunkRequest { method: string; url: string; } export interface ContentChunkRequest { method: string; url: string; }

View file

@ -1,5 +1,5 @@
import { createSocket, type Socket } from "node:dgram"; import { createSocket, type Socket } from "node:dgram";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
CultCache, CultCache,
@ -20,6 +20,13 @@ import {
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportConnection,
rudpClientBindHost, rudpClientBindHost,
CultNetSchemaCatalog, CultNetSchemaCatalog,
CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS,
WriteTracker,
helloAdvertisesWriteReceipts,
resultWindowMs,
cultNetMessageInvalidError,
cultNetTextError,
cultNetWriteNotAuthorizedError,
CultNetShardCatalog, CultNetShardCatalog,
cultNetBuiltinSchemaRegistry, cultNetBuiltinSchemaRegistry,
decodeRudpPacket, decodeRudpPacket,
@ -31,6 +38,7 @@ import {
sendRudpDatagram, sendRudpDatagram,
type CultNetErrorMessage, type CultNetErrorMessage,
type CultNetDocumentBinding, type CultNetDocumentBinding,
type CultNetDocumentDeleteMessage,
type CultNetMessage, type CultNetMessage,
type CultNetOperationRequestMessage, type CultNetOperationRequestMessage,
type CultNetOperationResponseMessage, type CultNetOperationResponseMessage,
@ -40,7 +48,9 @@ import {
type CultNetSchemaCatalogOptions, type CultNetSchemaCatalogOptions,
type CultNetSnapshotResponseRawMessage, type CultNetSnapshotResponseRawMessage,
type CultNetWireContract, type CultNetWireContract,
} from "cultnet-ts"; type WriteSettlement,
type WriteUnconfirmedReason,
} from "@gamecult/cultnet-ts";
import { import {
CultMeshQuicRealtimeConnector, CultMeshQuicRealtimeConnector,
@ -3991,6 +4001,63 @@ export type CultMeshRudpDocumentPut = {
| { readonly decoded: false; readonly payload: DocumentPayload } | { readonly decoded: false; readonly payload: DocumentPayload }
); );
/** The peer a write arrived from: the datagram's source, nothing the peer claimed. */
export interface CultMeshRemoteWritePeer {
address: string;
family: string;
port: number;
}
export type CultMeshRemoteWriteOperation = "put" | "delete";
/**
* One peer write as the authority sees it. `schemaId` is the canonical id the registry resolved for the write (the id
* as sent when no binding takes it), never an alias the peer used when a binding resolves it. `shardId` and
* `shardEpoch` are as a put carried them, `null` when it sent none (always `null` for a delete, which has none); a
* put carrying either with the wrong type is refused before any authority is asked.
*/
export interface CultMeshRemoteWriteRequest {
peer: CultMeshRemoteWritePeer;
operation: CultMeshRemoteWriteOperation;
schemaId: string;
recordKey: string;
shardId: string | null;
shardEpoch: number | null;
}
export interface CultMeshRemoteWriteDecision {
granted: boolean;
/** Told to the refused peer after `write_not_authorized:`; keep it free of anything secret. */
reason?: string;
}
/**
* The one question a document server asks before it applies a peer's put or delete (C# `ICultNetRemoteWriteAuthority`).
* A server with no authority refuses every peer write; one whose authority throws, rejects or answers anything but
* `granted: true` refuses too.
*/
export interface CultMeshRemoteWriteAuthority {
decide(request: CultMeshRemoteWriteRequest): CultMeshRemoteWriteDecision | Promise<CultMeshRemoteWriteDecision>;
}
/**
* Grants every peer write. For a host that has already authenticated its peers, or a test rig: it is an explicit
* choice because serving without an authority refuses writes.
*/
export class CultMeshGrantAllWrites implements CultMeshRemoteWriteAuthority {
decide(): CultMeshRemoteWriteDecision {
return { granted: true };
}
}
/** A delete as `onDocumentDeleteRaw` receives it, after the authority granted it. */
export interface CultMeshRudpDocumentDelete {
messageId: string;
schemaId: string;
recordKey: string;
remote: CultMeshRemoteWritePeer;
}
export interface CultMeshRudpDocumentReceipt<TDefinition extends AnyCultCacheDocumentDefinition = AnyCultCacheDocumentDefinition> { export interface CultMeshRudpDocumentReceipt<TDefinition extends AnyCultCacheDocumentDefinition = AnyCultCacheDocumentDefinition> {
binding: CultNetDocumentBinding<TDefinition>; binding: CultNetDocumentBinding<TDefinition>;
recordKey: string; recordKey: string;
@ -4030,10 +4097,24 @@ export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOpt
documents: CultNetDocumentRegistry; documents: CultNetDocumentRegistry;
getCache?: () => Promise<CultCache> | CultCache; getCache?: () => Promise<CultCache> | CultCache;
onError?: (error: Error) => void; onError?: (error: Error) => void;
/**
* Who may put and delete. Without it every peer put and delete is refused with a typed `write_not_authorized`
* (and `onDocumentPutRaw` is never called); pass `new CultMeshGrantAllWrites()` to accept them all. The authority is
* asked before the document is sized, resolved or decoded.
*/
writeAuthority?: CultMeshRemoteWriteAuthority;
/**
* How long the write authority has to answer before the write is refused (default
* `CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_DECIDE_TIMEOUT_MS`). A `decide()` that never settles is a refusal like any
* other, so it cannot hold up the frames that follow it on the session.
*/
writeAuthorityTimeoutMs?: number;
onDocumentPutRaw?: (document: CultMeshRudpDocumentPut) => onDocumentPutRaw?: (document: CultMeshRudpDocumentPut) =>
| CultMeshRudpDocumentReceipt | CultMeshRudpDocumentReceipt
| void | void
| Promise<CultMeshRudpDocumentReceipt | void>; | Promise<CultMeshRudpDocumentReceipt | void>;
/** Applies a delete the authority granted. Without it a granted delete is answered with a text refusal. */
onDocumentDeleteRaw?: (request: CultMeshRudpDocumentDelete) => void | Promise<void>;
onOperationRequest?: ( onOperationRequest?: (
request: CultNetOperationRequestMessage, request: CultNetOperationRequestMessage,
session: CultMeshRudpServerSession, session: CultMeshRudpServerSession,
@ -4043,6 +4124,19 @@ export interface CultMeshRudpDocumentServerOptions extends CultMeshRudpSocketOpt
sessionTimeoutMs?: number; sessionTimeoutMs?: number;
} }
/** A write authority that has not answered in this long has refused the write. */
export const CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_DECIDE_TIMEOUT_MS = 5_000;
/**
* How many consecutive refused frames of one kind a `createRudpDocumentServer` session may send before it is
* ended: undecodable frames (reset by any frame that decodes) and deletes the write authority refuses (reset by any
* decoded frame that is not a refused delete). Fewer are answered with a typed refusal and the session is kept; the
* frame that reaches this number is answered too, then the session ends. The same number is the cap in every runtime.
*/
export const CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES = 8;
/** How long a session whose capped frame was answered waits for the peer to acknowledge the answers before it ends anyway. */
const CULTMESH_RUDP_DOCUMENT_SERVER_CAPPED_ANSWER_GRACE_MS = 2000;
/** Replies larger than one fragment are split into fragments of at most this many bytes. */ /** Replies larger than one fragment are split into fragments of at most this many bytes. */
export const CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES = 1200; export const CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES = 1200;
@ -4095,7 +4189,64 @@ export interface CultMeshRudpDocumentServer {
close(): void; close(): void;
} }
/**
* A write the peer refused: the typed `cultnet.error.v0` it answered with (`write_not_authorized`,
* `message_invalid`, ...), whichever of the transport ack and the result frame came first.
*/
export class CultMeshRudpWriteRefusedError extends Error {
readonly code: string | undefined;
readonly response: Extract<CultNetMessage, { schemaVersion: "cultnet.error.v0" | "cultnet.error.v1" }>;
constructor(response: Extract<CultNetMessage, { schemaVersion: "cultnet.error.v0" | "cultnet.error.v1" }>) {
super(response.error);
this.name = "CultMeshRudpWriteRefusedError";
this.code = response.code ?? undefined;
this.response = response;
}
}
/**
* Nothing settled the write (write-receipt.md, "unconfirmed"): the result window ran out with no answer, the
* session ended first, or the client's own send failed. Not success and not refusal; a caller that needs admission treats it as not admitted.
*/
export class CultMeshRudpWriteUnconfirmedError extends Error {
readonly reason: WriteUnconfirmedReason;
readonly messageId: string;
constructor(messageId: string, reason: WriteUnconfirmedReason) {
super(`Write ${messageId} was not confirmed: ${reason}.`);
this.name = "CultMeshRudpWriteUnconfirmedError";
this.reason = reason;
this.messageId = messageId;
}
}
export interface CultMeshRudpDocumentPublishOptions extends CultMeshRudpPeerOptions { export interface CultMeshRudpDocumentPublishOptions extends CultMeshRudpPeerOptions {
/**
* How long, counted from the send, the put may wait for its result frame. A reliable-transport ack is not
* admission; the outcome is the peer's result frame. Default: 5000 ms against a server whose hello lists the
* write-receipt frames, 500 ms otherwise. A put nothing settled within the window is unconfirmed, never
* published, whatever the server advertised: only a `write_admitted` is admission. The send itself is also
* bounded by the window (`flushTimeoutMs` is the upper bound); a send not acknowledged by then is
* unconfirmed as `local_send_failed`.
*/
resultWindowMs?: number;
/**
* Declare the write-receipt capability: send a hello listing `cultnet.write_admitted.v0` and `cultnet.error.v1`
* before the put. A server that lists both back is receipt-capable: the put then resolves only on its
* `write_admitted`, rejects with `CultMeshRudpWriteRefusedError` on its `error.v1`, and rejects with
* `CultMeshRudpWriteUnconfirmedError` when nothing settles it. Unset, no hello is sent and the server answers
* as it always did.
*/
writeReceipts?: boolean;
/** With `writeReceipts`, how long to wait for the server's hello before treating it as legacy. Default 500 ms. */
helloWaitMs?: number;
/**
* Send the put and report only that it was sent: no hello, no wait for a result frame. Resolves `"sent"` once the
* transport has acknowledged the put (`flushTimeoutMs`), rejects `CultMeshRudpWriteUnconfirmedError`
* (`local_send_failed`) if it cannot be sent, and never resolves `"admitted"`: whether the server applied or
* refused it is unknown. For callers whose server cannot answer a write yet. Opt-in per call; not combinable with
* `writeReceipts`.
*/
sendOnly?: boolean;
messageId?: string; messageId?: string;
sourceRuntimeId?: string; sourceRuntimeId?: string;
sourceAgentId?: string; sourceAgentId?: string;
@ -5459,6 +5610,11 @@ export class CultMesh {
closed: boolean; closed: boolean;
/** A packet it owed could never be sent, so the session ended. */ /** A packet it owed could never be sent, so the session ended. */
unsendable: boolean; unsendable: boolean;
/** Consecutive undecodable frames, and consecutive deletes the authority refused. */
unreadableInARow: number;
refusedDeletesInARow: number;
/** Set once the peer's capped frame is answered: the session ends when the answers are acknowledged, or at this time. */
endingDeadlineMs?: number;
work: Promise<void>; work: Promise<void>;
}; };
const sessions = new Map<string, SessionRecord>(); const sessions = new Map<string, SessionRecord>();
@ -5466,6 +5622,11 @@ export class CultMesh {
let sendFailures = 0; let sendFailures = 0;
const resendPollMs = Math.max(10, options.resendPollMs ?? 25); const resendPollMs = Math.max(10, options.resendPollMs ?? 25);
const sessionTimeoutMs = Math.max(1_000, options.sessionTimeoutMs ?? 30_000); const sessionTimeoutMs = Math.max(1_000, options.sessionTimeoutMs ?? 30_000);
const decideTimeoutMs = options.writeAuthorityTimeoutMs ?? CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_DECIDE_TIMEOUT_MS;
// A timer past 2^31-1 ms (or NaN) fires after 1 ms in Node, which would refuse every write that is not instant.
if (!(decideTimeoutMs > 0 && decideTimeoutMs <= 0x7fffffff)) {
throw new RangeError("CultMesh RUDP document server writeAuthorityTimeoutMs must be greater than zero and at most 2147483647.");
}
const wireContract = options.wireContract ?? "cultnet.schema.v0"; const wireContract = options.wireContract ?? "cultnet.schema.v0";
const maxFragmentBytes = options.maxFragmentBytes ?? CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES; const maxFragmentBytes = options.maxFragmentBytes ?? CULTMESH_RUDP_DOCUMENT_SERVER_DEFAULT_MAX_FRAGMENT_BYTES;
if (!(maxFragmentBytes > 0)) { if (!(maxFragmentBytes > 0)) {
@ -5508,6 +5669,8 @@ export class CultMesh {
connectPayload, connectPayload,
closed: false, closed: false,
unsendable: false, unsendable: false,
unreadableInARow: 0,
refusedDeletesInARow: 0,
session: new CultNetRudpSession({ session: new CultNetRudpSession({
connectionId, connectionId,
initialSequence: options.initialSequence, initialSequence: options.initialSequence,
@ -5572,15 +5735,36 @@ export class CultMesh {
record: SessionRecord, record: SessionRecord,
payload: Uint8Array, payload: Uint8Array,
): Promise<void> { ): Promise<void> {
if (record.closed) return; // Nothing after the capped frame is served while its answer is delivered.
const message = parseCultNetMessage(decodeWireValue(payload), wireContract); if (record.closed || record.endingDeadlineMs !== undefined) return;
let decoded: unknown;
let message: CultNetMessage;
try {
decoded = decodeWireValue(payload);
message = parseCultNetMessage(decoded, wireContract);
} catch (error) {
// A frame the server cannot read is judged as the write it looks like (a put when it does not even decode), so
// an ungranted peer hears the same refusal for it as for any other write, not a parse error.
const write = readableWrite(decoded);
record.unreadableInARow += 1;
if (decoded !== undefined && !write) {
// It decodes but is no message the parser takes (an unknown schemaVersion, a non-map) and is no write the
// authority could judge: answered and counted like any other unreadable frame.
reportError(error);
sendSchemaMessage(record, cultNetMessageInvalidError("message", "CultMesh RUDP document server could not read the message."));
} else if (!await writeRefused(record, write?.operation ?? "put", write?.schemaId ?? "", write?.recordKey ?? "", null, null)) {
reportError(error);
sendSchemaMessage(record, cultNetMessageInvalidError("message", "CultMesh RUDP document server could not read the write."));
}
if (record.unreadableInARow >= CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES) endCappedSession(record);
return;
}
record.unreadableInARow = 0;
if (message.schemaVersion !== "cultnet.document_delete.v0") record.refusedDeletesInARow = 0;
switch (message.schemaVersion) { switch (message.schemaVersion) {
case "cultnet.snapshot_request.v0": { case "cultnet.snapshot_request.v0": {
if (!options.getCache) { if (!options.getCache) {
sendSchemaMessage(record, { sendSchemaMessage(record, cultNetTextError("CultMesh RUDP document server has no cache for snapshot requests."));
schemaVersion: "cultnet.error.v0",
error: "CultMesh RUDP document server has no cache for snapshot requests.",
});
return; return;
} }
let reply: CultNetMessage; let reply: CultNetMessage;
@ -5609,11 +5793,32 @@ export class CultMesh {
sendSchemaMessage(record, cultNetBuiltinSchemaRegistry.createCatalogResponse(message)); sendSchemaMessage(record, cultNetBuiltinSchemaRegistry.createCatalogResponse(message));
return; return;
case "cultnet.document_put_raw.v0": case "cultnet.document_put_raw.v0":
{
// The parser passes shard fields of any type through a put. The authority is asked first, with the shard
// fields it can trust (null when wrong-typed), so an ungranted peer hears only the refusal; a granted peer
// whose shard fields are wrong-typed is then refused as malformed.
const { shardId, shardEpoch } = message as { shardId?: unknown; shardEpoch?: unknown };
const malformedShard =
(shardId !== undefined && typeof shardId !== "string") ||
(shardEpoch !== undefined && !Number.isSafeInteger(shardEpoch));
if (await writeRefused(
record, "put", message.document.schemaId, message.document.recordKey,
malformedShard ? null : (shardId as string | undefined) ?? null,
malformedShard ? null : (shardEpoch as number | undefined) ?? null,
)) return;
if (malformedShard) {
sendSchemaMessage(record, cultNetMessageInvalidError(
typeof shardId !== "undefined" && typeof shardId !== "string" ? "shardId" : "shardEpoch",
"Raw put messages must carry a string shardId and an integer shardEpoch.",
));
return;
}
}
if (options.onDocumentPutRaw) { if (options.onDocumentPutRaw) {
const unservable = unservablePut(message); const unservable = unservablePut(message);
if (unservable) { if (unservable) {
reportError(unservable); reportError(unservable);
sendSchemaMessage(record, { schemaVersion: "cultnet.error.v0", error: unservable.message }); sendSchemaMessage(record, cultNetTextError(unservable.message));
return; return;
} }
const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote, options.documents)); const receipt = await options.onDocumentPutRaw(normalizeRudpDocumentPut(message, record.remote, options.documents));
@ -5623,32 +5828,119 @@ export class CultMesh {
} catch (error) { } catch (error) {
// The put is stored: the peer must hear that its receipt is not coming. // The put is stored: the peer must hear that its receipt is not coming.
reportError(error); reportError(error);
sendSchemaMessage(record, { sendSchemaMessage(record, cultNetTextError(`CultMesh RUDP document server stored a put but could not send its receipt.`));
schemaVersion: "cultnet.error.v0",
error: `CultMesh RUDP document server stored a put but could not send its receipt.`,
});
} }
} }
} }
return; return;
case "cultnet.document_delete.v0": {
if (await writeRefused(record, "delete", message.schemaId, message.recordKey, null, null)) {
record.refusedDeletesInARow += 1;
if (record.refusedDeletesInARow >= CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES) endCappedSession(record);
return;
}
record.refusedDeletesInARow = 0;
if (!options.onDocumentDeleteRaw) {
sendSchemaMessage(record, cultNetTextError("CultMesh RUDP document server has no delete handler."));
return;
}
await options.onDocumentDeleteRaw({
messageId: message.messageId,
schemaId: message.schemaId,
recordKey: message.recordKey,
remote: { ...record.remote },
});
return;
}
case "cultnet.operation_request.v0": case "cultnet.operation_request.v0":
if (!options.onOperationRequest) { if (!options.onOperationRequest) {
sendSchemaMessage(record, { sendSchemaMessage(record, cultNetTextError("CultMesh RUDP document server has no operation handler."));
schemaVersion: "cultnet.error.v0",
error: "CultMesh RUDP document server has no operation handler.",
});
return; return;
} }
sendSchemaMessage(record, await options.onOperationRequest(message, publicSession(record))); sendSchemaMessage(record, await options.onOperationRequest(message, publicSession(record)));
return; return;
default: default:
sendSchemaMessage(record, { sendSchemaMessage(record, cultNetTextError(`Unsupported CultMesh RUDP document request ${message.schemaVersion}.`));
schemaVersion: "cultnet.error.v0",
error: `Unsupported CultMesh RUDP document request ${message.schemaVersion}.`,
});
} }
} }
function clipUtf8(text: string, maxBytes: number): string {
const bytes = Buffer.from(text, "utf8");
return bytes.byteLength <= maxBytes ? text : new TextDecoder().decode(bytes.subarray(0, maxBytes)).replace(/\uFFFD+$/, "");
}
/** The put or delete a decoded frame claims to be, with the ids it carries when they are strings. */
function readableWrite(value: unknown): { operation: CultMeshRemoteWriteOperation; schemaId: string; recordKey: string } | undefined {
if (typeof value !== "object" || value === null) return undefined;
const frame = value as { schemaVersion?: unknown; schemaId?: unknown; recordKey?: unknown; document?: unknown };
const str = (v: unknown): string => (typeof v === "string" ? v : "");
if (frame.schemaVersion === "cultnet.document_delete.v0") {
return { operation: "delete", schemaId: str(frame.schemaId), recordKey: str(frame.recordKey) };
}
if (frame.schemaVersion === "cultnet.document_put_raw.v0") {
const document = (typeof frame.document === "object" && frame.document !== null ? frame.document : {}) as { schemaId?: unknown; recordKey?: unknown };
return { operation: "put", schemaId: str(document.schemaId), recordKey: str(document.recordKey) };
}
return undefined;
}
/**
* Asks the write authority about a put or delete, before anything of the write is sized, resolved or decoded, and
* answers a refusal with the typed `write_not_authorized` naming the record. True when the write is refused.
* No authority refuses; an authority that throws, rejects or does not say `granted: true` refuses too (fail
* closed), and a failure is reported without quoting it.
*/
async function writeRefused(
record: SessionRecord,
operation: CultMeshRemoteWriteOperation,
schemaId: string,
recordKey: string,
shardId: string | null,
shardEpoch: number | null,
): Promise<boolean> {
let reason: string | undefined;
const authority = options.writeAuthority;
if (!authority) {
reason = "no remote write authority is configured";
} else {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
const timedOut = Symbol("decide timeout");
const decision = await Promise.race([
Promise.resolve().then(() => authority.decide({
peer: { ...record.remote },
operation,
schemaId: options.documents.canonicalSchemaId(schemaId) ?? schemaId,
recordKey,
shardId,
shardEpoch,
})),
new Promise<typeof timedOut>((resolve) => { timer = setTimeout(() => resolve(timedOut), decideTimeoutMs); }),
]);
if (decision === timedOut) {
reportError(new Error(`CultMesh remote write authority did not answer within ${decideTimeoutMs} ms; the write was refused.`));
reason = "the write authority timed out";
} else {
if (decision?.granted === true) return false;
reason = typeof decision?.reason === "string" ? decision.reason : undefined;
}
} catch (error) {
reportError(new Error(`CultMesh remote write authority failed (${error instanceof Error ? error.name : typeof error}); the write was refused.`));
reason = "the write authority failed";
} finally {
clearTimeout(timer);
}
}
try {
// The key is the peer's and the reason the authority's: both are clipped so the refusal fits `maxPayloadBytes`
// whatever they are (the peer is told the clipped key; a `maxPayloadBytes` under about 512 can still not carry it).
sendSchemaMessage(record, cultNetWriteNotAuthorizedError(clipUtf8(recordKey, 64), reason === undefined ? undefined : clipUtf8(reason, 96)));
} catch (error) {
reportError(error);
}
return true;
}
function publicSession(record: SessionRecord): CultMeshRudpServerSession { function publicSession(record: SessionRecord): CultMeshRudpServerSession {
return { return {
sessionId: record.sessionId, sessionId: record.sessionId,
@ -5698,6 +5990,17 @@ export class CultMesh {
sendRudpDatagram(socket, goodbye, record.remote.port, record.remote.address, () => {}); sendRudpDatagram(socket, goodbye, record.remote.port, record.remote.address, () => {});
} }
/**
* A session that reached the cap of consecutive refused frames: its last refusal went out like any reply
* (reliable, so a lost datagram is resent), and the session ends once the peer has acknowledged every reply or
* the grace runs out. The resend timer ends it.
*/
function endCappedSession(record: SessionRecord): void {
const key = `${record.remote.address}:${record.remote.port}`;
if (sessions.get(key) !== record) return;
record.endingDeadlineMs ??= Date.now() + CULTMESH_RUDP_DOCUMENT_SERVER_CAPPED_ANSWER_GRACE_MS;
}
/** The session owes its peer a packet that can never be sent as built. */ /** The session owes its peer a packet that can never be sent as built. */
function endUnsendableSession(record: SessionRecord, error: Error): void { function endUnsendableSession(record: SessionRecord, error: Error): void {
if (record.unsendable) return; if (record.unsendable) return;
@ -5741,7 +6044,7 @@ export class CultMesh {
*/ */
function refuse(record: SessionRecord, text: string): void { function refuse(record: SessionRecord, text: string): void {
if (record.closed) return; if (record.closed) return;
const payload = encodeSchemaMessage({ schemaVersion: "cultnet.error.v0", error: text }); const payload = encodeSchemaMessage(cultNetTextError(text));
for (const packet of record.session.sendMany("schema", payload, { for (const packet of record.session.sendMany("schema", payload, {
reliable: false, reliable: false,
ordered: false, ordered: false,
@ -5831,6 +6134,11 @@ export class CultMesh {
closeSession(record); closeSession(record);
continue; continue;
} }
if (record.endingDeadlineMs !== undefined
&& (record.session.outstandingReliablePacketCount === 0 || nowMs >= record.endingDeadlineMs)) {
endRefusedSession(key, record);
continue;
}
for (const packet of record.session.dueResends(nowMs)) { for (const packet of record.session.dueResends(nowMs)) {
sendPacket(record, packet); sendPacket(record, packet);
} }
@ -5908,15 +6216,16 @@ export class CultMesh {
recordKey: string, recordKey: string,
value: CultCacheDocumentValue<TDefinition>, value: CultCacheDocumentValue<TDefinition>,
options: CultMeshRudpDocumentPublishOptions = {}, options: CultMeshRudpDocumentPublishOptions = {},
): Promise<void> { ): Promise<"admitted" | "sent"> {
requireNonEmpty(runtimeId, "runtimeId"); requireNonEmpty(runtimeId, "runtimeId");
requireNonEmpty(recordKey, "recordKey"); requireNonEmpty(recordKey, "recordKey");
if (options.sendOnly && options.writeReceipts) throw new TypeError("sendOnly and writeReceipts cannot be combined.");
const registry = new CultNetDocumentRegistry([binding]); const registry = new CultNetDocumentRegistry([binding]);
const peer = await CultMesh.createRudpPeer(runtimeId, connectionId, endpoint, options); const messageId = options.messageId ?? `${runtimeId}:${binding.definition.type}:${recordKey}`;
try { // Built before any connection and outside every try: a put that cannot be built is the caller's error, with its cause.
peer.send(registry.createRawDocumentPutMessage( const put = registry.createRawDocumentPutMessage(
binding, binding,
options.messageId ?? `${runtimeId}:${binding.definition.type}:${recordKey}`, messageId,
recordKey, recordKey,
value, value,
{ {
@ -5925,8 +6234,70 @@ export class CultMesh {
sourceRole: options.sourceRole, sourceRole: options.sourceRole,
tags: options.tags, tags: options.tags,
}, },
)); );
const peer = await CultMesh.createRudpPeer(runtimeId, connectionId, endpoint, options);
try {
if (options.sendOnly) {
try {
peer.send(put);
await peer.flush(options.flushTimeoutMs ?? 30_000); await peer.flush(options.flushTimeoutMs ?? 30_000);
} catch {
throw new CultMeshRudpWriteUnconfirmedError(messageId, "local_send_failed");
}
return "sent";
}
// A transport ack is not admission: the put completes on its result frame, and the WriteTracker alone decides
// how it settles (write-receipt.md, "Client rules"). This function only maps the settlement to resolve/throw.
let receiptCapable = false;
let tracker: WriteTracker | undefined;
let settlement: WriteSettlement | undefined;
let wake: (() => void) | undefined;
let serverHello: (() => void) | undefined;
peer.on("message", (message: CultNetMessage) => {
if (message.schemaVersion === "cultnet.hello.v0") {
receiptCapable = helloAdvertisesWriteReceipts(message);
serverHello?.();
} else {
tracker?.frame(message, Date.now());
}
});
peer.on("close", () => tracker?.sessionEnd(Date.now()));
if (options.writeReceipts) {
const answered = new Promise<void>((resolve) => { serverHello = resolve; });
peer.sendHello({
schemaVersion: "cultnet.hello.v0", runtimeId, runtimeKind: "cultmesh-ts",
supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS],
});
let helloTimer: NodeJS.Timeout | undefined;
await Promise.race([answered, new Promise<void>((resolve) => { helloTimer = setTimeout(resolve, options.helloWaitMs ?? 500); })]);
clearTimeout(helloTimer);
}
const writeTracker = new WriteTracker({
windowMs: options.resultWindowMs ?? resultWindowMs(receiptCapable),
onSettle: (_id, result) => { settlement = result; wake?.(); },
});
tracker = writeTracker;
writeTracker.send(messageId, Date.now());
try {
peer.send(put);
// The flush may not outlast the result window: a send nobody acknowledged by then is a local send failure.
const windowRemaining = writeTracker.nextDeadlineMs(Date.now()) ?? 0;
await peer.flush(Math.min(options.flushTimeoutMs ?? 30_000, Math.max(windowRemaining, 1)));
} catch {
// Our own send failed or was never acknowledged: the put may or may not have left. Never a refusal.
writeTracker.sendFailed(messageId, Date.now());
}
while (!settlement) {
const remaining = writeTracker.nextDeadlineMs(Date.now()) ?? 0;
await new Promise<void>((resolve) => {
const timer = setTimeout(resolve, remaining);
wake = () => { clearTimeout(timer); resolve(); };
});
writeTracker.tick(Date.now());
}
if (settlement.outcome === "refused") throw new CultMeshRudpWriteRefusedError(settlement.response);
if (settlement.outcome === "unconfirmed") throw new CultMeshRudpWriteUnconfirmedError(messageId, settlement.reason);
return "admitted";
} finally { } finally {
peer.close(); peer.close();
} }
@ -5945,6 +6316,7 @@ export class CultMesh {
const receipt = new Promise<CultCacheDocumentValue<TReceiptDefinition>>((resolve, reject) => { const receipt = new Promise<CultCacheDocumentValue<TReceiptDefinition>>((resolve, reject) => {
const timeout = setTimeout(() => { cleanup(); reject(new Error(`Timed out waiting for RUDP application receipt for ${recordKey}.`)); }, options.receiptTimeoutMs ?? 5_000); const timeout = setTimeout(() => { cleanup(); reject(new Error(`Timed out waiting for RUDP application receipt for ${recordKey}.`)); }, options.receiptTimeoutMs ?? 5_000);
const onMessage = (message: CultNetMessage): void => { const onMessage = (message: CultNetMessage): void => {
if (message.schemaVersion === "cultnet.error.v0") { cleanup(); reject(new CultMeshRudpWriteRefusedError(message)); return; }
if (message.schemaVersion !== "cultnet.document_put_raw.v0" || message.messageId !== messageId || message.document.schemaId !== receiptBinding.definition.schemaId) return; if (message.schemaVersion !== "cultnet.document_put_raw.v0" || message.messageId !== messageId || message.document.schemaId !== receiptBinding.definition.schemaId) return;
try { try {
const decoded = decodeDocumentPayload(receiptBinding.definition, message.document.payload); const decoded = decodeDocumentPayload(receiptBinding.definition, message.document.payload);

View file

@ -1,7 +1,7 @@
import { randomUUID } from "node:crypto"; import { randomUUID } from "node:crypto";
import { createSocket, type Socket } from "node:dgram"; import { createSocket, type Socket } from "node:dgram";
import { documentPayloadFromBytes } from "@gamecult/cultcache-ts"; import { documentPayloadFromBytes } from "@gamecult/cultcache-ts";
import { encodeWireValue } from "cultnet-ts/wire"; import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
CultNetPeer, CultNetPeer,
CultNetRudpSocketTransportConnection, CultNetRudpSocketTransportConnection,
@ -9,7 +9,7 @@ import {
type CultNetOperationRequestMessage, type CultNetOperationRequestMessage,
type CultNetOperationResponseMessage, type CultNetOperationResponseMessage,
type CultNetRawDocumentRecord, type CultNetRawDocumentRecord,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import type { import type {
CultMeshProviderCommand, CultMeshProviderCommand,

View file

@ -1,11 +1,11 @@
import { encodeDocumentPayload } from "@gamecult/cultcache-ts"; import { encodeDocumentPayload } from "@gamecult/cultcache-ts";
import { encodeWireValue } from "cultnet-ts/wire"; import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import type { import type {
CultNetDocumentPutRawMessage, CultNetDocumentPutRawMessage,
CultNetOperationRequestMessage, CultNetOperationRequestMessage,
CultNetOperationResponseMessage, CultNetOperationResponseMessage,
CultNetRawDocumentRecord, CultNetRawDocumentRecord,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import type { CultMeshRudpServerSession } from "./index"; import type { CultMeshRudpServerSession } from "./index";
import { import {

View file

@ -1,6 +1,6 @@
import { decodeDocumentPayload, defineDocumentType } from "@gamecult/cultcache-ts"; import { decodeDocumentPayload, defineDocumentType } from "@gamecult/cultcache-ts";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import type { CultNetRawDocumentRecord } from "cultnet-ts"; import type { CultNetRawDocumentRecord } from "@gamecult/cultnet-ts";
export const CULTMESH_PROVIDER_SESSION_SERVICE_ID = "gamecult.mesh.provider_session"; export const CULTMESH_PROVIDER_SESSION_SERVICE_ID = "gamecult.mesh.provider_session";

View file

@ -21,8 +21,8 @@ import {
trimCSharp, trimCSharp,
verifyAuthorityRoute, verifyAuthorityRoute,
type CultMeshAuthorityTrustPolicy, type CultMeshAuthorityTrustPolicy,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import type { CultMeshVerseDescriptorMessage } from "cultnet-ts/contracts"; import type { CultMeshVerseDescriptorMessage } from "@gamecult/cultnet-ts/contracts";
import { import {
decodeRealtimeFrame, decodeRealtimeFrame,

View file

@ -16,7 +16,7 @@
// agree with itself. // agree with itself.
import { documentPayloadBytes, documentPayloadFromBytes, type DocumentPayload } from "@gamecult/cultcache-ts"; import { documentPayloadBytes, documentPayloadFromBytes, type DocumentPayload } from "@gamecult/cultcache-ts";
import { isNullOrWhiteSpaceCSharp } from "cultnet-ts"; import { isNullOrWhiteSpaceCSharp } from "@gamecult/cultnet-ts";
/** `CultMeshRealtimeWireProtocol.ApplicationProtocolName`: the QUIC ALPN. */ /** `CultMeshRealtimeWireProtocol.ApplicationProtocolName`: the QUIC ALPN. */
export const CULTMESH_REALTIME_ALPN = "cultmesh-state-v1"; export const CULTMESH_REALTIME_ALPN = "cultmesh-state-v1";
@ -70,7 +70,7 @@ const INT64_MAX = 2n ** 63n - 1n;
* `CultMeshRealtimeFrame.Validate`. The C# reading of "non-empty" is * `CultMeshRealtimeFrame.Validate`. The C# reading of "non-empty" is
* `string.IsNullOrWhiteSpace`, whose whitespace set is not * `string.IsNullOrWhiteSpace`, whose whitespace set is not
* `String.prototype.trim`'s, so this borrows the one TypeScript implementation * `String.prototype.trim`'s, so this borrows the one TypeScript implementation
* of that set from `cultnet-ts` rather than keeping a second reading here. * of that set from `@gamecult/cultnet-ts` rather than keeping a second reading here.
* *
* The range check has no C# counterpart because `long` gives it for free; a * The range check has no C# counterpart because `long` gives it for free; a
* `bigint` does not, and a `DataView` would otherwise throw a bare `RangeError` * `bigint` does not, and a `DataView` would otherwise throw a bare `RangeError`

View file

@ -0,0 +1,120 @@
// Heimdall's invariant: no client may treat a reliable-transport ack as write admission. A put completes only
// on its result frame (write_not_authorized, or the success reply). Each test serves a client a peer that
// acknowledges the put and refuses it, the ack arriving before the refusal and after it.
import assert from "node:assert/strict";
import { createSocket, type Socket } from "node:dgram";
import test from "node:test";
import { z } from "zod";
import { defineDocumentType } from "@gamecult/cultcache-ts";
import {
CultNetDocumentRegistry,
CultNetRudpSession,
cultNetWriteNotAuthorizedError,
decodeRudpPacket,
defineCultNetDocumentBinding,
encodeCultNetMessageForWire,
encodeRudpPacket,
} from "@gamecult/cultnet-ts";
import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../src/index";
const isTheRefusal = (error: unknown): boolean =>
error instanceof CultMeshRudpWriteRefusedError && error.code === "write_not_authorized";
const note = defineDocumentType({
type: "cultmesh.completion_note",
schemaId: "cultmesh.completion_note.v0",
schema: z.object({ noteId: z.string(), text: z.string() }),
name: "noteId",
});
const binding = defineCultNetDocumentBinding({ definition: note });
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
type Order = "ack-then-refusal" | "refusal-then-ack";
/** A peer that acknowledges every reliable put and refuses it with write_not_authorized, in the given order. */
async function refusingPeer(connectionId: number, order: Order) {
const socket: Socket = createSocket("udp4");
await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));
const session = new CultNetRudpSession({ connectionId, resendDelayMs: 50 });
const timers = new Set<NodeJS.Timeout>();
let closed = false;
const send = (packet: Parameters<typeof encodeRudpPacket>[0], port: number, address: string) => {
if (!closed) socket.send(encodeRudpPacket(packet), port, address);
};
const later = (action: () => void) => { const timer = setTimeout(() => { timers.delete(timer); action(); }, 120); timers.add(timer); };
socket.on("message", (wire, remote) => {
const packet = decodeRudpPacket(wire);
const now = Date.now();
if (packet.packetType === "connect") {
send(session.acceptConnect(packet, now), remote.port, remote.address);
return;
}
const result = session.receive(packet, now);
if (result.reply) send(result.reply, remote.port, remote.address);
for (const frame of result.delivered) {
if (frame.channelId !== "schema") continue;
const ack = session.createAckForReceived(packet.sequence);
const refusal = session.sendMany(
"schema",
encodeWireValue(encodeCultNetMessageForWire(cultNetWriteNotAuthorizedError("tests:completion:a"), "cultnet.schema.v0")),
{ reliable: true, ordered: true, nowMs: now },
);
if (order === "ack-then-refusal") {
send(ack, remote.port, remote.address);
later(() => refusal.forEach((p) => send(p, remote.port, remote.address)));
} else {
// The refusal carries no acknowledgement of its own; the ack follows it.
refusal.forEach((p) => send({ ...p, ack: 0, ackMask: 0 }, remote.port, remote.address));
later(() => send(ack, remote.port, remote.address));
}
}
if (packet.reliable) send(session.createAckForReceived(packet.sequence), remote.port, remote.address);
});
return { endpoint: `rudp://127.0.0.1:${socket.address().port}`, close: () => { closed = true; timers.forEach(clearTimeout); socket.close(); } };
}
const orders: Order[] = ["ack-then-refusal", "refusal-then-ack"];
let nextConnection = 0x10205000;
for (const order of orders) {
test(`publishRudpDocumentOnce does not complete on the ack of a refused put (${order})`, async () => {
const peer = await refusingPeer(nextConnection, order);
try {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("completion-once", nextConnection++, peer.endpoint, binding, "tests:completion:a", { noteId: "a", text: "x" }, { resendDelayMs: 50, resendPollMs: 5, flushTimeoutMs: 2_000 }),
isTheRefusal,
);
} finally { peer.close(); }
});
test(`publishRudpDocumentAndWaitForReceipt reports a refused put as refused, never as success (${order})`, async () => {
const peer = await refusingPeer(nextConnection, order);
try {
await assert.rejects(
CultMesh.publishRudpDocumentAndWaitForReceipt("completion-receipt", nextConnection++, peer.endpoint, binding, "tests:completion:a", { noteId: "a", text: "x" }, binding, { resendDelayMs: 50, resendPollMs: 5, receiptTimeoutMs: 800 }),
isTheRefusal,
);
} finally { peer.close(); }
await sleep(10);
});
}
test("a put the server applied but did not answer is unconfirmed, never published", async () => {
const connectionId = nextConnection++;
const puts: string[] = [];
const server = CultMesh.createRudpDocumentServer("completion-admit", connectionId, {
documents: new CultNetDocumentRegistry([binding]),
writeAuthority: new CultMeshGrantAllWrites(),
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 50, resendPollMs: 5,
onDocumentPutRaw: (put) => { puts.push(put.recordKey); },
});
await server.start();
try {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("completion-admit-client", connectionId, `rudp://127.0.0.1:${server.bind.port}`, binding, "tests:completion:a", { noteId: "a", text: "x" }, { resendDelayMs: 50, resendPollMs: 5, resultWindowMs: 200 }),
(error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed",
);
assert.deepEqual(puts, ["tests:completion:a"], "the server did apply it; this server just does not answer");
} finally { server.close(); }
});

View file

@ -19,8 +19,8 @@ import {
CultNetDocumentRegistry, CultNetDocumentRegistry,
defineCultNetDocumentBinding, defineCultNetDocumentBinding,
type CultNetPeer, type CultNetPeer,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import { CultMesh, cultMeshDocumentFromSingleFile, type CultMeshRudpDocumentPut } from "../src/index"; import { CultMesh, CultMeshGrantAllWrites, cultMeshDocumentFromSingleFile, type CultMeshRudpDocumentPut } from "../src/index";
// A document written in the reference's positional shape, and a plain map document beside it. Every mesh reader of a // A document written in the reference's positional shape, and a plain map document beside it. Every mesh reader of a
// payload reads it the way the cache does, so both read through the mesh. // payload reads it the way the cache does, so both read through the mesh.
@ -77,6 +77,7 @@ test("the mesh syncs a codec document from a peer snapshot and returns a codec r
const receiptBinding = defineCultNetDocumentBinding({ definition: codecReceipt }); const receiptBinding = defineCultNetDocumentBinding({ definition: codecReceipt });
const puts: unknown[] = []; const puts: unknown[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-codec-server", connectionId, { const server = CultMesh.createRudpDocumentServer("cultmesh-ts-codec-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([commandBinding, plainBinding, receiptBinding]), documents: new CultNetDocumentRegistry([commandBinding, plainBinding, receiptBinding]),
getCache: () => source.cache, getCache: () => source.cache,
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5, bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
@ -131,6 +132,7 @@ test("a RUDP put naming a schema the server has no definition for reaches the ha
const errors: Error[] = []; const errors: Error[] = [];
const puts: CultMeshRudpDocumentPut[] = []; const puts: CultMeshRudpDocumentPut[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-unregistered-server", connectionId, { const server = CultMesh.createRudpDocumentServer("cultmesh-ts-unregistered-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([known]), documents: new CultNetDocumentRegistry([known]),
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5, bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onError: (error) => errors.push(error), onError: (error) => errors.push(error),
@ -171,6 +173,7 @@ test("a payload past the nesting limit is refused at the network doors: a RUDP p
const errors: unknown[] = []; const errors: unknown[] = [];
const puts: CultMeshRudpDocumentPut[] = []; const puts: CultMeshRudpDocumentPut[] = [];
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-depth-server", connectionId, { const server = CultMesh.createRudpDocumentServer("cultmesh-ts-depth-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry, documents: registry,
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5, bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onError: (error) => errors.push(error), onError: (error) => errors.push(error),

View file

@ -8,7 +8,7 @@ import { join } from "node:path";
import test, { mock } from "node:test"; import test, { mock } from "node:test";
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { EMPTY_SHA256, chunkRecordKey, packContent, sha256Hex } from "cultnet-ts/content"; import { EMPTY_SHA256, chunkRecordKey, packContent, sha256Hex } from "@gamecult/cultnet-ts/content";
import { closeSync, constants as fsConstants, openSync, symlinkSync } from "node:fs"; import { closeSync, constants as fsConstants, openSync, symlinkSync } from "node:fs";
import { import {

View file

@ -4,7 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import test from "node:test"; import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { decodeWireValue, encodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { z } from "zod"; import { z } from "zod";
import { SchemaConflictError, defineDocumentType, documentPayloadBytes, documentPayloadFromBytes } from "@gamecult/cultcache-ts"; import { SchemaConflictError, defineDocumentType, documentPayloadBytes, documentPayloadFromBytes } from "@gamecult/cultcache-ts";
import { import {
@ -12,6 +12,7 @@ import {
CultNetPeer, CultNetPeer,
CultNetRudpSession, CultNetRudpSession,
cultNetBuiltinSchemaRegistry, cultNetBuiltinSchemaRegistry,
cultNetTextError,
decodeRudpPacket, decodeRudpPacket,
defineCultNetDocumentBinding, defineCultNetDocumentBinding,
encodeRudpPacket, encodeRudpPacket,
@ -19,8 +20,8 @@ import {
type CultNetRudpPacket, type CultNetRudpPacket,
type CultNetMessage, type CultNetMessage,
type CultNetSnapshotResponseRawMessage, type CultNetSnapshotResponseRawMessage,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import { CultMesh, CultMeshRudpUnservableDocumentError } from "../src/index"; import { CultMesh, CultMeshGrantAllWrites, CultMeshRudpUnservableDocumentError, CultMeshRudpWriteUnconfirmedError } from "../src/index";
// A record's payload as the bytes a peer would put on the wire. // A record's payload as the bytes a peer would put on the wire.
const payloadOf = (value: unknown) => documentPayloadFromBytes(encodeWireValue(value)); const payloadOf = (value: unknown) => documentPayloadFromBytes(encodeWireValue(value));
@ -2856,6 +2857,7 @@ test("CultMesh TS RUDP document server accepts raw document puts from multiple p
"cultmesh-ts-document-server", "cultmesh-ts-document-server",
connectionId, connectionId,
{ {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
bindHost: "127.0.0.1", bindHost: "127.0.0.1",
bindPort: 0, bindPort: 0,
@ -2944,6 +2946,7 @@ test("CultMesh TS publishes one registered document to a RUDP catalog", async ()
"cultmesh-ts-odin-catalog", "cultmesh-ts-odin-catalog",
connectionId, connectionId,
{ {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
bindHost: "127.0.0.1", bindHost: "127.0.0.1",
bindPort: 0, bindPort: 0,
@ -2965,7 +2968,9 @@ test("CultMesh TS publishes one registered document to a RUDP catalog", async ()
try { try {
await server.start(); await server.start();
await CultMesh.publishRudpDocumentOnce( // This server answers a put with nothing, so the writer cannot know the put landed: unconfirmed, though it did.
await assert.rejects(
CultMesh.publishRudpDocumentOnce(
"cultmesh-ts-muninn", "cultmesh-ts-muninn",
connectionId, connectionId,
`rudp://127.0.0.1:${server.bind.port}`, `rudp://127.0.0.1:${server.bind.port}`,
@ -2981,9 +2986,13 @@ test("CultMesh TS publishes one registered document to a RUDP catalog", async ()
maxFragmentBytes: 1024, maxFragmentBytes: 1024,
maxPendingReliablePackets: 16, maxPendingReliablePackets: 16,
connectTimeoutMs: 1_000, connectTimeoutMs: 1_000,
flushTimeoutMs: 25, // The flush is bounded by the result window, so the window must outlast the transport ack on a loaded
// runner: a short one turns a slow ack into local_send_failed, which is not the path this test checks.
resultWindowMs: 750,
sourceRole: "test-provider", sourceRole: "test-provider",
}, },
),
(error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed",
); );
await waitFor(() => received !== undefined, "published RUDP document"); await waitFor(() => received !== undefined, "published RUDP document");
@ -3019,6 +3028,7 @@ test("CultMesh TS returns a correlated provider receipt after a RUDP document mu
const commandBinding = defineCultNetDocumentBinding({ definition: noteDocument }); const commandBinding = defineCultNetDocumentBinding({ definition: noteDocument });
const receiptBinding = defineCultNetDocumentBinding({ definition: noteReceiptDocument }); const receiptBinding = defineCultNetDocumentBinding({ definition: noteReceiptDocument });
const server = CultMesh.createRudpDocumentServer("cultmesh-ts-receipt-server", connectionId, { const server = CultMesh.createRudpDocumentServer("cultmesh-ts-receipt-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([commandBinding, receiptBinding]), bindHost: "127.0.0.1", bindPort: 0, documents: new CultNetDocumentRegistry([commandBinding, receiptBinding]), bindHost: "127.0.0.1", bindPort: 0,
resendDelayMs: 25, resendPollMs: 5, resendDelayMs: 25, resendPollMs: 5,
onDocumentPutRaw: async (document) => ({ onDocumentPutRaw: async (document) => ({
@ -3054,6 +3064,7 @@ test("CultMesh TS reads remote RUDP snapshots through document handles", async (
"cultmesh-ts-rudp-snapshot-server", "cultmesh-ts-rudp-snapshot-server",
connectionId, connectionId,
{ {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([ documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: noteDocument }), defineCultNetDocumentBinding({ definition: noteDocument }),
]), ]),
@ -3151,6 +3162,7 @@ test("CultMesh TS syncs remote RUDP snapshots into a local node", async () => {
"cultmesh-ts-rudp-sync-server", "cultmesh-ts-rudp-sync-server",
connectionId, connectionId,
{ {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([ documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: noteDocument }), defineCultNetDocumentBinding({ definition: noteDocument }),
]), ]),
@ -3232,6 +3244,7 @@ test("CultMesh TS peer snapshots never take another type's record at the key", a
"cultmesh-ts-rudp-foreign-snapshot-server", "cultmesh-ts-rudp-foreign-snapshot-server",
connectionId, connectionId,
{ {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry([ documents: new CultNetDocumentRegistry([
defineCultNetDocumentBinding({ definition: incompatibleNoteDocument }), defineCultNetDocumentBinding({ definition: incompatibleNoteDocument }),
defineCultNetDocumentBinding({ definition: foreignNoteDocument }), defineCultNetDocumentBinding({ definition: foreignNoteDocument }),
@ -3473,6 +3486,7 @@ async function withServedBoundRig(
const messages: CultNetMessage[] = []; const messages: CultNetMessage[] = [];
const unparsed: Error[] = []; const unparsed: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, { const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry, documents: registry,
getCache: () => node.cache, getCache: () => node.cache,
bindHost: "127.0.0.1", bindHost: "127.0.0.1",
@ -3634,6 +3648,7 @@ async function withRawPeerRig(
for (const put of stored) await registry.applyRawDocumentPutMessage(node.cache, put); for (const put of stored) await registry.applyRawDocumentPutMessage(node.cache, put);
const errors: Error[] = []; const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, { const server = CultMesh.createRudpDocumentServer(SERVED_BOUND_SERVER, connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: registry, documents: registry,
getCache: () => (getCache ? getCache(node.cache) : node.cache) as typeof node.cache, getCache: () => (getCache ? getCache(node.cache) : node.cache) as typeof node.cache,
bindHost: "127.0.0.1", bindHost: "127.0.0.1",
@ -3708,7 +3723,7 @@ test("CultMesh TS RUDP document server answers a peer whose reliable queue is fu
while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5); while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5);
const refusal = refusalIn(rig.inbox); const refusal = refusalIn(rig.inbox);
assert.ok(refusal, "the refusal reaches the peer"); assert.ok(refusal, "the refusal reaches the peer");
assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot response could not be queued" }); assert.deepEqual(refusal.message, cultNetTextError("the snapshot response could not be queued"));
for (const part of refusal.parts) { for (const part of refusal.parts) {
assert.ok(refused.every((sequence) => !acknowledges(part, sequence)), `ack ${part.ack} mask ${part.ackMask}`); assert.ok(refused.every((sequence) => !acknowledges(part, sequence)), `ack ${part.ack} mask ${part.ackMask}`);
} }
@ -3725,7 +3740,7 @@ test("CultMesh TS RUDP document server refuses a snapshot with fixed text, never
while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5); while (!refusalIn(rig.inbox) && Date.now() - startedAt < 3_000) await delay(5);
const refusal = refusalIn(rig.inbox); const refusal = refusalIn(rig.inbox);
assert.ok(refusal, "the refusal reaches the peer"); assert.ok(refusal, "the refusal reaches the peer");
assert.deepEqual(refusal.message, { schemaVersion: "cultnet.error.v0", error: "the snapshot source failed" }); assert.deepEqual(refusal.message, cultNetTextError("the snapshot source failed"));
assert.match(rig.errors[0]?.message ?? "", /CANARY-7f3a/); assert.match(rig.errors[0]?.message ?? "", /CANARY-7f3a/);
}); });
}); });

View file

@ -18,8 +18,8 @@
// harness can dial a peer late and exercise Cut C's retained-state seed // harness can dial a peer late and exercise Cut C's retained-state seed
// instead of the provider always tearing down the moment it is done sending. // instead of the provider always tearing down the moment it is done sending.
// //
// Neither mode imports `cultmesh-ts` itself (the harness drives processes, // Neither mode imports `@gamecult/cultmesh-ts` itself (the harness drives processes,
// and the dependency direction is `cultmesh-ts` -> `cultnet-ts`, never the // and the dependency direction is `@gamecult/cultmesh-ts` -> `@gamecult/cultnet-ts`, never the
// reverse); this script reaches the provider/connector through its own // reverse); this script reaches the provider/connector through its own
// package's `src/`. // package's `src/`.

View file

@ -0,0 +1,434 @@
// The TypeScript write-receipt client (cultnet-ts WriteTracker and decoder, cultmesh-ts one-shot writer) against the two real
// receipt servers over loopback, as child processes on ephemeral ports:
//
// rust packages/cultmesh-rs/examples/receipt_interop_server.rs, the RUDP document server, reached over RUDP.
// csharp tests/GameCult.Networking.InteropPeer `receipt-serve`, CultNetDatabaseServer on Server (LiteNetLib). TypeScript has no
// LiteNetLib client, so a second child, `receipt-relay`, carries bytes between the test and the server (4-byte
// big-endian length, then the CultNet frame: CultNetPeer's own stream framing). It decodes and judges nothing.
//
// Every scenario runs against both targets; its outcome is read from the WriteTracker (admitted, refused, unconfirmed), and the
// server's own stdout facts say what was committed. Contract: contracts/cultnet/interop/write-receipt.md and its vectors.
//
// Needs cargo and dotnet; run it with `npm run test:interop` in packages/cultmesh-ts (CARGO and DOTNET override the commands;
// RECEIPT_INTEROP_PREBUILT=1 skips the two builds).
import assert from "node:assert/strict";
import { execFile, spawn, spawnSync, type ChildProcess } from "node:child_process";
import { readFileSync } from "node:fs";
import { join, resolve } from "node:path";
import { Duplex } from "node:stream";
import { after, before, beforeEach, describe, test } from "node:test";
import { promisify } from "node:util";
import { encode } from "@msgpack/msgpack";
import { z } from "zod";
import { defineDocumentType } from "@gamecult/cultcache-ts";
import {
CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS,
CultNetPeer,
WriteTracker,
defineCultNetDocumentBinding,
helloAdvertisesWriteReceipts,
resultWindowMs,
type CultNetErrorV1Message,
type CultNetHelloMessage,
type CultNetMessage,
type WriteSettlement,
} from "@gamecult/cultnet-ts";
import { CultMesh, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../../src/index";
const execFileAsync = promisify(execFile);
// dist-test/test/interop -> the repository root
const repoRoot = resolve(__dirname, "..", "..", "..", "..", "..");
const cargo = process.env.CARGO ?? "cargo";
const dotnet = process.env.DOTNET ?? "dotnet";
const rustManifestDir = join(repoRoot, "packages", "cultmesh-rs");
const csharpProject = join(repoRoot, "tests", "GameCult.Networking.InteropPeer", "GameCult.Networking.InteropPeer.csproj");
const csharpDll = join(repoRoot, "bin", "GameCult.Networking.InteropPeer", "Debug", "net10.0", "GameCult.Networking.InteropPeer.dll");
// Set when the server binaries were built beforehand (the builds themselves cannot start under a tight address-space cap).
const prebuilt = process.env.RECEIPT_INTEROP_PREBUILT === "1";
const vectors = JSON.parse(readFileSync(join(repoRoot, "contracts", "cultnet", "interop", "write-receipt-vectors.json"), "utf8"));
const SCHEMA_ID = "receipt.interop_note.v1";
const UNREADABLE = "message_invalid: the message could not be read";
const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms));
async function waitFor(predicate: () => boolean, what: string, ms = 5_000): Promise<void> {
const startedAt = Date.now();
while (!predicate()) {
if (Date.now() - startedAt > ms) throw new Error(`timed out waiting for ${what}`);
await sleep(5);
}
}
// ---- the servers -------------------------------------------------------------------------------------------------------
interface Fact { event: string; recordKey?: string; messageId?: string; [key: string]: unknown }
/** A running server child and the JSON facts it prints on stdout. */
class ServerProcess {
readonly facts: Fact[] = [];
stderr = "";
port = 0;
constructor(readonly child: ChildProcess) {
let pending = "";
child.stdout!.on("data", (chunk: Buffer) => {
pending += chunk.toString("utf8");
for (let at = pending.indexOf("\n"); at >= 0; at = pending.indexOf("\n")) {
const line = pending.slice(0, at).trim();
pending = pending.slice(at + 1);
if (line) this.facts.push(JSON.parse(line) as Fact);
}
});
child.stderr!.on("data", (chunk: Buffer) => { this.stderr += chunk.toString("utf8"); });
}
/** How many times `event` was printed for `recordKey`. */
count(event: string, recordKey: string): number {
return this.facts.filter((fact) => fact.event === event && fact.recordKey === recordKey).length;
}
async stop(): Promise<void> {
this.child.stdin!.end();
await new Promise<void>((done) => {
const killer = setTimeout(() => this.child.kill("SIGKILL"), 5_000);
this.child.once("exit", () => { clearTimeout(killer); done(); });
if (this.child.exitCode !== null) done();
});
}
}
async function launch(command: string, args: string[]): Promise<ServerProcess> {
const server = new ServerProcess(spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] }));
await waitFor(() => server.facts.some((fact) => fact.event === "listening") || server.child.exitCode !== null, "the server to listen", 60_000);
const listening = server.facts.find((fact) => fact.event === "listening");
if (!listening) throw new Error(`the server exited before listening:\n${server.stderr}`);
server.port = listening.port as number;
return server;
}
/** One connection to a server: the peer that speaks CultNet, and how to close it. */
interface Connection { peer: CultNetPeer; close(): void }
interface Target {
name: string;
/** Shard fields the server's database requires on a write, if any. */
shard?: { shardId: string; shardEpoch: number };
/** A document payload this target's store reads. */
payload(text: string): Uint8Array;
start(): Promise<ServerProcess>;
connect(server: ServerProcess): Promise<Connection>;
}
let nextConnectionId = 0x20206000;
const rust: Target = {
name: "rust",
payload: (text) => encode({ text }),
async start() {
if (!prebuilt) await execFileAsync(cargo, ["build", "--example", "receipt_interop_server", "--message-format", "short"], { cwd: rustManifestDir });
const metadata = spawnSync(cargo, ["metadata", "--format-version", "1", "--no-deps"], { cwd: rustManifestDir, encoding: "utf8" });
if (metadata.status !== 0) throw new Error(`cargo metadata failed: ${metadata.stderr}`);
const exe = join(JSON.parse(metadata.stdout).target_directory, "debug", "examples", `receipt_interop_server${process.platform === "win32" ? ".exe" : ""}`);
return launch(exe, []);
},
async connect(server) {
const peer = await CultMesh.createRudpPeer("receipt-interop", nextConnectionId++, { host: "127.0.0.1", port: server.port, uri: `rudp://127.0.0.1:${server.port}` });
return { peer, close: () => peer.close() };
},
};
// The C# server admits 30 connection requests per IP per minute (Server.MaxConnectionAttemptsPerMinute) and answers the rest with
// no hello. Every scenario wants a fresh session, so before each C# test the harness waits until the last minute holds at most
// CONNECTIONS_PER_MINUTE connections, leaving room for the two a test may open. The server's limit stays as it is.
const CONNECTIONS_PER_MINUTE = 24;
const connectedAt: number[] = [];
async function awaitConnectionBudget(): Promise<void> {
for (;;) {
const now = Date.now();
while (connectedAt.length > 0 && now - connectedAt[0] >= 61_000) connectedAt.shift();
if (connectedAt.length <= CONNECTIONS_PER_MINUTE) return;
await sleep(connectedAt[0] + 61_000 - now);
}
}
const csharp: Target = {
name: "csharp",
shard: { shardId: "receipt-interop-shard", shardEpoch: 1 },
payload: (text) => encode([text]),
async start() {
if (!prebuilt) await execFileAsync(dotnet, ["build", csharpProject, "-nologo", "-v", "q"], { cwd: repoRoot, maxBuffer: 64 * 1024 * 1024 });
return launch(dotnet, [csharpDll, "receipt-serve"]);
},
async connect(server) {
connectedAt.push(Date.now());
const relay = spawn(dotnet, [csharpDll, "receipt-relay", "--port", String(server.port)], { stdio: ["pipe", "pipe", "ignore"] });
const peer = new CultNetPeer(Duplex.from({ readable: relay.stdout!, writable: relay.stdin! }), { wireContract: "cultnet.schema.v0" });
return { peer, close: () => { relay.stdin!.end(); relay.kill(); } };
},
};
// ---- a client session: one connection, the frames it saw, one WriteTracker per write -----------------------------------------
class Session {
readonly frames: CultNetMessage[] = [];
readonly invalid: Error[] = [];
private readonly trackers = new Set<WriteTracker>();
private serverReceipts = false;
private constructor(readonly target: Target, private readonly connection: Connection) {
connection.peer.on("message", (message: CultNetMessage) => {
if (message.schemaVersion === "cultnet.hello.v0") this.serverReceipts = helloAdvertisesWriteReceipts(message);
this.frames.push(message);
for (const tracker of this.trackers) tracker.frame(message, Date.now());
});
connection.peer.on("invalidMessage", (error: Error) => this.invalid.push(error));
connection.peer.on("close", () => { for (const tracker of this.trackers) tracker.sessionEnd(Date.now()); });
}
static async open(target: Target, server: ServerProcess): Promise<Session> {
return new Session(target, await target.connect(server));
}
/** Declares the receipt capability and waits for the server's own hello. */
async hello(versions: readonly string[] = CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS): Promise<CultNetHelloMessage> {
this.connection.peer.sendHello({ schemaVersion: "cultnet.hello.v0", runtimeId: "receipt-interop", runtimeKind: "cultmesh-ts", supportedMessageVersions: [...versions] });
await waitFor(() => this.frames.some((frame) => frame.schemaVersion === "cultnet.hello.v0"), "the server's hello");
return this.frames.find((frame) => frame.schemaVersion === "cultnet.hello.v0") as CultNetHelloMessage;
}
put(messageId: string, recordKey: string, text: string, document: Record<string, unknown> = {}): CultNetMessage {
return this.shard({
schemaVersion: "cultnet.document_put_raw.v0",
messageId,
document: {
schemaId: SCHEMA_ID, recordKey, storedAt: new Date().toISOString(), payloadEncoding: "messagepack",
payload: this.target.payload(text), ...document,
},
});
}
delete(messageId: string, recordKey: string): CultNetMessage {
return this.shard({ schemaVersion: "cultnet.document_delete.v0", messageId, schemaId: SCHEMA_ID, recordKey });
}
private shard(message: unknown): CultNetMessage {
return { ...(message as object), ...this.target.shard } as CultNetMessage;
}
/**
* Sends one write and settles it with its own tracker, windowed by what the server advertised (5000 ms against a receipt
* server, 500 ms otherwise). Only the tracker decides the outcome.
*/
async write(message: CultNetMessage): Promise<WriteSettlement> {
const messageId = (message as { messageId: string }).messageId;
const tracker = new WriteTracker({ windowMs: resultWindowMs(this.serverReceipts) });
this.trackers.add(tracker);
tracker.send(messageId, Date.now());
this.connection.peer.send(message);
for (;;) {
tracker.tick(Date.now());
const state = tracker.state(messageId)!;
if (state.outcome !== "pending") return state;
await sleep(Math.min(20, tracker.nextDeadlineMs(Date.now()) ?? 20));
}
}
/** Frames of `schemaVersion` that name `messageId`. */
answers(messageId: string, schemaVersion: string): CultNetMessage[] {
return this.frames.filter((frame) => frame.schemaVersion === schemaVersion && (frame as { messageId?: string }).messageId === messageId);
}
close(): void { this.connection.close(); }
}
function refusal(settlement: WriteSettlement): CultNetErrorV1Message {
assert.equal(settlement.outcome, "refused", JSON.stringify(settlement));
return (settlement as Extract<WriteSettlement, { outcome: "refused" }>).response as CultNetErrorV1Message;
}
// ---- the scenarios, run against each server -----------------------------------------------------------------------------------
for (const target of [rust, csharp]) {
describe(`write receipt, TypeScript client against the real ${target.name} server`, () => {
let server: ServerProcess;
let session: Session | undefined;
before(async () => { server = await target.start(); }, { timeout: 180_000 });
after(async () => { session?.close(); await server?.stop(); });
beforeEach(async () => { if (target === csharp) await awaitConnectionBudget(); }, { timeout: 90_000 });
/** A fresh receipt session (hello sent, the server's hello read) for a scenario. */
async function receiptSession(): Promise<Session> {
session?.close();
session = await Session.open(target, server);
const hello = await session.hello();
assert.ok(helloAdvertisesWriteReceipts(hello), "the server's hello lists both receipt frames");
return session;
}
test("hello listing both frames: the server answers with its own hello listing both, then a put is receipted after it", { timeout: 30_000 }, async () => {
const s = await receiptSession();
assert.equal(s.frames[0].schemaVersion, "cultnet.hello.v0");
const settlement = await s.write(s.put("hello-1", "hello:a", "one"));
assert.deepEqual(settlement, { outcome: "admitted" });
assert.deepEqual(s.frames.map((frame) => frame.schemaVersion), ["cultnet.hello.v0", "cultnet.write_admitted.v0"]);
});
test("a hello listing only one of the two frames does not opt in: no receipt, and the put is applied", { timeout: 30_000 }, async () => {
for (const listed of CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS) {
session?.close();
session = await Session.open(target, server);
session.hello([listed]).catch(() => undefined); // a server may stay silent to a hello that does not opt in
await sleep(300);
const settlement = await session.write(session.put(`half-${listed}`, `half:${listed}`, "one"));
assert.deepEqual(settlement, { outcome: "unconfirmed", reason: "window_elapsed" }, `listing only ${listed}`);
assert.ok(!session.frames.some((frame) => frame.schemaVersion === "cultnet.write_admitted.v0" || frame.schemaVersion === "cultnet.error.v1"));
await waitFor(() => server.count("applied", `half:${listed}`) === 1, "the put to be applied");
}
});
test("put admitted: the receipt echoes the write and the store has it once", { timeout: 30_000 }, async () => {
const s = await receiptSession();
const settlement = await s.write(s.put("put-1", "put:a", "one"));
assert.deepEqual(settlement, { outcome: "admitted" });
assert.deepEqual(s.answers("put-1", "cultnet.write_admitted.v0"), [
{ schemaVersion: "cultnet.write_admitted.v0", messageId: "put-1", operation: "put", schemaId: SCHEMA_ID, recordKey: "put:a" },
]);
await waitFor(() => server.count("applied", "put:a") === 1, "the put to be applied");
});
// The Rust RUDP document server has no delete: its sink only accepts documents, and every delete on a receipt session is
// answered with a refusal (rudp_document_server.rs, deletes_on_a_receipt_session_are_refused_one_by_one). The spec
// (Server rules 1 to 3) has a delete admitted and receipted like a put.
test("delete admitted: the receipt says operation delete and the store drops the record", {
timeout: 30_000,
todo: target.name === "rust" ? "the Rust RUDP document server refuses every delete; there is no delete port in CultMeshRudpRawDocumentSink" : false,
}, async () => {
const s = await receiptSession();
assert.deepEqual(await s.write(s.put("del-put", "del:a", "one")), { outcome: "admitted" });
assert.deepEqual(await s.write(s.delete("del-1", "del:a")), { outcome: "admitted" });
assert.deepEqual(s.answers("del-1", "cultnet.write_admitted.v0"), [
{ schemaVersion: "cultnet.write_admitted.v0", messageId: "del-1", operation: "delete", schemaId: SCHEMA_ID, recordKey: "del:a" },
]);
await waitFor(() => server.count("removed", "del:a") === 1, "the delete to be applied");
});
test("refused write: an error.v1 carrying the write's id, and nothing is applied", { timeout: 30_000 }, async () => {
const s = await receiptSession();
const response = refusal(await s.write(s.put("deny-1", "refuse:a", "one")));
assert.equal(response.schemaVersion, "cultnet.error.v1");
assert.equal(response.messageId, "deny-1");
assert.equal(response.code, "write_not_authorized");
// The session is kept: the next write on it is admitted.
assert.deepEqual(await s.write(s.put("deny-2", "deny:b", "one")), { outcome: "admitted" });
assert.equal(server.count("applied", "refuse:a"), 0);
});
test("resend of the same id and content on the same session: re-receipted, applied once", { timeout: 30_000 }, async () => {
const s = await receiptSession();
assert.deepEqual(await s.write(s.put("resend-1", "resend:a", "one")), { outcome: "admitted" });
assert.deepEqual(await s.write(s.put("resend-1", "resend:a", "one")), { outcome: "admitted" });
const receipts = s.answers("resend-1", "cultnet.write_admitted.v0");
assert.equal(receipts.length, 2);
assert.deepEqual(receipts[0], receipts[1]);
await sleep(200); // a second application would be printed by now
assert.equal(server.count("applied", "resend:a"), 1);
});
test("same id with different content: message_invalid naming the id, never a receipt, the first write untouched", { timeout: 30_000 }, async () => {
const s = await receiptSession();
assert.deepEqual(await s.write(s.put("clash-1", "clash:a", "one")), { outcome: "admitted" });
const response = refusal(await s.write(s.put("clash-1", "clash:a", "other")));
assert.equal(response.code, "message_invalid");
assert.equal(response.messageId, "clash-1");
assert.equal(response.details?.field, "messageId");
assert.equal(s.answers("clash-1", "cultnet.write_admitted.v0").length, 1, "no receipt for the changed write");
await sleep(200);
assert.equal(server.count("applied", "clash:a"), 1);
});
// Each case of the vectors' blankFields section: a document that names nothing is refused as an unreadable frame, with the
// write's id and the fixed text, and never applied; a document that is merely missing optional fields is admitted.
for (const blank of vectors.blankFields.cases as { name: string; set: Record<string, unknown>; outcome: "admitted" | "refused" }[]) {
test(`blank-field vector ${blank.name}: ${blank.outcome}`, { timeout: 30_000 }, async () => {
const s = await receiptSession();
const { payloadHex, ...fields } = blank.set;
// A case that sets recordKey replaces the harness key, so the store is read under the key the server actually saw.
const recordKey = typeof fields.recordKey === "string" ? fields.recordKey : `blank:${blank.name}`;
const message = s.put(`blank-${blank.name}`, recordKey, "one", fields);
const sent = (message as unknown as { document: Record<string, unknown> }).document;
for (const [key, value] of Object.entries(fields)) if (value === null) delete sent[key]; // nil means absent on the wire here
if (payloadHex === "") sent.payload = new Uint8Array();
const settlement = await s.write(message);
if (blank.outcome === "admitted") {
assert.deepEqual(settlement, { outcome: "admitted" });
await waitFor(() => server.count("applied", recordKey) === 1, "the put to be applied");
return;
}
const response = refusal(settlement);
assert.equal(response.code, "message_invalid");
assert.equal(response.error, UNREADABLE);
assert.equal(response.details?.field, "message");
assert.equal(response.messageId, `blank-${blank.name}`);
await sleep(200);
assert.equal(server.count("applied", recordKey), 0);
});
}
test("a delete that names nothing is refused as unreadable with its id", { timeout: 30_000 }, async () => {
const s = await receiptSession();
const message = s.delete("blank-del", "blank:del");
(message as unknown as { schemaId: string }).schemaId = "";
const response = refusal(await s.write(message));
assert.equal(response.code, "message_invalid");
assert.equal(response.error, UNREADABLE);
assert.equal(response.details?.field, "message");
assert.equal(response.messageId, "blank-del");
});
test("legacy client (no hello): no receipt frames, the write is applied, and its refusal is the old error.v0", { timeout: 30_000 }, async () => {
session?.close();
session = await Session.open(target, server);
assert.deepEqual(await session.write(session.put("legacy-1", "legacy:a", "one")), { outcome: "unconfirmed", reason: "window_elapsed" });
await waitFor(() => server.count("applied", "legacy:a") === 1, "the put to be applied");
const refused = (await session.write(session.put("legacy-2", "refuse:legacy", "one"))) as Extract<WriteSettlement, { outcome: "refused" }>;
assert.equal(refused.outcome, "refused");
assert.equal(refused.response.schemaVersion, "cultnet.error.v0");
assert.deepEqual(session.frames.map((frame) => frame.schemaVersion), ["cultnet.error.v0"]);
assert.equal(session.invalid.length, 0);
});
});
}
// ---- the one-shot writer, which is the real cultmesh-ts client path, against the Rust RUDP server ----------------------------
// (The C# server speaks LiteNetLib, not RUDP: no RUDP client path reaches it.)
describe("write receipt, cultmesh-ts publishRudpDocumentOnce against the real rust server", () => {
const note = defineDocumentType({ type: "receipt.interop_note", schemaId: SCHEMA_ID, schema: z.object({ text: z.string() }), name: "text" });
const binding = defineCultNetDocumentBinding({ definition: note });
let server: ServerProcess;
before(async () => { server = await rust.start(); }, { timeout: 180_000 });
after(async () => { await server?.stop(); });
const endpoint = () => ({ host: "127.0.0.1", port: server.port, uri: `rudp://127.0.0.1:${server.port}` });
test("writeReceipts: the put resolves admitted on the receipt, after the server applied it", { timeout: 30_000 }, async () => {
const outcome = await CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "once:a", { text: "one" }, { writeReceipts: true, messageId: "once-1" });
assert.equal(outcome, "admitted");
await waitFor(() => server.count("applied", "once:a") === 1, "the put to be applied");
});
test("writeReceipts: a refused put rejects with the server's error.v1 naming the put", { timeout: 30_000 }, async () => {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "refuse:once", { text: "one" }, { writeReceipts: true, messageId: "once-2" }),
(error: unknown) => {
assert.ok(error instanceof CultMeshRudpWriteRefusedError);
assert.equal(error.response.schemaVersion, "cultnet.error.v1");
assert.equal((error.response as CultNetErrorV1Message).messageId, "once-2");
return true;
},
);
});
test("without writeReceipts the server stays silent: the put is unconfirmed, not admitted, though the server applied it", { timeout: 30_000 }, async () => {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("receipt-interop", nextConnectionId++, endpoint(), binding, "once:legacy", { text: "one" }, { messageId: "once-3" }),
(error: unknown) => error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed",
);
await waitFor(() => server.count("applied", "once:legacy") === 1, "the put to be applied");
});
});

View file

@ -8,8 +8,8 @@ import {
documentPayloadFromBytes, documentPayloadFromBytes,
type DocumentPayload, type DocumentPayload,
} from "@gamecult/cultcache-ts"; } from "@gamecult/cultcache-ts";
import { decodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue } from "@gamecult/cultnet-ts/wire";
import type { CultNetRawDocumentRecord } from "cultnet-ts"; import type { CultNetRawDocumentRecord } from "@gamecult/cultnet-ts";
import type { CultMeshRudpDocumentPut } from "../src/index"; import type { CultMeshRudpDocumentPut } from "../src/index";
import { decodeRealtimeFrame, encodeRealtimeFrame, type CultMeshRealtimeFrame } from "../src/realtime-wire"; import { decodeRealtimeFrame, encodeRealtimeFrame, type CultMeshRealtimeFrame } from "../src/realtime-wire";

View file

@ -2,7 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { createSocket } from "node:dgram"; import { createSocket } from "node:dgram";
import { documentPayloadBytes } from "@gamecult/cultcache-ts"; import { documentPayloadBytes } from "@gamecult/cultcache-ts";
import { decodeWireValue } from "cultnet-ts/wire"; import { decodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
CultNetDocumentRegistry, CultNetDocumentRegistry,
CultNetRudpSession, CultNetRudpSession,
@ -10,10 +10,11 @@ import {
encodeRudpPacket, encodeRudpPacket,
type CultNetOperationRequestMessage, type CultNetOperationRequestMessage,
type CultNetRudpPacket, type CultNetRudpPacket,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import { import {
CultMesh, CultMesh,
CultMeshGrantAllWrites,
CultMeshProviderRudpTransport, CultMeshProviderRudpTransport,
CultMeshProviderSessionBroker, CultMeshProviderSessionBroker,
CULTMESH_PROVIDER_SESSION_SERVICE_ID, CULTMESH_PROVIDER_SESSION_SERVICE_ID,
@ -64,6 +65,7 @@ test("RUDP provider transport requires broker acceptance for the full lifecycle"
}, },
}); });
const server = CultMesh.createRudpDocumentServer("odin-test", 0x43554c54, { const server = CultMesh.createRudpDocumentServer("odin-test", 0x43554c54, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0, bindPort: 0,
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
onOperationRequest: (request, session) => broker.handle(request, session), onOperationRequest: (request, session) => broker.handle(request, session),
@ -256,6 +258,7 @@ test("a replaced RUDP generation drops operations queued behind an active handle
let handlerCalls = 0; let handlerCalls = 0;
let closedSessions = 0; let closedSessions = 0;
const server = CultMesh.createRudpDocumentServer("odin-queue-test", connectionId, { const server = CultMesh.createRudpDocumentServer("odin-queue-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0, bindPort: 0,
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
onOperationRequest: async request => { onOperationRequest: async request => {
@ -284,18 +287,21 @@ test("a replaced RUDP generation drops operations queued behind an active handle
runtimeId: identity.serviceInstanceId, runtimeId: identity.serviceInstanceId,
connectionId, connectionId,
sessionToken: "signed-provider-token", sessionToken: "signed-provider-token",
operationTimeoutMs: 100, operationTimeoutMs: 1, // expires long before the test ends: the settle-by-timeout path is always exercised
socketFactory: () => socket, socketFactory: () => socket,
}).connect(identity, new AbortController().signal); }).connect(identity, new AbortController().signal);
try { try {
// The handler is held open and the closed generation never answers, so these two settle only by the
// client's operation timeout or by connection.close(). Observe them from the start: whichever fires
// first is a legitimate end of the call, and this test asserts on server-side handler calls, not on it.
const first = connection.register( const first = connection.register(
{ identity, requestedLeaseDurationMs: 10_000 }, { identity, requestedLeaseDurationMs: 10_000 },
new AbortController().signal, new AbortController().signal,
); ).then(() => undefined, () => undefined);
const second = connection.register( const second = connection.register(
{ identity, requestedLeaseDurationMs: 10_000 }, { identity, requestedLeaseDurationMs: 10_000 },
new AbortController().signal, new AbortController().signal,
); ).then(() => undefined, () => undefined);
await waitFor(() => handlerCalls === 1, "first queued provider operation"); await waitFor(() => handlerCalls === 1, "first queued provider operation");
const replacement = new CultNetRudpSession({ connectionId }); const replacement = new CultNetRudpSession({ connectionId });
@ -315,7 +321,7 @@ test("a replaced RUDP generation drops operations queued behind an active handle
assert.equal(handlerCalls, 1, "transport-queued work from the closed generation must be dropped"); assert.equal(handlerCalls, 1, "transport-queued work from the closed generation must be dropped");
connection.close(); connection.close();
await Promise.allSettled([first, second]); await Promise.all([first, second]);
} finally { } finally {
connection.close(); connection.close();
server.close(); server.close();
@ -326,6 +332,7 @@ test("a client restarted on the same address with the same Connect payload repla
const connectionId = 0x43554c54; const connectionId = 0x43554c54;
let closedSessions = 0; let closedSessions = 0;
const server = CultMesh.createRudpDocumentServer("odin-restart-test", connectionId, { const server = CultMesh.createRudpDocumentServer("odin-restart-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0, bindPort: 0,
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
onSessionClosed: () => { closedSessions += 1; }, onSessionClosed: () => { closedSessions += 1; },
@ -364,6 +371,7 @@ test("a client restarted on the same address with the same Connect payload repla
test("the RUDP document server does not acknowledge by name a reliable packet its session did not receive", async () => { test("the RUDP document server does not acknowledge by name a reliable packet its session did not receive", async () => {
const connectionId = 0x43554c55; const connectionId = 0x43554c55;
const server = CultMesh.createRudpDocumentServer("odin-ack-test", connectionId, { const server = CultMesh.createRudpDocumentServer("odin-ack-test", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
bindPort: 0, bindPort: 0,
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
onError: () => undefined, onError: () => undefined,

View file

@ -2,7 +2,7 @@ import test from "node:test";
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { documentPayloadBytes, documentPayloadFromBytes, encodeDocumentPayload, type DocumentPayload } from "@gamecult/cultcache-ts"; import { documentPayloadBytes, documentPayloadFromBytes, encodeDocumentPayload, type DocumentPayload } from "@gamecult/cultcache-ts";
import { encodeWireValue } from "cultnet-ts/wire"; import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
cultMeshProviderSessionSchemas, cultMeshProviderSessionSchemas,

View file

@ -21,8 +21,8 @@ import {
type CultMeshAuthorityRouteView, type CultMeshAuthorityRouteView,
type CultMeshAuthorityTrustPolicy, type CultMeshAuthorityTrustPolicy,
type CultMeshP256PublicKey, type CultMeshP256PublicKey,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import type { CultMeshAuthorityRouteMessage, CultMeshVerseDescriptorMessage } from "cultnet-ts/contracts"; import type { CultMeshAuthorityRouteMessage, CultMeshVerseDescriptorMessage } from "@gamecult/cultnet-ts/contracts";
import { import {
CultMeshQuicNativeRuntime, CultMeshQuicNativeRuntime,

View file

@ -14,8 +14,8 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import test from "node:test"; import test from "node:test";
import type { CultMeshAuthorityTrustPolicy } from "cultnet-ts"; import type { CultMeshAuthorityTrustPolicy } from "@gamecult/cultnet-ts";
import type { CultMeshAuthorityRouteMessage, CultMeshVerseDescriptorMessage } from "cultnet-ts/contracts"; import type { CultMeshAuthorityRouteMessage, CultMeshVerseDescriptorMessage } from "@gamecult/cultnet-ts/contracts";
import { import {
CultMeshQuicRealtimeSessionManager, CultMeshQuicRealtimeSessionManager,

View file

@ -0,0 +1,685 @@
// A peer's put or delete is applied only when the server's write authority grants it. Ports the behaviours of
// cultmesh-py test_remote_write_authority.py (no forwarding: this server does not forward non-primary writes).
import assert from "node:assert/strict";
import { createSocket, type Socket } from "node:dgram";
import { readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { z } from "zod";
import { documentPayloadFromBytes, defineDocumentType } from "@gamecult/cultcache-ts";
import { decodeRudpPacket } from "@gamecult/cultnet-ts";
import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import {
CultNetDocumentRegistry,
CultNetPeer,
cultNetWriteNotAuthorizedError,
defineCultNetDocumentBinding,
type CultNetMessage,
} from "@gamecult/cultnet-ts";
import {
CultMesh,
CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES,
CultMeshGrantAllWrites,
type CultMeshRemoteWriteAuthority,
type CultMeshRemoteWriteDecision,
type CultMeshRemoteWriteRequest,
type CultMeshRudpDocumentDelete,
type CultMeshRudpDocumentPut,
} from "../src/index";
const SCHEMA_ID = "cultmesh.authority_note.v0";
const ALIAS = "runtime.generated.authority-note.ui.42";
const KEY_A = "tests:authority:a";
const KEY_B = "tests:authority:b";
const note = defineDocumentType({
type: "cultmesh.authority_note",
schemaId: SCHEMA_ID,
compatibleSchemaIds: [ALIAS],
schema: z.object({ noteId: z.string(), text: z.string() }),
name: "noteId",
});
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
function put(recordKey: string, extra: Record<string, unknown> = {}, schemaId = SCHEMA_ID, payload?: Uint8Array) {
return {
schemaVersion: "cultnet.document_put_raw.v0" as const,
messageId: `put-${recordKey}`,
document: {
schemaId,
recordKey,
storedAt: "2026-11-07T00:00:00Z",
payloadEncoding: "messagepack" as const,
payload: documentPayloadFromBytes(payload ?? encodeWireValue({ noteId: recordKey, text: "peer" })),
},
...extra,
} as CultNetMessage;
}
function del(recordKey: string, schemaId = SCHEMA_ID): CultNetMessage {
return { schemaVersion: "cultnet.document_delete.v0", messageId: `delete-${recordKey}`, schemaId, recordKey };
}
class Recording implements CultMeshRemoteWriteAuthority {
readonly requests: CultMeshRemoteWriteRequest[] = [];
constructor(private readonly answer: (request: CultMeshRemoteWriteRequest) => unknown) {}
decide(request: CultMeshRemoteWriteRequest): CultMeshRemoteWriteDecision | Promise<CultMeshRemoteWriteDecision> {
this.requests.push(request);
return this.answer(request) as CultMeshRemoteWriteDecision | Promise<CultMeshRemoteWriteDecision>;
}
}
const grant = () => ({ granted: true });
interface Rig {
puts: CultMeshRudpDocumentPut[];
deletes: CultMeshRudpDocumentDelete[];
errors: Error[];
replies: CultNetMessage[];
peer: CultNetPeer;
settle(): Promise<unknown>;
close(): void;
}
let nextConnection = 0x10204000;
async function rig(writeAuthority?: CultMeshRemoteWriteAuthority, extra: { maxPayloadBytes?: number; writeAuthorityTimeoutMs?: number } = {}): Promise<Rig> {
const connectionId = nextConnection++;
const puts: CultMeshRudpDocumentPut[] = [];
const deletes: CultMeshRudpDocumentDelete[] = [];
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer("authority-server", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority,
bindHost: "127.0.0.1",
bindPort: 0,
resendDelayMs: 25,
resendPollMs: 5,
onDocumentPutRaw: (document) => { puts.push(document); },
onDocumentDeleteRaw: (request) => { deletes.push(request); },
onError: (error) => errors.push(error),
...extra,
});
await server.start();
const peer: CultNetPeer = await CultMesh.createRudpPeer("authority-peer", connectionId, `rudp://127.0.0.1:${server.bind.port}`, {
resendDelayMs: 25,
resendPollMs: 5,
connectTimeoutMs: 2_000,
});
const replies: CultNetMessage[] = [];
peer.on("message", (message) => replies.push(message));
return {
puts, deletes, errors, replies, peer,
// A refusal is a reply; a grant sends none, so settle on a quiet period after the last send.
settle: () => sleep(250),
close: () => { peer.close(); server.close(); },
};
}
async function using(r: Rig, body: (r: Rig) => Promise<unknown>): Promise<void> {
try { await body(r); } finally { r.close(); }
}
function assertRefused(reply: CultNetMessage | undefined, key: string, error?: string): void {
assert.ok(reply && reply.schemaVersion === "cultnet.error.v0");
assert.equal(reply.code, "write_not_authorized");
assert.ok(reply.error.startsWith("write_not_authorized"));
assert.deepEqual(reply.details, { field: "recordKey", value: key, asOf: null, current: null });
if (error !== undefined) assert.equal(reply.error, error);
}
test("with no authority a peer's put and delete are refused and the handlers never run", async () => {
await using(await rig(undefined), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
r.peer.send(put(KEY_B));
await r.settle();
assert.equal(r.replies.length, 3);
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assertRefused(r.replies[2], KEY_B);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
assert.deepEqual(r.errors, []);
});
});
test("a granted put and delete reach their handlers, send nothing back, and the authority saw this peer", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assert.deepEqual(r.replies, []);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A]);
assert.deepEqual(r.deletes.map((d) => d.recordKey), [KEY_A]);
assert.equal(authority.requests.length, 2);
for (const request of authority.requests) {
assert.equal(request.peer.address, "127.0.0.1");
assert.ok(request.peer.port > 0);
assert.equal(request.schemaId, SCHEMA_ID, "a granted write was judged under the canonical schema id");
}
assert.deepEqual(authority.requests[1]!.peer, r.deletes[0]!.remote, "the delete handler sees the peer the authority was asked about");
});
});
test("the request carries the resolved write, and scoped grants refuse their neighbours", async () => {
const authority = new Recording((request) =>
request.operation === "put" && request.recordKey === KEY_A ? { granted: true } : { granted: false, reason: "scoped" });
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A, { shardId: "authority-shard", shardEpoch: 1 }, ALIAS));
await r.settle();
const request = authority.requests[0]!;
assert.equal(request.schemaId, SCHEMA_ID, "the authority sees the canonical id, not the alias as sent");
assert.equal(request.operation, "put");
assert.equal(request.recordKey, KEY_A);
assert.equal(request.shardId, "authority-shard");
assert.equal(request.shardEpoch, 1);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A]);
r.peer.send(put(KEY_B));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_B, "write_not_authorized: scoped");
assertRefused(r.replies[1], KEY_A, "write_not_authorized: scoped");
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A], "a grant scoped to key a refuses key b");
assert.deepEqual(r.deletes, [], "a grant scoped to put refuses delete");
assert.equal(authority.requests.at(-1)!.operation, "delete");
assert.equal(authority.requests.at(-1)!.schemaId, SCHEMA_ID);
assert.equal(authority.requests.at(-1)!.shardId, null);
});
});
test("a delete sent under a schema alias asks the authority with the canonical id", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(del(KEY_A, ALIAS));
await r.settle();
assert.equal(authority.requests[0]!.schemaId, SCHEMA_ID);
assert.equal(r.deletes.length, 1);
});
});
test("refusal precedes every other judgment of the put", async () => {
await using(await rig(undefined, { maxPayloadBytes: 256 }), async (r) => {
r.peer.send(put("unrelated:authority", {}, "sha256:nobody-owns-this"));
r.peer.send(put(KEY_A, {}, SCHEMA_ID, new Uint8Array(20_000)));
await r.settle();
assertRefused(r.replies[0], "unrelated:authority");
assertRefused(r.replies[1], KEY_A);
assert.deepEqual(r.errors, [], "the gate ran before the put was sized or resolved");
assert.equal(r.puts.length, 0);
});
const granting = new Recording(grant);
await using(await rig(granting, { maxPayloadBytes: 256 }), async (r) => {
r.peer.send(put(KEY_A, {}, SCHEMA_ID, new Uint8Array(20_000)));
await r.settle();
assert.equal(r.replies[0]?.schemaVersion, "cultnet.error.v0");
assert.notEqual((r.replies[0] as { code?: string }).code, "write_not_authorized", "a granted put still meets the size judgment");
assert.equal(r.errors.length, 1);
});
});
test("an authority that throws or rejects refuses, fails closed, and is reported without being quoted", async () => {
for (const decide of [
() => { throw new Error("authority exploded"); },
() => Promise.reject(new Error("authority exploded")),
]) {
await using(await rig(new Recording(decide)), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
assert.equal(r.errors.length, 2);
assert.ok(r.errors.every((e) => e.message.includes("Error") && !e.message.includes("exploded")));
});
}
});
test("an authority that never settles refuses after the timeout and does not block the frames behind it", async () => {
// The first put hangs forever; later frames from the same session must still be judged.
const authority = new Recording((request) => request.recordKey === KEY_A ? new Promise(() => {}) : { granted: true });
await using(await rig(authority, { writeAuthorityTimeoutMs: 100 }), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(put(KEY_B));
await sleep(600);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_B], "the granted put behind the hung one was applied");
assert.equal(r.replies.length, 1);
assertRefused(r.replies[0], KEY_A);
assert.equal((r.replies[0] as { error: string }).error.includes("timed out"), true);
assert.equal(r.errors.length, 1);
assert.ok(r.errors[0]!.message.includes("did not answer within 100 ms"));
});
});
test("an authority that settles GRANTED after the timeout is still refused and the write never reaches the handler", async () => {
const authority = new Recording((request) => request.recordKey === KEY_A
? new Promise((resolve) => setTimeout(() => resolve({ granted: true }), 300))
: { granted: true });
await using(await rig(authority, { writeAuthorityTimeoutMs: 100 }), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await sleep(700);
assert.equal(r.replies.length, 2, "one refusal per frame, no late second reply");
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0], "the late grant never reached the handler");
});
});
test("a write authority timeout that is not a usable timer delay is refused at construction", () => {
for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY, 2 ** 31]) {
assert.throws(() => CultMesh.createRudpDocumentServer("authority-server", 1, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
bindHost: "127.0.0.1",
bindPort: 0,
writeAuthorityTimeoutMs: bad,
}), RangeError, String(bad));
}
});
test("a refusal with no reason still says why, and a missing decision refuses", async () => {
await using(await rig(new Recording(() => ({ granted: false }))), async (r) => {
r.peer.send(put(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A, "write_not_authorized");
});
for (const answer of [null, undefined, {}, { granted: "yes" }, { granted: 1 }]) {
await using(await rig(new Recording(() => answer)), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assertRefused(r.replies[0], KEY_A);
assertRefused(r.replies[1], KEY_A);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0]);
});
}
});
test("the refusal on the wire is the pinned error-vectors bytes", async () => {
const vectors = JSON.parse(readFileSync(join(__dirname, "../../../../contracts/cultnet/interop/error-vectors.json"), "utf8")).vectors;
const vector = vectors.find((v: { name: string }) => v.name === "write_not_authorized");
const expected = Buffer.from(vector.messagePackHex, "hex");
assert.deepEqual(Buffer.from(encodeWireValue(cultNetWriteNotAuthorizedError("some:key", "not granted"))), expected);
await using(await rig(new Recording(() => ({ granted: false, reason: "not granted" }))), async (r) => {
r.peer.send(put("some:key"));
await r.settle();
assert.deepEqual(Buffer.from(encodeWireValue(r.replies[0])), expected);
});
});
test("wrong-typed shard fields on a put are judged with null shard fields, then refused as malformed once granted", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
const bad: Record<string, unknown>[] = [
{ shardId: { not: "a string" } }, { shardId: 5 }, { shardEpoch: "7" }, { shardEpoch: true }, { shardEpoch: 1.5 },
];
for (const fields of bad) r.peer.send(put(KEY_A, fields));
await r.settle();
assert.equal(r.replies.length, bad.length);
assert.deepEqual(
r.replies.map((reply) => reply.schemaVersion === "cultnet.error.v0" ? [reply.code, reply.details?.field] : reply),
["shardId", "shardId", "shardEpoch", "shardEpoch", "shardEpoch"].map((field) => ["message_invalid", field]),
);
assert.equal(authority.requests.length, bad.length, "the authority is asked first");
assert.ok(authority.requests.every((q) => q.shardId === null && q.shardEpoch === null), "with null shard fields");
assert.equal(r.puts.length, 0);
});
await using(await rig(undefined), async (r) => {
r.peer.send(put(KEY_A, { shardId: 5 }));
await r.settle();
assertRefused(r.replies[0], KEY_A);
});
});
test("a refusal fits maxPayloadBytes however long the record key and reason are", async () => {
const longKey = "k".repeat(3_000) + "é";
await using(await rig(new Recording(() => ({ granted: false, reason: "r".repeat(100_000) })), { maxPayloadBytes: 1024 }), async (r) => {
r.peer.send(put(longKey));
r.peer.send(del(longKey));
await r.settle();
assert.equal(r.replies.length, 2);
for (const reply of r.replies) {
assert.equal((reply as { code?: string }).code, "write_not_authorized");
assert.ok(encodeWireValue(reply).byteLength <= 1024);
assert.ok(longKey.startsWith((reply as { details: { value: string } }).details.value));
}
assert.deepEqual(r.errors, []);
});
});
test("well-typed shard fields reach the authority as sent", async () => {
const authority = new Recording(grant);
await using(await rig(authority), async (r) => {
r.peer.send(put(KEY_A, { shardId: "authority-shard", shardEpoch: 1 }));
await r.settle();
assert.deepEqual([authority.requests[0]!.shardId, authority.requests[0]!.shardEpoch], ["authority-shard", 1]);
});
});
test("grant-all is an explicit choice that grants every write", async () => {
await using(await rig(new CultMeshGrantAllWrites()), async (r) => {
r.peer.send(put(KEY_A));
r.peer.send(del(KEY_A));
await r.settle();
assert.deepEqual([r.puts.length, r.deletes.length, r.replies.length], [1, 1, 0]);
});
});
test("a granted delete with no delete handler is answered with a text refusal", async () => {
const connectionId = nextConnection++;
const server = CultMesh.createRudpDocumentServer("no-delete", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority: new CultMeshGrantAllWrites(),
bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
});
await server.start();
const peer = await CultMesh.createRudpPeer("p", connectionId, `rudp://127.0.0.1:${server.bind.port}`, { resendDelayMs: 25, resendPollMs: 5, connectTimeoutMs: 2_000 });
const replies: CultNetMessage[] = [];
peer.on("message", (m) => replies.push(m));
try {
peer.send(del(KEY_A));
await sleep(250);
assert.equal(replies.length, 1);
assert.notEqual((replies[0] as { code?: string }).code, "write_not_authorized");
} finally { peer.close(); server.close(); }
});
// Hostile frames, sent as raw bytes the typed peer would never build.
const bin = (n: number, ...tail: number[]) => [0xc6, (n >>> 24) & 255, (n >>> 16) & 255, (n >>> 8) & 255, n & 255, ...tail]; // bin32 header
const str = (t: string) => [0xa0 | t.length, ...Buffer.from(t)];
function rawPut(payloadBytes: number[], key = KEY_A): Uint8Array {
// {schemaVersion, messageId, document: {schemaId, recordKey, storedAt, payloadEncoding, payload: <payloadBytes>}}
return Uint8Array.from([
0x83, ...str("schemaVersion"), ...str("cultnet.document_put_raw.v0"), ...str("messageId"), ...str("raw"),
...str("document"), 0x85, ...str("schemaId"), ...str(SCHEMA_ID), ...str("recordKey"), ...str(key),
...str("storedAt"), ...str("2026-11-07T00:00:00Z"), ...str("payloadEncoding"), ...str("messagepack"),
...str("payload"), ...payloadBytes,
]);
}
async function rawRig(writeAuthority?: CultMeshRemoteWriteAuthority) {
const connectionId = nextConnection++;
const puts: CultMeshRudpDocumentPut[] = [];
const deletes: CultMeshRudpDocumentDelete[] = [];
const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer("authority-raw", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority, bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onDocumentPutRaw: (d) => { puts.push(d); }, onDocumentDeleteRaw: (d) => { deletes.push(d); }, onError: (e) => errors.push(e),
});
await server.start();
const client = await CultMesh.createRudpClient("raw", connectionId, `rudp://127.0.0.1:${server.bind.port}`, { resendDelayMs: 25, resendPollMs: 5 });
client.connect();
const started = Date.now();
while (!client.connected) {
if (Date.now() - started > 2_000) throw new Error("not connected");
await sleep(5);
}
const replies: CultNetMessage[] = [];
new CultNetPeer(client, { wireContract: "cultnet.schema.v0" }).on("message", (m) => replies.push(m));
return { puts, deletes, errors, replies, send: (b: Uint8Array) => client.send("schema", b), close: () => { client.close(); server.close(); } };
}
const float64 = (v: number) => { const b = Buffer.alloc(9); b[0] = 0xcb; b.writeDoubleBE(v, 1); return [...b]; };
// Each hostile frame, the operation it is judged as, and the ids the authority is told (empty when the frame does not carry them).
const hostile: { name: string; frame: Uint8Array; operation: "put" | "delete"; schemaId: string; recordKey: string }[] = [
{ name: "an int payload", frame: rawPut([0x2a]), operation: "put", schemaId: SCHEMA_ID, recordKey: KEY_A },
{ name: "a uint64-max integer payload", frame: rawPut([0xcf, 255, 255, 255, 255, 255, 255, 255, 255]), operation: "put", schemaId: SCHEMA_ID, recordKey: KEY_A },
{ name: "a float64 2**70 payload", frame: rawPut(float64(2 ** 70)), operation: "put", schemaId: SCHEMA_ID, recordKey: KEY_A },
{ name: "a bin whose claimed length exceeds the frame", frame: rawPut(bin(1_000_000_000, 1, 2, 3)), operation: "put", schemaId: "", recordKey: "" },
{ name: "a frame that does not decode at all", frame: Uint8Array.from([0xc1]), operation: "put", schemaId: "", recordKey: "" },
{ name: "a put whose document is not a map", frame: Uint8Array.from([0x82, ...str("schemaVersion"), ...str("cultnet.document_put_raw.v0"), ...str("document"), 0x05]), operation: "put", schemaId: "", recordKey: "" },
{ name: "a delete whose recordKey is not a string", frame: Uint8Array.from([0x84, ...str("schemaVersion"), ...str("cultnet.document_delete.v0"), ...str("messageId"), ...str("d"), ...str("schemaId"), ...str(SCHEMA_ID), ...str("recordKey"), 0x07]), operation: "delete", schemaId: SCHEMA_ID, recordKey: "" },
];
/** Records the size of every buffer a frame makes the process allocate, so a transient allocation is seen after it is freed. */
function watchAllocations(): { largest: () => number; stop: () => void } {
let largest = 0;
const note = (n: unknown) => { if (typeof n === "number" && n > largest) largest = n; };
const originals = { alloc: Buffer.alloc, unsafe: Buffer.allocUnsafe, slow: Buffer.allocUnsafeSlow, u8: globalThis.Uint8Array, ab: globalThis.ArrayBuffer };
Buffer.alloc = ((n: number, ...rest: never[]) => { note(n); return originals.alloc.call(Buffer, n, ...rest); }) as typeof Buffer.alloc;
Buffer.allocUnsafe = ((n: number) => { note(n); return originals.unsafe.call(Buffer, n); }) as typeof Buffer.allocUnsafe;
Buffer.allocUnsafeSlow = ((n: number) => { note(n); return originals.slow.call(Buffer, n); }) as typeof Buffer.allocUnsafeSlow;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const watched = (ctor: any): any => new Proxy(ctor, { construct: (target, args, newTarget) => { note(args[0]); return Reflect.construct(target, args, newTarget); } });
(globalThis as { Uint8Array: unknown }).Uint8Array = watched(originals.u8);
(globalThis as { ArrayBuffer: unknown }).ArrayBuffer = watched(originals.ab);
return {
largest: () => largest,
stop: () => {
Buffer.alloc = originals.alloc; Buffer.allocUnsafe = originals.unsafe; Buffer.allocUnsafeSlow = originals.slow;
(globalThis as { Uint8Array: unknown }).Uint8Array = originals.u8;
(globalThis as { ArrayBuffer: unknown }).ArrayBuffer = originals.ab;
},
};
}
test("an ungranted peer's unreadable write is refused with write_not_authorized naming what it carried, and nothing is allocated for it", async () => {
for (const h of hostile) {
const authority = new Recording(() => ({ granted: false }));
for (const withAuthority of [false, true]) {
const r = await rawRig(withAuthority ? authority : undefined);
const watch = watchAllocations();
try {
r.send(h.frame);
await sleep(250);
} finally { watch.stop(); }
try {
assert.equal(r.replies.length, 1, h.name);
assertRefused(r.replies[0], h.recordKey);
assert.ok(watch.largest() < 10_000_000, `${h.name}: allocated ${watch.largest()} bytes`);
assert.deepEqual([r.puts.length, r.deletes.length, r.errors.length], [0, 0, 0], h.name);
} finally { r.close(); }
}
assert.equal(authority.requests.length, 1, h.name);
assert.deepEqual(
[authority.requests[0]!.operation, authority.requests[0]!.schemaId, authority.requests[0]!.recordKey],
[h.operation, h.schemaId, h.recordKey], h.name);
}
});
test("the allocation watch sees a transient allocation", () => {
const watch = watchAllocations();
try { void Buffer.alloc(20_000_000); } finally { watch.stop(); }
assert.ok(watch.largest() >= 20_000_000);
const typed = watchAllocations();
try { void new Uint8Array(20_000_000); } finally { typed.stop(); }
assert.ok(typed.largest() >= 20_000_000);
});
test("a granted peer's unreadable write reaches onError and gets a malformed refusal, and no handler runs", async () => {
for (const h of hostile) {
const authority = new Recording(grant);
const r = await rawRig(authority);
try {
r.send(h.frame);
await sleep(250);
assert.equal(r.replies.length, 1, h.name);
const reply = r.replies[0] as { code: unknown; error: string; details: { field: string } };
assert.equal(reply.code, "message_invalid", h.name);
assert.equal(reply.details.field, "message", h.name);
assert.equal(r.errors.length, 1, h.name);
assert.deepEqual([r.puts.length, r.deletes.length], [0, 0], h.name);
assert.deepEqual([authority.requests.length, authority.requests[0]!.operation, authority.requests[0]!.recordKey], [1, h.operation, h.recordKey], h.name);
} finally { r.close(); }
}
});
const CAP = 8; // the cap every runtime shares; the exported constant must stay this number
test("the consecutive-refused-frames cap is the number every runtime shares", () => {
assert.equal(CULTMESH_RUDP_DOCUMENT_SERVER_MAX_CONSECUTIVE_REFUSED_FRAMES, CAP);
});
test("unreadable frames are answered and the session kept until eight in a row; any decoded frame resets the run", async () => {
const r = await rawRig(new Recording(grant));
try {
const batch = async (frames: number) => {
for (let i = 0; i < frames; i++) r.send(Uint8Array.from([0xc1]));
await sleep(400);
};
await batch(CAP - 1);
assert.equal(r.replies.length, CAP - 1, "each is answered");
r.send(encodeWireValue(put(KEY_A)));
await sleep(250);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A], "the session was kept through seven");
await batch(CAP - 1);
assert.equal(r.replies.length, 2 * (CAP - 1), "the valid frame reset the run");
r.send(Uint8Array.from([0xc1]));
await sleep(300);
assert.equal(r.replies.length, 2 * (CAP - 1) + 1, "the eighth consecutive one is answered too");
assert.ok(r.replies.every((reply) => (reply as { code?: string }).code === "message_invalid"));
// The goodbye reached the peer: its client no longer takes a send.
assert.throws(() => r.send(encodeWireValue(put(KEY_B))), /before the session is connected/, "then the session ended");
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A]);
} finally { r.close(); }
});
test("deletes the authority refuses are answered and the session kept until eight in a row; any other decoded frame resets the run", async () => {
const authority = new Recording((request) => request.recordKey === KEY_B ? { granted: true } : { granted: false });
await using(await rig(authority), async (r) => {
const refuse = async (deletes: number) => {
for (let i = 0; i < deletes; i++) r.peer.send(del(KEY_A));
await sleep(400);
};
await refuse(CAP - 1);
assert.equal(r.replies.length, CAP - 1);
r.peer.send(del(KEY_B)); // granted: resets the run
await sleep(250);
assert.deepEqual(r.deletes.map((d) => d.recordKey), [KEY_B]);
await refuse(CAP - 1);
assert.equal(r.replies.length, 2 * (CAP - 1));
r.peer.send(put(KEY_B)); // a decoded non-delete resets too
await sleep(250);
await refuse(CAP - 1);
assert.equal(r.replies.length, 3 * (CAP - 1), "a put reset the run");
r.peer.send(del(KEY_A));
await sleep(300);
assert.equal(r.replies.length, 3 * (CAP - 1) + 1, "the eighth consecutive refused delete is answered too");
for (const reply of r.replies) assertRefused(reply, KEY_A);
assert.throws(() => r.peer.send(del(KEY_B)), /before the session is connected/, "then the session ended");
assert.equal(r.deletes.length, 1);
});
});
test("a frame that decodes but is no message the parser takes is answered, counted, and ended at eight in a row like any unreadable frame", async () => {
const r = await rawRig(new Recording(grant));
const unknown = () => encodeWireValue({ schemaVersion: "cultnet.not-a-message.v0", messageId: "x" });
try {
const batch = async (frames: number) => {
for (let i = 0; i < frames; i++) r.send(unknown());
await sleep(400);
};
await batch(CAP - 1);
assert.equal(r.replies.length, CAP - 1, "each is answered");
assert.equal(r.errors.length, CAP - 1, "and reported");
r.send(encodeWireValue(put(KEY_A)));
await sleep(250);
assert.deepEqual(r.puts.map((p) => p.recordKey), [KEY_A], "the session was kept through seven");
await batch(CAP - 1);
assert.equal(r.replies.length, 2 * (CAP - 1), "the decoded put reset the run");
r.send(unknown());
await sleep(300);
assert.equal(r.replies.length, 2 * (CAP - 1) + 1, "the eighth is answered too");
for (const reply of r.replies) {
assert.equal((reply as { code?: string }).code, "message_invalid");
assert.equal((reply as { details: { field: string } }).details.field, "message");
}
assert.throws(() => r.send(unknown()), /before the session is connected/, "then the session ended");
} finally { r.close(); }
});
/** A UDP relay between a client and a server that drops the first (or, with `dropEvery`, every) server datagram carrying `payloadContains` once armed. */
async function lossyRelay(serverPort: number, payloadContains: string, dropEvery = false) {
const dropped: unknown[] = [];
let armed = false;
let clientAddress: { port: number; address: string } | undefined;
const toClient: Socket = createSocket("udp4");
const toServer: Socket = createSocket("udp4");
toServer.on("message", (wire) => {
if (!clientAddress) return;
if (armed && (dropEvery || dropped.length === 0)) {
const packet = decodeRudpPacket(wire);
if (packet.packetType === "data" && Buffer.from(packet.payload ?? []).includes(payloadContains)) {
dropped.push(packet);
return;
}
}
toClient.send(wire, clientAddress.port, clientAddress.address);
});
toClient.on("message", (wire, remote) => {
clientAddress = remote;
toServer.send(wire, serverPort, "127.0.0.1");
});
await new Promise<void>((resolve) => toClient.bind(0, "127.0.0.1", resolve));
await new Promise<void>((resolve) => toServer.bind(0, "127.0.0.1", resolve));
return {
port: toClient.address().port,
dropped,
arm: () => { armed = true; },
close: () => { toClient.close(); toServer.close(); },
};
}
async function cappedOverRelay(dropEvery: boolean, body: (x: { relay: Awaited<ReturnType<typeof lossyRelay>>; client: { send(channel: string, payload: Uint8Array): void }; replies: CultNetMessage[] }) => Promise<void>) {
const connectionId = nextConnection++;
const server = CultMesh.createRudpDocumentServer("authority-lossy", connectionId, {
documents: new CultNetDocumentRegistry([defineCultNetDocumentBinding({ definition: note })]),
writeAuthority: new Recording(grant), bindHost: "127.0.0.1", bindPort: 0, resendDelayMs: 25, resendPollMs: 5,
onDocumentPutRaw: () => {}, onError: () => {},
});
await server.start();
const relay = await lossyRelay(server.bind.port, "message_invalid", dropEvery);
const client = await CultMesh.createRudpClient("lossy", connectionId, `rudp://127.0.0.1:${relay.port}`, { resendDelayMs: 25, resendPollMs: 5 });
try {
client.connect();
const started = Date.now();
while (!client.connected) {
if (Date.now() - started > 2_000) throw new Error("not connected");
await sleep(5);
}
const replies: CultNetMessage[] = [];
new CultNetPeer(client, { wireContract: "cultnet.schema.v0" }).on("message", (m) => replies.push(m));
for (let i = 0; i < CAP - 1; i++) client.send("schema", Uint8Array.from([0xc1]));
await sleep(300);
assert.equal(replies.length, CAP - 1);
relay.arm();
client.send("schema", Uint8Array.from([0xc1]));
await body({ relay, client, replies });
} finally { client.close(); server.close(); relay.close(); }
}
test("the capped frame's answer is resent when its datagram is lost, and the goodbye follows only after it arrived", async () => {
await cappedOverRelay(false, async ({ relay, client, replies }) => {
await sleep(600);
assert.equal(relay.dropped.length, 1, "fixture: the first transmission of the last answer was lost");
assert.equal(replies.length, CAP, "the lost answer was resent and arrived");
assert.equal((replies[CAP - 1] as { code?: string }).code, "message_invalid");
assert.throws(() => client.send("schema", Uint8Array.from([0xc1])), /before the session is connected/, "then the session ended");
});
});
test("a capped session whose answer is never acknowledged still ends, after the grace", async () => {
await cappedOverRelay(true, async ({ client, replies }) => {
await sleep(1200);
assert.equal(replies.length, CAP - 1, "fixture: the last answer never arrives");
client.send("schema", Uint8Array.from([0xc1])); // still connected: the server is waiting for the acknowledgement
await sleep(1500);
assert.throws(() => client.send("schema", Uint8Array.from([0xc1])), /before the session is connected/, "the grace ran out and the goodbye went out");
});
});
test("nothing behind the capped frame is served while its answer is delivered", async () => {
const r = await rawRig(new Recording(grant));
try {
for (let i = 0; i < CAP; i++) r.send(Uint8Array.from([0xc1]));
r.send(encodeWireValue(put(KEY_A)));
await sleep(500);
assert.equal(r.replies.length, CAP);
assert.deepEqual(r.puts, [], "the put behind the cap was not served");
} finally { r.close(); }
});

View file

@ -6,15 +6,15 @@ import assert from "node:assert/strict";
import { createSocket, type RemoteInfo, type Socket } from "node:dgram"; import { createSocket, type RemoteInfo, type Socket } from "node:dgram";
import test from "node:test"; import test from "node:test";
import { documentPayloadFromBytes } from "@gamecult/cultcache-ts"; import { documentPayloadFromBytes } from "@gamecult/cultcache-ts";
import { encodeWireValue } from "cultnet-ts/wire"; import { encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { import {
CultNetDocumentRegistry, CultNetDocumentRegistry,
CultNetRudpSession, CultNetRudpSession,
decodeRudpPacket, decodeRudpPacket,
encodeRudpPacket, encodeRudpPacket,
type CultNetPeer, type CultNetPeer,
} from "cultnet-ts"; } from "@gamecult/cultnet-ts";
import { CultMesh } from "../src/index"; import { CultMesh, CultMeshGrantAllWrites } from "../src/index";
async function waitFor(predicate: () => boolean, description: string): Promise<void> { async function waitFor(predicate: () => boolean, description: string): Promise<void> {
const startedAt = Date.now(); const startedAt = Date.now();
@ -64,6 +64,7 @@ async function startServer(connectionId: number, socket: Socket): Promise<Server
const closed: number[] = []; const closed: number[] = [];
const errors: Error[] = []; const errors: Error[] = [];
const server = CultMesh.createRudpDocumentServer("send-failure-server", connectionId, { const server = CultMesh.createRudpDocumentServer("send-failure-server", connectionId, {
writeAuthority: new CultMeshGrantAllWrites(),
documents: new CultNetDocumentRegistry(), documents: new CultNetDocumentRegistry(),
socket, socket,
bindHost: "127.0.0.1", bindHost: "127.0.0.1",

View file

@ -0,0 +1,243 @@
// Client side of contracts/cultnet/interop/write-receipt.md in the one-shot writer: with `writeReceipts` the put
// completes only on a write_admitted carrying its id; a refusal, a silent window and a legacy server each end as the
// spec says. Each test serves the client a fake RUDP peer that acknowledges the put and answers as scripted.
import assert from "node:assert/strict";
import { createSocket, type Socket } from "node:dgram";
import test from "node:test";
import { z } from "zod";
import { defineDocumentType } from "@gamecult/cultcache-ts";
import {
CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS,
CultNetRudpSession,
decodeRudpPacket,
defineCultNetDocumentBinding,
encodeCultNetMessageForWire,
encodeRudpPacket,
type CultNetMessage,
} from "@gamecult/cultnet-ts";
import { decodeWireValue, encodeWireValue } from "@gamecult/cultnet-ts/wire";
import { CultMesh, CultMeshRudpWriteRefusedError, CultMeshRudpWriteUnconfirmedError } from "../src/index";
const note = defineDocumentType({
type: "cultmesh.receipt_note",
schemaId: "cultmesh.receipt_note.v0",
schema: z.object({ noteId: z.string(), text: z.string() }),
name: "noteId",
});
const binding = defineCultNetDocumentBinding({ definition: note });
let nextConnection = 0x10206000;
interface Script {
/** Does the server's hello list both receipt frames? */
advertise: boolean;
/** What the server answers a put with, `delayMs` after it arrives. */
answer: "admit" | "refuse" | "wrong-id" | "silence" | "goodbye" | "echo";
delayMs?: number;
/** Acknowledge the reliable packets it receives? Default true. */
ack?: boolean;
}
async function fakeServer(connectionId: number, script: Script) {
const socket: Socket = createSocket("udp4");
await new Promise<void>((resolve) => socket.bind(0, "127.0.0.1", resolve));
const session = new CultNetRudpSession({ connectionId, resendDelayMs: 50 });
const timers = new Set<NodeJS.Timeout>();
const seen: string[] = [];
let closed = false;
const send = (packet: Parameters<typeof encodeRudpPacket>[0], port: number, address: string) => {
if (!closed) socket.send(encodeRudpPacket(packet), port, address);
};
const say = (message: CultNetMessage, port: number, address: string) => {
const packets = session.sendMany("schema", encodeWireValue(encodeCultNetMessageForWire(message)), { reliable: true, ordered: true, nowMs: Date.now() });
packets.forEach((p) => send(p, port, address));
};
socket.on("message", (wire, remote) => {
const packet = decodeRudpPacket(wire);
const now = Date.now();
if (packet.packetType === "connect") {
send(session.acceptConnect(packet, now), remote.port, remote.address);
return;
}
const result = session.receive(packet, now);
if (result.reply) send(result.reply, remote.port, remote.address);
for (const frame of result.delivered) {
if (frame.channelId !== "schema") continue;
const message = decodeWireValue(frame.payload) as { schemaVersion: string; messageId?: string };
seen.push(message.schemaVersion);
if (message.schemaVersion === "cultnet.hello.v0") {
say({
schemaVersion: "cultnet.hello.v0", runtimeId: "fake", runtimeKind: "fake",
...(script.advertise ? { supportedMessageVersions: [...CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS] } : {}),
}, remote.port, remote.address);
continue;
}
if (message.schemaVersion !== "cultnet.document_put_raw.v0" || script.answer === "silence") continue;
const timer = setTimeout(() => {
timers.delete(timer);
if (script.answer === "echo") {
say({ schemaVersion: "cultnet.document_put_raw.v0", messageId: message.messageId!, document: { schemaId: "cultmesh.receipt_note.v0", recordKey: "tests:receipt:a", storedAt: "t", payloadEncoding: "messagepack", payload: new Uint8Array([1]) } } as unknown as CultNetMessage, remote.port, remote.address);
} else if (script.answer === "goodbye") {
send(session.endUnsendableSession(new Error("scripted goodbye")), remote.port, remote.address);
} else if (script.answer === "refuse") {
say({ schemaVersion: "cultnet.error.v1", error: "write_not_authorized", routingHint: null, code: "write_not_authorized", details: null, messageId: message.messageId! }, remote.port, remote.address);
} else {
const messageId = script.answer === "wrong-id" ? "someone-else" : message.messageId!;
say({ schemaVersion: "cultnet.write_admitted.v0", messageId, operation: "put", schemaId: "cultmesh.receipt_note.v0", recordKey: "tests:receipt:a" }, remote.port, remote.address);
}
}, script.delayMs ?? 20);
timers.add(timer);
}
if (packet.reliable && script.ack !== false) send(session.createAckForReceived(packet.sequence), remote.port, remote.address);
});
return { endpoint: `rudp://127.0.0.1:${socket.address().port}`, seen, close: () => { closed = true; timers.forEach(clearTimeout); socket.close(); } };
}
const transport = { resendDelayMs: 50, resendPollMs: 5, flushTimeoutMs: 2_000 };
const publish = (server: { endpoint: string }, options: Record<string, unknown>) =>
CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: "a", text: "x" }, { ...transport, ...options });
test("a receipt-capable server's write_admitted completes the put, past the legacy 500 ms window", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "admit", delayMs: 700 });
try {
await publish(server, { writeReceipts: true });
assert.deepEqual(server.seen.slice(0, 2), ["cultnet.hello.v0", "cultnet.document_put_raw.v0"]);
} finally { server.close(); }
});
test("a receipt-capable server's error.v1 refuses the put with its code", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "refuse" });
try {
await assert.rejects(publish(server, { writeReceipts: true }), (error: unknown) =>
error instanceof CultMeshRudpWriteRefusedError && error.code === "write_not_authorized" && error.response.schemaVersion === "cultnet.error.v1");
} finally { server.close(); }
});
test("a receipt-capable server that stays silent leaves the put unconfirmed, never published", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "silence" });
try {
await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 250 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed");
} finally { server.close(); }
});
test("a receipt for another id settles nothing", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "wrong-id" });
try {
await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 250 }), CultMeshRudpWriteUnconfirmedError);
} finally { server.close(); }
});
test("a server whose hello does not advertise leaves a silent put unconfirmed after the 500 ms window, never published", async () => {
const server = await fakeServer(nextConnection, { advertise: false, answer: "silence" });
const started = Date.now();
try {
await assert.rejects(publish(server, { writeReceipts: true }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed");
assert.ok(Date.now() - started >= 500, "the legacy window ran from the send");
} finally { server.close(); }
});
test("a session that ends before any result leaves the put unconfirmed (session_ended), against a legacy server too", async () => {
for (const advertise of [false, true]) {
const server = await fakeServer(nextConnection, { advertise, answer: "goodbye" });
try {
await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 3_000 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "session_ended");
} finally { server.close(); }
}
});
test("a put whose send is never acknowledged is unconfirmed as local_send_failed, not an untyped error", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false });
const started = Date.now();
try {
await assert.rejects(publish(server, { writeReceipts: true, flushTimeoutMs: 300 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed");
assert.ok(Date.now() - started < 2_500, "flushTimeoutMs bounds the send inside the 5 s window");
} finally { server.close(); }
});
test("the flush is bounded by the result window: a send nobody acknowledges is local_send_failed at the window, not at the flush timeout", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false });
const started = Date.now();
try {
await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 300, flushTimeoutMs: 20_000 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed");
assert.ok(Date.now() - started < 3_000, "it did not wait out the 20 s flush timeout");
} finally { server.close(); }
});
test("a server that does not advertise receipts and echoes the put's id back has not admitted it", async () => {
const server = await fakeServer(nextConnection, { advertise: false, answer: "echo" });
try {
await assert.rejects(publish(server, { writeReceipts: true, resultWindowMs: 300 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "window_elapsed");
} finally { server.close(); }
});
test("a silent server never yields admitted, in either mode: the default is unconfirmed, sendOnly is the distinct outcome sent", async () => {
const dflt = await fakeServer(nextConnection, { advertise: false, answer: "silence" });
try {
await assert.rejects(publish(dflt, { resultWindowMs: 200 }), CultMeshRudpWriteUnconfirmedError);
} finally { dflt.close(); }
const sendOnly = await fakeServer(nextConnection, { advertise: false, answer: "silence" });
try {
const outcome = await publish(sendOnly, { sendOnly: true });
assert.equal(outcome, "sent");
assert.notEqual(outcome, "admitted");
assert.deepEqual(sendOnly.seen, ["cultnet.document_put_raw.v0"], "sendOnly sends no hello");
} finally { sendOnly.close(); }
});
test("only a write_admitted resolves admitted, and sendOnly does not wait for or act on an answer", async () => {
const admitting = await fakeServer(nextConnection, { advertise: true, answer: "admit" });
try {
assert.equal(await publish(admitting, { writeReceipts: true }), "admitted");
} finally { admitting.close(); }
const refusing = await fakeServer(nextConnection, { advertise: true, answer: "refuse", delayMs: 1 });
try {
assert.equal(await publish(refusing, { sendOnly: true }), "sent", "a refusal is not awaited: sendOnly says only that the put was sent");
} finally { refusing.close(); }
});
test("sendOnly fails local_send_failed when the send is never acknowledged", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "silence", ack: false });
try {
await assert.rejects(publish(server, { sendOnly: true, flushTimeoutMs: 300 }), (error: unknown) =>
error instanceof CultMeshRudpWriteUnconfirmedError && error.reason === "local_send_failed");
} finally { server.close(); }
});
test("sendOnly keeps the cause of a put that cannot be built: it is not reported as local_send_failed", async () => {
const server = await fakeServer(nextConnection, { advertise: false, answer: "silence" });
try {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: 1 } as unknown as { noteId: string; text: string }, { ...transport, sendOnly: true }),
(error: unknown) => !(error instanceof CultMeshRudpWriteUnconfirmedError) && error instanceof Error,
);
assert.deepEqual(server.seen, [], "nothing was sent");
} finally { server.close(); }
});
test("the receipt path keeps the cause of a put that cannot be built: it is not reported as local_send_failed", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "admit" });
try {
await assert.rejects(
CultMesh.publishRudpDocumentOnce("receipt-client", nextConnection++, server.endpoint, binding, "tests:receipt:a", { noteId: 1 } as unknown as { noteId: string; text: string }, { ...transport, writeReceipts: true }),
(error: unknown) => !(error instanceof CultMeshRudpWriteUnconfirmedError) && error instanceof Error,
);
assert.ok(!server.seen.includes("cultnet.document_put_raw.v0"), "no put was sent");
} finally { server.close(); }
});
test("sendOnly cannot be combined with writeReceipts", async () => {
await assert.rejects(publish({ endpoint: "rudp://127.0.0.1:9" }, { sendOnly: true, writeReceipts: true }), TypeError);
});
test("without writeReceipts no hello is sent and the receipt frames are never asked for", async () => {
const server = await fakeServer(nextConnection, { advertise: true, answer: "silence" });
try {
await assert.rejects(publish(server, { resultWindowMs: 100 }), CultMeshRudpWriteUnconfirmedError);
assert.deepEqual(server.seen, ["cultnet.document_put_raw.v0"]);
} finally { server.close(); }
});

View file

@ -2,6 +2,8 @@
## Unreleased (breaking; version 0.x, so the next minor) ## Unreleased (breaking; version 0.x, so the next minor)
- Decodes the write receipt frames of `contracts/cultnet/interop/write-receipt.md`: `parse_message` validates `cultnet.write_admitted.v0` and `cultnet.error.v1` against their closed schemas (unknown keys, empty or non-string ids, an unknown operation or code are refused; `error.v1` requires `messageId`, string or null; `limit_reached` is `error.v1` only). Added `CULTNET_ERROR_V1_CODES`, `CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS`, `write_content_hash` and `hello_advertises_write_receipts`; `hello` takes `supported_message_versions`. `tests/test_write_receipt.py` replays the vectors' `contentHash`, `wire` and `schemaInvalid` sections. Not implemented here: the client write tracker (`scenarios`) and the server rules (`dedupe`, `blankFields`); this package has no receipt server and no write client.
- Added `message_invalid` to `CULTNET_ERROR_CODES` and `message_invalid_error(field, reason)`, byte-identical to the C# `ForMessageInvalid`. `cultmesh-py` refuses a malformed put or delete with it instead of the out-of-schema `malformed_document_put` and `malformed_document_delete`, which are removed.
- Added `CultNetRudpSocketTransportServer` (`cultnet_py.rudp_server`): one UDP socket serving many RUDP peers, one session per - Added `CultNetRudpSocketTransportServer` (`cultnet_py.rudp_server`): one UDP socket serving many RUDP peers, one session per
remote endpoint, ported from the C# `CultNetRudpSocketTransportServer` and held to its bytes by remote endpoint, ported from the C# `CultNetRudpSocketTransportServer` and held to its bytes by
`tests/vectors/rudp-multipeer-server/transcript.txt`. The caller drives it (`try_receive_once`, `poll_resends`). Like the C# `tests/vectors/rudp-multipeer-server/transcript.txt`. The caller drives it (`try_receive_once`, `poll_resends`). Like the C#

View file

@ -8,7 +8,7 @@ wire contracts that both a node and a bare peer have to agree on.
It depends on `cultcache-py` and `msgpack`; AES-GCM helpers on `CultNetSecret` It depends on `cultcache-py` and `msgpack`; AES-GCM helpers on `CultNetSecret`
light up with the optional `crypto` extra. `cultmesh-py` builds on it. The light up with the optional `crypto` extra. `cultmesh-py` builds on it. The
layering mirrors `cultnet-rs` and `cultnet-ts`. layering mirrors `cultnet-rs` and `@gamecult/cultnet-ts`.
## Example ## Example

View file

@ -39,6 +39,8 @@ from .cultmesh_contracts import (
from .framing import decode_frame, encode_frame, read_frame, write_frame from .framing import decode_frame, encode_frame, read_frame, write_frame
from .messages import ( from .messages import (
CULTNET_ERROR_CODES, CULTNET_ERROR_CODES,
CULTNET_ERROR_V1_CODES,
CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS,
CultNetMessage, CultNetMessage,
CultNetWitnessArtifactBundle, CultNetWitnessArtifactBundle,
compute_simulation_claim_hash, compute_simulation_claim_hash,
@ -49,8 +51,11 @@ from .messages import (
document_put_raw, document_put_raw,
encode_witness_artifact_bundle_payload, encode_witness_artifact_bundle_payload,
error_message, error_message,
message_invalid_error,
unsupported_schema_version_error, unsupported_schema_version_error,
write_content_hash,
hello, hello,
hello_advertises_write_receipts,
login, login,
login_success, login_success,
parse_message, parse_message,
@ -175,6 +180,8 @@ __all__ = [
"verse_catalog_request", "verse_catalog_request",
"verse_from_wire", "verse_from_wire",
"CULTNET_ERROR_CODES", "CULTNET_ERROR_CODES",
"CULTNET_ERROR_V1_CODES",
"CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS",
"CultNetMessage", "CultNetMessage",
"CultNetWitnessArtifactBundle", "CultNetWitnessArtifactBundle",
"CultNetDatabaseSubscription", "CultNetDatabaseSubscription",
@ -262,8 +269,11 @@ __all__ = [
"encode_frame", "encode_frame",
"encode_rudp_packet", "encode_rudp_packet",
"error_message", "error_message",
"message_invalid_error",
"unsupported_schema_version_error", "unsupported_schema_version_error",
"hello", "hello",
"hello_advertises_write_receipts",
"write_content_hash",
"INTEROP_WIRE_CONTRACT", "INTEROP_WIRE_CONTRACT",
"login", "login",
"login_success", "login_success",

View file

@ -58,6 +58,7 @@ class CultNetRawClient:
create_transport: CultNetSchemaTransportFactory | None = None create_transport: CultNetSchemaTransportFactory | None = None
def send(self, message: CultNetMessage | dict[str, Any]) -> None: def send(self, message: CultNetMessage | dict[str, Any]) -> None:
"""Fire-and-forget: an ack or a return is not admission; read the result frame."""
wire = message.to_wire() if isinstance(message, CultNetMessage) else message wire = message.to_wire() if isinstance(message, CultNetMessage) else message
with self.open_transport() as transport: with self.open_transport() as transport:
transport.send("schema", msgpack.packb(wire, use_bin_type=True)) transport.send("schema", msgpack.packb(wire, use_bin_type=True))
@ -319,6 +320,7 @@ class CultNetDatabaseSubscription:
self._transport = None self._transport = None
def send(self, message: CultNetMessage | dict[str, Any]) -> None: def send(self, message: CultNetMessage | dict[str, Any]) -> None:
"""Fire-and-forget: an ack or a return is not admission; read the result frame."""
if self._transport is None: if self._transport is None:
raise RuntimeError("CultNet database subscription is not open") raise RuntimeError("CultNet database subscription is not open")
wire = message.to_wire() if isinstance(message, CultNetMessage) else message wire = message.to_wire() if isinstance(message, CultNetMessage) else message

View file

@ -6,6 +6,8 @@ from typing import Any
import msgpack import msgpack
from .unicode_messageid_tables import DEFAULT_IGNORABLE, LETTER_OR_NUMBER
@dataclass(frozen=True) @dataclass(frozen=True)
class CultNetMessage: class CultNetMessage:
@ -29,7 +31,11 @@ def parse_message(payload: bytes) -> CultNetMessage:
body = dict(decoded) body = dict(decoded)
del body["schemaVersion"] del body["schemaVersion"]
if schema_version == "cultnet.error.v0": if schema_version == "cultnet.error.v0":
_validate_error_body(body) _validate_error_body(body, "cultnet.error.v0", CULTNET_ERROR_CODES)
elif schema_version == "cultnet.error.v1":
_validate_error_body(body, "cultnet.error.v1", CULTNET_ERROR_V1_CODES)
elif schema_version == "cultnet.write_admitted.v0":
_validate_write_admitted_body(body)
return CultNetMessage(schema_version=schema_version, body=body) return CultNetMessage(schema_version=schema_version, body=body)
@ -44,8 +50,16 @@ CULTNET_ERROR_CODES: tuple[str, ...] = (
"unowned_schema", "unowned_schema",
"write_not_authorized", "write_not_authorized",
"unsupported_schema_version", "unsupported_schema_version",
"message_invalid",
) )
# cultnet.error.v1 (contracts/cultnet/interop/cultnet.error.v1.schema.json): v0's codes plus limit_reached.
CULTNET_ERROR_V1_CODES: tuple[str, ...] = (*CULTNET_ERROR_CODES, "limit_reached")
# The two frames a receipt-capable hello lists in supportedMessageVersions; a peer lists both or neither
# (contracts/cultnet/interop/write-receipt.md, "Capability: opting in").
CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS: tuple[str, ...] = ("cultnet.write_admitted.v0", "cultnet.error.v1")
_ERROR_DETAILS_KEYS = ("field", "value", "asOf", "current") _ERROR_DETAILS_KEYS = ("field", "value", "asOf", "current")
@ -53,16 +67,80 @@ def _is_uint(value: Any) -> bool:
return isinstance(value, int) and not isinstance(value, bool) and value >= 0 return isinstance(value, int) and not isinstance(value, bool) and value >= 0
def _validate_error_body(body: dict[str, Any]) -> None: def _is_name(value: Any) -> bool:
"""Refuse a cultnet.error.v0 body that is not the full-key shape the schema requires.""" return isinstance(value, str) and value != ""
expected = ("error", "routingHint", "code", "details")
# write-receipt.md: a letter (Lu Ll Lt Lm Lo) or number (Nd Nl No) somewhere, no Default_Ignorable code point anywhere, as of
# Unicode 16.0, compared raw (never stripped). The tables are embedded (unicode_messageid_tables.py, generated by
# scripts/gen-unicode-messageid-tables.py), not unicodedata's, so the running Python's Unicode version changes no result;
# the other four runtimes embed the same generated tables.
def _in_ranges(ranges: tuple[int, ...], point: int) -> bool:
"""Whether [point] lies in the flattened, sorted (low, high) pairs."""
low, high = 0, len(ranges) // 2 - 1
while low <= high:
mid = (low + high) // 2
if point < ranges[2 * mid]:
high = mid - 1
elif point > ranges[2 * mid + 1]:
low = mid + 1
else:
return True
return False
def _is_admitted_message_id(value: Any) -> bool:
if not isinstance(value, str):
return False
has_letter_or_number = False
for ch in value:
point = ord(ch)
if _in_ranges(DEFAULT_IGNORABLE, point):
return False
has_letter_or_number = has_letter_or_number or _in_ranges(LETTER_OR_NUMBER, point)
return has_letter_or_number
def _validate_write_admitted_body(body: dict[str, Any]) -> None:
"""Refuse a cultnet.write_admitted.v0 body that is not exactly the five keys of its closed schema."""
expected = ("messageId", "operation", "schemaId", "recordKey")
if set(body) != set(expected): if set(body) != set(expected):
raise ValueError(f"cultnet.error.v0 must carry exactly {list(expected)}, got {sorted(body)}") raise ValueError(f"cultnet.write_admitted.v0 must carry exactly {list(expected)}, got {sorted(body)}")
for key in ("messageId", "schemaId", "recordKey"):
if not _is_name(body[key]):
raise ValueError(f"cultnet.write_admitted.v0 {key} must be a non-empty string")
if not _is_admitted_message_id(body["messageId"]):
raise ValueError("cultnet.write_admitted.v0 messageId must contain a letter or number and no Default_Ignorable code point")
if body["operation"] not in ("put", "delete"):
raise ValueError("cultnet.write_admitted.v0 operation must be put or delete")
def write_content_hash(operation: str, schema_id: str, record_key: str, payload: bytes | None) -> bytes:
"""SHA-256 of the MessagePack array [operation, schemaId, recordKey, payload] (write-receipt.md, rule 5).
payload is the raw document payload, packed as a MessagePack bin for a put and nil for a delete.
"""
return hashlib.sha256(msgpack.packb([operation, schema_id, record_key, payload], use_bin_type=True)).digest()
def hello_advertises_write_receipts(hello_message: CultNetMessage) -> bool:
"""True when a hello lists both receipt frames: the only thing that makes a connection receipt-capable."""
listed = hello_message.body.get("supportedMessageVersions")
return isinstance(listed, list) and all(version in listed for version in CULTNET_WRITE_RECEIPT_MESSAGE_VERSIONS)
def _validate_error_body(body: dict[str, Any], version: str, codes: tuple[str, ...]) -> None:
"""Refuse a cultnet.error body that is not the full-key shape its closed schema requires."""
expected = ("error", "routingHint", "code", "details") + (("messageId",) if version == "cultnet.error.v1" else ())
if set(body) != set(expected):
raise ValueError(f"{version} must carry exactly {list(expected)}, got {sorted(body)}")
if not isinstance(body["error"], str) or not body["error"]: if not isinstance(body["error"], str) or not body["error"]:
raise ValueError("cultnet.error.v0 error must be a non-empty string") raise ValueError(f"{version} error must be a non-empty string")
code = body["code"] code = body["code"]
if code is not None and (not isinstance(code, str) or code not in CULTNET_ERROR_CODES): if code is not None and (not isinstance(code, str) or code not in codes):
raise ValueError(f"cultnet.error.v0 code {code!r} is not a recognized refusal code") raise ValueError(f"{version} code {code!r} is not a recognized refusal code")
if "messageId" in body and body["messageId"] is not None and not _is_name(body["messageId"]):
raise ValueError(f"{version} messageId must be a non-empty string or null")
hint = body["routingHint"] hint = body["routingHint"]
if hint is not None: if hint is not None:
if ( if (
@ -71,17 +149,17 @@ def _validate_error_body(body: dict[str, Any]) -> None:
or not isinstance(hint["reason"], str) or not isinstance(hint["reason"], str)
or not (hint["shard"] is None or isinstance(hint["shard"], dict)) or not (hint["shard"] is None or isinstance(hint["shard"], dict))
): ):
raise ValueError("cultnet.error.v0 routingHint must be null or {shard, reason}") raise ValueError(f"{version} routingHint must be null or {{shard, reason}}")
details = body["details"] details = body["details"]
if details is not None: if details is not None:
if not isinstance(details, dict) or set(details) != set(_ERROR_DETAILS_KEYS): if not isinstance(details, dict) or set(details) != set(_ERROR_DETAILS_KEYS):
raise ValueError(f"cultnet.error.v0 details must be null or carry exactly {list(_ERROR_DETAILS_KEYS)}") raise ValueError(f"{version} details must be null or carry exactly {list(_ERROR_DETAILS_KEYS)}")
for key in ("field", "value"): for key in ("field", "value"):
if details[key] is not None and not isinstance(details[key], str): if details[key] is not None and not isinstance(details[key], str):
raise ValueError(f"cultnet.error.v0 details.{key} must be a string or null") raise ValueError(f"{version} details.{key} must be a string or null")
for key in ("asOf", "current"): for key in ("asOf", "current"):
if details[key] is not None and not _is_uint(details[key]): if details[key] is not None and not _is_uint(details[key]):
raise ValueError(f"cultnet.error.v0 details.{key} must be a non-negative integer or null") raise ValueError(f"{version} details.{key} must be a non-negative integer or null")
def hello( def hello(
@ -91,17 +169,18 @@ def hello(
supported_schema_versions: list[str] | None = None, supported_schema_versions: list[str] | None = None,
supported_mutation_contracts: list[dict[str, Any]] | None = None, supported_mutation_contracts: list[dict[str, Any]] | None = None,
transport_profiles: list[dict[str, Any]] | None = None, transport_profiles: list[dict[str, Any]] | None = None,
supported_message_versions: list[str] | None = None,
) -> CultNetMessage: ) -> CultNetMessage:
return CultNetMessage( body: dict[str, Any] = {
"cultnet.hello.v0",
{
"runtimeId": runtime_id, "runtimeId": runtime_id,
"supportedWireContracts": supported_wire_contracts or ["cultnet.schema.v0"], "supportedWireContracts": supported_wire_contracts or ["cultnet.schema.v0"],
"supportedSchemaVersions": supported_schema_versions or [], "supportedSchemaVersions": supported_schema_versions or [],
"supportedMutationContracts": supported_mutation_contracts or [], "supportedMutationContracts": supported_mutation_contracts or [],
"transportProfiles": transport_profiles or [], "transportProfiles": transport_profiles or [],
}, }
) if supported_message_versions is not None:
body["supportedMessageVersions"] = supported_message_versions
return CultNetMessage("cultnet.hello.v0", body)
def login( def login(
@ -171,7 +250,7 @@ def error_message(
} }
if details is not None and set(details) - set(_ERROR_DETAILS_KEYS): if details is not None and set(details) - set(_ERROR_DETAILS_KEYS):
raise ValueError(f"cultnet.error.v0 details has unknown keys {sorted(set(details) - set(_ERROR_DETAILS_KEYS))}") raise ValueError(f"cultnet.error.v0 details has unknown keys {sorted(set(details) - set(_ERROR_DETAILS_KEYS))}")
_validate_error_body(body) _validate_error_body(body, "cultnet.error.v0", CULTNET_ERROR_CODES)
return CultNetMessage("cultnet.error.v0", body) return CultNetMessage("cultnet.error.v0", body)
@ -185,6 +264,11 @@ def unsupported_schema_version_error(schema_version: Any) -> CultNetMessage:
) )
def message_invalid_error(field: str, reason: str) -> CultNetMessage:
"""The refusal for a request that lacks a required field or carries an ill-typed one (C# ForMessageInvalid)."""
return error_message(f"message_invalid: {reason}", code="message_invalid", details={"field": field})
def login_success( def login_success(
*, *,
nonce: str, nonce: str,

View file

@ -22,6 +22,7 @@ CULTNET_ERROR_CODES = (
"unowned_schema", "unowned_schema",
"write_not_authorized", "write_not_authorized",
"unsupported_schema_version", "unsupported_schema_version",
"message_invalid",
) )
WIRE_MESSAGE_SCHEMA_VERSIONS = ( WIRE_MESSAGE_SCHEMA_VERSIONS = (

View file

@ -1256,6 +1256,7 @@ class CultNetRudpSocketTransportConnection:
self._send_packet(self.session.create_connect(_now_ms(), payload)) self._send_packet(self.session.create_connect(_now_ms(), payload))
def send(self, channel_id: str, payload: bytes) -> None: def send(self, channel_id: str, payload: bytes) -> None:
"""Fire-and-forget: an ack or a return is not admission; read the result frame."""
packets = self.session.send_many( packets = self.session.send_many(
channel_id, channel_id,
payload, payload,
@ -1567,6 +1568,7 @@ class TcpFramedTransportConnection:
) )
def send(self, channel_id: str, payload: bytes) -> None: def send(self, channel_id: str, payload: bytes) -> None:
"""Fire-and-forget: an ack or a return is not admission; read the result frame."""
if channel_id != "schema": if channel_id != "schema":
raise ValueError(f"tcp_framed transport only supports the schema channel, got {channel_id!r}") raise ValueError(f"tcp_framed transport only supports the schema channel, got {channel_id!r}")
before = len(payload) + 4 before = len(payload) + 4

Some files were not shown because too many files have changed in this diff Show more