oficina / equipo Public

Astra round 2: attachment quota at admission; sweep stops on lookup error

Arriving files count against the quota by declared size; a new file is
admitted only if it fits once the oldest unprotected delivered files
make room, else refused: its chunks acked unwritten and the turn fails
runner_storage_full, said in words in the conversation. Protected are a
running turn's files and admitted files whose message has not come. A
sweep removes nothing when protection cannot be read (cancelled, query,
scan or decode errors). Tests failed first.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev d0d690e09656abf339b7542b4f2f9d9986ccfb72 parent 3edda02
14 files changed, +546 −92
  • .rastrillo/budgets.txt +1 −1
  • docs/superpowers/plans/COMPOSER-PROGRESS.md +29 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +1 −0
  • internal/equipo/chat_page.go +6 −1
  • internal/equipo/copy.go +1 −0
  • internal/equipo/static/chat-stream.js +1 −1
  • internal/equipo/templates/chat.html +1 −1
  • internal/runner/thin/claude.go +10 −1
  • internal/runner/thin/codex.go +1 −1
  • internal/runner/thin/files.go +245 −73
  • internal/runner/thin/files_test.go +160 −2
  • internal/runner/thin/state.go +46 −11
  • internal/thintest/attachments_contract_test.go +38 −0
  • internal/wire/frames.go +6 −0

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index fff90972..1d9cb875 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -35,7 +35,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full
perf GET /releases/* skip Verified runner release file downloads, not browser GET screens.
time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; niced serial reruns measured 5.773s and 5.750s. The added coordinator mount check has no repeated launches to remove; 15s leaves 38 percent headroom for namespace, process-exit and recovery assertions.
time internal/tryequipo 30s Release starter-set controller K3 records CI runs of 10.8s and 13.1s; 30s retains the guide integration checks with headroom on the shared runner.
-size internal/runner/thin 12100 - Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path.
+size internal/runner/thin 12300 - Astra round 2 moves the attachment quota to admission: arriving files counted by declared size, admissions protecting a file until its message names it, room made from the oldest unprotected files, refusal as runner_storage_full, and a sweep that stops when protection cannot be read (about 150 lines); measured 12191. Composer attachments add the chunked receipt with exactly-once writes, the read-only desk delivery and its checks (files.go, about 230 lines), image blocks and localImage inputs, the attachment read through read_file; measured 11736. Connections slice 1 Astra round 1 adds the Codex step path (codexstep.go: Engineering and Review on the pinned app-server in the implement and inspect containment, about 300 lines); measured 11345. Connections slice 1 (after Astra round 1) also keeps a durable ledger of each turn's write tools so a later attempt never repeats one (effects.go), the waiting state between attempts and usage rows per attempt, about 500 lines more; measured 10590 before gate 1d. Connections slice 1 adds the Codex coordinator beside the Claude one (codex.go: the pinned app-server over JSON-RPC in the converse containment, sharing the coordinator base, desk, tool socket and session table), the connection registry over the bindings with health and provider limits (conns.go), in-app sign-in attempts (connector.go) and turn failover and holding (failover.go), about 1500 lines; the pure parts (the choice function, limit parsing, the app-server client, the sign-in flows) live in internal/runner/connect. Measured 10097. Thin v1 UX1 adds step activity lines from the specialist's stream, the repository head and checks gate in the index and project-tagged notes (about 120 lines); measured 8615 with slice 4c's review fixes. Thin v1 slice 4c adds the merge step (mergestep.go, about 190 lines) and the rebase round beside the slice 4b ask fixes. Thin v1 slice 3 adds Engineering steps beside the coordinator: the durable step state and engine (step.go) and the executor that checks out the task tree, runs the CLI in the implement containment, commits and pushes (engineer.go), about 800 lines sharing the coordinator's launch, tool socket and account selection. Measured 5686 source lines. Splitting would export the launch internals; revisit at the slice 7 sweep. Slice 4 adds checks and review on a candidate (judge.go) and the merge watch (merge.go), about 800 lines, sharing the Engineer launch path; measured 6808, 7035 after review round 1 (branch head watch, deadlines, streamed outputs). Slice 4b keeps Engineering and Review sessions and answers the creator's questions from them (ask.go: kept-session and ask state, read-only git tools, the answer stream), about 700 lines on the same launch path.
time internal/thintest 75s Housekeeping slice 1 adds six contract tests (combine, Undo round trips and the race, Pause, auto-disable, quiet hours, restart while claimed; about 6s); the package measured 67.7s beside other packages locally, so 75s. Thin v1 slice 4c adds the merge, adoption, cancel and retention contract tests (CI measured 35.7s). Thin v1 contract tests: a real instance and a scripted runner per test, fixtures replayed against every request, frame and event. Slice 3 adds the task, step-sync and grant contracts; CI measured 14.805s. 30s keeps room for the slice 4 review contracts. UX1 adds step activity, task source and duplicates, coordinator merging and project facts (four contracts, about 6s); the package measured 34s locally under load, so 40s. UX1's inner screens gallery (two owners, seven tasks, every page) adds about 3s; measured 40.9s locally under load, so 60s.
time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). Measured 17.8s locally under load. Slice 4b review adds a 16 MiB git output bound, an injected index-pack failure and stall (3s deadline) and held-answer tests; measured 30.3s locally under load. 45s keeps 33 percent headroom.
time internal/headless 480s Connections slice 1 after Astra round 1 adds attempts that wait for a connection, Review on a refused credential, Codex Engineering and Review and the preference (about 90s more; loaded CI measured 6m42s). It first adds TestHeadlessConnections (usage rows, failover, Codex coordinator, device code, Claude sign-in, failure kinds, cancel and sign-out, writes replayed, Engineering and Review moving connection, the waiting turn): eleven scenarios, about 55 to 100s locally. Thin v1 headless suite: real instance, runner and bubblewrap per scenario (spec 7, under two minutes). Slice 4 adds the review and checks scenarios (4_review with its fix rounds, branch move and merge; 4_checks_honest); loaded CI measured 170s on 2026-11-07. Slice 4b adds 4b_ask (about 12s); loaded CI measured 182.9s. 240s keeps 30 percent headroom.
diff --git a/docs/superpowers/plans/COMPOSER-PROGRESS.md b/docs/superpowers/plans/COMPOSER-PROGRESS.md
index 01828739..7974a908 100644
--- a/docs/superpowers/plans/COMPOSER-PROGRESS.md
+++ b/docs/superpowers/plans/COMPOSER-PROGRESS.md
@@ -505,6 +505,35 @@ The sets, in full (copy for review, accepted for now):
- Handing to Engineering (15): Dispatching to Engineering… | Spawning a worker… | Forking a task… | Queueing the job… | Piping it to Engineering… | Delegating… | Opening a branch… | Scheduling the work… | Handing off… | Enqueuing… | Launching a subtask… | Writing the spec… | Assigning the job… | Starting a process… | Kicking off the build…
- Any other tool (15): Running tools… | Compiling… | Spinning up… | Executing… | Invoking… | Calling the API… | Running checks… | Linting… | Installing… | Linking… | Building… | Fetching… | Polling… | Syncing… | Warming caches…
+## Round: Astra round 2 (final), REQUEST CHANGES
+
+Five of six resolved; one open and one new (`~/.cache/tmp/equipo/comprev2-final.md`):
+1. Disk quota at admission. The one-hour exemption is gone. A new
+ attachment is admitted (table `file_admits`) only if, counting
+ delivered files and every arriving one by its declared size, it fits
+ the person's and the runner's quota once room is made from the oldest
+ delivered files nothing protects. Protected: files a running turn
+ names, and files admitted whose message has not yet named them (the
+ message frame clears their admissions; the running turn protects them
+ from then on). Otherwise it is refused (`file_refused`): every chunk is
+ acked unwritten, and the turn fails `runner_storage_full`, which the
+ conversation says in words: "Your runner has no room left for these
+ attachments. Try fewer or smaller files." (copy for review, accepted
+ for now). The sweep enforces the same quota with the same protection.
+ `TestAttachmentQuotaAdmission`: a 1-file, 1-byte quota never holds a
+ byte over (three 10-byte files all refused); a protected file is
+ never removed to make room and the new one is refused; once its turn
+ ends it makes room; an arriving file counts. Failed with the room check
+ off, with arriving files uncounted, and with running turns unprotected.
+ `TestContractStorageFullInWords` failed first on the old page.
+2. A sweep stops when protection cannot be read: `runningAttachments`
+ returns an error on a query, scan, decode or iteration failure, and
+ `Files.protected` on a cancelled context; nothing is removed and the
+ failure is logged. `TestAttachmentSweepAbortsOnLookupFailure`
+ (cancelled, an injected query error, a record that does not decode;
+ then a healthy sweep keeps the protected and removes the rest). Failed
+ with a failed lookup read as "nothing protected".
+
## Staging
Not restaged (the controller sequences it).
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 6b97974b..7f22de6d 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -5150,6 +5150,7 @@ records remain unchanged.
| `api.attachment_too_large` | That file is over 10 MB. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `api.attachment_type` | Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `api.attachment_heic` | HEIC photos cannot be read yet. Share it as a JPEG and try again. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
+| `chat.failed_storage` | Your runner has no room left for these attachments. Try fewer or smaller files. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `api.attachment_pixels` | That image is too large: at most 12,000 pixels on a side and 40 megapixels. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `api.attachment_limit` | Too many files are waiting to send. Send or remove some first. | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
| `settings.saved` | Saved | Composer and attachments (2026-11-08) | Runtime; COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context) |
diff --git a/internal/equipo/chat_page.go b/internal/equipo/chat_page.go
index da453e11..5008386b 100644
--- a/internal/equipo/chat_page.go
+++ b/internal/equipo/chat_page.go
@@ -259,7 +259,12 @@ func (a *application) chatPage(w http.ResponseWriter, r *http.Request) {
}
}
if latest != nil && (latest.State == wire.TurnFailed || latest.State == wire.TurnCancelled) {
- view.Ended = &chatEnded{ID: latest.ID, Key: "chat." + latest.State}
+ key := "chat." + latest.State
+ if latest.Reason == wire.ReasonStorageFull {
+ // The runner had no room for an attachment: said in words.
+ key = "chat.failed_storage"
+ }
+ view.Ended = &chatEnded{ID: latest.ID, Key: key}
}
data.Chat, data.ChatStream, data.RequestID = view, true, rand.Text()
data.ThinkingSet, data.ThinkingWords = a.thinkingFor(ctx, address)
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index e75704e5..9fa30025 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -1084,6 +1084,7 @@ var pageCopy = map[string]string{
"api.attachment_too_large": "That file is over 10 MB.",
"api.attachment_type": "Equipo takes images (PNG, JPEG, WebP, GIF) and text, Markdown, CSV, JSON, log and PDF files.",
"api.attachment_heic": "HEIC photos cannot be read yet. Share it as a JPEG and try again.",
+ "chat.failed_storage": "Your runner has no room left for these attachments. Try fewer or smaller files.",
"api.attachment_pixels": "That image is too large: at most 12,000 pixels on a side and 40 megapixels.",
"api.attachment_limit": "Too many files are waiting to send. Send or remove some first.",
// COPY ACCEPTED FOR NOW (Paul, 2026-11-04; iterate in context): conversation.send
diff --git a/internal/equipo/static/chat-stream.js b/internal/equipo/static/chat-stream.js
index aac9d1ca..9b9373f0 100644
--- a/internal/equipo/static/chat-stream.js
+++ b/internal/equipo/static/chat-stream.js
@@ -565,7 +565,7 @@
if (v.kind) return;
var note = template("equipo-ended-template");
note.dataset.ended = v.id;
- note.querySelector("p").textContent = v.state === "failed" ? form.dataset.failed : form.dataset.cancelled;
+ note.querySelector("p").textContent = v.state !== "failed" ? form.dataset.cancelled : v.reason === "runner_storage_full" && form.dataset.failedStorage ? form.dataset.failedStorage : form.dataset.failed;
feed.append(note);
scroll();
}
diff --git a/internal/equipo/templates/chat.html b/internal/equipo/templates/chat.html
index 2fa8c32d..819f0eb0 100644
--- a/internal/equipo/templates/chat.html
+++ b/internal/equipo/templates/chat.html
@@ -43,7 +43,7 @@
</div>
<div equipo-announcements role="status" aria-live="polite" aria-atomic="false"></div>
<div id="chat-composer">
-<form id="composer" equipo-form equipo-composer method="post" action="/conversation" data-failed="{{copy "chat.failed"}}" data-retry="{{copy "conversation.retry"}}" data-cancelled="{{copy "chat.cancelled"}}" data-upload="/conversation/attachments" data-max-files="5" data-max-bytes="10485760" data-too-large="{{copy "api.attachment_too_large"}}" data-heic="{{copy "api.attachment_heic"}}" data-too-many="{{copy "chat.attach.too_many"}}" data-upload-failed="{{copy "chat.attach.failed"}}" data-uploading="{{copy "chat.attach.uploading"}}" data-remove="{{copy "chat.attach.remove"}}">
+<form id="composer" equipo-form equipo-composer method="post" action="/conversation" data-failed="{{copy "chat.failed"}}" data-failed-storage="{{copy "chat.failed_storage"}}" data-retry="{{copy "conversation.retry"}}" data-cancelled="{{copy "chat.cancelled"}}" data-upload="/conversation/attachments" data-max-files="5" data-max-bytes="10485760" data-too-large="{{copy "api.attachment_too_large"}}" data-heic="{{copy "api.attachment_heic"}}" data-too-many="{{copy "chat.attach.too_many"}}" data-upload-failed="{{copy "chat.attach.failed"}}" data-uploading="{{copy "chat.attach.uploading"}}" data-remove="{{copy "chat.attach.remove"}}">
<input type="hidden" name="request_id" value="{{.RequestID}}">
<div equipo-adder hidden><button type="button" equipo-plus aria-label="{{copy "chat.attach.add"}}" title="{{copy "chat.attach.add"}}" aria-haspopup="menu" aria-expanded="false" aria-controls="attach-menu">{{icon "plus"}}</button><div equipo-add-menu id="attach-menu" role="menu" aria-label="{{copy "chat.attach.add"}}" hidden><button type="button" role="menuitem" data-pick="image">{{icon "image"}}<span>{{copy "chat.attach.image"}}</span></button><button type="button" role="menuitem" data-pick="file">{{icon "file-text"}}<span>{{copy "chat.attach.file"}}</span></button></div><input type="file" data-picker="image" accept="image/*" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden><input type="file" data-picker="file" accept=".txt,.md,.markdown,.csv,.json,.log,.pdf,text/plain,text/markdown,text/csv,application/json,application/pdf" multiple tabindex="-1" aria-hidden="true" equipo-visually-hidden></div>
<div equipo-pill>
diff --git a/internal/runner/thin/claude.go b/internal/runner/thin/claude.go
index 65a41c37..258674b8 100644
--- a/internal/runner/thin/claude.go
+++ b/internal/runner/thin/claude.go
@@ -299,7 +299,7 @@ func (c *claudeCoordinator) Turn(ctx context.Context, in TurnInput, emit func(st
// Every attachment is on the desk whole, or the turn fails visibly.
files, err := heldFiles(c.desk, in.Attachments)
if err != nil {
- return TurnResult{Reason: wire.ReasonAttachmentUnavailable}
+ return c.missing(ctx, in)
}
p := c.proc
if p != nil {
@@ -534,6 +534,15 @@ const houseRule = "2026-11-07.9"
// sessionAccount records the account and house rule a session runs on.
func (c *coordBase) sessionAccount() string { return c.account.ID + "#rule-" + houseRule }
+// missing is a turn that cannot have its files: refused for room on this
+// runner (runner_storage_full), or not here whole.
+func (c *coordBase) missing(ctx context.Context, in TurnInput) TurnResult {
+ if c.o.State != nil && c.o.State.anyRefused(ctx, in.Attachments) {
+ return TurnResult{Reason: wire.ReasonStorageFull}
+ }
+ return TurnResult{Reason: wire.ReasonAttachmentUnavailable}
+}
+
// attachmentNote lists the turn's attachments for the model: what each is
// and where it is in the namespace, as the person's data, never as
// instructions. shown are the images in the frame itself. A text file is
diff --git a/internal/runner/thin/codex.go b/internal/runner/thin/codex.go
index c641a9b5..07315414 100644
--- a/internal/runner/thin/codex.go
+++ b/internal/runner/thin/codex.go
@@ -120,7 +120,7 @@ func (c *codexCoordinator) Turn(ctx context.Context, in TurnInput, emit func(str
defer c.mu.Unlock()
files, err := heldFiles(c.desk, in.Attachments)
if err != nil {
- return TurnResult{Reason: wire.ReasonAttachmentUnavailable}
+ return c.missing(ctx, in)
}
if c.idle != nil {
c.idle.Stop()
diff --git a/internal/runner/thin/files.go b/internal/runner/thin/files.go
index 8584c1d3..d92374a3 100644
--- a/internal/runner/thin/files.go
+++ b/internal/runner/thin/files.go
@@ -33,20 +33,27 @@ import (
// /workspace/attachments/<id>/<name> and can never write it.
const (
- fileSchema = `CREATE TABLE IF NOT EXISTS file_chunks (attachment_id TEXT NOT NULL, idx INTEGER NOT NULL, PRIMARY KEY (attachment_id, idx));`
+ fileSchema = `CREATE TABLE IF NOT EXISTS file_chunks (attachment_id TEXT NOT NULL, idx INTEGER NOT NULL, PRIMARY KEY (attachment_id, idx));
+CREATE TABLE IF NOT EXISTS file_admits (attachment_id TEXT PRIMARY KEY, person TEXT NOT NULL, size INTEGER NOT NULL, state TEXT NOT NULL, at TEXT NOT NULL);
+CREATE TABLE IF NOT EXISTS file_refused (attachment_id TEXT PRIMARY KEY, at TEXT NOT NULL);`
// attachmentsDir is the desk's attachments directory.
attachmentsDir = "attachments"
// keepFiles is how long a delivered attachment stays on the runner.
keepFiles = 14 * 24 * time.Hour
// keepParts is how long an unfinished one waits for its chunks.
keepParts = 2 * 24 * time.Hour
- // keepFresh spares a file just delivered: its message frame, and so
- // the running turn that protects it, comes after its chunks.
- keepFresh = time.Hour
+ // admitIncoming and admitDelivered are an admitted file's states: its
+ // chunks arriving, or delivered and waiting for the message frame that
+ // names it (which then protects it as a running turn's).
+ admitIncoming = "incoming"
+ admitDelivered = "delivered"
)
var attachmentID = regexp.MustCompile(`^at_[a-z0-9]{8,60}$`)
+// fileStamp is a sortable time: fixed width, so text order is time order.
+const fileStamp = "2006-01-02T15:04:05.000000000Z"
+
// Files receives attachment chunks for every person and keeps the
// runner's disk bounded (Sweep).
type Files struct {
@@ -61,8 +68,12 @@ type Files struct {
fault func(step string) error
}
-// Quota bounds delivered attachments, per person and on the whole runner.
-// Over it the oldest go first; a file a running turn names never goes.
+// Quota bounds attachments on the runner, per person and in all: those
+// delivered and those still arriving (by their declared size). A new file
+// is admitted only if it fits, after the oldest delivered files that
+// nothing protects make room; otherwise it is refused ("runner storage
+// full") and its turn fails in words. A file a running turn names, or one
+// admitted and not yet named by its message, is never removed.
type Quota struct {
PersonBytes, PersonFiles, TotalBytes, TotalFiles int64
}
@@ -133,6 +144,11 @@ func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChu
final := filepath.Join(desk.Dir, attachmentsDir, c.ID, c.Name)
incoming := filepath.Join(filepath.Dir(desk.Dir), "incoming")
part, ready := filepath.Join(incoming, c.ID+".part"), filepath.Join(incoming, c.ID+".ready")
+ if f.State.refused(ctx, c.ID) {
+ // Refused for room: every chunk is acked unwritten.
+ _, err := f.State.SeenResult(ctx, frameID)
+ return err
+ }
if info, err := os.Lstat(final); err == nil && info.Mode().IsRegular() && info.Size() == c.Size {
// Delivered already (an ack was lost, or the turn moved): tidy up
// what a crash after delivery may have left, then ack.
@@ -142,6 +158,15 @@ func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChu
_, err := f.State.SeenResult(ctx, frameID)
return err
}
+ admitted, err := f.admit(ctx, c.Person, c.ID, c.Size)
+ if err != nil {
+ return err
+ }
+ if !admitted {
+ f.log("attachment refused: runner storage full", errors.New(c.ID))
+ _, err := f.State.SeenResult(ctx, frameID)
+ return err
+ }
if _, err := os.Lstat(ready); err != nil {
// Not yet whole: write this chunk.
if err := os.MkdirAll(incoming, 0700); err != nil {
@@ -169,6 +194,9 @@ func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChu
// Discarded: the turn that names it fails; a resend starts afresh.
f.log("attachment discarded", err)
os.Remove(part)
+ if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE attachment_id=?", c.ID); err != nil {
+ return err
+ }
return f.forget(ctx, c.ID, part, ready)
}
if err != nil {
@@ -177,8 +205,8 @@ func (f *Files) Accept(ctx context.Context, frameID string, c wire.AttachmentChu
if err := f.forget(ctx, c.ID, part, ready); err != nil {
return err
}
- f.sweep(ctx, false)
- return nil
+ _, err = f.State.db.ExecContext(ctx, "UPDATE file_admits SET state=? WHERE attachment_id=?", admitDelivered, c.ID)
+ return err
}
// forget drops a finished or discarded file's chunk records and leftovers.
@@ -287,13 +315,15 @@ func (f *Files) Run(ctx context.Context, every time.Duration) {
// Sweep keeps the runner's attachments bounded and its records true:
// unfinished files past keepParts go with their chunk records; chunk
// records with no file go; delivered files past keepFiles go; then, over
-// the quota for a person or the runner, the oldest delivered files go
-// first. A file a running turn names, or one delivered in the last hour,
-// is never removed for the quota.
+// the quota for a person or the runner, the oldest delivered files that
+// nothing protects go first. If what is protected cannot be read (a query
+// fails, a record does not decode, ctx ends), nothing is removed.
func (f *Files) Sweep(ctx context.Context) {
f.mu.Lock()
defer f.mu.Unlock()
- f.sweep(ctx, true)
+ if err := f.sweep(ctx); err != nil {
+ f.log("attachment sweep", err)
+ }
}
type heldDir struct {
@@ -302,36 +332,64 @@ type heldDir struct {
bytes, files int64
}
-func (f *Files) sweep(ctx context.Context, records bool) {
- if f.SessionRoot == "" {
- return
+// usage is bytes and files.
+type usage [2]int64
+
+// protected is every attachment that must stay: named by a running turn,
+// or admitted and not yet named by its message (within keepParts). Any
+// failure to read it is an error: nothing is then removed.
+func (f *Files) protected(ctx context.Context) (map[string]bool, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ out, err := f.State.runningAttachments(ctx)
+ if err != nil {
+ return nil, err
}
- protect := f.State.runningAttachments(ctx)
- people, _ := os.ReadDir(f.SessionRoot)
- var all []heldDir
- partial := map[string]bool{}
- for _, p := range people {
- if !p.IsDir() {
- continue
+ rows, err := f.State.db.QueryContext(ctx, "SELECT attachment_id FROM file_admits WHERE at >= ?", time.Now().Add(-keepParts).UTC().Format(fileStamp))
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ return nil, err
}
- base := filepath.Join(f.SessionRoot, p.Name())
- incoming := filepath.Join(base, "incoming")
- entries, _ := os.ReadDir(incoming)
- for _, e := range entries {
- name := e.Name()
- id := strings.TrimSuffix(strings.TrimSuffix(name, ".part"), ".ready")
- info, err := e.Info()
- if err != nil || id == name {
- continue
- }
- if info.ModTime().Before(time.Now().Add(-keepParts)) && !protect[id] {
- os.Remove(filepath.Join(incoming, name))
- f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id)
- continue
- }
- partial[id] = true
+ out[id] = true
+ }
+ return out, rows.Err()
+}
+
+// arriving is what admitted files still arriving hold, by person key and
+// in all (their declared size, one file each).
+func (f *Files) arriving(ctx context.Context) (map[string]usage, usage, error) {
+ by := map[string]usage{}
+ var total usage
+ rows, err := f.State.db.QueryContext(ctx, "SELECT person, size FROM file_admits WHERE state=?", admitIncoming)
+ if err != nil {
+ return nil, total, err
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var p string
+ var n int64
+ if err := rows.Scan(&p, &n); err != nil {
+ return nil, total, err
}
- root := filepath.Join(base, "desk", attachmentsDir)
+ v := by[p]
+ by[p] = usage{v[0] + n, v[1] + 1}
+ total = usage{total[0] + n, total[1] + 1}
+ }
+ return by, total, rows.Err()
+}
+
+// delivered lists delivered attachments, oldest first.
+func (f *Files) delivered() []heldDir {
+ var all []heldDir
+ people, _ := os.ReadDir(f.SessionRoot)
+ for _, p := range people {
+ root := filepath.Join(f.SessionRoot, p.Name(), "desk", attachmentsDir)
dirs, _ := os.ReadDir(root)
for _, d := range dirs {
info, err := d.Info()
@@ -346,52 +404,166 @@ func (f *Files) sweep(ctx context.Context, records bool) {
h.files++
}
}
- if h.at.Before(time.Now().Add(-keepFiles)) && !protect[h.id] {
- removeAll(h.path)
- continue
- }
all = append(all, h)
}
}
- if records {
- // Chunk records whose file is gone (pruned, or never written).
- rows, err := f.State.db.QueryContext(ctx, "SELECT DISTINCT attachment_id FROM file_chunks")
- if err == nil {
- var gone []string
- for rows.Next() {
- var id string
- if rows.Scan(&id) == nil && !partial[id] {
- gone = append(gone, id)
- }
- }
- rows.Close()
- for _, id := range gone {
- f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id)
- }
- }
- }
- // Oldest first, within each person, then over the whole runner.
sort.Slice(all, func(i, j int) bool { return all[i].at.Before(all[j].at) })
+ return all
+}
+
+// makeRoom removes the oldest unprotected delivered files until every
+// person and the runner fit the quota with extra added for person (""
+// for none). It reports whether they fit; it removes nothing a protected
+// file needs, and only files that help: a person over quota loses their
+// own oldest first, the runner's oldest after.
+func (f *Files) makeRoom(ctx context.Context, protect map[string]bool, person string, extra usage) (bool, error) {
+ byArriving, arriving, err := f.arriving(ctx)
+ if err != nil {
+ return false, err
+ }
+ all := f.delivered()
q := f.quota()
- byPerson := map[string][2]int64{}
- var total [2]int64
+ by := map[string]usage{}
+ for p, v := range byArriving {
+ by[p] = v
+ }
+ total := arriving
for _, h := range all {
- v := byPerson[h.person]
- byPerson[h.person] = [2]int64{v[0] + h.bytes, v[1] + h.files}
- total[0] += h.bytes
- total[1] += h.files
+ v := by[h.person]
+ by[h.person] = usage{v[0] + h.bytes, v[1] + h.files}
+ total = usage{total[0] + h.bytes, total[1] + h.files}
+ }
+ if person != "" {
+ v := by[person]
+ by[person] = usage{v[0] + extra[0], v[1] + extra[1]}
+ total = usage{total[0] + extra[0], total[1] + extra[1]}
}
+ over := func(u usage, bytes, files int64) bool { return u[0] > bytes || u[1] > files }
for _, h := range all {
- v := byPerson[h.person]
- over := v[0] > q.PersonBytes || v[1] > q.PersonFiles || total[0] > q.TotalBytes || total[1] > q.TotalFiles
- if !over || protect[h.id] || h.at.After(time.Now().Add(-keepFresh)) {
+ personOver := over(by[h.person], q.PersonBytes, q.PersonFiles)
+ if !personOver && !over(total, q.TotalBytes, q.TotalFiles) {
continue
}
+ if protect[h.id] {
+ continue
+ }
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
removeAll(h.path)
- byPerson[h.person] = [2]int64{v[0] - h.bytes, v[1] - h.files}
- total[0] -= h.bytes
- total[1] -= h.files
+ v := by[h.person]
+ by[h.person] = usage{v[0] - h.bytes, v[1] - h.files}
+ total = usage{total[0] - h.bytes, total[1] - h.files}
+ }
+ for p, u := range by {
+ if over(u, q.PersonBytes, q.PersonFiles) && (person == "" || p == person) {
+ return false, nil
+ }
+ }
+ return !over(total, q.TotalBytes, q.TotalFiles), nil
+}
+
+// admit takes a new attachment in if it fits once room is made, recording
+// it as arriving; one admitted already stays admitted. False refuses it
+// for good (file_refused): its chunks are acked unwritten.
+func (f *Files) admit(ctx context.Context, person, id string, size int64) (bool, error) {
+ var n int
+ if err := f.State.db.QueryRowContext(ctx, "SELECT count(*) FROM file_admits WHERE attachment_id=?", id).Scan(&n); err != nil || n > 0 {
+ return n > 0, err
+ }
+ protect, err := f.protected(ctx)
+ if err != nil {
+ return false, err
+ }
+ key := filepath.Base(personDir(f.SessionRoot, person))
+ fits, err := f.makeRoom(ctx, protect, key, usage{size, 1})
+ if err != nil {
+ return false, err
+ }
+ at := time.Now().UTC().Format(fileStamp)
+ if !fits {
+ _, err := f.State.db.ExecContext(ctx, "INSERT INTO file_refused(attachment_id, at) VALUES(?,?) ON CONFLICT DO NOTHING", id, at)
+ return false, err
}
+ _, err = f.State.db.ExecContext(ctx, "INSERT INTO file_admits(attachment_id, person, size, state, at) VALUES(?,?,?,?,?)", id, key, size, admitIncoming, at)
+ return err == nil, err
+}
+
+func (f *Files) sweep(ctx context.Context) error {
+ if f.SessionRoot == "" {
+ return nil
+ }
+ protect, err := f.protected(ctx)
+ if err != nil {
+ return err
+ }
+ stale := time.Now().Add(-keepParts)
+ people, _ := os.ReadDir(f.SessionRoot)
+ partial := map[string]bool{}
+ for _, p := range people {
+ if !p.IsDir() {
+ continue
+ }
+ incoming := filepath.Join(f.SessionRoot, p.Name(), "incoming")
+ entries, _ := os.ReadDir(incoming)
+ for _, e := range entries {
+ name := e.Name()
+ id := strings.TrimSuffix(strings.TrimSuffix(name, ".part"), ".ready")
+ info, err := e.Info()
+ if err != nil || id == name {
+ continue
+ }
+ if info.ModTime().Before(stale) && !protect[id] {
+ os.Remove(filepath.Join(incoming, name))
+ if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil {
+ return err
+ }
+ continue
+ }
+ partial[id] = true
+ }
+ }
+ for _, h := range f.delivered() {
+ if h.at.Before(time.Now().Add(-keepFiles)) && !protect[h.id] {
+ removeAll(h.path)
+ }
+ }
+ // Chunk records whose file is gone (pruned, or never written).
+ rows, err := f.State.db.QueryContext(ctx, "SELECT DISTINCT attachment_id FROM file_chunks")
+ if err != nil {
+ return err
+ }
+ var gone []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ rows.Close()
+ return err
+ }
+ if !partial[id] {
+ gone = append(gone, id)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return err
+ }
+ rows.Close()
+ for _, id := range gone {
+ if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_chunks WHERE attachment_id=?", id); err != nil {
+ return err
+ }
+ }
+ // Admissions and refusals past their time.
+ cut := stale.UTC().Format(fileStamp)
+ if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_admits WHERE at < ?", cut); err != nil {
+ return err
+ }
+ if _, err := f.State.db.ExecContext(ctx, "DELETE FROM file_refused WHERE at < ?", time.Now().Add(-keepFiles).UTC().Format(fileStamp)); err != nil {
+ return err
+ }
+ _, err = f.makeRoom(ctx, protect, "", usage{})
+ return err
}
// removeAll removes a tree whose files were made read-only.
diff --git a/internal/runner/thin/files_test.go b/internal/runner/thin/files_test.go
index 2d6f8fc0..13ff434d 100644
--- a/internal/runner/thin/files_test.go
+++ b/internal/runner/thin/files_test.go
@@ -252,10 +252,10 @@ func TestAttachmentFinishCrashes(t *testing.T) {
// Astra round 1: retention had no aggregate bound and ran only when a
// file arrived. Sweep removes stale parts with their records, records with
// no file, files past retention, and, over a person's or the runner's
-// quota, the oldest delivered files first; never one a running turn names.
+// quota, the oldest delivered files first; never one a running turn names
+// (b3, the newest, stays only because the quota is met without it).
func TestAttachmentSweep(t *testing.T) {
f, ctx := filesRig(t)
- f.Quota = Quota{PersonBytes: 250, PersonFiles: 100, TotalBytes: 1 << 30, TotalFiles: 4}
deliver := func(person, id string, age time.Duration) wire.AttachmentRef {
t.Helper()
chunks, ref := chunksOf(person, id, "n.txt", []byte(strings.Repeat("x", 100)))
@@ -303,6 +303,10 @@ func TestAttachmentSweep(t *testing.T) {
for _, id := range []string{"at_stale0000", "at_orphan000", "at_fresh0000"} {
f.State.db.Exec("INSERT INTO file_chunks(attachment_id, idx) VALUES(?,0)", id)
}
+ // Their messages came and went (the admissions are done); then the
+ // quota shrinks below what is held.
+ f.State.db.Exec("DELETE FROM file_admits")
+ f.Quota = Quota{PersonBytes: 250, PersonFiles: 100, TotalBytes: 1 << 30, TotalFiles: 4}
f.Sweep(ctx)
// Person a: 400 bytes over 250; a1 is protected, so a2 and a3 go.
for id, want := range map[string]bool{"at_a1aaaaaaaa": true, "at_a2aaaaaaaa": false, "at_a3aaaaaaaa": false, "at_a4aaaaaaaa": true} {
@@ -331,3 +335,157 @@ func TestAttachmentSweep(t *testing.T) {
t.Fatalf("chunk records left %v, want only the fresh part's", ids)
}
}
+
+// held is what delivered and arriving attachments hold on disk: bytes and
+// files under every desk's attachments and every incoming directory.
+func held(t *testing.T, root string) (int64, int) {
+ t.Helper()
+ var bytes int64
+ files := 0
+ for _, pattern := range []string{"*/desk/attachments/*/*", "*/incoming/*"} {
+ paths, _ := filepath.Glob(filepath.Join(root, pattern))
+ for _, p := range paths {
+ if info, err := os.Stat(p); err == nil && info.Mode().IsRegular() {
+ bytes += info.Size()
+ files++
+ }
+ }
+ }
+ return bytes, files
+}
+
+// Astra round 2: the quota exempted every file delivered in the last hour
+// and left partial files out, so a 1-file, 1-byte quota held three files.
+// Admission counts arriving files by their declared size; room is made from
+// the oldest unprotected delivered files; failing that the file is refused
+// (runner_storage_full) and its chunks acked unwritten. Never a protected
+// file removed.
+func TestAttachmentQuotaAdmission(t *testing.T) {
+ ctx := context.Background()
+ t.Run("one file one byte", func(t *testing.T) {
+ t.Parallel()
+ f, _ := filesRig(t)
+ f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1}
+ for i, id := range []string{"at_q1aaaaaaaa", "at_q2aaaaaaaa", "at_q3aaaaaaaa"} {
+ chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!"))
+ if err := f.Accept(ctx, "q"+itoa(int64(i)), chunks[0]); err != nil {
+ t.Fatal(err)
+ }
+ if b, n := held(t, f.SessionRoot); b > 1 || n > 1 {
+ t.Fatalf("after %s the runner holds %d bytes in %d files", id, b, n)
+ }
+ if !f.State.anyRefused(ctx, []wire.AttachmentRef{ref}) {
+ t.Fatalf("%s was not refused", id)
+ }
+ }
+ })
+ t.Run("room from the oldest unprotected, never the protected", func(t *testing.T) {
+ t.Parallel()
+ f, _ := filesRig(t)
+ f.Quota = Quota{PersonBytes: 100, PersonFiles: 1, TotalBytes: 100, TotalFiles: 1}
+ ten := []byte("ten bytes!")
+ c1, r1 := chunksOf("p@example.com", "at_r1aaaaaaaa", "a.txt", ten)
+ if err := f.Accept(ctx, "r1", c1[0]); err != nil {
+ t.Fatal(err)
+ }
+ // Its message names it: a running turn now protects it.
+ if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: []wire.AttachmentRef{r1}}); err != nil {
+ t.Fatal(err)
+ }
+ c2, r2 := chunksOf("p@example.com", "at_r2aaaaaaaa", "b.txt", ten)
+ if err := f.Accept(ctx, "r2", c2[0]); err != nil {
+ t.Fatal(err)
+ }
+ desk, _ := OpenDesk(f.SessionRoot, "p@example.com")
+ if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err != nil || !f.State.anyRefused(ctx, []wire.AttachmentRef{r2}) {
+ t.Fatalf("the protected file went or the new one was taken in: %v", err)
+ }
+ // The turn ends: r1 is no longer protected, and makes room for r3.
+ f.State.db.Exec("UPDATE runs SET state='done'")
+ c3, r3 := chunksOf("p@example.com", "at_r3aaaaaaaa", "c.txt", ten)
+ if err := f.Accept(ctx, "r3", c3[0]); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := heldFiles(desk, []wire.AttachmentRef{r3}); err != nil {
+ t.Fatalf("r3 not delivered: %v", err)
+ }
+ if _, err := heldFiles(desk, []wire.AttachmentRef{r1}); err == nil {
+ t.Fatal("r1 kept beyond the quota")
+ }
+ // An arriving file counts: its first chunk holds the one file, so a
+ // file behind it is refused while it is still arriving.
+ f.State.db.Exec("DELETE FROM file_admits")
+ os.RemoveAll(filepath.Join(desk.Dir, attachmentsDir))
+ big := []byte(strings.Repeat("y", attach.ChunkBytes+10))
+ f.Quota = Quota{PersonBytes: 1 << 20, PersonFiles: 1, TotalBytes: 1 << 20, TotalFiles: 1}
+ c4, _ := chunksOf("p@example.com", "at_r4aaaaaaaa", "d.txt", big)
+ if err := f.Accept(ctx, "r4", c4[0]); err != nil {
+ t.Fatal(err)
+ }
+ c5, r5 := chunksOf("p@example.com", "at_r5aaaaaaaa", "e.txt", ten)
+ if err := f.Accept(ctx, "r5", c5[0]); err != nil {
+ t.Fatal(err)
+ }
+ if !f.State.anyRefused(ctx, []wire.AttachmentRef{r5}) {
+ t.Fatal("an arriving file did not count against the quota")
+ }
+ })
+}
+
+// Astra round 2: a failed protection lookup read as "nothing protected",
+// so a cancelled sweep removed a running turn's file. A sweep whose
+// lookup fails (cancelled, a query error, a record that does not decode)
+// removes nothing.
+func TestAttachmentSweepAbortsOnLookupFailure(t *testing.T) {
+ for _, tc := range []string{"cancelled", "query", "decode"} {
+ t.Run(tc, func(t *testing.T) {
+ t.Parallel()
+ f, ctx := filesRig(t)
+ var refs []wire.AttachmentRef
+ for _, id := range []string{"at_s1aaaaaaaa", "at_s2aaaaaaaa", "at_s3aaaaaaaa"} {
+ chunks, ref := chunksOf("p@example.com", id, "n.txt", []byte("ten bytes!"))
+ if err := f.Accept(ctx, "f-"+id, chunks[0]); err != nil {
+ t.Fatal(err)
+ }
+ refs = append(refs, ref)
+ }
+ if err := f.State.Accept(ctx, "m1", wire.MessageCommand{Person: "p@example.com", TurnID: "t_1", Attempt: 1, Text: "x", PersonText: []string{"x"}, Tail: []wire.TailMessage{}, Attachments: refs[:1]}); err != nil {
+ t.Fatal(err)
+ }
+ f.State.db.Exec("DELETE FROM file_admits")
+ f.Quota = Quota{PersonBytes: 1, PersonFiles: 1, TotalBytes: 1, TotalFiles: 1}
+ sweep := ctx
+ switch tc {
+ case "cancelled":
+ c, cancel := context.WithCancel(ctx)
+ cancel()
+ sweep = c
+ case "query":
+ f.State.fault = func(op string) error {
+ if op == "running_attachments" {
+ return errors.New("disk I/O error")
+ }
+ return nil
+ }
+ case "decode":
+ f.State.db.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, created_at) VALUES('t_bad','p@example.com',1,?, 'x','[]','','[]','{not json',?)", runRunning, now())
+ }
+ _, before := held(t, f.SessionRoot)
+ f.Sweep(sweep)
+ if _, after := held(t, f.SessionRoot); after != before {
+ t.Fatalf("a sweep whose lookup failed removed %d files", before-after)
+ }
+ // A healthy sweep removes the unprotected, keeps the protected.
+ f.State.fault = nil
+ f.State.db.Exec("DELETE FROM runs WHERE turn_id='t_bad'")
+ f.Sweep(ctx)
+ desk, _ := OpenDesk(f.SessionRoot, "p@example.com")
+ if _, err := heldFiles(desk, refs[:1]); err != nil {
+ t.Fatal("the protected file went")
+ }
+ if _, after := held(t, f.SessionRoot); after != 1 {
+ t.Fatalf("a healthy sweep left %d files", after)
+ }
+ })
+ }
+}
diff --git a/internal/runner/thin/state.go b/internal/runner/thin/state.go
index 124b121f..fd2e429a 100644
--- a/internal/runner/thin/state.go
+++ b/internal/runner/thin/state.go
@@ -361,8 +361,17 @@ func (s *State) Accept(ctx context.Context, frameID string, m wire.MessageComman
if err != nil || !fresh {
return err
}
- _, err = t.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, created_at) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", m.TurnID, m.Person, max(m.Attempt, 1), runRunning, m.Text, string(tail), m.Kind, string(own), string(files), now())
- return err
+ if _, err = t.Exec("INSERT INTO runs(turn_id, person, attempt, state, text, tail, kind, person_text, attachments, created_at) VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT DO NOTHING", m.TurnID, m.Person, max(m.Attempt, 1), runRunning, m.Text, string(tail), m.Kind, string(own), string(files), now()); err != nil {
+ return err
+ }
+ // The running turn protects its files from here; their admissions
+ // (which protected them until now) are done.
+ for _, r := range m.Attachments {
+ if _, err = t.Exec("DELETE FROM file_admits WHERE attachment_id=? AND state=?", r.ID, admitDelivered); err != nil {
+ return err
+ }
+ }
+ return nil
})
}
@@ -595,23 +604,49 @@ func (s *State) saveSession(ctx context.Context, person, provider, account, id,
return err
}
-// runningAttachments are the attachment ids the person's running turns
-// name: files the sweep must keep.
-func (s *State) runningAttachments(ctx context.Context) map[string]bool {
+// runningAttachments are the attachment ids the running turns name:
+// files the sweep must keep. Any failure is an error, never "none".
+func (s *State) runningAttachments(ctx context.Context) (map[string]bool, error) {
+ if s.fault != nil {
+ if err := s.fault("running_attachments"); err != nil {
+ return nil, err
+ }
+ }
out := map[string]bool{}
rows, err := s.db.QueryContext(ctx, "SELECT attachments FROM runs WHERE state=?", runRunning)
if err != nil {
- return out
+ return nil, err
}
defer rows.Close()
for rows.Next() {
var raw string
var refs []wire.AttachmentRef
- if rows.Scan(&raw) == nil && json.Unmarshal([]byte(raw), &refs) == nil {
- for _, r := range refs {
- out[r.ID] = true
- }
+ if err := rows.Scan(&raw); err != nil {
+ return nil, err
+ }
+ if err := json.Unmarshal([]byte(raw), &refs); err != nil {
+ return nil, err
+ }
+ for _, r := range refs {
+ out[r.ID] = true
+ }
+ }
+ return out, rows.Err()
+}
+
+// refused reports an attachment refused for room.
+func (s *State) refused(ctx context.Context, id string) bool {
+ var n int
+ return s.db.QueryRowContext(ctx, "SELECT count(*) FROM file_refused WHERE attachment_id=?", id).Scan(&n) == nil && n > 0
+}
+
+// anyRefused reports whether any of a turn's attachments was refused for
+// room on this runner.
+func (s *State) anyRefused(ctx context.Context, refs []wire.AttachmentRef) bool {
+ for _, r := range refs {
+ if s.refused(ctx, r.ID) {
+ return true
}
}
- return out
+ return false
}
diff --git a/internal/thintest/attachments_contract_test.go b/internal/thintest/attachments_contract_test.go
index 8bc6ede1..5b4b2edc 100644
--- a/internal/thintest/attachments_contract_test.go
+++ b/internal/thintest/attachments_contract_test.go
@@ -242,3 +242,41 @@ func waitAcked(t *testing.T, r *rig, id string) {
}
t.Fatal("ack not recorded")
}
+
+// TestContractStorageFullInWords: Astra round 2: a runner with no room
+// for an attachment refuses it and fails the turn runner_storage_full;
+// the conversation says so in words, not the general failure.
+func TestContractStorageFullInWords(t *testing.T) {
+ r := newRig(t)
+ runner := r.dial(0)
+ r.wait("runner online", func(c *Conversation) bool { return c.Runner.Online })
+ a, err := r.client.Upload(r.ctx, "notes.txt", "text/plain", []byte("notes"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ sent, err := r.client.SendWith(r.ctx, "look", "k-full", []string{a.ID})
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, _, err := runner.Expect(r.ctx, wire.FrameAttachment)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-"+f.ID, wire.FrameAck, wire.Ack{ID: f.ID})
+ m, _, err := runner.Expect(r.ctx, wire.FrameMessage)
+ if err != nil {
+ t.Fatal(err)
+ }
+ runner.Send(r.ctx, "a-"+m.ID, wire.FrameAck, wire.Ack{ID: m.ID})
+ if err := runner.Send(r.ctx, "r-full", wire.FrameTurn, wire.TurnReport{TurnID: sent.Turn.ID, Attempt: 1, State: wire.TurnFailed, Reason: wire.ReasonStorageFull}); err != nil {
+ t.Fatal(err)
+ }
+ r.wait("failed", func(c *Conversation) bool {
+ v := c.Turns[sent.Turn.ID]
+ return v.State == wire.TurnFailed && v.Reason == wire.ReasonStorageFull
+ })
+ page := r.inst.Get(t, "/conversation")
+ if !strings.Contains(page, `data-ended="`+sent.Turn.ID+`"><p>Your runner has no room left for these attachments.`) || !strings.Contains(page, `data-failed-storage="Your runner has no room left`) {
+ t.Fatal("the conversation does not say the runner had no room")
+ }
+}
diff --git a/internal/wire/frames.go b/internal/wire/frames.go
index 6399fbf4..f3ce105a 100644
--- a/internal/wire/frames.go
+++ b/internal/wire/frames.go
@@ -570,7 +570,13 @@ var Reasons = map[string]bool{
// attachment_unavailable: a file the turn carries never arrived
// whole on the runner (its size or SHA-256 did not match).
ReasonAttachmentUnavailable: true,
+ // runner_storage_full: the runner refused an attachment for room.
+ ReasonStorageFull: true,
}
+// ReasonStorageFull fails a turn whose attachment the runner had no room
+// for (its quota, after the oldest unprotected files made room).
+const ReasonStorageFull = "runner_storage_full"
+
// ReasonAttachmentUnavailable fails a turn whose attachment is missing.
const ReasonAttachmentUnavailable = "attachment_unavailable"