Skip to content

feat(directconn): run the direct connection engine on one API replica at a time - #5273

Merged
Quick104 merged 5 commits into
Silo-Server:mainfrom
darthShadow:pr/direct-engine-lease
Nov 25, 2026
Merged

Quick104 merged 5 commits into
Silo-Server:mainfrom
darthShadow:pr/direct-engine-lease

Conversation

@darthShadow

@darthShadow darthShadow commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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 from SECRET_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. In server.mode = api the 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, the directconn imports, make verify-fork-pins, and THIRD_PARTY_NOTICES.md back at github.com/darthShadow/shunpike v0.1.1 and 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 from v0.1.2 to v0.1.1 because Silo-Server's v0.1.2 is 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 api or integrated mode, keeps one member in the Redis sorted set silo: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 in docs/architecture/direct-connections.md lists every case:

  • Without Redis, a single integrated process runs the engine with no census or lease. In server.mode = api the engine stays off with replica_census_unavailable, because separate API processes can share the lease only through Redis.
  • With more than one replica, or a failed census, a holder keeps its established sessions, but new direct connections are unavailable.
  • When Redis is configured but its client fails to build, the gate stays closed with 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 with replica_lease_pending until 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 with udp_port_invalid. A start that cannot bind the port reports udp_port_bind_failed, and any other start failure reports engine_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 with engine_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 strips Forwarded, 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 answers 421 when 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 engine feature and seven reasons: multiple_api_replicas, replica_census_unavailable, replica_lease_pending, replica_lease_held, udp_port_invalid, udp_port_bind_failed, and engine_start_failed. The direct row 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 report min and max. Five environment variables are new: SILO_NET_DIRECT_UDP_PORT, SILO_NET_DIRECT_RECEIVE_WINDOW, SILO_NET_DIRECT_GSO, SILO_NET_DIRECT_ACK_DECIMATION, and SILO_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 unrecognized SILO_NET_DIRECT_GSO, SILO_NET_DIRECT_ACK_DECIMATION, or SILO_NET_DIRECT_BBR_LOSS value 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, and docs/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 clamped and invalid_default reason labels, and the reworded engine_start_failed label, port mapping description, and note under the toggle. .silo-translations pins release 2026.11.25-6f78912, the first release with them.

Validation

  • At 1eff26d54 (Quick104 merged main and re-synced translations to 2026.11.25-6f78912; same tree as the checks below ran on), on macOS with GOMAXPROCS=2 and -p 2: go test -race -count=1 over ./internal/directconn/... ./internal/tuning/... ./internal/cache/... passed, go vet on those packages and ./internal/config/... exited 0, gofmt reported no changes, tsc -b in web/ exited 0, and DirectConnectionsSection.test.tsx passed (15 tests).
  • At this head, a1ab56158: TestShutdownInterruptsInFlightReplicaUpdate had 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 when Shutdown no longer interrupts that census. go test -race over ./internal/directconn/... ./internal/cache/... passed with -count=1, and over ./internal/directconn/ with -count=20; go vet exited 0, gofmt reported no changes, and golangci-lint run --new-from-rev=c297994fb reported 0 issues.
  • At the lease fix, 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 = api without Redis, the start failure reasons on the direct row, 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.
  • At c297994fb, on macOS with GOMAXPROCS=2 and -p 2: go test -race over ./internal/directconn/... ./internal/tuning/... ./internal/cache/... passed with -count=1 and with -count=20. go vet on those packages exited 0, gofmt reported no changes, and golangci-lint run --new-from-rev=9fb002550 on those packages reported 0 issues. The generated web locale files matched the generator byte for byte.
  • Not run at this head or at c297994fb: the full gate, the web tests (including the new admin section tests), the cmd/silo build and vet (the macOS host lacks the native libraries), the Postgres suites, and any Linux or lab run.
  • At the previous head, 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.
  • At 9fb002550, on Linux with Go 1.27.4: the full gate from "Validate your change" passed, including make 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.
  • The cmd/silo wiring (the deadline Redis client, the unusable-Redis flag, the Redis requirement in server.mode = api, and the handler wait) has no unit test. The build covered it at 9fb002550, before the Redis requirement was added.
  • A lab deployment of 9fb002550 with docker-compose.advanced.yml (PostgreSQL, Redis, Silo), with direct_connections.enabled set through the admin settings API: with one API replica the status engine row reads on and the page shows Direct connection engine On. After a second replica joined on the same PostgreSQL and Redis, both replicas reported direct off with multiple_api_replicas; the lease holder kept its engine on with that reason and the other replica reported its engine off. 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 head 9fb002550, 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 the invalid_default label.

Risks

  • Upgrade. Turning on direct_connections.enabled now 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.
  • One API replica. Direct connections work only while a single API replica runs. With two or more, the status reports multiple_api_replicas and 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 with replica_lease_pending for 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.
  • No Redis. In server.mode = api the 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.
  • Fence at the lease deadline. If a packet check and a lease renewal see the same clock reading at the deadline, the fence latches closed while the grant stays held. The fence also reads the clock after it takes the grant and deadline under the monitor lock, so a renewal that lands at the deadline between those reads can latch it the same way. In both cases direct traffic on that host stops until the next grant change. Both cases are accepted as they are.
  • Rolling update from the previous release. The previous release writes its presence marker under a different Redis key, so the census does not count it. During the update, the network access warning about multiple API replicas may not fire. The previous release runs no direct engine.
  • Work with the feature off. With Redis configured, every API and integrated process now registers its presence member in Redis and opens a second Redis client with socket deadlines. Before, only API-mode processes with plugins registered a marker. The direct service also rereads its settings once a minute. With the feature off, no census or lease runs, no engine starts, and no UDP port is bound.
  • Port. The Dockerfile does not expose 8094/udp. That does not matter yet, because no client can connect.
  • Hidden toggle. The only way to turn the feature on is still the admin settings API.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • Each test this pull request adds meets "Decide what to test" in CONTRIBUTING.md.
  • The Evidence section shows every change a user can see, or how I checked a change nobody sees.

AI Disclosure

  • Harness: Claude Code, run in T3 Code; Codex CLI, run in T3 Code
  • Tool(s): Claude Code, Codex CLI
  • Model(s): claude-opus-5-5, claude-sonnet-5-5 (Claude Code); gpt-6.2-sol, gpt-6.1-sol (Codex CLI)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Two reviewers on different models (claude-opus-5-5 in Claude Code, gpt-6.2-sol in Codex CLI) read the first two commits against the base, wrote tests that reproduce the main defects, and discussed their findings, and a separate claude-sonnet-5-5 session 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 missing clamped label), 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-5 in Claude Code, gpt-6.2-sol in Codex CLI), merged by claude-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 independent claude-sonnet-5-5 verifier 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 by claude-opus-5-5 and gpt-6.1-sol before it was rebuilt on the current base.

Note

Run the direct connection engine on one API replica at a time

  • Adds a full direct-engine lifecycle to the directconn service: engine start/stop, HTTP/3 server, key derivation, and synchronous Shutdown, wired into API-host startup in main.go
  • Coordinates replicas through a Redis-backed lease (90s TTL, 60s self-stop) and an APIReplicaPresence census 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 loss
  • Adds periodic settings rereads (bounded by the recheck interval) so a missed settings-change event cannot leave the engine on stale settings indefinitely
  • Adds five direct tuning knobs (UDP port, GSO, BBR loss, receive window, ACK decimation) to tuning.go, exposed in the status API, OpenAPI schema, and the admin direct-connections UI; adds wrapDirect in wrapper.go which strips proxy headers and rejects requests without a valid peer with 421
  • Adds locale strings for all new direct-connection, playback-timeout, password, export-job, and rating messages across all catalogs
  • Behavioral Change: requests through a direct path are now always classified as remote in location.go; streamlocation.FromContext and netaccess.Path consumers should be checked. Redis is now required for the engine when multiple API replicas run; without usable Redis the direct feature reports unavailable

Macroscope summarized a1ab561.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request go Pull requests that update go code priority: P2 Limited scope, workaround exists, or polish size/XXXL 3000+ added + deleted lines (all files); change volume, not priority.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants