PLAN-PROCESSING-UNITS.md raw

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.

(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.

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.

bound the damage when a check is present but a unit is too large.

1. Batches

BatchItemsReason for the order
B010, plus the shutdown test harnessThe tests depend on Close reporting which domains hung. Without it a regression is invisible.
B11, 2, 6, 7Largest starvation win per line changed, all inside one domain.
B28, 5I/O waits first, then the blob units that sit on top of them.
B33, 4Store changes are the only ones that can corrupt data; they go last, after the harness exists.
B49Deletions; 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:

the name it currently discards.

at error level as domain %s did not stop within 5s. The return value is the test hook; production callers may ignore it.

channel is closed. cmd/torly/main.go logs the name instead of the current "a relay domain exited".

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:
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()
}
  1. 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.

  1. 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:

on close, so iteration has a resumable index. The map stays the lookup.

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.

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):

ch.Stop.Done(). The acceptor already has the breaker when it accepts: newFDConn(nfd, addr, ch.Stop.Done()).

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".

arrived before the read, which the wait now covers.

Change, level 2 (recommended, ~60 lines, eliminates the idle wakeups):

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.

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:

// 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()
}

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.

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.

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.

  1. 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.

  1. 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:

stops after max records and more reports whether the range still had entries.

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.

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:

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.

the socket accepts without reading, run for 2 s, close, assert within 250 ms and that Close reports no hung domains.

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

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.

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.

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.

the per-domain forwarder alternative reintroduces unstructured goroutines.

once. A knob nobody measures is not a safety valve.

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:

ItemChangeTest that fails without it
10Close returns and logs the domains that did not stop; Exited names the one that returnedTestCloseNamesHungDomain, TestExitedNamesDomain
1breaker checked at the top of net.Run; one budget per pass; adaptive poll revertedTestDomainLoopsCheckTheBreaker
2drain(&budget) spends one budget across workers, database, verifiers and BlossomTestDrainBudget
6queryJob delivers queryChunk events per passTestAdvanceQueryChunks, TestAdvanceQuerySkipsClosedConn
7broadcastJob offers broadcastChunk connections per pass from a tombstoned order listTestAdvanceBroadcastChunks, TestBroadcastSkipsClosedSlot
8waitFD checks the breaker on every poll sliceTestTreeShutdownWithBlockedWriter (6.7 s and two named domains without it)
5PutJob and RestoreJob step by blossom.StepBytesTestPutJobSteps, TestRestoreJobSteps, TestRestoreJobRejectsBadDigest
3checkpoints are owed, not performed; CheckpointStep per turnTestCheckpointInterruptedBySave (one event lost without the save-counter guard)
4PurgeExpired(now, max) returns more; the domain drains 100 per tickTestPurgeIsBounded
9httpsrv.Server and ws.Conn deletedthe ported parser and framing tests

Deviations from the plan as written, and why:

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.

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.

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.

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.

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.

ItemFileFunction or symbol
10pkg/relay/tree.goTree.Close (:204), Tree.Exited (:189)
1pkg/domain/net/net.goRun (:225), breaker check at :249
2pkg/domain/net/net.godrain (:287), netUnitBudget (:63)
6pkg/domain/net/net.goadvanceQuery (:348), queryChunk (:66)
7pkg/domain/net/net.goadvanceBroadcast (:373), broadcastChunk (:67), maxBroadcastJobs (:74)
8pkg/domain/io/fdconn.gowaitFD (:135)
5pkg/blossom/jobs.goBeginPut (:76), PutJob.Step (:102), BeginRestore (:274), RestoreJob.Step (:284); driven from pkg/domain/blob/blob.go
3pkg/store/engine.goCheckpointPending (:1146), CheckpointStep (:1161); DeferCheckpoint set at pkg/domain/db/db.go:44, stepped at :75
4pkg/store/engine.goPurgeExpired (:903)
9pkg/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 e85e9feHEAD
seed events/s2676 / 26402621 / 2367
kind1-limit5000 p5026.7 / 20.9 ms34.7 / 24.2 ms
kind1-limit100 p998.9 / 0.5 ms3.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.

CheckResult
tinygo build -o torly ./cmd/torly5.3 MB binary, 76 s cold
tinygo test ./...13 packages, all pass
tools/torly-e2e against the built binaryhealth, NIP-11, publish, query, count, close: pass
scripts/e2e.sh against the built binaryNIP-11, publish/query, count, search, replaceable, deletion, blossom upload, restart persistence, WAL crash recovery, shutdown: pass
SIGTERM on the built binaryexit 0, 49 ms, received terminated, shutting down logged
SIGTERM 2 ms after execexit 0 (was 143, see below)
make build, vet, test, test-tinygo, e2e, sizeall 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.

  1. 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.