# Plan: bounded processing units and prompt termination This plan addresses the ten findings from the processing-unit audit. Each item states the symptom, the change, the files, the test, and the acceptance condition. Items appear in batch order, not numeric order; the batch table in section 1 maps them. Nothing here changes `pkg/wire`, so no client-visible protocol behaviour changes. The two visible differences are faster shutdown and, under broadcast overload only, dropped live deliveries with a logged count (item 7). ## 0. The invariant `docs/ARCHITECTURE.md` section 2 already states it: "Closing it wakes every domain: the acceptor's poll and the reader/writer deadlines return within 200 ms, the network loop within its 2 ms tick". Those numbers are currently not true. The rule this plan enforces is the one that claim was reaching for: > Every domain loop checks the breaker at the top of the loop, performs at most > one bounded unit of work, and returns to a wait that includes the breaker. Bounded means: a fixed number of messages, bytes, records or fsyncs, chosen so the worst case between two breaker checks is well under 250 ms. A select that is only reachable when the system is idle does not satisfy this. The enforcement mechanism is uniformity, a structural test, and a latency test. - The top-of-loop check is `ch.Stop.Closed()`, which already exists (`pkg/tinyspawn/tinyspawn.go:106`) and is a non-blocking select. No new API, just the same one line at the top of every domain loop, as `io/reader.go:26` already does. - Reachability is checked at the source level by `pkg/relay/invariant_test.go`: for each domain entry point, the first statement of the loop must be an `if ...Closed()` guard or a select whose first case is the breaker. This is a lint in test form, and it is the only deterministic way to check the property. A timing test cannot: a full inbound channel is drained within the pass that observes it, so no client-side rate can force a domain to starve. Two attempts at such a test passed with the check deleted. - Per-unit-shape latency tests in `pkg/relay` and `pkg/domain/net` (section 11) bound the damage when a check is present but a unit is too large. ## 1. Batches | Batch | Items | Reason for the order | |---|---|---| | B0 | 10, plus the shutdown test harness | The tests depend on `Close` reporting which domains hung. Without it a regression is invisible. | | B1 | 1, 2, 6, 7 | Largest starvation win per line changed, all inside one domain. | | B2 | 8, 5 | I/O waits first, then the blob units that sit on top of them. | | B3 | 3, 4 | Store changes are the only ones that can corrupt data; they go last, after the harness exists. | | B4 | 9 | Deletions; can happen any time after B2 because the tests reference `ReadRequest`, not `Server`. | Each batch is a separate commit series and ends with `make test && make e2e`. Batches B1 through B4 are independent of each other except B2 before B4. ## 2. Item 10 - shutdown failure must be visible Symptom: `Tree.Close` counts stopped domains into a variable that is never read (`pkg/relay/tree.go:189`, `:197`), so a domain that ignores the breaker for the full five second deadline is silently abandoned, and `Exited` cannot say which domain died. Change: - `Tree.done` becomes `[]domainRef{name string; ch <-chan struct{}}`. `add` keeps the name it currently discards. - `Close() []string` returns the names that did not stop in time. Each is logged at error level as `domain %s did not stop within 5s`. The return value is the test hook; production callers may ignore it. - `Exited() (string, bool)` returns the name of the first domain whose lifecycle channel is closed. `cmd/torly/main.go` logs the name instead of the current "a relay domain exited". - Keep the 200 ms ticker in `main` rather than a fan-in select: a real fan-in needs either `reflect.Select` (absent in TinyGo) or one forwarder goroutine per domain, and unstructured goroutines are what this tree exists to avoid. State that reason in a comment so the next reader does not "fix" it. Files: `pkg/relay/tree.go`, `cmd/torly/main.go`. Test: `pkg/relay/shutdown_test.go::TestCloseNamesHungDomain`. Spawn a domain that ignores its breaker via `tinyspawn.Spawn`, assert `Close` returns its name. Done when: a hung domain produces one error line naming it, and the name is returned by `Close`. ## 3. Item 1 - the network loop must reach its wait Symptom: `pkg/domain/net/net.go:186-203` does work first and waits second, with `if worked { continue }`. Under any sustained inbound traffic the select at `:196` is never reached, so the net domain never observes `Stop`. This is the worst of the ten because it is the domain every connection depends on. Change, in this order: 1. Top-of-loop check: ```go for { if ch.Stop.Closed() { return } s.flush() s.flushOut() s.flushHTTP() var budget = netUnitBudget s.drain(&budget) s.dispatch() if budget < netUnitBudget { continue // made progress; the breaker was checked this iteration } s.wait() } ``` 2. `s.wait()` becomes a method that selects on the ticker, the ping ticker, the breaker, and `s.nextDeadline` (section 5). `pump` moves from the always-run path into the ticker branch: it is O(connections) and only matters when somebody is paced. 3. Make the 2 ms ticker adaptive. `pollInterval = 2 * time.Millisecond` means an idle relay wakes 500 times a second and runs four O(connections) passes each time. The tick exists to release paced delivery and retry queued frames, so it is only needed while something is queued: use 2 ms when `s.hasQueuedWork()` (any `outQ`, `outQueue`, `dbOut`, `blobOut`, `httpOut` non-empty), else 50 ms. Under no load and no queued work the loop blocks in `wait` on the breaker and the 50 ms tick: 20 wakeups a second instead of 500. Files: `pkg/domain/net/net.go`. Test: `TestTreeShutdownUnderLoad` (section 11), plus a unit test `TestIdleNetLoopBlocks` that starts the server with no connections and asserts the select is reached (instrument with a counter or a test hook, not a timer). Done when: shutdown under a sustained flood returns within 250 ms, and an idle relay wakes no more than ~25 times a second. ## 4. Item 2 - one work budget for a pass, not 32 per worker Symptom: `drain` caps each worker at 32 messages (`net.go:208`) and leaves the database and verify response loops unbounded (`:219`, `:229`), so a pass can be 32 x `ConnWorkers` JSON parses followed by every queued database response, each of which may carry `QueryLimit` events. Change: `drain(budget *int)`, where the budget is spent once per handled message and once per handled database, verify or blob response. Every inner loop is `for *budget > 0 { select { ... default: } }`. One constant, `netUnitBudget = 256`, documented as "the most messages one pass may parse before the breaker is checked again". Do not add a config knob: a number nobody measures is worse than a constant with a stated reason. Files: `pkg/domain/net/net.go`. Test: feed 10 000 messages into a worker channel, assert the domain returns to the breaker within one pass, and assert no message is dropped by comparing the count of dispatched responses. Done when: the number of messages parsed between two breaker checks is a constant, independent of channel depth. ## 5. Item 6 - query delivery is a resumable job Symptom: `handleDB` (`net.go:869-873`) sorts the result, then encodes and sends `QueryLimit` events in one stretch. At 500 events that is 500 `AppendJSON` calls and 500 sends without a check. Change: a `queryJob{conn *connState; sub string; events []nostr.Event; next int}` held on the server in `s.queries []*queryJob`. `handleDB` sorts once and appends the job; the main loop advances jobs by `queryChunk = 64` events per pass and sends `EOSE` and drops the job when `next == len(events)`. Re-check `conn.closed` per chunk: a client may close mid-delivery. Cap the number of concurrent jobs (say 64) and refuse a new query with `CLOSED` when at the cap, so a client cannot multiply memory by issuing subscriptions faster than delivery drains. Files: `pkg/domain/net/net.go`. Test: `TestQueryDeliveryYields`. Subscribe with a limit of 500, record the number of events delivered between two breaker checks on a hook, assert it is `queryChunk`, and assert all 500 arrive in order before `EOSE`. Done when: a 500 event response is delivered in more than one turn and the frame sequence is unchanged. ## 6. Item 7 - broadcast fan-out is chunked, and honestly bounded Symptom: `broadcast` (`net.go:915-930`) iterates every connection, every subscription and every filter for each accepted event, in one stretch. At 10 000 connections that is tens of thousands of match tests before the breaker is seen. Change: - Maintain `s.order []wire.ConnID` beside `s.conns`: append on open, swap-remove on close, so iteration has a resumable index. The map stays the lookup. - `broadcastJob{data []byte; next int; ev *nostr.Event}`; each pass walks `broadcastChunk = 256` entries of `s.order`. Jobs queue in a small slice, capped at 4; when full, drop the oldest job and log the count of skipped deliveries, because a dropped live event is better than unbounded memory and subscribers re-sync on reconnect anyway. - Encode the event JSON once per job, as today. State the limitation in the code comment: this fixes Stop latency and latency spikes, it does not fix throughput. The per-event cost stays O(connections x subscriptions x filters) on one thread. The throughput answer, if measurement demands it, is delivery shards (N domains each owning a slice of connections) and that is a separate design with its own memory cost per domain; do not pretend chunking solved it. Files: `pkg/domain/net/net.go`. Test: `TestBroadcastYields` with 1 000 synthetic connections, assert the breaker is observed mid-broadcast and that every connection receives exactly one copy. Done when: broadcast over 10 000 connections cannot delay termination by more than one chunk. ## 7. Item 8 - make the innermost socket wait breaker-aware Symptom: `fdConn.Read` and `fdConn.Write` loop through `waitFD`, which polls in 200 ms slices but never returns on a timeout (`pkg/domain/io/fdconn.go:120-150`). A timeout only refreshes the poll, so the enclosing `bufio.Reader` never sees control again until data arrives or the deadline expires. One correction to the original audit: a stalled reader is usually unblocked anyway, because its paired writer closes the shared fd on teardown. That is an accident of who owns the fd, not a guarantee. It fails exactly when the writer is itself blocked in a write, and then both waits run to their deadlines: with the check removed, `TestTreeShutdownWithBlockedWriter` takes 6.7 s and reports `[reader/1 writer/1]`, which is what the fix removes. Change, level 1 (minimum, ~15 lines): - `fdConn` gains `stop <-chan struct{}`, set at construction from `ch.Stop.Done()`. The acceptor already has the breaker when it accepts: `newFDConn(nfd, addr, ch.Stop.Done())`. - `waitFD(fd, events, deadline, stop)`: on each loop iteration, before polling, `select { case <-stop: return errStopped; default: }`. `errStopped` is a package-level sentinel; `Read`, `Write`, `ReadRequest`, `readWebSocket` and `writeAll` all treat any error as "close and return to the loop". - Delete the `select/default` poll at `reader.go:135`; it only checks a flag that arrived before the read, which the wait now covers. Change, level 2 (recommended, ~60 lines, eliminates the idle wakeups): - Add a shared self-pipe to the tree: `unix.Pipe2` wrapper in `pkg/unix`, a `tinyspawn.Breaker` variant that writes one byte to the write end when closed, and `waitFD` polling two fds. With that, `waitFD` can poll with an infinite timeout and wake instantly on the breaker: zero idle wakeups per connection and immediate cancellation. - Verify `syscall.Pipe2` links under TinyGo on linux/amd64 before committing to this. If it does not, stop at level 1 and record why in the code comment. Files: `pkg/domain/io/fdconn.go`, `pkg/domain/io/acceptor.go`, `pkg/domain/io/reader.go`, `pkg/domain/io/writer.go`, optionally `pkg/unix/unix.go` and `pkg/tinyspawn`. Test: `TestShutdownWithStalledClient`. Connect, send a request line and headers with a `Content-Length` that is never satisfied, then call `Tree.Close` and assert it returns within 400 ms (level 1) with the domain count complete. Done when: a stalled client cannot delay shutdown past one poll slice, and (deleted) `httpsrv.ReadRequest`'s five minute deadline is a client-facing bound rather than a shutdown bound. ## 8. Item 5 - blob work becomes stepwise Symptom: two units with no internal yield. `blob.checkRestore` (`pkg/domain/blob/blob.go:90-117`) hands a whole tar to `blossom.Restore`, which loops every entry. `blossom.handlePut` (`pkg/blossom/blossom.go:478-535`) hashes up to `BlossomMaxBlob` bytes in one `sha256Bytes` call, then writes and fsyncs. Change: a job type in `pkg/blossom`, owned by the blob domain: ```go // Job is one unit at a time of a long running blob operation. type Job interface { Step(budget int) (Response, bool, error) // response, done, error Cancel() } ``` - Restore job: holds the `tar.Reader`, the file and the entry map; steps one tar entry per call. The manifest read stays as step zero. The index append for an entry happens only after that entry's file is written and synced, so a stop mid-restore leaves no half-entry in the index. That is already true per entry in `restoreOne`; the job just makes the entry the unit. - Put job: holds the body (already in memory, owned by the blob domain), a `hash.Hash`, the destination file and an offset; steps 4 MiB of hashing plus one write per call. `Finish` compares the digest, fsyncs and appends the index record. - The blob domain keeps one job at a time in `s.job`, advances it by `blobStepBudget` (4 MiB) per pass, and re-enters the select between steps. Files: `pkg/blossom/blossom.go`, `pkg/blossom/backup.go`, `pkg/domain/blob/blob.go`. Test: `TestPutJobSteps` and `TestRestoreJobSteps` drive the jobs with a 1 KiB budget and assert that they take several steps, that a blob is not visible until its entry is complete, and that the stored bytes match. `TestRestoreJobRejectsBadDigest` asserts a corrupt entry leaves no file and no `.tmp`. A domain-level timing test cannot discriminate here: a test-sized upload finishes in a few hundred milliseconds whether it is stepwise or not, and the shutdown budget is five seconds. The domain half is covered by `TestDomainLoopsCheckTheBreaker` plus the one-step-per-turn loop; the job half is covered by counting steps. Done when: no blob operation holds the domain for more than one 4 MiB step. ## 9. Item 3 - split the save path from the fsync path Symptom: `db.Run` calls `handle` and cannot return to the select until it does (`pkg/domain/db/db.go:60`). Inside, every 256th `SaveEvent` (`pkg/store/engine.go:405-411`) runs `checkpointNow`, which fsyncs the WAL, `QuickFlush(true)`s every index file, then syncs the checkpoint (`engine.go:1088-1101`). That is roughly a dozen fsyncs on the one thread, in the middle of one client request. The `took > time.Second` warning at `db.go:61` exists because of it. Change, three parts: 1. Move the checkpoint off the request path. `SaveEvent` sets `e.syncPending = true` (or `e.saveN` reaches the threshold) and returns. `Engine` gains `SyncDue() bool` and `SyncStep() (bool, error)`: the db loop, on its own ticker, advances a checkpoint step when one is due. The durability window is unchanged (it is already "up to 256 saves"), but no client waits for it. 2. Make the checkpoint a step machine. `checkpointState{walSynced bool; fileIdx int; ckptSynced bool}`. One `SyncStep` call does: WAL `Sync` once, then one index `QuickFlush(true)` per file, then the final `ckpt.Set` plus `ckpt.Sync`. The checkpoint value is written only after every index is durable, which is the existing ordering requirement; preserve it and test it. 3. The domain drives the checkpoint between requests, one durable step per turn, and does not save while one is pending. That ordering is not optional: a save that lands after an index file is flushed and before the checkpoint record is written leaves an index entry in memory that the checkpoint would step over, and recovery would never rebuild it. The engine detects the interleaving with a save counter and restarts the run; `TestCheckpointInterruptedBySave` fails with one lost event when that guard is removed. Files: `pkg/store/engine.go`, `pkg/domain/db/db.go`. Risk: this is the only item that can lose data if the ordering is wrong. The mitigation is that the step machine must be provably equivalent to the current single call, and that is asserted by a crash test, not by reading the diff. Test: `TestCheckpointStepOrder` injects a failure after the WAL sync and after each index flush, then reopens the engine and asserts recovery replays from the old checkpoint and the data is present. `TestSaveNeverCheckpoints` asserts a single `SaveEvent` performs no `Sync` on the index files (instrument the store with a sync counter in a test build). Benchmark `BenchmarkSaveEventP99` before and after; the acceptance is that the p99 drops by the fsync cost and the throughput does not regress. Done when: no client request contains an fsync, the crash test passes at every step boundary, and a save's p99 is within one WAL write of the median. ## 10. Item 4 - bounded expiry purge Symptom: `PurgeExpired` (`pkg/store/engine.go:870-904`) scans every already expired record and tombstones each, with no cap. After a month of downtime the first tick is one enormous unit inside the db domain. Change: - `PurgeExpired(now int64, max int) (n int, more bool, err error)`. The scan stops after `max` records and `more` reports whether the range still had entries. - `db.Run` keeps `purgeActive bool`: a tick starts a purge; if it returned `more`, the following ticks continue it before starting anything else. `purgeBatch = 100` events. Log the drained count at info level once the backlog is empty. - This is the same shape as `ProcessGraphBacklog(1)` at `db.go:72`, which is already the right pattern in this codebase. Files: `pkg/store/engine.go`, `pkg/domain/db/db.go`. Test: `TestPurgeIsBounded` inserts 1 000 expired events, calls the purge with `max = 100`, asserts ten calls and `more` false on the last, and asserts every event is tombstoned. `TestPurgeContinuesAcrossTicks` asserts the db loop drains over ticks without blocking another request. Done when: expiry cost per turn is a constant and the backlog still drains. ## 11. Cross-cutting test harness `pkg/relay/shutdown_test.go`, package `relay` so it can import every domain: - `TestTreeShutdownIdle`: start a real tree on a temp dir and port 0, close, assert every lifecycle channel is closed within 150 ms. The floor is the acceptor's 50 ms poll slice, which is why `acceptPollSlice` was lowered from 200 ms in B0: it was the idle shutdown floor for the whole tree. - `TestTreeShutdownUnderLoad`: start, open 8 connections, write events as fast as the socket accepts without reading, run for 2 s, close, assert within 250 ms and that `Close` reports no hung domains. - `TestTreeShutdownWithStalledClient`: item 8's case, assert within 400 ms. - `TestTreeShutdownDuringQuery`: subscribe with a limit large enough to make delivery span turns, close mid-delivery, assert within 250 ms. These are the tests that make the invariant real. They must be in the default `make test` run, not behind a build tag. The last property is proved by `TestDomainLoopsCheckTheBreaker`, which was confirmed red with the check deleted from `net.Run` before B1 merged; the latency tests alone do not prove it. ## 12. Documentation to correct `docs/ARCHITECTURE.md` section 2 claims 200 ms for reader/writer deadlines and 2 ms for the network loop. Replace with the numbers the tests assert: 150 ms for an idle tree, 250 ms for any domain under load, 400 ms with a stalled client. Section 10 and section 13 may also need the tick change noted. Also add the invariant text from section 0 of this plan to the same section, so the rule and the claim live in the same place. ## 13. Measurement Before B1, record the baseline: `make size`, `cmd/torly-stress` throughput and p99, idle CPU over 60 s with no connections, and `TestTreeShutdown*` timings (which will fail before B0/B1). After each batch, repeat. The numbers that matter are shutdown latency under each of the four shapes, idle wakeups, save p99, and throughput at fixed connection count. No item is done because the diff looks right. Each is done when its named test fails before the change and passes after, and `make e2e` still passes. ## 14. Rejected options - **Per-connection delivery domains for item 7.** The real throughput fix, but it multiplies goroutine stacks by connection count and it is a memory decision, not a latency decision. Revisit only if the measurement says fan-out dominates. - **Chunked read deadlines instead of a breaker-aware `waitFD`.** Works, but it parks a socket read for the deadline on every idle connection forever, and it is more code than checking the breaker in the loop that already exists. - **An adaptive poll interval in the network loop** (2 ms when queued, 50 ms when idle). Tried and reverted: one relay request crosses the loop three or four times, so a 50 ms idle wait became 160 ms per published event. In a multi-hop pipeline the poll interval multiplies by the hop count, and only the hop count changes if the loop is left to poll. - **`reflect.Select` fan-in for `Tree.Exited`.** No reflection in this tree, and the per-domain forwarder alternative reintroduces unstructured goroutines. - **A config knob per budget.** Constants with a stated latency target, measured once. A knob nobody measures is not a safety valve. - **io_uring or any async file I/O.** Not reachable from TinyGo's syscall surface and there is one thread; the answer for file I/O is smaller units, not overlap. ## 15. Implementation status All ten items are implemented, in the batch order above. Evidence per item: | Item | Change | Test that fails without it | |---|---|---| | 10 | `Close` returns and logs the domains that did not stop; `Exited` names the one that returned | `TestCloseNamesHungDomain`, `TestExitedNamesDomain` | | 1 | breaker checked at the top of `net.Run`; one budget per pass; adaptive poll reverted | `TestDomainLoopsCheckTheBreaker` | | 2 | `drain(&budget)` spends one budget across workers, database, verifiers and Blossom | `TestDrainBudget` | | 6 | `queryJob` delivers `queryChunk` events per pass | `TestAdvanceQueryChunks`, `TestAdvanceQuerySkipsClosedConn` | | 7 | `broadcastJob` offers `broadcastChunk` connections per pass from a tombstoned order list | `TestAdvanceBroadcastChunks`, `TestBroadcastSkipsClosedSlot` | | 8 | `waitFD` checks the breaker on every poll slice | `TestTreeShutdownWithBlockedWriter` (6.7 s and two named domains without it) | | 5 | `PutJob` and `RestoreJob` step by `blossom.StepBytes` | `TestPutJobSteps`, `TestRestoreJobSteps`, `TestRestoreJobRejectsBadDigest` | | 3 | checkpoints are owed, not performed; `CheckpointStep` per turn | `TestCheckpointInterruptedBySave` (one event lost without the save-counter guard) | | 4 | `PurgeExpired(now, max)` returns `more`; the domain drains 100 per tick | `TestPurgeIsBounded` | | 9 | `httpsrv.Server` and `ws.Conn` deleted | the ported parser and framing tests | Deviations from the plan as written, and why: - **The adaptive poll interval did not survive.** 2 ms while queued and 50 ms when idle multiplied by the three or four loop hops one request makes, taking a published event from about 15 ms to 160 ms. Reverted to a constant 2 ms. - **Reachability is checked structurally, not by timing.** Two attempts at a timing test passed with the top-of-loop check deleted, because a full channel is drained inside the pass that observes it. `invariant_test.go` parses each domain entry point instead. - **Item 8 stopped at level 1.** The self-pipe variant needs `syscall.Pipe2` to link under TinyGo, which could not be verified on this machine. The 200 ms poll slice meets the stated bound, so level 2 is a known available improvement rather than an unfinished requirement. - **Checkpoints stay inline for non-domain callers.** `Options.DeferCheckpoint` is set by the database domain only. The stress rig and the CLI keep the old behaviour, so their measurements remain comparable and a long-running library user cannot silently stop fsyncing. - **Item 5's restore still holds one blob entry open across steps**, with the per-step byte budget bounding the work. An entry is at most `BlossomMaxBlob` (50 MiB by default). ### Where each change lives Line numbers are from the tree at the end of this work and will drift; the function names are the stable part. | Item | File | Function or symbol | |---|---|---| | 10 | `pkg/relay/tree.go` | `Tree.Close` (:204), `Tree.Exited` (:189) | | 1 | `pkg/domain/net/net.go` | `Run` (:225), breaker check at :249 | | 2 | `pkg/domain/net/net.go` | `drain` (:287), `netUnitBudget` (:63) | | 6 | `pkg/domain/net/net.go` | `advanceQuery` (:348), `queryChunk` (:66) | | 7 | `pkg/domain/net/net.go` | `advanceBroadcast` (:373), `broadcastChunk` (:67), `maxBroadcastJobs` (:74) | | 8 | `pkg/domain/io/fdconn.go` | `waitFD` (:135) | | 5 | `pkg/blossom/jobs.go` | `BeginPut` (:76), `PutJob.Step` (:102), `BeginRestore` (:274), `RestoreJob.Step` (:284); driven from `pkg/domain/blob/blob.go` | | 3 | `pkg/store/engine.go` | `CheckpointPending` (:1146), `CheckpointStep` (:1161); `DeferCheckpoint` set at `pkg/domain/db/db.go:44`, stepped at `:75` | | 4 | `pkg/store/engine.go` | `PurgeExpired` (:903) | | 9 | `pkg/httpsrv/`, `pkg/ws/` | `Server.Serve` and `ws.Conn` deleted; the parser and framing tests remain | The tests are in `pkg/relay/shutdown_test.go`, `pkg/relay/invariant_test.go`, `pkg/domain/net/unit_test.go`, `pkg/blossom/jobs_test.go` and `pkg/store/engine_test.go`. The TinyGo side was verified after the fact; section 17 records it. Two defects that only appear in the real build came out of that run, and both are fixed. `go test -race ./...` passes once cgo is pointed at clang, which section 17 records. Everything above was verified with `go build`, `go vet` and `go test ./...` (the tree builds and tests under the standard toolchain, which is how the repository's tests run). The one TinyGo-pinned decision that remains unverified is `syscall.Pipe2`, which this plan did not change. ## 16. Measurement `cmd/torly-stress` is a store-engine rig, so it measures the engine rather than the relay. Two runs per build, 20 000 seeded events, 3 s mixed workload, 4 readers and 1 writer: | | base `e85e9fe` | HEAD | |---|---|---| | seed events/s | 2676 / 2640 | 2621 / 2367 | | `kind1-limit5000` p50 | 26.7 / 20.9 ms | 34.7 / 24.2 ms | | `kind1-limit100` p99 | 8.9 / 0.5 ms | 3.9 / 6.8 ms | The base build moved further between its own two runs (20.9 to 26.7 ms on the large scan) than HEAD moved away from it, so this box cannot resolve a difference below about 15% on these numbers. Nothing here is a regression outside that band, and the query path was not touched. The relay-level numbers that matter are the shutdown assertions, which are exact: 150 ms idle, 250 ms under load, 500 ms with a blocked writer. ## 17. TinyGo verification The tree was built and tested under TinyGo for the first time at the end of this work: **tinygo 0.44.0**, using **go 1.27.2** and **LLVM 22.1.4**, installed to `~/.local/tinygo` and put on `PATH` by `scripts/env.sh`. | Check | Result | |---|---| | `tinygo build -o torly ./cmd/torly` | 5.3 MB binary, 76 s cold | | `tinygo test ./...` | 13 packages, all pass | | `tools/torly-e2e` against the built binary | health, NIP-11, publish, query, count, close: pass | | `scripts/e2e.sh` against the built binary | NIP-11, publish/query, count, search, replaceable, deletion, blossom upload, restart persistence, WAL crash recovery, shutdown: pass | | `SIGTERM` on the built binary | exit 0, 49 ms, `received terminated, shutting down` logged | | `SIGTERM` 2 ms after `exec` | exit 0 (was 143, see below) | | `make build`, `vet`, `test`, `test-tinygo`, `e2e`, `size` | all pass | | `CC=clang CGO_ENABLED=1 go test -race ./...` | 13 packages, no race reported | `size torly`: 5 486 968 bytes on disk after the SIGPIPE disposition moved into `pkg/sigtrap`; 1.1 MB text, 35 KB data, 125 KB bss. make 4.4.1 was installed by extracting its `.deb` into `~/.local`, which needs no root; the box has no passwordless sudo for this user. cgo needs a C compiler, and the system clang serves: `CC=clang CGO_ENABLED=1` is enough for `-race`. `scripts/env.sh` now appends `~/.local/bin` and the local TinyGo to `PATH`, and sets `TMPDIR` to `~/.cache/tmp` when it is unset: `/tmp` here is a small tmpfs with a quota, and a Go or TinyGo link step inside it dies part way through with EDQUOT. The earlier 4.5 MB figure was the build before the SIGPIPE fix; installing `signal.Ignore` pulls in the signal machinery, so the number moved once the fix landed. nak, which `scripts/e2e.sh` needs, was installed from its prebuilt release because building it here needs cgo for its lmdb backend and there is no C compiler. Two defects were found by running the real build, and neither is visible under `go test`: 1. **SIGPIPE killed the process.** The Go runtime ignores SIGPIPE for every fd other than 1 and 2; TinyGo installs no such disposition, and its own runtime has no mention of SIGPIPE. A write to a socket whose peer has closed is therefore fatal: one client that goes away mid-response kills the relay. It showed up first as `tinygo test` failing on a single test with no output at all - the test process, acting as a client, died silently inside `Tree.Close` while writing to sockets the relay had just closed. The same binary passed when run directly, which is what made it look like a runner problem. Fixed by calling `sigtrap.IgnorePipe()` as the first act of `serve()`, and in a `TestMain` for `pkg/relay` so the test binary survives the same writes. The disposition lives in `pkg/sigtrap` so the two runtimes are handled in one place: on TinyGo it calls `signal.Ignore(syscall.SIGPIPE)`, on the Go runtime it is a no-op because the runtime already does it. 2. **The signal handler was installed too late.** `signal.Notify` ran after configuration, `os.MkdirAll`, opening the store and spawning 68 domains. A `SIGTERM` inside that window hits the default action and kills the process without closing the tree: measured at exit 143 for a 10 ms delay, clean exit 0 from 50 ms. That is a restart loop's timing. The handler is now installed before any of that work, and a 2 ms delay exits cleanly. Both are the kind of defect the audit could not see from the source: the Go toolchain defines the behaviour the relay was relying on, and TinyGo does not.