carlos / platform Public

devbox mode (#474): registrar fix round 1 (Astra review)

1. The spool cap now counts every directory an upload creates, including
   the parents ExtractSite makes implicitly for nested files, plus three
   publication blocks (link dir, current, the transient swap symlink).
   Entry names are capped at 4096 bytes and entries plus distinct dirs at
   100k, so the scan's work and memory stay bounded.
2. swapCurrent reports whether its rename landed. A sync failure after
   the rename now points current back at the previous tree before the
   new one is discarded.
3. Naming a snapshot retries only a name that exists. Any other Lstat
   error is returned and the temp tree removed, with an attempt bound,
   so a persistent error cannot spin under the registrar lock.

Unexported seams lstatSnapshot and syncSpoolDir carry the failure
injection. Regression tests: TestShareFolderSpoolCapCountsImplicitDirs,
TestShareFolderSyncFailureRestoresCurrent,
TestShareFolderLstatErrorDoesNotSpin.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 7b9e1009b9127d3cfa00e65218e25f9d62ec3a71 parent 09f08bb
2 files changed, +253 −29
  • internal/devbox/registrar.go +104 −26
  • internal/devbox/registrar_test.go +149 −3

Intent

Human

<task-notification> <task-id>ac566491bcc233331</task-id> <tool-use-id>toolu_01L68Cz6t8X1AKb8VHrMTeQX</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/ac566491bcc233331.output</output-file> <status>completed</status> <summary>Agent "Implement Task 3: ServeDevbox front door" 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>All three review findings are fixed and committed as 09f08bbe. Not pushed. **Commits:** 3a8a59f6, 5deb672a and 09f08bbe. Other sessions have committed to design-devbox-mode in between (link store, registrar, spool, copy deck), so my commits are not contiguous. Both earlier commits are still ancestors of HEAD, and 09f08bbe touches only `devbox.go` and `devbox_test.go`. **Tests:** `go test ./internal/edge -run 'TestDevbox|TestWildcard'` passes, including all 8 TestDevbox* tests, and gofmt and vet are clean. Refused handshakes no longer print to the test output. **Fixes:** - **Drain timeout (IMPORTANT):** when the 10s Shutdown deadline passes, ServeDevbox now calls `srv.Close()` and returns an error that wraps the Shutdown error. A clean drain still returns nil. - **Drain test (MINOR):** the end-to-end test holds a proxied request open across cancellation. It checks that ServeDevbox has not returned while that request is in flight, that the request completes with 200, and that ServeDevbox then returns nil. The new `TestDevboxDrainTimeoutClosesAndReports` runs a 200ms drain out of time and checks for the error and the forced close. - **Log noise (MINOR):** refused handshakes now go to a captured error log, and the test checks the expected lines are there. - The test hooks are now one unexported struct, `devboxSeams` (bound address, server error log, drain timeout). Its zero value is production. **Checks:** I ran two deliberate code breaks, both reverted afterwards. Swallowing the drain error made the timeout test fail, and replacing Shutdown with an immediate Close made the drain test fail. **Concerns:** - In production, the server's log lines for refused handshakes are still not rate-limited. - The commit printed an error about `packed-refs.lock`, but it did land. That lock file is 0 bytes and probably belongs to another session's git process, so I left it alone. Report (fix round 1 appended): /home/paulca/amadan.net/carlos/platform/.claude/worktrees/devbox-mode/.superpowers/sdd/2026-10-30-devbox-mode/task-3-report.md</result> <usage><subagent_tokens>141900</subagent_tokens><tool_uses>11</tool_uses><duration_ms>221165</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bemeyzemr</task-id> <tool-use-id>toolu_01U4anXw1vh4LFoYqYCGQt6u</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/9b370a04-693c-4bda-b2eb-9a4b08f7626d/tasks/bemeyzemr.output</output-file> <status>completed</status> <summary>Background command "Run Astra scoped re-review for Task 3" completed (exit code 0)</summary> </task-notification>

Attributed to this commit: 16.9 g CO₂e (2,083,989 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on design-devbox-mode, 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/devbox/registrar.go b/internal/devbox/registrar.go
index d0df84fa8..57bd0563d 100644
--- a/internal/devbox/registrar.go
+++ b/internal/devbox/registrar.go
@@ -59,10 +59,21 @@ const (
// AnswerTimeout bounds each /list dial to a live link's port.
AnswerTimeout = 300 * time.Millisecond
- // maxFolderEntries caps the entries in one upload: the spool cap counts
- // bytes, so without this a small archive of empty files could use up
- // the disk's inodes.
+ // maxFolderEntries caps what one upload creates: its archive entries
+ // plus the distinct directories they imply. It bounds the scan's work
+ // and memory; the spool cap, which charges every entry a block, is what
+ // bounds the disk.
maxFolderEntries = 100_000
+ // maxEntryName caps one archive entry's name (PATH_MAX). With the entry
+ // cap it bounds the scan's work on names.
+ maxEntryName = 4096
+ // maxDirKeyBytes caps the bytes of directory paths the scan remembers.
+ maxDirKeyBytes = 16 << 20
+ // publishBlocks is what publishing a snapshot adds to the spool besides
+ // the snapshot itself: the link directory, current, and the fresh
+ // symlink that is renamed over current (both exist for a moment).
+ // Charged on every upload, even when the first two already exist.
+ publishBlocks = 3
// spoolBlock is what every spool entry costs at least, file, directory
// or symlink: the disk spends a block and an inode on each, so a byte
// count alone would let an archive of empty files fill the disk.
@@ -423,6 +434,7 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
if int64(len(data)) > need {
need = int64(len(data))
}
+ need += publishBlocks * spoolBlock
if used+need > r.SpoolCap {
return nil, refuse(http.StatusInsufficientStorage, CodeSpoolFull)
}
@@ -461,7 +473,14 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
discard(snapDir)
return nil, internalErr("links put", err)
}
- if err := swapCurrent(dir, snap); err != nil {
+ if published, err := swapCurrent(dir, snap); err != nil {
+ // The rename can land and the directory sync after it fail: then
+ // current already names the new tree, and must be pointed back
+ // before that tree goes. With no earlier tree, discard removes
+ // current with the rest.
+ if published && prevSnap != "" {
+ r.repointCurrent(name, dir, prevSnap)
+ }
r.restoreLink(name, prev, had)
discard(snapDir)
return nil, internalErr("swap current", err)
@@ -471,9 +490,7 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
// Point current back where it was; with no earlier tree, discard
// removes current along with the rest.
if prevSnap != "" {
- if serr := swapCurrent(dir, prevSnap); serr != nil {
- log.Printf("devbox registrar: rollback current %s: %v", name, serr)
- }
+ r.repointCurrent(name, dir, prevSnap)
}
r.restoreLink(name, prev, had)
discard(snapDir)
@@ -483,6 +500,15 @@ func (r *Registrar) serveShareFolder(uid uint32, w http.ResponseWriter, req *htt
return r.entry(link), nil
}
+// repointCurrent points current back at prevSnap during a rollback. A
+// failed sync after the rename still leaves current pointing at prevSnap,
+// which is what a rollback needs; only a failed rename leaves it wrong.
+func (r *Registrar) repointCurrent(name, dir, prevSnap string) {
+ if _, err := swapCurrent(dir, prevSnap); err != nil {
+ log.Printf("devbox registrar: rollback current %s: %v", name, err)
+ }
+}
+
// linkDir returns <SpoolRoot>/<name>, creating it. Whatever is at that path
// must be a real directory: a symlink there would let a write land outside
// the spool.
@@ -531,33 +557,55 @@ func extractSnapshot(data []byte, dir string) (string, *refusal) {
}
return "", refuse(http.StatusBadRequest, CodeBadRequest)
}
+ // Only a name that exists already is retried; any other Lstat error
+ // is returned, since this runs under the registrar lock and a
+ // persistent error must not spin there.
n := time.Now().UnixNano()
- for {
+ for attempt := 0; attempt < maxSnapshotAttempts; attempt, n = attempt+1, n+1 {
snap := strconv.FormatInt(n, 10)
dst := filepath.Join(dir, snap)
- if _, err := os.Lstat(dst); errors.Is(err, fs.ErrNotExist) {
- if err := os.Rename(tmp, dst); err != nil {
- os.RemoveAll(tmp)
- return "", internalErr("rename snapshot", err)
- }
- return snap, nil
+ _, err := lstatSnapshot(dst)
+ if err == nil {
+ continue
+ }
+ if !errors.Is(err, fs.ErrNotExist) {
+ os.RemoveAll(tmp)
+ return "", internalErr("lstat snapshot", err)
+ }
+ if err := os.Rename(tmp, dst); err != nil {
+ os.RemoveAll(tmp)
+ return "", internalErr("rename snapshot", err)
}
- n++
+ return snap, nil
}
+ os.RemoveAll(tmp)
+ return "", internalErr("snapshot name", errors.New("no free snapshot name"))
}
+// maxSnapshotAttempts bounds the search for a free snapshot name. Names are
+// nanoseconds and the lock serialises uploads, so a clash is already rare.
+const maxSnapshotAttempts = 1000
+
+// Seams for failure injection in tests.
+var (
+ lstatSnapshot = os.Lstat
+ syncSpoolDir = syncDir
+)
+
// swapCurrent points dir/current at snap: a fresh relative symlink renamed
// over the old one, so a reader sees the old tree or the new, never neither.
-func swapCurrent(dir, snap string) error {
+// published reports whether the rename landed, so current names snap even
+// when err (the directory sync after it) is not nil.
+func swapCurrent(dir, snap string) (published bool, err error) {
tmp := filepath.Join(dir, swapPrefix+strconv.FormatInt(time.Now().UnixNano(), 10))
if err := os.Symlink(snap, tmp); err != nil {
- return err
+ return false, err
}
if err := os.Rename(tmp, filepath.Join(dir, currentLink)); err != nil {
os.Remove(tmp)
- return err
+ return false, err
}
- return syncDir(dir)
+ return true, syncSpoolDir(dir)
}
// pruneSnapshots removes everything in dir except current, the new snapshot
@@ -620,7 +668,9 @@ func spoolUsage(root string) (int64, error) {
// scanSite reads a site.tar.gz the way edge.ExtractSite will, without
// writing anything, and returns what the snapshot will cost the spool
-// (blocks, as spoolUsage counts it), the snapshot directory included. It refuses what
+// (blocks, as spoolUsage counts it): the snapshot directory, every file,
+// and every distinct directory, whether the archive names it or
+// ExtractSite makes it implicitly for a file's parents. It refuses what
// ExtractSite would refuse (bad-request), and an archive that would unpack
// past limit or hold too many entries (folder-too-big). Decompression stops
// as soon as the declared sizes pass limit, so a gzip bomb costs little.
@@ -632,6 +682,28 @@ func scanSite(data []byte, limit int64) (int64, *refusal) {
defer gz.Close()
tr := tar.NewReader(gz)
total := int64(spoolBlock) // the snapshot directory itself
+ // dirs is every directory the extraction will create, relative to the
+ // snapshot. Keys are cloned so no entry name is kept alive whole.
+ dirs := map[string]struct{}{}
+ dirBytes := 0
+ tooBig := refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig)
+ // addDir charges d and each of its parents not seen yet. A seen
+ // directory's parents were all charged with it, so the walk stops there.
+ addDir := func(d string, entries int) *refusal {
+ for d != "." && d != "" {
+ if _, ok := dirs[d]; ok {
+ return nil
+ }
+ if entries+len(dirs) >= maxFolderEntries || dirBytes+len(d) > maxDirKeyBytes {
+ return tooBig
+ }
+ dirs[strings.Clone(d)] = struct{}{}
+ dirBytes += len(d)
+ total += spoolBlock
+ d = filepath.Dir(d)
+ }
+ return nil
+ }
for entries := 0; ; entries++ {
hdr, err := tr.Next()
if err == io.EOF {
@@ -640,9 +712,13 @@ func scanSite(data []byte, limit int64) (int64, *refusal) {
if err != nil {
return 0, refuse(http.StatusBadRequest, CodeBadRequest)
}
- if entries >= maxFolderEntries {
- return 0, refuse(http.StatusRequestEntityTooLarge, CodeFolderTooBig)
+ if entries+len(dirs) >= maxFolderEntries {
+ return 0, tooBig
+ }
+ if len(hdr.Name) > maxEntryName {
+ return 0, refuse(http.StatusBadRequest, CodeBadRequest)
}
+ // The same path ExtractSite writes to.
name := filepath.FromSlash(path.Clean(hdr.Name))
if !filepath.IsLocal(name) || strings.ContainsRune(hdr.Name, 0) {
return 0, refuse(http.StatusBadRequest, CodeBadRequest)
@@ -651,14 +727,16 @@ func scanSite(data []byte, limit int64) (int64, *refusal) {
case tar.TypeXGlobalHeader:
continue
case tar.TypeDir:
- // A directory ExtractSite makes implicitly for a file costs a
- // block too, and is not in the archive. Counting each file's
- // parents would be exact; the entry cap bounds the gap instead.
- total += spoolBlock
+ if ref := addDir(name, entries); ref != nil {
+ return 0, ref
+ }
case tar.TypeReg:
if hdr.Size < 0 {
return 0, refuse(http.StatusBadRequest, CodeBadRequest)
}
+ if ref := addDir(filepath.Dir(name), entries); ref != nil {
+ return 0, ref
+ }
total += blocks(hdr.Size)
default:
return 0, refuse(http.StatusBadRequest, CodeBadRequest)
diff --git a/internal/devbox/registrar_test.go b/internal/devbox/registrar_test.go
index 79f69dbcd..9ee251c5c 100644
--- a/internal/devbox/registrar_test.go
+++ b/internal/devbox/registrar_test.go
@@ -17,6 +17,7 @@ import (
"runtime"
"sort"
"strings"
+ "syscall"
"testing"
"time"
@@ -563,9 +564,11 @@ func TestShareFolderOverCapRefused(t *testing.T) {
func TestSpoolFullRefused(t *testing.T) {
f := newFixture(t)
- // The spool counts blocks: "one" costs its dir, current, the snapshot
- // dir and a.bin, a block each (16 KiB). A second upload needs two more.
- f.r.SpoolCap = 20000
+ // The spool counts blocks: "one" occupies its dir, current, the
+ // snapshot dir and a.bin, a block each (16 KiB). Admitting an upload
+ // charges its snapshot dir and file plus three publication blocks
+ // (20 KiB), so a second upload no longer fits under 32 KiB.
+ f.r.SpoolCap = 32 << 10
wantOK(t, f.shareFolder(t, 1001, "one", packSite(t, map[string]string{"a.bin": strings.Repeat("a", 2000)})))
wantCode(t, f.shareFolder(t, 1002, "two", packSite(t, map[string]string{"b.bin": strings.Repeat("b", 2000)})), CodeSpoolFull)
if _, err := os.Stat(filepath.Join(f.spool, "two")); err == nil {
@@ -896,3 +899,146 @@ func sorted(s ...string) []string {
sort.Strings(s)
return s
}
+
+// The spool cap holds after every accepted upload, counting the
+// directories ExtractSite makes implicitly for nested files and the
+// publication entries (link dir, current), not just archive entries.
+func TestShareFolderSpoolCapCountsImplicitDirs(t *testing.T) {
+ const b = spoolBlock
+ nested := rawTar(t, &tar.Header{Name: "a/b/c/file", Typeflag: tar.TypeReg, Mode: 0o644})
+
+ // One empty a/b/c/file occupies 7 blocks once published: link dir,
+ // current, snapshot dir, a, a/b, a/b/c, file. Admission charges those
+ // plus the transient swap symlink: 8 blocks.
+ f := newFixture(t)
+ f.r.SpoolCap = 8*b - 1
+ wantCode(t, f.shareFolder(t, 1001, "shop", nested), CodeSpoolFull)
+ if _, err := os.Lstat(filepath.Join(f.spool, "shop")); !os.IsNotExist(err) {
+ t.Fatalf("refused upload left a spool dir: %v", err)
+ }
+ f.r.SpoolCap = 8 * b
+ wantOK(t, f.shareFolder(t, 1001, "shop", nested))
+ if used, err := spoolUsage(f.spool); err != nil || used != 7*b {
+ t.Fatalf("usage = %d, %v; want %d", used, err, 7*b)
+ }
+
+ // Many distinct directory chains, no directory headers, uploaded until
+ // the spool refuses: usage never passes the cap.
+ var hdrs []*tar.Header
+ for i := 0; i < 10; i++ {
+ hdrs = append(hdrs, &tar.Header{Name: fmt.Sprintf("d%d/x/y/z/f", i), Typeflag: tar.TypeReg, Mode: 0o644})
+ }
+ chains := rawTar(t, hdrs...)
+ g := newFixture(t)
+ g.r.SpoolCap = 150 * b
+ accepted := 0
+ for i := 0; i < 20; i++ {
+ name := fmt.Sprintf("s%d", i%3) // reshares too, so R7's kept trees count
+ rec := g.shareFolder(t, 1001, name, chains)
+ if rec.Code != 200 {
+ wantCode(t, rec, CodeSpoolFull)
+ break
+ }
+ accepted++
+ used, err := spoolUsage(g.spool)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if used > g.r.SpoolCap {
+ t.Fatalf("upload %d: usage %d passes the cap %d", i, used, g.r.SpoolCap)
+ }
+ }
+ if accepted == 0 {
+ t.Fatal("nothing accepted")
+ }
+}
+
+// A directory sync that fails after the rename landed leaves current
+// pointing at the previous tree, not at the new one rollback deletes.
+func TestShareFolderSyncFailureRestoresCurrent(t *testing.T) {
+ f := newFixture(t)
+ wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "one"})))
+ k0, _ := f.r.Links.Get("shop")
+ row0 := f.row(t, "shop")
+
+ failed := 0
+ syncSpoolDir = func(string) error { failed++; return syscall.EIO }
+ t.Cleanup(func() { syncSpoolDir = syncDir })
+ if rec := f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "two"})); rec.Code != 500 {
+ t.Fatalf("reshare with a failing sync = %d %s", rec.Code, rec.Body)
+ }
+ if failed == 0 {
+ t.Fatal("the sync seam was not reached")
+ }
+ if got := readCurrent(t, f.spool, "shop", "index.html"); got != "one" {
+ t.Fatalf("current after rollback = %q", got)
+ }
+ if target, _ := os.Readlink(filepath.Join(f.spool, "shop", "current")); target != k0.Snapshot {
+ t.Fatalf("current -> %q, want %q", target, k0.Snapshot)
+ }
+ if k, _ := f.r.Links.Get("shop"); k != k0 {
+ t.Fatalf("link not restored: %+v -> %+v", k0, k)
+ }
+ if names := dirNames(t, filepath.Join(f.spool, "shop")); !equal(names, sorted("current", k0.Snapshot)) {
+ t.Fatalf("spool after rollback: %v", names)
+ }
+ if rt := f.row(t, "shop"); rt.Kind != row0.Kind || rt.App != row0.App {
+ t.Fatalf("row changed: %+v", rt)
+ }
+
+ // A first share whose sync fails leaves nothing behind.
+ if rec := f.shareFolder(t, 1001, "fresh", packSite(t, map[string]string{"index.html": "x"})); rec.Code != 500 {
+ t.Fatalf("first share with a failing sync = %d", rec.Code)
+ }
+ if _, err := os.Lstat(filepath.Join(f.spool, "fresh")); !os.IsNotExist(err) {
+ t.Fatalf("spool dir left: %v", err)
+ }
+ if _, ok := f.r.Links.Get("fresh"); ok {
+ t.Fatal("link left")
+ }
+ if f.row(t, "fresh") != nil {
+ t.Fatal("row written")
+ }
+
+ // With the sync back, the next upload works.
+ syncSpoolDir = syncDir
+ wantOK(t, f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "three"})))
+ if got := readCurrent(t, f.spool, "shop", "index.html"); got != "three" {
+ t.Fatalf("current = %q", got)
+ }
+}
+
+// An Lstat error other than not-exist while naming the snapshot is returned,
+// not retried forever under the registrar lock, and the extracted temp tree
+// is removed.
+func TestShareFolderLstatErrorDoesNotSpin(t *testing.T) {
+ f := newFixture(t)
+ calls := 0
+ lstatSnapshot = func(string) (os.FileInfo, error) { calls++; return nil, syscall.EACCES }
+ t.Cleanup(func() { lstatSnapshot = os.Lstat })
+
+ done := make(chan *httptest.ResponseRecorder, 1)
+ go func() { done <- f.shareFolder(t, 1001, "shop", packSite(t, map[string]string{"index.html": "x"})) }()
+ var rec *httptest.ResponseRecorder
+ select {
+ case rec = <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("share did not return: the snapshot loop spins")
+ }
+ if rec.Code != 500 {
+ t.Fatalf("share = %d %s", rec.Code, rec.Body)
+ }
+ if calls != 1 {
+ t.Fatalf("lstat called %d times, want 1", calls)
+ }
+ if _, err := os.Lstat(filepath.Join(f.spool, "shop")); !os.IsNotExist(err) {
+ t.Fatalf("spool dir left: %v", err)
+ }
+ if _, ok := f.r.Links.Get("shop"); ok {
+ t.Fatal("link written")
+ }
+
+ // The lock was released: the next share goes through.
+ lstatSnapshot = os.Lstat
+ wantOK(t, f.shareLive(t, 1001, "other", 8080))
+}