Repository navigation
feat(directconn): run the direct connection engine on one API replica at a time - #5273
Merged
Merged
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Related issue: #4440
Validation tasks: none
Other clients: Apple Silo-Server/silo-apple#1248 (native client support for the direct path, which the third pull request of this feature enables; this one adds the engine and its admin status rows, and no client can connect yet); Android Silo-Server/silo-android#1028 (same); Roku N/A (silo-roku's spec plans no direct-connection, enrollment, or UDP feature)
#4440 adds a direct UDP path between native clients and the API host. #5047 added the readiness check, but nothing listens for direct traffic yet. This pull request starts the direct engine when an administrator turns on
direct_connections.enabled, and serves Silo's HTTP handler over HTTP/3 on the engine's UDP socket. Every API replica derives the same direct identity fromSECRET_KEY, so two replicas running the engine would present one identity from two places. A Redis lease lets only one replica run it. A replica that loses the lease drops its direct packets at once, and a replica that gains it waits 90 seconds before serving, so the previous holder has stopped first. Inserver.mode = apithe engine needs Redis. The admin status says why the engine is off when it is. Production code still registers no peers, so no client can connect yet. Enrollment, peer registration, and direct playback come in the third pull request.Approach
Modules. The first commit points
go.mod, thedirectconnimports,make verify-fork-pins, andTHIRD_PARTY_NOTICES.mdback atgithub.com/darthShadow/shunpikev0.1.1and the darthShadow forks of quic-go and Tailscale, both still tagged-shunpike.2. The Silo-Server copies stay as backups that receive tags, and the build reads none of them. The shunpike version goes fromv0.1.2tov0.1.1because Silo-Server'sv0.1.2is the commit that renamed the module. No other requirement changes.One engine per deployment. The engine uses the API replica presence that network access providers already use. With Redis, each API process, in
apiorintegratedmode, keeps one member in the Redis sorted setsilo:api-replicas, scored with its expiry in Redis time. One script call prunes expired members, adds this process if it is missing, and counts, so the cost does not grow with the keyspace. While direct connections are on, each replica runs this census every 30 seconds, and a Redis lease (silo:direct:engine-lease, 90-second expiry, renewed every 30 seconds) picks one holder. Turning the feature off closes the engine first, then stops the census and releases the lease. A failed lease call is retried after 5 seconds. The holder stops its engine once its last successful renewal is more than 60 seconds old, whether or not a census or renewal is still running. The census and the lease call each have their own 2-second bound. The presence and the lease use a Redis client that enforces those deadlines on its sockets, so a Redis that stops answering cannot hold up startup, shutdown, or the self-stop. The gate table indocs/architecture/direct-connections.mdlists every case:server.mode = apithe engine stays off withreplica_census_unavailable, because separate API processes can share the lease only through Redis.replica_census_unavailable. Silo does not treat that as a deployment without Redis.Grants and the hold. A grant is one stretch of ownership of the lease. Only Redis's confirmation of an acquisition opens one. A renewal answered
0, a release, or a renewal that finishes after the grant's 60-second deadline ends it, so the next success is a new grant, even for the same process. The acquisition script also accepts a key that already holds this process's value, so a retry after a lost reply succeeds. A new grant keeps the engine off withreplica_lease_pendinguntil 90 seconds, the lease TTL, have passed since the call that opened it was sent. By then the previous holder has stopped serving.Packet fence. The UDP connection handed to HTTP/3 drops every packet in both directions, including segmented writes, once the grant that started the engine ends or its local deadline (last renewal plus 60 seconds) passes. The drop happens before teardown, and HTTP/3 sees ordinary packet loss rather than an error that would end its server. When the lease forces a stop, HTTP/3 connections close at once, with no grace period. The fence covers the HTTP/3 path Silo owns; shunpike's own discovery and transport paths are outside it. No local check covers a process paused between a check and a send; the 30 seconds between the 60-second self-stop and the 90-second expiry bound that case.
Engine lifecycle. The node key is derived with HKDF-SHA256 from
SECRET_KEY. The engine binds UDP port 8094 by default. An invalid port leaves it off withudp_port_invalid. A start that cannot bind the port reportsudp_port_bind_failed, and any other start failure reportsengine_start_failed. An engine built while the lease or the settings changed under it is closed without being published, and that is not a failure. No engine starts until the HTTP handler it serves exists. The service rereads its settings once a minute, because Redis drops a settings-change event published while a subscriber reconnects. If the HTTP/3 server stops while nobody asked it to, Silo withdraws the engine and turns its status row off withengine_start_failed. It restarts the engine once, after a new settings read and, with Redis, a new lease renewal or acquisition. A second unexpected stop leaves it off until the settings or the gate change. On process stop, the direct service drains HTTP/3, closes the engine, and only then releases the lease, so no successor holds the lease while this engine is still open.Request path. The HTTP/3 server uses the LAN TLS certificate and SPKI pin with ALPN
h3. Before the router runs, it stripsForwarded,X-Forwarded-*,X-Real-IP, and both network access ingress headers. It takes the client address from the engine's observed endpoint for the admitted peer, and answers421when the peer or the endpoint is missing. The direct path carries no user, device, or policy and grants no application authority; the router still checks the caller's token. Stream location treats a direct request as remote even from a private address.Status and tuning. The admin status gains an
enginefeature and seven reasons:multiple_api_replicas,replica_census_unavailable,replica_lease_pending,replica_lease_held,udp_port_invalid,udp_port_bind_failed, andengine_start_failed. Thedirectrow turns off while the gate refuses new connections, and also, with the engine's own reason, when the engine is stopped by a port or start failure. Numeric tuning rows now reportminandmax. Five environment variables are new:SILO_NET_DIRECT_UDP_PORT,SILO_NET_DIRECT_RECEIVE_WINDOW,SILO_NET_DIRECT_GSO,SILO_NET_DIRECT_ACK_DECIMATION, andSILO_NET_DIRECT_BBR_LOSS. A bad value never stops startup. An out-of-range receive window is clamped (clamped), and a malformed one keeps its default (invalid_default). An unrecognizedSILO_NET_DIRECT_GSO,SILO_NET_DIRECT_ACK_DECIMATION, orSILO_NET_DIRECT_BBR_LOSSvalue turns that knob off (invalid), as the TCP knobs do. The receive window and ACK decimation are client policy, and no client receives them yet. The API contract diff reports 10 additive changes. The Direct Connections admin section labels the new feature, the reasons, and the five direct knobs, shows on, off, and sizes in readable form, and shows each numeric knob's allowed range. The note under the toggle now says that turning it on starts the engine.Docs:
docs/architecture/direct-connections.md,docs/architecture/network-access.md, anddocs/direct-connections-api.md.UI text. Six strings come from Silo-Server/silo-translations#168, which has translations for all 38 languages: the range line, the
clampedandinvalid_defaultreason labels, and the rewordedengine_start_failedlabel, port mapping description, and note under the toggle..silo-translationspins release2026.11.25-6f78912, the first release with them.Validation
1eff26d54(Quick104 merged main and re-synced translations to2026.11.25-6f78912; same tree as the checks below ran on), on macOS withGOMAXPROCS=2and-p 2:go test -race -count=1over./internal/directconn/... ./internal/tuning/... ./internal/cache/...passed,go veton those packages and./internal/config/...exited 0,gofmtreported no changes,tsc -binweb/exited 0, andDirectConnectionsSection.test.tsxpassed (15 tests).a1ab56158:TestShutdownInterruptsInFlightReplicaUpdatehad stopped testing anything after the lease fix, because the monitor now starts only after a settings read and the test shut down before one. It now starts the monitor, checks that a census reached the stalled Redis call, and fails whenShutdownno longer interrupts that census.go test -raceover./internal/directconn/... ./internal/cache/...passed with-count=1, and over./internal/directconn/with-count=20;go vetexited 0,gofmtreported no changes, andgolangci-lint run --new-from-rev=c297994fbreported 0 issues.c297994fb, the tests cover the packet fence at the deadline and on a grant change, the 90-second hold on enable, on a quick re-enable, and after a lost grant is reacquired, a late renewal opening a new grant, a lost acquisition reply, the release after the shutdown context ends,server.mode = apiwithout Redis, the start failure reasons on thedirectrow, the census counting this process, and the admin section's labels, ranges, and pseudo-locale text. An independent check planted a defect in each fixed behavior, and each one made its test fail.c297994fb, on macOS withGOMAXPROCS=2and-p 2:go test -raceover./internal/directconn/... ./internal/tuning/... ./internal/cache/...passed with-count=1and with-count=20.go veton those packages exited 0,gofmtreported no changes, andgolangci-lint run --new-from-rev=9fb002550on those packages reported 0 issues. The generated web locale files matched the generator byte for byte.c297994fb: the full gate, the web tests (including the new admin section tests), thecmd/silobuild and vet (the macOS host lacks the native libraries), the Postgres suites, and any Linux or lab run.9fb002550: each review fix had a test that fails on its defect: Redis configured but unusable, an engine starting before its handler exists, a stalled Redis write at startup and shutdown, the order of the withdrawal and the lease count after HTTP/3 stops, a follow-up settings read treated as a settings event, the census using up the renewal's time, and the lease released before the engine closed. Five planted defects in the minute reread, the retry rule, and the restart rule each made their test fail, and 50 repeats of those tests passed.9fb002550, on Linux with Go 1.27.4: the full gate from "Validate your change" passed, includingmake verify-fork-pins(Fork pins match github.com/darthShadow/[email protected]), the contract checks (apiv2-contract-diff: 10 change(s), none breaking without approval), the web tests (3,300 passed), and the database pin run (1,069 pins). The pin run left out./cmd/silo TestBeforeMigrateBackupOnAnOldSchemaDB, an existing test that is flaky on main. This head changes no contract files.cmd/silowiring (the deadline Redis client, the unusable-Redis flag, the Redis requirement inserver.mode = api, and the handler wait) has no unit test. The build covered it at9fb002550, before the Redis requirement was added.9fb002550withdocker-compose.advanced.yml(PostgreSQL, Redis, Silo), withdirect_connections.enabledset through the admin settings API: with one API replica the statusenginerow readsonand the page shows Direct connection engine On. After a second replica joined on the same PostgreSQL and Redis, both replicas reporteddirectoff withmultiple_api_replicas; the lease holder kept its engineonwith that reason and the other replica reported its engineoff. The same deployment at the base shows no engine row. No client connected, because production code registers no peers yet.Evidence
Evidence: https://evidence.siloserver.org/r/silo-server/pr-5273/
Surface and build: Admin > Server > Network Access at 1440 x 900 and 390 x 844; before at the base
0e8470bca, after at the previous head9fb002550, each built from its commit. The captures predate this head's changes to the Direct Connections section: the note under the toggle, the port mapping description, the direct knob labels and values, the range lines, and theinvalid_defaultlabel.Risks
direct_connections.enablednow starts the engine, and that includes servers upgraded with the setting already on for the feat(directconn): show administrators whether the host can accept direct connections #5047 readiness check. After the upgrade such a server starts the engine with no further action: it opens UDP port 8094 and, when port mapping is on, asks the router for a port mapping.multiple_api_replicasand new direct connections are unavailable. Every new grant waits 90 seconds before the engine serves, so after the feature is turned on, or after the lease moves, direct connections stay unavailable withreplica_lease_pendingfor at least that long. A replica that stops cleanly releases the lease. After a crash, the next holder can take the lease only once it expires, up to 90 seconds after the last renewal, and then waits its own 90 seconds.server.mode = apithe engine stays off without Redis. A single integrated process without Redis runs the engine with no lease, so two integrated processes without Redis that overlap during a rolling restart can both run it. That case is documented and left open.8094/udp. That does not matter yet, because no client can connect.Checklist
AI Disclosure
claude-opus-5-5,claude-sonnet-5-5(Claude Code);gpt-6.2-sol,gpt-6.1-sol(Codex CLI)claude-opus-5-5in Claude Code,gpt-6.2-solin Codex CLI) read the first two commits against the base, wrote tests that reproduce the main defects, and discussed their findings, and a separateclaude-sonnet-5-5session merged them. They checked the replica gate, the lease and engine lifecycle, startup and shutdown order, the retry rule, the contract, and the docs. They found two High defects (Redis configured but unusable opened the gate, and a slow startup could keep the engine open past the lease deadline), five rated Medium or High (a stalled Redis blocking startup and shutdown, the withdrawal order after HTTP/3 stops, a follow-up read treated as a settings event, the census starving the renewal, and the missingclampedlabel), and seven Low. All fourteen were fixed; the two label fixes ship in feat(catalog): add direct connection tuning ranges and fallback reasons silo-translations#168. A second pair of reviewers (claude-opus-5-5in Claude Code,gpt-6.2-solin Codex CLI), merged byclaude-sonnet-5-5, read the lease fix before it was committed. They found two High defects (a new lease could skip the 90-second hold after Redis recovered, and a late renewal could reopen an expired fence) and lower findings, which were fixed or, for the warning across versions, documented. An independentclaude-sonnet-5-5verifier then broke each fixed behavior and checked that its test failed; of its three Low findings, one is the fence edge under Risks and two are test-only and left as they are. An earlier version of the lease commit had a review round byclaude-opus-5-5andgpt-6.1-solbefore it was rebuilt on the current base.Note
Run the direct connection engine on one API replica at a time
directconnservice: engine start/stop, HTTP/3 server, key derivation, and synchronousShutdown, wired into API-host startup in main.goAPIReplicaPresencecensus backed by one sorted set; only the lease holder runs the engine, and packet I/O is fenced via fence.go so a stale engine stops forwarding after lease losswrapDirectin wrapper.go which strips proxy headers and rejects requests without a valid peer with 421streamlocation.FromContextandnetaccess.Pathconsumers should be checked. Redis is now required for the engine when multiple API replicas run; without usable Redis the direct feature reports unavailableMacroscope summarized a1ab561.