carlos / platform Public

edge: conservative process-held accounting and explicit record barriers (#471 Task 7 fix round 1)

Astra review, Task 7:

- Case 13 now measures the bytes the processes hold in one byte domain.
  The sender's share is its unsent bytes only (SIOCOUTQNSD), sampled
  after the hub's SIOCINQ, so nothing is counted twice. Each stalled
  client dials TLS 1.3 with fixed 16 KiB records, and the queued
  ciphertext converts to a lower bound on its plaintext: 22 bytes of
  overhead per touched record, plus one record for the partial write the
  deadline cut. Every rounding raises the process-held figure. Measured
  at -short: 340 to 372 KB against 4.26 MB. A box buffer of the slack +
  128 KiB fails at 4 379 684; the slack - 256 KiB passes.
- Production values, run once more because the accounting changed (nice
  19): PASS, wall 1.2 s, peak RSS 252 MiB. The processes hold 1.32 to
  1.38 MB per socket against 5.24 MB.
- Case 18 installs and releases the record:before and record:after
  barriers in all three schedules. Both ends are closed before Watch
  records. A record taken before Reload is killed at the barrier.
- The comments state the amended process-held bound.
- sendHandshake is split, so writeHandshake takes the caller's conn.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev a4707bc518aaaf56fefe82521c83e777dd9e8ac5 parent 501f272
2 files changed, +135 −50
  • internal/edge/tunnel_ws_e2e_test.go +6 −1
  • internal/edge/tunnel_ws_load_e2e_test.go +129 −49

Intent

Human

<task-notification> <task-id>a183e06b7000fc3f7</task-id> <tool-use-id>toolu_01E24BbSsCaWYGL6A5mg5cHo</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/a183e06b7000fc3f7.output</output-file> <status>completed</status> <summary>Agent "#471 Task 7: load, restart, reloads" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Status:** DONE **Commit:** 501f2724 (docs only, not pushed). It amends spec §4.8 (c) and §8.2 case 13 to the ruled bound and adds the kernel-queue known-limit note. The ruling is recorded in `task-7-report.md`. No code changed: the test from f0f699d7 already checks this form of the bound.</result> <usage><subagent_tokens>265091</subagent_tokens><tool_uses>75</tool_uses><duration_ms>1605938</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bfq3nmuj3</task-id> <tool-use-id>toolu_019ZX8FNzyDwU8gwZCipekkJ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/ba9fa944-a429-4788-9b3c-f2b2f42617f3/tasks/bfq3nmuj3.output</output-file> <status>completed</status> <summary>Background command "Run Astra review of #471 Task 7" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 11.4 g CO₂e (1,344,382 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-tunnel-websockets-471, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.

diff --git a/internal/edge/tunnel_ws_e2e_test.go b/internal/edge/tunnel_ws_e2e_test.go
index 4991fb931..57e931b08 100644
--- a/internal/edge/tunnel_ws_e2e_test.go
+++ b/internal/edge/tunnel_ws_e2e_test.go
@@ -950,7 +950,12 @@ type hs struct {
// the Upgrade token tok. It does not read the answer.
func (s *wsScene) sendHandshake(t *testing.T, addr, host, path, cookie, tok string) hs {
t.Helper()
- c := s.dialTLS(t, addr, host)
+ return writeHandshake(t, s.dialTLS(t, addr, host), host, path, cookie, tok)
+}
+
+// writeHandshake is sendHandshake on a connection the caller dialed.
+func writeHandshake(t *testing.T, c net.Conn, host, path, cookie, tok string) hs {
+ t.Helper()
c.SetDeadline(time.Now().Add(15 * time.Second))
k := make([]byte, 16)
rand.Read(k)
diff --git a/internal/edge/tunnel_ws_load_e2e_test.go b/internal/edge/tunnel_ws_load_e2e_test.go
index d0ff55f95..a878a7608 100644
--- a/internal/edge/tunnel_ws_load_e2e_test.go
+++ b/internal/edge/tunnel_ws_load_e2e_test.go
@@ -180,11 +180,51 @@ func stallWrite(c net.Conn, ceiling int64) (int64, error) {
return n, errors.New("never pushed back")
}
-// tcpQueued is what the kernel holds of one client socket's bytes once
-// its writes are stalled: the client's unsent send queue (SIOCOUTQ) plus
-// the hub's unread receive queue (SIOCINQ) on the connection the hub
-// accepted for it, found by address among s.ln's.
-func tcpQueued(t *testing.T, s *wsScene, c net.Conn) (out, in int64) {
+// The stalled clients' TLS records. Each client dials with dynamic
+// record sizing off, so every record of a 32 KiB chunk carries
+// tlsMaxPlain bytes, and the TLS 1.3 AEAD record adds tlsOverhead: a
+// 5-byte header, the 1-byte inner content type and a 16-byte tag (every
+// TLS 1.3 suite's tag is 16 bytes).
+const (
+ tlsMaxPlain = 16 << 10
+ tlsOverhead = 5 + 1 + 16
+ tlsRecord = tlsMaxPlain + tlsOverhead
+)
+
+// dialStalled dials the hub for host as a stalled client: TLS 1.3 with
+// fixed full-size records, so its queued ciphertext converts to a bound
+// on the plaintext in it.
+func dialStalled(t *testing.T, addr, host string) *tls.Conn {
+ t.Helper()
+ c, err := tls.DialWithDialer(&net.Dialer{Timeout: 5 * time.Second}, "tcp", addr,
+ &tls.Config{ServerName: host, MinVersion: tls.VersionTLS13, DynamicRecordSizingDisabled: true})
+ if err != nil {
+ t.Fatalf("TLS to the hub as %s: %v", host, err)
+ }
+ t.Cleanup(func() { c.NetConn().Close() }) // a TLS close would wait behind the stalled bytes
+ if v := c.ConnectionState().Version; v != tls.VersionTLS13 {
+ t.Fatalf("negotiated TLS version %#x, want 1.3", v)
+ }
+ return c
+}
+
+// plainIn is a lower bound on the plaintext in a span of n contiguous
+// bytes of a stream of tlsRecord-sized records: the span touches at most
+// ceil(n/tlsRecord)+1 records (a partial one at each end), and only
+// tlsOverhead bytes of each are not plaintext. Rounding goes down.
+func plainIn(n int64) int64 {
+ touched := (n+tlsRecord-1)/tlsRecord + 1
+ return max(0, n-touched*tlsOverhead)
+}
+
+// kernelQueues samples, for one stalled client, the hub's unread
+// receive queue (SIOCINQ, on the connection the hub accepted for it,
+// found by address among s.ln's) and then the client's unsent send queue
+// (SIOCOUTQNSD). Unsent bytes cannot also be in the hub's queue, as
+// SIOCOUTQ's sent-but-unacknowledged bytes can. Sampling the receiver
+// first means a byte that moves between the samples is missed by both,
+// never counted twice.
+func kernelQueues(t *testing.T, s *wsScene, c *tls.Conn) (unsent, unread int64) {
t.Helper()
ioctl := func(nc net.Conn, req uint) int64 {
tcp, ok := nc.(*net.TCPConn)
@@ -202,19 +242,31 @@ func tcpQueued(t *testing.T, s *wsScene, c net.Conn) (out, in int64) {
}
return int64(v)
}
- client := c.(*tls.Conn).NetConn()
- out, in = ioctl(client, unix.SIOCOUTQ), -1
+ client := c.NetConn()
+ unread = -1
s.ln.mu.Lock()
- defer s.ln.mu.Unlock()
for _, ac := range s.ln.conns {
if ac.RemoteAddr().String() == client.LocalAddr().String() {
- in = ioctl(ac, unix.SIOCINQ)
+ unread = ioctl(ac, unix.SIOCINQ)
}
}
- if in < 0 {
+ s.ln.mu.Unlock()
+ if unread < 0 {
t.Fatalf("the hub accepted no connection from %s", client.LocalAddr())
}
- return out, in
+ return ioctl(client, unix.SIOCOUTQNSD), unread
+}
+
+// processHeld is an upper bound on what the hub and box processes hold
+// of one stalled client's accepted plaintext: accepted minus a lower
+// bound on the plaintext in the kernel's two queues. The write that hit
+// its deadline may have left one partial record in the queues whose
+// plaintext Write never counted as accepted, so one record's plaintext
+// is taken off the kernel's share too. Every rounding makes the result
+// larger.
+func processHeld(accepted, unsent, unread int64) int64 {
+ kernel := max(0, plainIn(unsent)+plainIn(unread)-tlsMaxPlain)
+ return accepted - kernel
}
// tcpMax is the kernel's ceiling for one TCP buffer (the third field of
@@ -241,8 +293,9 @@ func tcpMax(t *testing.T, name string) int64 {
// worth of upgraded sockets open on one tunnel and every app side not
// reading, (a) the plain requests still get stream slots, (b) a plain
// upload still gets connection credit, and (c) each stalled client is
-// pushed back by flow control after at most StreamWindow plus 4 MiB of
-// kernel buffers. Production values unless -short, scaled under it.
+// pushed back by flow control, the hub and box processes holding at most
+// StreamWindow + 4 MiB of its bytes (the kernel's TCP queues are outside
+// the bound). Production values unless -short, scaled under it.
func TestTunnelWebSocketMaximumLoad(t *testing.T) {
child, fx := runTrustedChild(t)
if !child {
@@ -282,7 +335,7 @@ func TestTunnelWebSocketMaximumLoad(t *testing.T) {
socks := make([]stalled, capN)
for i := range socks {
id := newHandshakeID()
- h := s.sendHandshake(t, s.addr, wsLoadHost, "/stall?"+wsIDParam+"="+id, "", "websocket")
+ h := writeHandshake(t, dialStalled(t, s.addr, wsLoadHost), wsLoadHost, "/stall?"+wsIDParam+"="+id, "", "websocket")
h.read(t)
wantStatus(t, h, http.StatusSwitchingProtocols, fmt.Sprintf("upgrade %d", i+1))
if got, want := h.resp.Header.Get("Sec-WebSocket-Accept"), acceptFor(h.key); got != want {
@@ -297,29 +350,18 @@ func TestTunnelWebSocketMaximumLoad(t *testing.T) {
t.Fatalf("with %d sockets open the channel's count is %d", capN, n)
}
- // (c) Every client writes until flow control pushes it back. The
- // spec's bound is StreamWindow plus 4 MiB of kernel buffers. On Linux
- // the kernel's share is not 4 MiB: autotuning grows the client's send
- // buffer to tcp_wmem's ceiling and the hub's receive buffer toward
- // tcp_rmem's (4 MiB and 6 MiB by default, measured at nearly 10 MiB
- // between them on loopback). So the kernel's queues on the client's
- // connection are measured once the writes stall and taken off, and
- // what is left, everything the processes and the box's side hold, is
- // held to StreamWindow + 4 MiB. (The queues are the kernel's to bound,
- // near its ceilings: a send queue can pass tcp_wmem by part of a
- // segment.)
+ // (c) Every client writes until flow control pushes it back, and
+ // what the hub and box processes hold of its bytes is at most
+ // StreamWindow + 4 MiB (spec §4.8 (c)). The kernel's own TCP queues
+ // are outside the bound (§4.8, known limit): they are measured once
+ // the writes stall and taken off, conservatively (processHeld).
wmax, rmax := tcpMax(t, "tcp_wmem"), tcpMax(t, "tcp_rmem")
bound := int64(lim.StreamWindow) + 4<<20
type pushed struct {
- n, out, in int64
- err error
+ n, unsent, unread, held int64
+ err error
}
res := make([]pushed, capN)
- for _, sk := range socks {
- // On a failure: drop each connection, as the success path does,
- // rather than let a TLS close wait behind the stalled bytes.
- t.Cleanup(func() { sk.h.conn.(*tls.Conn).NetConn().Close() })
- }
writing := time.Now()
var wg sync.WaitGroup
for i := range socks {
@@ -330,24 +372,24 @@ func TestTunnelWebSocketMaximumLoad(t *testing.T) {
}
wg.Wait()
took := time.Since(writing)
- var lo, hi, maxOut, maxIn, total int64 = 1 << 62, 0, 0, 0, 0
+ var lo, hi, maxUnsent, maxUnread, total int64 = 1 << 62, 0, 0, 0, 0
for i := range res {
r := &res[i]
var ne net.Error
if !errors.As(r.err, &ne) || !ne.Timeout() {
t.Fatalf("socket %d: its writes stopped with %v after %d bytes, want a write deadline", i+1, r.err, r.n)
}
- r.out, r.in = tcpQueued(t, s, socks[i].h.conn)
- if rest := r.n - r.out - r.in; rest > bound {
- t.Fatalf("socket %d: %d bytes accepted, %d of them beyond the TCP queues (%d + %d); want at most StreamWindow + 4 MiB = %d",
- i+1, r.n, rest, r.out, r.in, bound)
+ r.unsent, r.unread = kernelQueues(t, s, socks[i].h.conn.(*tls.Conn))
+ r.held = processHeld(r.n, r.unsent, r.unread)
+ if r.held > bound {
+ t.Fatalf("socket %d: %d bytes accepted, at most %d of them in the kernel's queues (%d unsent, %d unread), so the processes hold %d; want at most StreamWindow + 4 MiB = %d",
+ i+1, r.n, r.n-r.held, r.unsent, r.unread, r.held, bound)
}
- rest := r.n - r.out - r.in
- lo, hi, total = min(lo, rest), max(hi, rest), total+r.n
- maxOut, maxIn = max(maxOut, r.out), max(maxIn, r.in)
+ lo, hi, total = min(lo, r.held), max(hi, r.held), total+r.n
+ maxUnsent, maxUnread = max(maxUnsent, r.unsent), max(maxUnread, r.unread)
}
- t.Logf("each of %d sockets pushed back with %d to %d bytes beyond the TCP queues (bound %d), in %s; the queues at most %d (client; tcp_wmem %d) and %d (hub; tcp_rmem %d); %d bytes accepted in all",
- capN, lo, hi, bound, took.Round(time.Millisecond), maxOut, wmax, maxIn, rmax, total)
+ t.Logf("each of %d sockets pushed back in %s, the processes holding %d to %d bytes of it (bound %d, slack at least %d); the kernel's queues at most %d unsent (tcp_wmem %d) and %d unread (tcp_rmem %d); %d bytes accepted in all",
+ capN, took.Round(time.Millisecond), lo, hi, bound, bound-hi, maxUnsent, wmax, maxUnread, rmax, total)
for i, sk := range socks {
notClosed(t, sk.ac.closed, fmt.Sprintf("the app's end of socket %d", i+1))
}
@@ -607,6 +649,18 @@ func refusedNow(t *testing.T, s *wsScene, when string) {
t.Logf("%s: the new handshake got %d", when, h.resp.StatusCode)
}
+// wsClosed asserts both ends of a socket have already closed.
+func wsClosed(t *testing.T, when string, c *cableClient, ac *appConn) {
+ t.Helper()
+ for name, ch := range map[string]<-chan struct{}{"the client's socket": c.closed, "the app's socket": ac.closed} {
+ select {
+ case <-ch:
+ default:
+ t.Fatalf("%s: %s is still open", when, name)
+ }
+ }
+}
+
// TestTunnelWebSocketTwoReloads is spec §8.2 case 18 over the real scene:
// Task 4's schedule (TestTwoReloadsInterleave) with a socket open on the
// forward row, and its item 7, the close at both endpoints.
@@ -627,7 +681,8 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
tc := s.channel(t, wsBox1)
c, ac, res := wsReloadSocket(t, s)
sc := newReloadScript(t, s.hub, "A", "B")
- sc.hold("A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep", "B:afterPublish", "B:afterSweep")
+ sc.hold("A:afterRead", "A:beforePublish", "A:afterPublish", "A:afterSweep", "B:afterPublish", "B:afterSweep",
+ "record:before", "record:after")
tick := startTickedWatch(t, s.hub, sc)
// 1. A (SIGHUP's stand-in) stops after its registry reads.
@@ -689,12 +744,21 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
t.Fatalf("the first releaser is %v, want relSweep", got)
}
sc.release("B:afterSweep")
- sc.wait("record:after")
+ // The record, between its barriers: B has returned, its sweep has
+ // closed both ends, and Watch holds the fingerprint it read after
+ // the owner change.
+ sc.wait("record:before")
sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
- "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after")
+ "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before")
+ wsClosed(t, "at record:before", c, ac)
if got := sc.recorded(); !slices.Equal(got, []string{fp}) {
- t.Fatalf("Watch recorded %q, want the fingerprint read after the owner change, %q", got, fp)
+ t.Fatalf("Watch records %q, want the fingerprint read after the owner change, %q", got, fp)
}
+ sc.release("record:before")
+ sc.wait("record:after")
+ sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
+ "B:afterRead", "B:beforePublish", "B:afterPublish", "B:afterSweep", "record:before", "record:after")
+ sc.release("record:after")
waitOpen(t, s.hub, tc, 0, "after B's sweep")
refusedNow(t, s, "after B")
})
@@ -707,7 +771,7 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
tc := s.channel(t, wsBox1)
c, ac, res := wsReloadSocket(t, s)
sc := newReloadScript(t, s.hub, "A", "B", "C")
- sc.hold("A:afterRead", "C:enter")
+ sc.hold("A:afterRead", "C:enter", "record:before", "record:after")
sc.failAt("B:afterRead", errors.New("registry read failed (test)"))
tick := startTickedWatch(t, s.hub, sc)
@@ -736,11 +800,19 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
stillOpen(t, s, c, ac, res, "after B failed")
deadline := time.Now().Add(2 * time.Second)
sc.release("C:enter")
+ // C swaps and sweeps before Watch records: the record waits at its
+ // barrier while both ends close.
+ sc.wait("record:before")
+ sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
+ "B:afterRead", "C:enter", "C:afterRead", "C:beforePublish", "C:afterPublish", "C:afterSweep",
+ "record:before")
+ closedBy(t, deadline, "C's sweep", c, ac)
+ sc.release("record:before")
sc.wait("record:after")
sc.logIs("A:enter", "A:afterRead", "B:enter", "A:beforePublish", "A:afterPublish", "A:afterSweep",
"B:afterRead", "C:enter", "C:afterRead", "C:beforePublish", "C:afterPublish", "C:afterSweep",
"record:before", "record:after")
- closedBy(t, deadline, "C's sweep", c, ac)
+ sc.release("record:after")
if got := res.firstReleaser(); got != relSweep {
t.Fatalf("the first releaser is %v, want relSweep", got)
}
@@ -759,7 +831,7 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
tc := s.channel(t, wsBox1)
c, ac, res := wsReloadSocket(t, s)
sc := newReloadScript(t, s.hub, "B", "A")
- sc.hold("B:afterSweep")
+ sc.hold("B:afterSweep", "record:before", "record:after")
tick := startTickedWatch(t, s.hub, sc)
setFleetOwner(t, s.hub, "home", fwdOther)
@@ -781,8 +853,16 @@ func TestTunnelWebSocketTwoReloads(t *testing.T) {
t.Fatalf("A read the registry while B holds the reload: %v", sc.snapshot())
}
sc.release("B:afterSweep")
+ // Watch reaches its record once B returns, and waits there; A runs
+ // to its end meanwhile, so A never depends on the record.
+ sc.wait("record:before")
awaitReload(t, aDone, "A")
+ if sc.has("record:after") {
+ t.Fatalf("Watch passed its held record: %v", sc.snapshot())
+ }
+ sc.release("record:before")
sc.wait("record:after")
+ sc.release("record:after")
// B's run and Watch's record are one ordered sequence, and so is
// A's; A entered after B's sweep and read only after B returned.