carlos / platform Public

Clone
git clone https://amadan.net/carlos/platform

Plain git — no account needed to clone.

Download

Download this file

1# Seeded Instances, Plan 6: The Import Door Implementation Plan
2
3> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
5**Goal:** The console's half of importing an instance the platform never ran: begin (with a once-shown verify token), a pinned upload checked twice before it reaches the bucket, the app's "stopped", commit after verification, abort before commit, the delete refusal, the console's finish of an abandoned seed, and `carlos instances import` that drives it end to end.
6
7**Architecture:** Begin is the create door with `"import"` in its body: after every ordinary check it hands off to `createImport` (new file), which checks the region (one box, Plan 3), the declared length and hash, mints the seed `ID` and the verify token, writes the record `awaiting-upload` with only the token's hash, provisions an empty store marked with the seed, and answers the token once. Upload streams into a spool under the shared scratch pool, hashing as it writes; a mismatch or a file that fails `CheckDBContext` is refused; one `PutFrom` writes `seeds/<host>/<id>/snapshot.db`; the seed becomes `uploaded`. `stopped`, `commit` and `abort` are record CASes through `SetRecordSeed`, so a commit and an abort racing on the etag end with one winner. `finishSeed` is the console's last word on an abandoned seed (spec §5.6, codex R6-1): tear down the store whose declared seed is this `ID`, then delete the record by `If-Match`, only while it still names this `ID`. The CLI command is a thin driver over these five calls plus the instance read.
8
9**Tech Stack:** Go 1.25, `http.MaxBytesReader`, `http.ResponseController` read deadlines, `lease.CheckDBContext`, `release.PutObjectFrom`, `release.DeleteIfMatch`, `objstore.TeardownIn`.
10
11**Spec:** `docs/superpowers/specs/2026-10-08-seeded-instances-design.md` rev 7: §5.1, §5.2 (codex 19, 20), §5.3, §5.4's commit, §5.5, §5.6's abort, delete refusal and console finish (codex R2-7, R6-1), §6.1, §7 (audit rows, errors). Index: `2026-10-08-seeded-instances-0-index.md`. Copy deck rows SD-N48 to SD-N82, SD-N89, SD-N90, SD-N115.
12
13**Dependency:** Task 5 reads `provision.Record.ActiveRun` (run spec §5.1, the run series' record task). Build Task 5 after that task has merged; Tasks 1 to 4 and 6 do not need it.
14
15## Global Constraints
16
17- Every user-facing string (CLI output, errors, console messages, docs prose) is copy-reviewed by Paul before it is written into code; implementation tasks use only strings from the copy deck. Copy voice: no em dashes; full stops and new sentences instead.
18- CI cross-compiles darwin and windows: linux-only code needs `//go:build linux` plus a `!linux` stub.
19- Local test commands: targeted tests (`go test ./internal/<pkg>/ -run TestX`), not the full suite in a loop. Inside the sandbox the default Go build cache may be read-only; if so use `GOCACHE=$TMPDIR/gocache` re-exported per command. Socket tests need a short TMPDIR (`TMPDIR=/tmp/g`). The local gate may need `GOFLAGS=-buildvcs=false`.
20- Heavy loops run under `nice`; no -race full suite until the end of a plan.
21- Production use needs nested boxes; the claim-armed path is refused here and left to #250 (spec §3.4).
22- Commits end with `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`.
23- No new file in this series imports `internal/moves`. New sentences go in new files (`apiinstanceimport.go`, `seedfinish.go`, `instances_import.go`), never in a file listed in `movesScanFiles`; `apiinstances.go` and `authcli.go` gain only calls and routes.
24- `TestClaimAuthoritySourceCensus` inventories console calls in its `selected` set (`Open` among them); add each new site to `internal/console/testdata/claim-authority-sites.txt`.
25- When a task wires a deck row, append its id to `seededWiredIDs` in `approved_seeded_copy_test.go` in the same commit.
26- Write each deck sentence as exactly one string literal or one format string holding the row's text, with `%s` or `%d` at each `<placeholder>` and nothing else: no prefix, no trailing `\n`, no leading spaces. The gate's matcher (`movesRowSpoken`, `approved_moves_copy_test.go:811`) anchors both ends. Print with `fmt.Fprintln(w, sentence)` or a `" %s\n"` format around a separately built sentence.
27- Every door here authorizes through `cliRoute` with `svcrole.Allow(svcrole.Instance)` and then `instanceGate` (membership for people), as `POST …/instances` does (spec §6.1).
28- The verify token is in exactly one response body (begin's 201). It is never logged, audited or stored; the record keeps `seeds.HashToken(token)`.
29
30## Review Focus
31
321. An upload whose body is longer than `bytes` must be cut at `bytes + 1` and refused without the console holding more than the reservation on disk. Test in Task 2 (`TestImportUploadRefusesLengthAndHash`).
332. A second upload after a successful one (a client retry) must be refused by state, not overwrite the snapshot the record now vouches for. Test in Task 2 (`TestImportUploadOnlyOnce`).
343. Commit and abort racing: exactly one wins, and the loser gets the "changed while" answer or the committed answer, never a 502. Test in Task 5 (`TestImportCommitAbortRace`).
354. `finishSeed` must never tear down a store whose declared seed is another `ID` or none, and must leave a record that names another seed `ID` alone. Test in Task 4 (`TestFinishSeedIsScopedToItsID`).
365. `carlos instances import --verify` on a verify path that answers 503 while the instance wakes must retry within a bound, not abort on the first 503. Test in Task 6 (`TestImportVerifyRetriesThroughTheWake`).
37
38---
39
40## File structure
41
42| path | responsibility |
43|---|---|
44| `internal/console/apiinstanceimport.go` | `createImport`, the upload, stopped, commit and abort handlers, `refuseImportDelete` |
45| `internal/console/seedfinish.go` | `finishSeed`: the seed-guarded store teardown and the record's `If-Match` delete |
46| `internal/console/apiinstances.go` | the request's `import` field and hand-off; one call in the delete handler |
47| `internal/console/authcli.go` | four routes |
48| `instances_import.go`, `cli.go` | `carlos instances import`, `import commit`, `import abort` |
49| `apimode.go` | the client calls |
50| `docs/site/cli.md` | SD-N89 |
51
52---
53
54### Task 1: Begin
55
56**Files:**
57- Create: `internal/console/apiinstanceimport.go`, `internal/console/apiinstanceimport_test.go`
58- Modify: `internal/console/apiinstances.go` (request struct; `seeded` covers `Import`; hand-off after `createFrom`'s)
59
60**Interfaces:**
61- Consumes: `seedCreate`, `seedCommonRefusal`, `seedPlacementRefusal`, `s.seedStoreRefusal`, `s.instanceStoreProvisionFor`, `s.seedRegionReady(ctx, region, true)` (Plans 3, 5); `seeds.NewID`, `seeds.NewVerifyToken`, `seeds.MaxBytes`; `provision.CreateRecord`, `SetRecordSeed`, `SeedAbort`; `s.dbResidencyRefusal`.
62- Produces: `type seedImportReq struct{ SHA256 string; Bytes int64; Replaces string }` (body key `import`); `(s *Server) createImport(w, r, c seedCreate, imp seedImportReq)`; the 201 body: the record view plus `"verify_token": "<token>"`.
63
64Begin's checks, after the create door's own (spec §5.1): placement (SD-N37); a data bucket (SD-N38); `bytes` in 1 to 4 GiB (SD-N48: 400 for ≤ 0, 413 above the limit); `sha256` as 64 lowercase hex (SD-N49); `replaces` as `host:port` with a numeric port (SD-N50); the record homed in this console's region (`rec.Region != s.cfg.Region`: 409 with the existing `dbResidencyRefusal`); `seedRegionReady(ctx, rec.Region, true)`; the store rule (`seedStoreRefusal`). Then mint the `ID` and token, `CreateRecord` with seed `awaiting-upload` (CAS conflict: the existing "instance <host> already exists", which is the "host isn't already a platform record" check), provision the store (abort on refusal), audit `instance-seed` (SD-N62), and answer 201.
65
66- [ ] **Step 1: Write the failing tests**
67
68```go
69package console
70
71import (
72 "context"
73 "encoding/json"
74 "net/http"
75 "strings"
76 "testing"
77
78 "github.com/carlosframework/platform/internal/provision"
79 "github.com/carlosframework/platform/internal/seeds"
80)
81
82func newImportFixture(t *testing.T) fromFixture {
83 t.Helper()
84 f := newFromFixture(t, 5) // Plan 5's fixture: a ready one-box home region, scratch, a data store
85 return f
86}
87
88func beginImport(t *testing.T, f fromFixture, host, sha string, bytes int64) (int, map[string]any) {
89 t.Helper()
90 body, _ := json.Marshal(map[string]any{"host": host, "import": map[string]any{"sha256": sha, "bytes": bytes, "replaces": "127.0.0.1:8401"}})
91 return f.create(t, string(body))
92}
93
94func TestImportBegin(t *testing.T) {
95 f := newImportFixture(t)
96 sha := strings.Repeat("a", 64)
97 code, out := beginImport(t, f, "old.go.tito.io", sha, 4096)
98 if code != http.StatusCreated {
99 t.Fatalf("begin = %d %v", code, out)
100 }
101 token := str(t, out, "verify_token")
102 if len(token) != 43 {
103 t.Fatalf("verify token %q", token)
104 }
105 rec, err := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", "old.go.tito.io")
106 if err != nil || rec.Seed == nil || rec.Seed.Kind != seeds.KindImport || rec.Seed.State != seeds.StateAwaitingUpload ||
107 rec.Seed.SHA256 != sha || rec.Seed.Bytes != 4096 || rec.Seed.Replaces != "127.0.0.1:8401" || rec.Seed.VerifyHash != seeds.HashToken(token) {
108 t.Fatalf("record = %+v, %v", rec.Seed, err)
109 }
110 raw, _, _ := f.fx.rel.Get(context.Background(), provision.RecordKey("bab", "titogo", "old.go.tito.io"))
111 if strings.Contains(string(raw), token) {
112 t.Fatal("the token itself reached the bucket")
113 }
114 // A second begin for the same host: the record holds it.
115 if code, _ := beginImport(t, f, "old.go.tito.io", sha, 4096); code != http.StatusConflict {
116 t.Fatalf("second begin = %d, want 409", code)
117 }
118}
119
120func TestImportBeginRefusals(t *testing.T) {
121 f := newImportFixture(t)
122 for _, c := range []struct {
123 body string
124 code int
125 want string
126 }{
127 {`{"host":"a.go.tito.io","import":{"sha256":"` + strings.Repeat("a", 64) + `","bytes":0,"replaces":"127.0.0.1:1"}}`, http.StatusBadRequest, "more than 0"},
128 {`{"host":"a.go.tito.io","import":{"sha256":"` + strings.Repeat("a", 64) + `","bytes":4294967297,"replaces":"127.0.0.1:1"}}`, http.StatusRequestEntityTooLarge, "at most 4 GiB"},
129 {`{"host":"a.go.tito.io","import":{"sha256":"ABC","bytes":10,"replaces":"127.0.0.1:1"}}`, http.StatusBadRequest, "64 lowercase hex"},
130 {`{"host":"a.go.tito.io","import":{"sha256":"` + strings.Repeat("a", 64) + `","bytes":10,"replaces":"nope"}}`, http.StatusBadRequest, "host:port"},
131 {`{"host":"a.go.tito.io","kind":"service","import":{"sha256":"` + strings.Repeat("a", 64) + `","bytes":10,"replaces":"127.0.0.1:1"}}`, http.StatusBadRequest, "ordinary instance"},
132 } {
133 if code, out := f.create(t, c.body); code != c.code || !strings.Contains(str(t, out, "error"), c.want) {
134 t.Errorf("%s = %d %v, want %d %q", c.body, code, out, c.code, c.want)
135 }
136 }
137}
138
139func TestImportBeginNeedsOneBox(t *testing.T) {
140 f := newImportFixture(t)
141 seedReadyBox(t, f.fx, "kass-2", "", 1, "v0.27.0", "v0.27.0", "nested", false)
142 if code, out := beginImport(t, f, "old.go.tito.io", strings.Repeat("a", 64), 10); code != http.StatusConflict || !strings.Contains(str(t, out, "error"), "more than one box") {
143 t.Fatalf("= %d %v", code, out)
144 }
145}
146```
147
148- [ ] **Step 2: Run the tests to verify they fail**
149
150Run: `go test ./internal/console/ -run 'TestImportBegin' -count=1`
151Expected: FAIL (the `import` key is ignored, so the request creates an ordinary instance, or compile errors once the test references new names).
152
153- [ ] **Step 3: Write `createImport`**
154
155`internal/console/apiinstanceimport.go`:
156
157```go
158package console
159
160import (
161 "errors"
162 "fmt"
163 "log"
164 "net"
165 "net/http"
166 "regexp"
167 "strconv"
168 "time"
169
170 "github.com/carlosframework/platform/internal/provision"
171 "github.com/carlosframework/platform/internal/release"
172 "github.com/carlosframework/platform/internal/seeds"
173)
174
175// seedImportReq is the create body's "import" (seeded-instances spec §5.1).
176type seedImportReq struct {
177 SHA256 string `json:"sha256"`
178 Bytes int64 `json:"bytes"`
179 Replaces string `json:"replaces"`
180}
181
182var sha256Hex = regexp.MustCompile(`^[0-9a-f]{64}$`)
183
184func validReplaces(addr string) bool {
185 host, port, err := net.SplitHostPort(addr)
186 if err != nil || host == "" {
187 return false
188 }
189 n, err := strconv.Atoi(port)
190 return err == nil && n > 0 && n < 65536
191}
192
193// createImport is the import door's begin (spec §5.1).
194func (s *Server) createImport(w http.ResponseWriter, r *http.Request, c seedCreate, imp seedImportReq) {
195 ctx := r.Context()
196 acct, app, host := c.acct, c.app, c.rec.Host
197 if ref := seedPlacementRefusal(c); ref != nil {
198 jsonError(w, ref.Status, ref.Msg)
199 return
200 }
201 if s.cfg.SeedData == nil || s.cfg.HibernateBucket == "" {
202 jsonError(w, http.StatusServiceUnavailable, "this console has no data bucket set up, so it cannot create a seeded instance.")
203 return
204 }
205 switch {
206 case imp.Bytes <= 0:
207 jsonError(w, http.StatusBadRequest, "bytes must be more than 0 and at most 4 GiB")
208 return
209 case imp.Bytes > seedMaxBytes:
210 jsonError(w, http.StatusRequestEntityTooLarge, "bytes must be more than 0 and at most 4 GiB")
211 return
212 case !sha256Hex.MatchString(imp.SHA256):
213 jsonError(w, http.StatusBadRequest, "sha256 must be 64 lowercase hex characters")
214 return
215 case !validReplaces(imp.Replaces):
216 jsonError(w, http.StatusBadRequest, "replaces must name the address the import takes over, as host:port")
217 return
218 }
219 if c.rec.Region != s.cfg.Region {
220 jsonError(w, http.StatusConflict, s.dbResidencyRefusal(c.rec))
221 return
222 }
223 if ref := s.seedRegionReady(ctx, c.rec.Region, true); ref != nil {
224 jsonError(w, ref.Status, ref.Msg)
225 return
226 }
227 id, err := seeds.NewID()
228 if err != nil {
229 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
230 return
231 }
232 token, hash, err := seeds.NewVerifyToken()
233 if err != nil {
234 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
235 return
236 }
237 if ref := s.seedStoreRefusal(ctx, c, id); ref != nil {
238 jsonError(w, ref.Status, ref.Msg)
239 return
240 }
241 rec := c.rec
242 rec.Seed = &provision.SeedSource{ID: id, Kind: seeds.KindImport, SHA256: imp.SHA256, Bytes: imp.Bytes,
243 State: seeds.StateAwaitingUpload, By: c.principal, At: time.Now().UTC(), Replaces: imp.Replaces, VerifyHash: hash}
244 if err := provision.CreateRecord(ctx, s.cfg.Releases, rec); err != nil {
245 if errors.Is(err, release.ErrCASConflict) {
246 jsonError(w, http.StatusConflict, "instance "+host+" already exists")
247 return
248 }
249 log.Printf("console: import %s: begin: %v", host, err)
250 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
251 return
252 }
253 if c.m.PrivateStorage {
254 if _, ok := s.instanceStoreProvisionFor(ctx, w, acct, app, rec.Environment, c.principal, id); !ok {
255 s.abortSeedQuietly(ctx, acct, app, host, id, "store provisioning")
256 return
257 }
258 }
259 short := imp.SHA256[:12]
260 s.auditActivity(acct, app, c.principal, Activity{
261 Action: "instance-seed", TargetType: "instance", Target: host, Message: c.message,
262 Detail: fmt.Sprintf("began an import of %s over %s (%s, %d bytes)", host, imp.Replaces, short, imp.Bytes),
263 })
264 out := struct {
265 apiRecordView
266 VerifyToken string `json:"verify_token"`
267 }{recordView(rec), token}
268 out.RegionFrom = c.regionFrom
269 writeJSON(w, http.StatusCreated, out)
270}
271```
272
273Add to `apiinstanceseed.go` the shared quiet abort (and use it in `createFrom`'s `abort` closure too, replacing its body):
274
275```go
276// abortSeedQuietly CASes a seed to aborted under a context the client's
277// departure cannot cancel, and bumps the serial so the box acts on it.
278func (s *Server) abortSeedQuietly(ctx context.Context, acct *Account, app, host, id, why string) {
279 bg, cancel := context.WithTimeout(context.WithoutCancel(ctx), instanceStoreTimeout)
280 defer cancel()
281 if _, err := provision.SetRecordSeed(bg, s.cfg.Releases, acct.Sqid, app, host, provision.SeedAbort(id)); err != nil {
282 log.Printf("console: seed %s of %s: abort after %s: %v", id, host, why, err)
283 }
284 s.bumpSerial(bg)
285}
286```
287
288In `handleAPIInstanceCreate`, add `Import *seedImportReq `json:"import,omitempty"`` beside `From`; `seeded := req.From != nil || req.Import != nil`; both together are refused with SD-N36's 400 (one seed door per create); and after `createFrom`'s hand-off:
289
290```go
291 if req.Import != nil {
292 s.createImport(w, r, seedCreate{acct: acct, app: app, principal: principal, message: message, m: m,
293 rec: rec, placed: placed, regionFrom: regionFrom}, *req.Import)
294 return
295 }
296```
297
298- [ ] **Step 4: Run the tests to verify they pass**
299
300Run: `go test ./internal/console/ -run 'TestImportBegin|TestFrom' -count=1`
301Expected: PASS.
302
303- [ ] **Step 5: Wire SD-N48 to SD-N50, SD-N62, SD-N67 and commit**
304
305```bash
306git add internal/console/apiinstanceimport.go internal/console/apiinstanceimport_test.go internal/console/apiinstanceseed.go internal/console/apiinstances.go approved_seeded_copy_test.go
307git commit -m "console: the import door's begin, with a once-shown verify token (Plan 6 Task 1)
308
309Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
310```
311
312### Task 2: Upload
313
314**Files:**
315- Modify: `internal/console/apiinstanceimport.go` (add `handleAPIImportUpload`, `importGate`)
316- Modify: `internal/console/authcli.go` (route beside `DELETE …/instances/{host}`, `:683`)
317- Test: `internal/console/apiinstanceimport_test.go`
318
319**Interfaces:**
320- Consumes: `s.instanceGate`, `s.seedScratch.reserve`, `checkSeedDBConsole` (a package var `= lease.CheckDBContext`), `release.PutObjectFrom`, `provision.SeedUploaded`.
321- Produces: `PUT /api/cli/apps/{account}/{app}/instances/{host}/import`; `(s *Server) importGate(w, r) (principal string, acct *Account, app, host string, rec *provision.Record, ok bool)` (instance gate, host shape, record read, "is an import" check: SD-N59); 200 `{"state":"uploaded"}`.
322
323The upload (spec §5.2): the record must be an import in `awaiting-upload` (SD-N53 otherwise); `seedRegionReady(ctx, rec.Region, true)` again (the door writes seed state); reserve `rec.Seed.Bytes` from the pool; extend the read deadline to 60 minutes; spool to `<scratch>/<host>.db` under `http.MaxBytesReader(w, r.Body, bytes+1)`, hashing as it writes; length or hash differs: 422 SD-N51; `CheckDBContext` under a 30-minute deadline: deadline 504 SD-N61, failure 422 SD-N52; one create-only `PutObjectFrom` to `seeds.SnapshotKey(host, id)` (a leftover object from an earlier failed attempt at the same key is deleted and the put retried once); the spool is removed on every path; `SeedUploaded`; audit SD-N63.
324
325- [ ] **Step 1: Write the failing tests**
326
327```go
328func uploadImport(t *testing.T, f fromFixture, host string, body []byte) (int, map[string]any) {
329 t.Helper()
330 req, _ := http.NewRequest(http.MethodPut, f.url+"/"+host+"/import", bytes.NewReader(body))
331 req.Header.Set("Authorization", "Bearer "+f.token)
332 res, err := http.DefaultClient.Do(req)
333 if err != nil {
334 t.Fatal(err)
335 }
336 defer res.Body.Close()
337 var out map[string]any
338 _ = json.NewDecoder(res.Body).Decode(&out)
339 return res.StatusCode, out
340}
341
342func sqliteBytes(t *testing.T) ([]byte, string) {
343 t.Helper()
344 p := filepath.Join(t.TempDir(), "snap.db")
345 db, err := sql.Open("sqlite", p)
346 if err != nil {
347 t.Fatal(err)
348 }
349 if _, err := db.Exec(`CREATE TABLE t (x INTEGER); INSERT INTO t VALUES (1)`); err != nil {
350 t.Fatal(err)
351 }
352 db.Close()
353 b, _ := os.ReadFile(p)
354 sum := sha256.Sum256(b)
355 return b, hex.EncodeToString(sum[:])
356}
357
358func TestImportUploadStoresTheSnapshot(t *testing.T) {
359 f := newImportFixture(t)
360 body, sha := sqliteBytes(t)
361 if code, out := beginImport(t, f, "old.go.tito.io", sha, int64(len(body))); code != http.StatusCreated {
362 t.Fatalf("begin = %d %v", code, out)
363 }
364 if code, out := uploadImport(t, f, "old.go.tito.io", body); code != http.StatusOK || out["state"] != "uploaded" {
365 t.Fatalf("upload = %d %v", code, out)
366 }
367 rec, _ := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", "old.go.tito.io")
368 got, _, err := f.data.Get(context.Background(), seeds.SnapshotKey(rec.Host, rec.Seed.ID))
369 if err != nil || !bytes.Equal(got, body) || rec.Seed.State != seeds.StateUploaded {
370 t.Fatalf("snapshot %d bytes, %v; state %s", len(got), err, rec.Seed.State)
371 }
372 if ents, _ := os.ReadDir(f.fx.srv.seedScratch.dir()); len(ents) != 0 {
373 t.Fatalf("spool left behind: %v", ents)
374 }
375}
376
377func TestImportUploadRefusesLengthAndHash(t *testing.T) {
378 f := newImportFixture(t)
379 body, sha := sqliteBytes(t)
380 beginImport(t, f, "old.go.tito.io", sha, int64(len(body)))
381 long := append(append([]byte{}, body...), 'x')
382 if code, out := uploadImport(t, f, "old.go.tito.io", long); code != http.StatusUnprocessableEntity || !strings.Contains(str(t, out, "error"), "does not match the length and sha256") {
383 t.Fatalf("too long = %d %v", code, out)
384 }
385 bad := append([]byte{}, body...)
386 bad[len(bad)-1] ^= 0xff
387 if code, _ := uploadImport(t, f, "old.go.tito.io", bad); code != http.StatusUnprocessableEntity {
388 t.Fatalf("wrong hash = %d", code)
389 }
390 junk := bytes.Repeat([]byte("j"), 100)
391 sum := sha256.Sum256(junk)
392 beginImport(t, f, "junk.go.tito.io", hex.EncodeToString(sum[:]), 100)
393 if code, out := uploadImport(t, f, "junk.go.tito.io", junk); code != http.StatusUnprocessableEntity || !strings.Contains(str(t, out, "error"), "integrity check") {
394 t.Fatalf("not a database = %d %v", code, out)
395 }
396 rec, _ := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", "old.go.tito.io")
397 if rec.Seed.State != seeds.StateAwaitingUpload {
398 t.Fatalf("a refused upload moved the state to %s", rec.Seed.State)
399 }
400}
401
402func TestImportUploadOnlyOnce(t *testing.T) {
403 f := newImportFixture(t)
404 body, sha := sqliteBytes(t)
405 beginImport(t, f, "old.go.tito.io", sha, int64(len(body)))
406 uploadImport(t, f, "old.go.tito.io", body)
407 if code, out := uploadImport(t, f, "old.go.tito.io", body); code != http.StatusConflict || !strings.Contains(str(t, out, "error"), "only while it waits for one") {
408 t.Fatalf("second upload = %d %v", code, out)
409 }
410}
411```
412
413(imports: `bytes`, `crypto/sha256`, `database/sql`, `encoding/hex`, `os`, `path/filepath`, `_ "modernc.org/sqlite"` if the console test package does not already register the driver.)
414
415- [ ] **Step 2: Run the tests to verify they fail**
416
417Run: `go test ./internal/console/ -run 'TestImportUpload' -count=1`
418Expected: FAIL: 404 for the unregistered route.
419
420- [ ] **Step 3: Write the gate and the upload**
421
422```go
423// checkSeedDBConsole is lease.CheckDBContext, a seam for the tests.
424var checkSeedDBConsole = lease.CheckDBContext
425
426const (
427 importUploadReadDeadline = 60 * time.Minute
428 importCheckDeadline = 30 * time.Minute
429)
430
431// importGate is every import call's gate: the instance gate (cliRoute has
432// already applied the instance role), the host, the record, an import.
433func (s *Server) importGate(w http.ResponseWriter, r *http.Request) (string, *Account, string, string, *provision.Record, bool) {
434 principal, acct, app, ok := s.instanceGate(w, r)
435 if !ok {
436 return "", nil, "", "", nil, false
437 }
438 host := r.PathValue("host")
439 if !provision.ValidHostShape(host) {
440 http.NotFound(w, r)
441 return "", nil, "", "", nil, false
442 }
443 rec, err := provision.GetRecord(r.Context(), s.cfg.Releases, acct.Sqid, app, host)
444 if errors.Is(err, os.ErrNotExist) {
445 http.NotFound(w, r)
446 return "", nil, "", "", nil, false
447 }
448 if err != nil {
449 log.Printf("console: import %s: read record: %v", host, err)
450 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
451 return "", nil, "", "", nil, false
452 }
453 if !rec.Seed.Import() {
454 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is not an import.", host))
455 return "", nil, "", "", nil, false
456 }
457 return principal, acct, app, host, rec, true
458}
459
460// handleAPIImportUpload is spec §5.2.
461func (s *Server) handleAPIImportUpload(w http.ResponseWriter, r *http.Request) {
462 principal, acct, app, host, rec, ok := s.importGate(w, r)
463 if !ok {
464 return
465 }
466 ctx := r.Context()
467 seed := rec.Seed
468 if seed.State != seeds.StateAwaitingUpload {
469 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is %s. It takes an upload only while it waits for one.", host, seed.State))
470 return
471 }
472 if ref := s.seedRegionReady(ctx, rec.Region, true); ref != nil {
473 jsonError(w, ref.Status, ref.Msg)
474 return
475 }
476 release_, ref := s.seedScratch.reserve(acct.Sqid+"/"+app, seed.Bytes)
477 if ref != nil {
478 jsonError(w, ref.Status, ref.Msg)
479 return
480 }
481 defer release_()
482 rc := http.NewResponseController(w)
483 if err := rc.SetReadDeadline(time.Now().Add(importUploadReadDeadline)); err != nil && !errors.Is(err, http.ErrNotSupported) {
484 log.Printf("console: import %s: set read deadline: %v", host, err)
485 }
486 defer func() { _ = rc.SetReadDeadline(time.Time{}) }()
487 spool := filepath.Join(s.seedScratch.dir(), host+".db")
488 defer os.Remove(spool)
489 f, err := os.OpenFile(spool, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)
490 if err != nil {
491 jsonError(w, http.StatusInsufficientStorage, "the console has no room for this right now. Try again later.")
492 return
493 }
494 h := sha256.New()
495 n, cerr := io.Copy(io.MultiWriter(f, h), http.MaxBytesReader(w, r.Body, seed.Bytes+1))
496 ferr := f.Close()
497 if cerr != nil && !isMaxBytes(cerr) {
498 if ctx.Err() == nil {
499 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
500 }
501 return
502 }
503 if ferr != nil {
504 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
505 return
506 }
507 if isMaxBytes(cerr) || n != seed.Bytes || hex.EncodeToString(h.Sum(nil)) != seed.SHA256 {
508 jsonError(w, http.StatusUnprocessableEntity, "the upload does not match the length and sha256 this import began with, so it was not kept.")
509 return
510 }
511 cctx, cancel := context.WithTimeout(ctx, importCheckDeadline)
512 defer cancel()
513 if err := checkSeedDBConsole(cctx, spool); err != nil {
514 if errors.Is(cctx.Err(), context.DeadlineExceeded) {
515 jsonError(w, http.StatusGatewayTimeout, "checking the upload took longer than 30 minutes, so it was not kept.")
516 return
517 }
518 jsonError(w, http.StatusUnprocessableEntity, "the upload is not a database that passes an integrity check, so it was not kept.")
519 return
520 }
521 if err := putSnapshot(ctx, s.cfg.SeedData, spool, seeds.SnapshotKey(host, seed.ID)); err != nil {
522 log.Printf("console: import %s: put snapshot: %v", host, err)
523 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
524 return
525 }
526 if _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, provision.SeedUploaded(seed.ID)); err != nil {
527 s.importTransitionFailure(w, host, err)
528 return
529 }
530 s.auditActivity(acct, app, principal, Activity{Action: "import-uploaded", TargetType: "instance", Target: host,
531 Detail: fmt.Sprintf("uploaded the snapshot for %s", host)})
532 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateUploaded})
533}
534
535func isMaxBytes(err error) bool {
536 var mbe *http.MaxBytesError
537 return errors.As(err, &mbe)
538}
539
540// putSnapshot writes path to key with one create-only PutFrom. An object
541// already there is a failed earlier attempt for this same seed id (the key
542// is scoped to it); it is deleted and the put retried once.
543func putSnapshot(ctx context.Context, data release.Store, path, key string) error {
544 put := func() error {
545 f, err := os.Open(path)
546 if err != nil {
547 return err
548 }
549 defer f.Close()
550 st, err := f.Stat()
551 if err != nil {
552 return err
553 }
554 _, err = release.PutObjectFrom(ctx, data, key, f, st.Size(), "")
555 return err
556 }
557 err := put()
558 if errors.Is(err, release.ErrCASConflict) {
559 if derr := data.Delete(ctx, key); derr != nil {
560 return derr
561 }
562 err = put()
563 }
564 return err
565}
566
567// importTransitionFailure answers a seed CAS that did not land.
568func (s *Server) importTransitionFailure(w http.ResponseWriter, host string, err error) {
569 if errors.Is(err, provision.ErrSeedConflict) {
570 jsonError(w, http.StatusConflict, fmt.Sprintf("%s changed while this request was made. Read its state with carlos instances list and try again.", host))
571 return
572 }
573 log.Printf("console: import %s: record: %v", host, err)
574 jsonError(w, http.StatusBadGateway, "could not store the upload. Try again.")
575}
576```
577
578Add `"context"`, `"crypto/sha256"`, `"encoding/hex"`, `"io"`, `"os"`, `"path/filepath"` and `"github.com/carlosframework/platform/internal/lease"` to the file's imports. Add the census lines for `os.Open(path)` in `putSnapshot` (and change Plan 5's `uploadSnapshot` to reuse `putSnapshot` for its upload, keeping its hashing).
579
580In `authcli.go`, after the `DELETE …/instances/{host}` route:
581
582```go
583 // The import door (seeded-instances spec §5): the instance role, like
584 // the create door that begins it.
585 s.cliRoute("PUT /api/cli/apps/{account}/{app}/instances/{host}/import", svcrole.Allow(svcrole.Instance), s.handleAPIImportUpload)
586```
587
588- [ ] **Step 4: Run the tests to verify they pass**
589
590Run: `go test ./internal/console/ -run 'TestImport' -count=1`
591Expected: PASS.
592
593- [ ] **Step 5: Wire SD-N51 to SD-N53, SD-N59 to SD-N61, SD-N63 and commit**
594
595```bash
596git add internal/console/ approved_seeded_copy_test.go
597git commit -m "console: the import upload, spooled, hashed, checked, then one PutFrom (Plan 6 Task 2)
598
599Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
600```
601
602### Task 3: Stopped and commit
603
604**Files:**
605- Modify: `internal/console/apiinstanceimport.go`, `internal/console/authcli.go`
606- Test: `internal/console/apiinstanceimport_test.go`
607
608**Interfaces:**
609- Produces: `POST …/instances/{host}/import/stopped` (200 `{"state":"ready"}`), `POST …/instances/{host}/import/commit` (200 `{"state":"committed"}`); handlers `handleAPIImportStopped`, `handleAPIImportCommit`.
610
611Stopped (spec §5.3): `uploaded` → `ready` (SD-N54 otherwise), `seedRegionReady` again, audit SD-N64, `bumpSerial` (the box swaps on its next pass). Commit (spec §5.4): `placed` → `committed`; an import before `placed` (`awaiting-upload`, `uploaded`, `ready`, `swapped`) answers 409 SD-N55; `committed` already answers 200 (a retried commit); `refused`, `aborted`, `rolled-back` answer 409 SD-N115; audit SD-N65; `bumpSerial` (the box clears the gate).
612
613- [ ] **Step 1: Write the failing tests**
614
615```go
616func postImport(t *testing.T, f fromFixture, host, verb string) (int, map[string]any) {
617 t.Helper()
618 code, _, raw := rawReq(t, http.MethodPost, f.url+"/"+host+"/import/"+verb, f.token, "")
619 var out map[string]any
620 _ = json.Unmarshal([]byte(raw), &out)
621 return code, out
622}
623
624func setSeedState(t *testing.T, f fromFixture, host string, steps ...func(string) func(*provision.Record) error) {
625 t.Helper()
626 rec, _ := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", host)
627 for _, step := range steps {
628 if _, err := provision.SetRecordSeed(context.Background(), f.fx.rel, "bab", "titogo", host, step(rec.Seed.ID)); err != nil {
629 t.Fatal(err)
630 }
631 }
632}
633
634func TestImportStoppedAndCommit(t *testing.T) {
635 f := newImportFixture(t)
636 body, sha := sqliteBytes(t)
637 beginImport(t, f, "old.go.tito.io", sha, int64(len(body)))
638 if code, out := postImport(t, f, "old.go.tito.io", "stopped"); code != http.StatusConflict || !strings.Contains(str(t, out, "error"), "after its upload") {
639 t.Fatalf("stopped before upload = %d %v", code, out)
640 }
641 uploadImport(t, f, "old.go.tito.io", body)
642 before := serial(t, f.fx)
643 if code, out := postImport(t, f, "old.go.tito.io", "stopped"); code != http.StatusOK || out["state"] != "ready" {
644 t.Fatalf("stopped = %d %v", code, out)
645 }
646 if serial(t, f.fx) == before {
647 t.Fatal("stopped did not bump the serial")
648 }
649 if code, out := postImport(t, f, "old.go.tito.io", "commit"); code != http.StatusConflict || !strings.Contains(str(t, out, "error"), "nothing has been verified yet") {
650 t.Fatalf("commit before placed = %d %v", code, out)
651 }
652 // The box swaps and places (Plans 4 and 7); the test plays the box.
653 setSeedState(t, f, "old.go.tito.io", provision.SeedSwapped, provision.SeedPlace)
654 if code, out := postImport(t, f, "old.go.tito.io", "commit"); code != http.StatusOK || out["state"] != "committed" {
655 t.Fatalf("commit = %d %v", code, out)
656 }
657 if code, _ := postImport(t, f, "old.go.tito.io", "commit"); code != http.StatusOK {
658 t.Fatalf("a retried commit = %d, want 200", code)
659 }
660}
661```
662
663(`serial(t, fx)` is the helper `apisystemlayout_test.go` uses.)
664
665- [ ] **Step 2: Run the tests to verify they fail**
666
667Run: `go test ./internal/console/ -run TestImportStoppedAndCommit -count=1`
668Expected: FAIL: 404.
669
670- [ ] **Step 3: Write the two handlers and routes**
671
672```go
673// handleAPIImportStopped is the app saying its own process is down (spec
674// §5.3): uploaded to ready, and a serial bump so the box swaps.
675func (s *Server) handleAPIImportStopped(w http.ResponseWriter, r *http.Request) {
676 principal, acct, app, host, rec, ok := s.importGate(w, r)
677 if !ok {
678 return
679 }
680 if rec.Seed.State != seeds.StateUploaded {
681 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is %s. Mark it stopped once, after its upload.", host, rec.Seed.State))
682 return
683 }
684 if ref := s.seedRegionReady(r.Context(), rec.Region, true); ref != nil {
685 jsonError(w, ref.Status, ref.Msg)
686 return
687 }
688 if _, err := provision.SetRecordSeed(r.Context(), s.cfg.Releases, acct.Sqid, app, host, provision.SeedStopped(rec.Seed.ID)); err != nil {
689 s.importTransitionFailure(w, host, err)
690 return
691 }
692 s.auditActivity(acct, app, principal, Activity{Action: "import-stopped", TargetType: "instance", Target: host,
693 Detail: fmt.Sprintf("marked the old process of %s stopped", host)})
694 s.bumpSerial(r.Context())
695 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateReady})
696}
697
698// handleAPIImportCommit is the app's verdict that the instance serves
699// (spec §5.4): placed to committed; the box then clears the gate.
700func (s *Server) handleAPIImportCommit(w http.ResponseWriter, r *http.Request) {
701 principal, acct, app, host, rec, ok := s.importGate(w, r)
702 if !ok {
703 return
704 }
705 switch rec.Seed.State {
706 case seeds.StateCommitted:
707 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateCommitted})
708 return
709 case seeds.StatePlaced:
710 case seeds.StateAwaitingUpload, seeds.StateUploaded, seeds.StateReady, seeds.StateSwapped:
711 jsonError(w, http.StatusConflict, "nothing has been verified yet. Send a request with the verify token first, then commit.")
712 return
713 default:
714 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is %s, so there is nothing to commit.", host, rec.Seed.State))
715 return
716 }
717 if _, err := provision.SetRecordSeed(r.Context(), s.cfg.Releases, acct.Sqid, app, host, provision.SeedCommit(rec.Seed.ID)); err != nil {
718 s.importTransitionFailure(w, host, err)
719 return
720 }
721 s.auditActivity(acct, app, principal, Activity{Action: "import-committed", TargetType: "instance", Target: host,
722 Detail: fmt.Sprintf("committed the import of %s", host)})
723 s.bumpSerial(r.Context())
724 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateCommitted})
725}
726```
727
728Routes beside the upload route:
729
730```go
731 s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/import/stopped", svcrole.Allow(svcrole.Instance), s.handleAPIImportStopped)
732 s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/import/commit", svcrole.Allow(svcrole.Instance), s.handleAPIImportCommit)
733```
734
735- [ ] **Step 4: Run the tests to verify they pass**
736
737Run: `go test ./internal/console/ -run 'TestImport' -count=1`
738Expected: PASS.
739
740- [ ] **Step 5: Wire SD-N54, SD-N55, SD-N64, SD-N65, SD-N115 and commit**
741
742```bash
743git add internal/console/ approved_seeded_copy_test.go
744git commit -m "console: the import's stopped and commit (Plan 6 Task 3)
745
746Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
747```
748
749### Task 4: The console's finish
750
751**Files:**
752- Create: `internal/console/seedfinish.go`, `internal/console/seedfinish_test.go`
753
754**Interfaces:**
755- Consumes: `objstore.GetIn`, `objstore.TeardownIn(ctx, s, p, sc, acct, app, env)`, `storeTeardownTimeout`, `provision.GetRecordETag`, `provision.RecordKey`, `release.DeleteIfMatch`.
756- Produces: `(s *Server) finishSeed(ctx context.Context, sqid, app, host, seedID string) error`: the store teardown, then the record delete. Plan 8's sweep calls it too, with the record's account sqid.
757
758Spec §5.6 "The console finishes" (codex R6-1): for a record whose seed is `rolled-back`:
759
7601. Read the store record for the record's environment. When its `Declared.Seed` is this `ID` and it holds any estate (`Grant` or `Provisioned`), run `objstore.TeardownIn`; a declared-only record with this seed is deleted with the teardown too (`TeardownIn` handles a partial store and deletes its record last, `walk.go:547`, `:728`). A store with another seed or none is never touched.
7612. Delete the record with `release.DeleteIfMatch` on the etag of the read that saw this seed `ID` in `rolled-back`. A record that names another `ID`, or another state, is left alone.
762
763The record holds the hostname until step 2, so a re-import of the same host never meets the leftover store §4 would refuse. Both steps are idempotent; a crash between them resumes at step 1, which then finds no store.
764
765- [ ] **Step 1: Write the failing tests**
766
767```go
768package console
769
770import (
771 "context"
772 "errors"
773 "os"
774 "testing"
775 "time"
776
777 "github.com/carlosframework/platform/internal/objstore"
778 "github.com/carlosframework/platform/internal/provision"
779 "github.com/carlosframework/platform/internal/seeds"
780)
781
782func rolledBackRecord(t *testing.T, fx *consoleFixture, host, env string) string {
783 t.Helper()
784 id, _ := seeds.NewID()
785 rec := provision.Record{Schema: 1, Host: host, Slug: "canary", App: "titogo", Account: "bab", Channel: "stable",
786 Environment: env, CreatedAt: time.Now().UTC(),
787 Seed: &provision.SeedSource{ID: id, Kind: seeds.KindImport, State: seeds.StateRolledBack, By: "t", At: time.Now().UTC()}}
788 if err := provision.CreateRecord(context.Background(), fx.rel, rec); err != nil {
789 t.Fatal(err)
790 }
791 return id
792}
793
794func TestFinishSeedDeletesTheRecordLast(t *testing.T) {
795 fx := newConsoleFixture(t)
796 id := rolledBackRecord(t, fx, "canary.go.tito.io", "canary")
797 teardowns := useFakeStoreTeardown(t, fx) // counts objstore.TeardownIn calls by env (seam: storeTeardown var in seedfinish.go)
798 putStoreRecord(t, fx, "titogo", "canary", `{"schema":1,"declared":{"env_prefix":"S3","at":"2026-10-08T09:00:00Z","by":"x","seed":"`+id+`"},"grant":{"backend":"aws","bucket":"b","source":"account-approval","at":"2026-10-08T09:00:00Z","by":"x"}}`)
799 if err := fx.srv.finishSeed(context.Background(), "bab", "titogo", "canary.go.tito.io", id); err != nil {
800 t.Fatal(err)
801 }
802 if (*teardowns)["canary"] != 1 {
803 t.Fatalf("teardowns = %v, want the seed's store torn down once", *teardowns)
804 }
805 if _, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", "canary.go.tito.io"); !errors.Is(err, os.ErrNotExist) {
806 t.Fatalf("record after finish: %v, want gone", err)
807 }
808}
809
810func TestFinishSeedIsScopedToItsID(t *testing.T) {
811 fx := newConsoleFixture(t)
812 id := rolledBackRecord(t, fx, "canary.go.tito.io", "canary")
813 teardowns := useFakeStoreTeardown(t, fx)
814 putStoreRecord(t, fx, "titogo", "canary", `{"schema":1,"declared":{"env_prefix":"S3","at":"2026-10-08T09:00:00Z","by":"x","seed":"sd_bbbbbbbbbbbbbbbbbbbbbbbbbb"},"grant":{"backend":"aws","bucket":"b","source":"account-approval","at":"2026-10-08T09:00:00Z","by":"x"}}`)
815 if err := fx.srv.finishSeed(context.Background(), "bab", "titogo", "canary.go.tito.io", id); err != nil {
816 t.Fatal(err)
817 }
818 if len(*teardowns) != 0 {
819 t.Fatalf("another seed's store was torn down: %v", *teardowns)
820 }
821 // A record naming another seed is left alone.
822 other := rolledBackRecord(t, fx, "other.go.tito.io", "other")
823 if err := fx.srv.finishSeed(context.Background(), "bab", "titogo", "other.go.tito.io", id); err != nil {
824 t.Fatal(err)
825 }
826 if rec, err := provision.GetRecord(context.Background(), fx.rel, "bab", "titogo", "other.go.tito.io"); err != nil || rec.Seed.ID != other {
827 t.Fatalf("a record naming another seed: %+v, %v", rec, err)
828 }
829}
830```
831
832`useFakeStoreTeardown` replaces `seedfinish.go`'s package var `storeTeardown = objstore.TeardownIn` with a counter keyed by `env` that also deletes the store record (as the real teardown does), and restores it on cleanup.
833
834- [ ] **Step 2: Run the tests to verify they fail**
835
836Run: `go test ./internal/console/ -run TestFinishSeed -count=1`
837Expected: FAIL to compile.
838
839- [ ] **Step 3: Write `seedfinish.go`**
840
841```go
842package console
843
844import (
845 "context"
846 "errors"
847 "fmt"
848 "os"
849
850 "github.com/carlosframework/platform/internal/objstore"
851 "github.com/carlosframework/platform/internal/provision"
852 "github.com/carlosframework/platform/internal/release"
853 "github.com/carlosframework/platform/internal/seeds"
854)
855
856// storeTeardown is objstore.TeardownIn, a seam for the tests.
857var storeTeardown = objstore.TeardownIn
858
859// finishSeed is the console's last word on an abandoned seed (spec §5.6,
860// codex R6-1): tear down the store this seed created, then delete the
861// record, only while it still names this seed and says rolled-back. The
862// record goes last: until then it holds the hostname.
863func (s *Server) finishSeed(ctx context.Context, sqid, app, host, seedID string) error {
864 rec, etag, err := provision.GetRecordETag(ctx, s.cfg.Releases, sqid, app, host)
865 if errors.Is(err, os.ErrNotExist) {
866 return nil
867 }
868 if err != nil {
869 return err
870 }
871 if rec.Seed == nil || rec.Seed.ID != seedID || rec.Seed.State != seeds.StateRolledBack {
872 return nil
873 }
874 store, _, err := objstore.GetIn(ctx, s.cfg.Releases, sqid, app, rec.Environment)
875 if err != nil {
876 return fmt.Errorf("read the store of %s: %w", host, err)
877 }
878 if store != nil && store.Declared != nil && store.Declared.Seed == seedID {
879 if s.cfg.StoreProvisioner == nil {
880 return errors.New("this console has no storage backend to tear the seed's store down with")
881 }
882 tctx, cancel := context.WithTimeout(ctx, storeTeardownTimeout)
883 defer cancel()
884 if err := storeTeardown(tctx, s.cfg.Releases, s.cfg.StoreProvisioner, s.cfg.StoreScanner, sqid, app, rec.Environment); err != nil {
885 return fmt.Errorf("tear down the store of %s: %w", host, err)
886 }
887 }
888 if err := release.DeleteIfMatch(ctx, s.cfg.Releases, provision.RecordKey(sqid, app, host), etag); err != nil && !errors.Is(err, os.ErrNotExist) {
889 return fmt.Errorf("delete the record of %s: %w", host, err)
890 }
891 s.bumpSerial(ctx)
892 return nil
893}
894```
895
896A store whose `Declared.Seed` is this seed's but which holds no estate still goes through `TeardownIn`, which deletes its record; a test fixture with a nil `StoreProvisioner` and such a store gets the error above, which the sweep logs and retries.
897
898- [ ] **Step 4: Run the tests to verify they pass**
899
900Run: `go test ./internal/console/ -run TestFinishSeed -count=1`
901Expected: PASS.
902
903- [ ] **Step 5: Commit**
904
905```bash
906git add internal/console/seedfinish.go internal/console/seedfinish_test.go
907git commit -m "console: finishSeed, the seed-guarded store teardown and the record delete last (Plan 6 Task 4)
908
909Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
910```
911
912### Task 5: Abort, and the delete refusal
913
914**Files:**
915- Modify: `internal/console/apiinstanceimport.go` (`handleAPIImportAbort`, `refuseImportDelete`, `activeRunOpen`), `internal/console/authcli.go`, `internal/console/apiinstances.go:1746` (one call in `handleAPIInstanceDelete`)
916- Test: `internal/console/apiinstanceimport_test.go`
917
918**Interfaces:**
919- Consumes: `provision.Record.ActiveRun` with `RunState.State` (run series); `provision.SeedAbort`, `provision.SeedRolledBackBeforeSwap`; `finishSeed`; `s.cfg.SeedData`.
920- Produces: `POST …/instances/{host}/import/abort` (200 `{"state":"aborted"}` or `{"state":"rolled-back"}` when the console finished it); `(s *Server) refuseImportDelete(w, r, acct *Account, app, host string) (answered, finished bool)`; `activeRunOpen(rec *provision.Record) bool`.
921
922Abort (spec §5.6): refused after `committed` (SD-N56); refused while a run is open (SD-N58), checked inside the same CAS as the transition; `aborted` already: 200; `rolled-back` already: `finishSeed`, then 200. Otherwise CAS to `aborted`, audit SD-N66, `bumpSerial`. Delete of an import that is not committed (spec §5.6, codex R2-7): `awaiting-upload`, `uploaded`, `refused` → CAS straight to `rolled-back`, delete `seeds/<host>/<id>/snapshot.db`, `finishSeed`, answer as the ordinary delete does; `rolled-back` → `finishSeed`; any other uncommitted state → 409 SD-N57.
923
924- [ ] **Step 1: Write the failing tests**
925
926```go
927func TestImportCommitAbortRace(t *testing.T) {
928 f := newImportFixture(t)
929 body, sha := sqliteBytes(t)
930 beginImport(t, f, "old.go.tito.io", sha, int64(len(body)))
931 uploadImport(t, f, "old.go.tito.io", body)
932 postImport(t, f, "old.go.tito.io", "stopped")
933 setSeedState(t, f, "old.go.tito.io", provision.SeedSwapped, provision.SeedPlace)
934 codes := make(chan int, 2)
935 for _, verb := range []string{"commit", "abort"} {
936 go func(verb string) {
937 code, _ := postImport(t, f, "old.go.tito.io", verb)
938 codes <- code
939 }(verb)
940 }
941 a, b := <-codes, <-codes
942 rec, _ := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", "old.go.tito.io")
943 ok := (rec.Seed.State == seeds.StateCommitted) != (rec.Seed.State == seeds.StateAborted)
944 if !ok || (a != http.StatusOK && b != http.StatusOK) || a == http.StatusBadGateway || b == http.StatusBadGateway {
945 t.Fatalf("codes %d %d, final state %s: want exactly one winner", a, b, rec.Seed.State)
946 }
947}
948
949func TestImportAbortRefusals(t *testing.T) {
950 f := newImportFixture(t)
951 body, sha := sqliteBytes(t)
952 beginImport(t, f, "old.go.tito.io", sha, int64(len(body)))
953 setRun(t, f, "old.go.tito.io", "picked") // writes Record.ActiveRun through the run series' transition
954 if code, out := postImport(t, f, "old.go.tito.io", "abort"); code != http.StatusConflict || !strings.Contains(str(t, out, "error"), "carlos run is busy") {
955 t.Fatalf("abort with a run open = %d %v", code, out)
956 }
957 setRun(t, f, "old.go.tito.io", "done")
958 if code, out := postImport(t, f, "old.go.tito.io", "abort"); code != http.StatusOK || out["state"] != "aborted" {
959 t.Fatalf("abort = %d %v", code, out)
960 }
961 if code, _ := postImport(t, f, "old.go.tito.io", "abort"); code != http.StatusOK {
962 t.Fatalf("abort again = %d, want 200", code)
963 }
964}
965
966func TestImportDeleteRefusedUntilCommittedOrUnswapped(t *testing.T) {
967 f := newImportFixture(t)
968 body, sha := sqliteBytes(t)
969 beginImport(t, f, "early.go.tito.io", sha, int64(len(body)))
970 if code, _, _ := rawReq(t, http.MethodDelete, f.url+"/early.go.tito.io", f.token, ""); code != http.StatusOK {
971 t.Fatalf("delete before upload = %d, want 200", code)
972 }
973 if _, err := provision.GetRecord(context.Background(), f.fx.rel, "bab", "titogo", "early.go.tito.io"); !errors.Is(err, os.ErrNotExist) {
974 t.Fatalf("record after an early delete: %v", err)
975 }
976 beginImport(t, f, "late.go.tito.io", sha, int64(len(body)))
977 uploadImport(t, f, "late.go.tito.io", body)
978 postImport(t, f, "late.go.tito.io", "stopped")
979 setSeedState(t, f, "late.go.tito.io", provision.SeedSwapped)
980 code, _, raw := rawReq(t, http.MethodDelete, f.url+"/late.go.tito.io", f.token, "")
981 if code != http.StatusConflict || !strings.Contains(raw, "Abort the import instead") {
982 t.Fatalf("delete after the swap = %d %s", code, raw)
983 }
984}
985```
986
987`setRun` writes the run series' field directly, through the public etag-guarded writer (an ordinary writer may change `ActiveRun` unless the run series protects it; if it does, apply its own transition instead):
988
989```go
990func setRun(t *testing.T, f fromFixture, host, state string) {
991 t.Helper()
992 rec, etag, err := provision.GetRecordETag(context.Background(), f.fx.rel, "bab", "titogo", host)
993 if err != nil {
994 t.Fatal(err)
995 }
996 rec.ActiveRun = &provision.RunState{ID: "run_1", State: state, Deadline: time.Now().Add(time.Hour)}
997 if err := provision.UpdateRecord(context.Background(), f.fx.rel, *rec, etag); err != nil {
998 t.Fatal(err)
999 }
1000}
1001```
1002
1003- [ ] **Step 2: Run the tests to verify they fail**
1004
1005Run: `go test ./internal/console/ -run 'TestImportCommitAbortRace|TestImportAbortRefusals|TestImportDelete' -count=1`
1006Expected: FAIL: 404 for abort; the early delete leaves the record or answers with a claim-free retire.
1007
1008- [ ] **Step 3: Write abort, the delete refusal and the route**
1009
1010```go
1011// activeRunOpen is the run series' record field read for abort's rule
1012// (spec §5.6): a run that is not done, cancelled or expired.
1013func activeRunOpen(rec *provision.Record) bool {
1014 if rec.ActiveRun == nil {
1015 return false
1016 }
1017 switch rec.ActiveRun.State {
1018 case "done", "cancelled", "expired":
1019 return false
1020 }
1021 return true
1022}
1023
1024var errRunOpen = errors.New("console: a run is open on the instance")
1025
1026// handleAPIImportAbort abandons an import before commit (spec §5.6).
1027func (s *Server) handleAPIImportAbort(w http.ResponseWriter, r *http.Request) {
1028 principal, acct, app, host, rec, ok := s.importGate(w, r)
1029 if !ok {
1030 return
1031 }
1032 ctx := r.Context()
1033 id := rec.Seed.ID
1034 switch rec.Seed.State {
1035 case seeds.StateCommitted:
1036 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is committed. Delete it with carlos instances delete instead.", host))
1037 return
1038 case seeds.StateAborted:
1039 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateAborted})
1040 return
1041 case seeds.StateRolledBack:
1042 if err := s.finishSeed(ctx, acct.Sqid, app, host, id); err != nil {
1043 log.Printf("console: import %s: finish: %v", host, err)
1044 }
1045 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateRolledBack})
1046 return
1047 }
1048 _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, func(rec *provision.Record) error {
1049 if activeRunOpen(rec) {
1050 return errRunOpen
1051 }
1052 return provision.SeedAbort(id)(rec)
1053 })
1054 switch {
1055 case errors.Is(err, errRunOpen):
1056 jsonError(w, http.StatusConflict, fmt.Sprintf("carlos run is busy on %s. Wait for it to finish, then abort.", host))
1057 return
1058 case errors.Is(err, provision.ErrSeedConflict):
1059 // The commit won the race, or the state moved: answer from the record.
1060 if cur, gerr := provision.GetRecord(ctx, s.cfg.Releases, acct.Sqid, app, host); gerr == nil && cur.Seed != nil && cur.Seed.State == seeds.StateCommitted {
1061 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is committed. Delete it with carlos instances delete instead.", host))
1062 return
1063 }
1064 s.importTransitionFailure(w, host, err)
1065 return
1066 case err != nil:
1067 s.importTransitionFailure(w, host, err)
1068 return
1069 }
1070 s.auditActivity(acct, app, principal, Activity{Action: "import-aborted", TargetType: "instance", Target: host,
1071 Detail: fmt.Sprintf("aborted the import of %s", host)})
1072 s.bumpSerial(ctx)
1073 writeJSON(w, http.StatusOK, map[string]string{"state": seeds.StateAborted})
1074}
1075
1076// refuseImportDelete is the delete door's import rule (spec §5.6, codex
1077// R2-7). answered: the delete must not go the ordinary way, and either this
1078// function has answered (a refusal) or, with finished, the import was
1079// finished here and the caller writes the ordinary delete's audit row and
1080// answer. A committed import, a --from seed and an unseeded record are
1081// (false, false).
1082func (s *Server) refuseImportDelete(w http.ResponseWriter, r *http.Request, acct *Account, app, host string) (answered, finished bool) {
1083 ctx := r.Context()
1084 rec, err := provision.GetRecord(ctx, s.cfg.Releases, acct.Sqid, app, host)
1085 if err != nil || !rec.Seed.Import() || rec.Seed.State == seeds.StateCommitted {
1086 return false, false
1087 }
1088 id := rec.Seed.ID
1089 switch rec.Seed.State {
1090 case seeds.StateAwaitingUpload, seeds.StateUploaded, seeds.StateRefused:
1091 if _, err := provision.SetRecordSeed(ctx, s.cfg.Releases, acct.Sqid, app, host, provision.SeedRolledBackBeforeSwap(id)); err != nil {
1092 s.importTransitionFailure(w, host, err)
1093 return true, false
1094 }
1095 if s.cfg.SeedData != nil {
1096 if err := s.cfg.SeedData.Delete(ctx, seeds.SnapshotKey(host, id)); err != nil && !errors.Is(err, os.ErrNotExist) {
1097 log.Printf("console: import %s: delete snapshot: %v", host, err)
1098 }
1099 }
1100 fallthrough
1101 case seeds.StateRolledBack:
1102 if err := s.finishSeed(ctx, acct.Sqid, app, host, id); err != nil {
1103 s.importTransitionFailure(w, host, err)
1104 return true, false
1105 }
1106 return true, true
1107 }
1108 jsonError(w, http.StatusConflict, fmt.Sprintf("%s is an import that is not committed. Abort the import instead.", host))
1109 return true, false
1110}
1111```
1112
1113In `handleAPIInstanceDelete`, after the host-shape check and before `retireInstanceRecord`:
1114
1115```go
1116 if answered, finished := s.refuseImportDelete(w, r, acct, app, host); answered {
1117 if finished {
1118 s.auditActivity(acct, app, principal, Activity{
1119 Action: "instance-delete", TargetType: "instance", Target: host, Message: message,
1120 Detail: "deleted instance " + host + " (cli)",
1121 })
1122 s.bumpSerial(ctx)
1123 writeJSON(w, http.StatusOK, map[string]any{"result": "deleted"})
1124 }
1125 return
1126 }
1127```
1128
1129The `Detail` and the body are `main`'s own (`apiinstances.go:1812-1820`), reused byte for byte, so the legacy-exempt file gains no sentence.
1130
1131Route:
1132
1133```go
1134 s.cliRoute("POST /api/cli/apps/{account}/{app}/instances/{host}/import/abort", svcrole.Allow(svcrole.Instance), s.handleAPIImportAbort)
1135```
1136
1137- [ ] **Step 4: Run the tests to verify they pass**
1138
1139Run: `go test ./internal/console/ -run 'TestImport|TestAPIInstanceDelete' -count=1 && go test . -run TestMoves -count=1`
1140Expected: PASS; `TestMovesLegacyExemptionsAreLegacy` passes (the delete handler gained a call and reused `main`'s own detail string).
1141
1142- [ ] **Step 5: Wire SD-N56 to SD-N58, SD-N66 and commit**
1143
1144```bash
1145git add internal/console/ approved_seeded_copy_test.go
1146git commit -m "console: the import's abort and the delete door's import rule (Plan 6 Task 5)
1147
1148Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
1149```
1150
1151### Task 6: `carlos instances import`
1152
1153**Files:**
1154- Create: `instances_import.go`, `instances_import_test.go`
1155- Modify: `cli.go:362` (`runInstances`: `case "import"`), `apimode.go` (client calls)
1156- Modify: `docs/site/cli.md` (under `### carlos instances`)
1157
1158**Interfaces:**
1159- Consumes: `requireAPISession`, `resolvedAccount`, `resolvedApp`, `consoleOption`, `appFlag`, `printUsing`, `sess.instanceGet`, `sess.postJSON`, `s.c.doStream`, `apiErrorFromBody`, `seedCell`.
1160- Produces: `runInstancesImport(args []string)`; `(s *apiSession) importBegin(ctx, a apiAcct, app, host, environment, sha string, bytes int64, replaces string) (apiInstanceRecord, string, error)`; `(s *apiSession) importUpload(ctx, a apiAcct, app, host string, f *os.File, size int64) error`; `(s *apiSession) importVerb(ctx, a apiAcct, app, host, verb string) error`; `verifyImport(ctx context.Context, client *http.Client, host, path, token string) (int, error)`.
1161
1162The command (spec §5): hash the file and print SD-N68; begin (keep the token in memory only); upload; `stopped` and SD-N69; poll the record every 3 seconds for up to 10 minutes, printing SD-N70 once: `swapped` or `placed` continues, `refused` prints SD-N78 and exits 1, the deadline prints SD-N79 and exits 1; print SD-N71. Without `--verify`: print SD-N72 and SD-N73 and exit 0. With `--verify <path>`: `GET https://<host><path>` with `Carlos-Import-Verify: <token>`, retrying a 503 (the gate's `Retry-After` while the instance wakes) up to 20 times; a 2xx prints SD-N74, waits (SD-N90) up to 5 minutes for `placed`, commits, prints SD-N75; anything else prints SD-N76, aborts, prints SD-N77, exits 1. `carlos instances import commit|abort --app --host` call the verb alone and print SD-N75 or SD-N77.
1163
1164- [ ] **Step 1: Write the failing tests**
1165
1166```go
1167package main
1168
1169import (
1170 "context"
1171 "net/http"
1172 "net/http/httptest"
1173 "sync/atomic"
1174 "testing"
1175)
1176
1177func TestImportVerifyRetriesThroughTheWake(t *testing.T) {
1178 var calls atomic.Int32
1179 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1180 if r.Header.Get("Carlos-Import-Verify") != "tok" {
1181 w.WriteHeader(http.StatusForbidden)
1182 return
1183 }
1184 if calls.Add(1) < 3 {
1185 w.Header().Set("Retry-After", "0")
1186 w.WriteHeader(http.StatusServiceUnavailable)
1187 return
1188 }
1189 w.WriteHeader(http.StatusNoContent)
1190 }))
1191 defer ts.Close()
1192 code, err := verifyImportURL(context.Background(), ts.Client(), ts.URL+"/up", "tok")
1193 if err != nil || code != http.StatusNoContent || calls.Load() != 3 {
1194 t.Fatalf("code %d err %v calls %d", code, err, calls.Load())
1195 }
1196}
1197
1198func TestImportVerifyStopsOnAFailure(t *testing.T) {
1199 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) }))
1200 defer ts.Close()
1201 code, err := verifyImportURL(context.Background(), ts.Client(), ts.URL+"/up", "tok")
1202 if err != nil || code != http.StatusInternalServerError {
1203 t.Fatalf("code %d err %v", code, err)
1204 }
1205}
1206
1207func TestImportClientCallsTheDoor(t *testing.T) {
1208 var seen []string
1209 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
1210 seen = append(seen, r.Method+" "+r.URL.Path)
1211 switch {
1212 case r.Method == http.MethodPost && r.URL.Path == "/api/cli/apps/bab/titogo/instances":
1213 w.WriteHeader(http.StatusCreated)
1214 w.Write([]byte(`{"host":"old.go.tito.io","verify_token":"tok","seed":{"kind":"import","state":"awaiting-upload"}}`))
1215 default:
1216 w.WriteHeader(http.StatusOK)
1217 w.Write([]byte(`{"state":"ok"}`))
1218 }
1219 }))
1220 defer ts.Close()
1221 s := newTestSession(ts.URL)
1222 a := apiAcct{Seg: "bab"}
1223 _, tok, err := s.importBegin(context.Background(), a, "titogo", "old.go.tito.io", "", "aa", 3, "127.0.0.1:8401")
1224 if err != nil || tok != "tok" {
1225 t.Fatalf("begin: %q %v", tok, err)
1226 }
1227 for _, verb := range []string{"stopped", "commit", "abort"} {
1228 if err := s.importVerb(context.Background(), a, "titogo", "old.go.tito.io", verb); err != nil {
1229 t.Fatalf("%s: %v", verb, err)
1230 }
1231 }
1232 want := []string{"POST /api/cli/apps/bab/titogo/instances", "POST /api/cli/apps/bab/titogo/instances/old.go.tito.io/import/stopped",
1233 "POST /api/cli/apps/bab/titogo/instances/old.go.tito.io/import/commit", "POST /api/cli/apps/bab/titogo/instances/old.go.tito.io/import/abort"}
1234 if len(seen) != len(want) {
1235 t.Fatalf("calls = %q", seen)
1236 }
1237 for i := range want {
1238 if seen[i] != want[i] {
1239 t.Fatalf("call %d = %q, want %q", i, seen[i], want[i])
1240 }
1241 }
1242}
1243```
1244
1245(`verifyImport` builds `"https://" + host + path` and calls `verifyImportURL`; the tests call the URL form.)
1246
1247- [ ] **Step 2: Run the tests to verify they fail**
1248
1249Run: `go test . -run 'TestImportVerify|TestImportClient' -count=1`
1250Expected: FAIL to compile.
1251
1252- [ ] **Step 3: Write `instances_import.go` and the client calls**
1253
1254```go
1255package main
1256
1257import (
1258 "context"
1259 "crypto/sha256"
1260 "encoding/hex"
1261 "flag"
1262 "fmt"
1263 "io"
1264 "log"
1265 "net/http"
1266 "os"
1267 "strconv"
1268 "strings"
1269 "time"
1270)
1271
1272const (
1273 importSwapWait = 10 * time.Minute
1274 importPlaceWait = 5 * time.Minute
1275 importPoll = 3 * time.Second
1276 importVerifyTries = 20
1277)
1278
1279// runInstancesImport is `carlos instances import` (seeded-instances spec §5).
1280func runInstancesImport(args []string) {
1281 if len(args) > 0 && (args[0] == "commit" || args[0] == "abort") {
1282 runInstancesImportVerb(args[0], args[1:])
1283 return
1284 }
1285 fs := flag.NewFlagSet("instances import", flag.ExitOnError)
1286 app := appFlag(fs, "app the instance belongs to")
1287 host := fs.String("host", "", "instance host — one DNS label + \".\" + the app's instance domain")
1288 file := fs.String("file", "", "the snapshot to import: a consistent SQLite file taken after the old process stopped")
1289 replaces := fs.String("replaces", "", "the address of the route this import takes over, as host:port")
1290 environment := fs.String("environment", "", "named config bundle this route binds to (default: the app's default bundle) — carlos env environments lists them")
1291 verify := fs.String("verify", "", "a path to request with the verify token once swapped. A 2xx commits the import, anything else aborts it")
1292 consoleFlag := consoleOption(fs, "console to create through (default: the only logged-in one)")
1293 acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)")
1294 acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account")
1295 fs.Usage = flagUsage(fs, "")
1296 fs.Parse(args)
1297 if *host == "" || *file == "" || *replaces == "" {
1298 fs.Usage()
1299 os.Exit(2)
1300 }
1301 ctx := context.Background()
1302 sess := requireAPISession("import", *consoleFlag)
1303 printUsing(stdout, sess)
1304 acct := resolvedAccount(sess, acctRaw, acctIDRaw)
1305 app2 := resolvedApp(sess, acct, *app, instancesRecordsUsage)
1306 f, err := os.Open(*file)
1307 if err != nil {
1308 log.Fatalf("instances import: %v", err)
1309 }
1310 defer f.Close()
1311 h := sha256.New()
1312 size, err := io.Copy(h, f)
1313 if err != nil {
1314 log.Fatalf("instances import: %v", err)
1315 }
1316 sha := hex.EncodeToString(h.Sum(nil))
1317 fmt.Fprintln(stdout, fmt.Sprintf("uploading %s (%s)", *file, humanBytes(&size)))
1318 _, token, err := sess.importBegin(ctx, acct, app2, *host, strings.TrimSpace(*environment), sha, size, strings.TrimSpace(*replaces))
1319 if err != nil {
1320 log.Fatalf("instances import: %v", err)
1321 }
1322 if _, err := f.Seek(0, io.SeekStart); err != nil {
1323 log.Fatalf("instances import: %v", err)
1324 }
1325 if err := sess.importUpload(ctx, acct, app2, *host, f, size); err != nil {
1326 log.Fatalf("instances import: %v", err)
1327 }
1328 if err := sess.importVerb(ctx, acct, app2, *host, "stopped"); err != nil {
1329 log.Fatalf("instances import: %v", err)
1330 }
1331 fmt.Fprintln(stdout, fmt.Sprintf("uploaded. The old process of %s is marked stopped, and the box swaps it on its next pass.", *host))
1332 fmt.Fprintln(stdout, fmt.Sprintf("waiting for the box to swap %s", *host))
1333 if !waitImport(ctx, sess, acct, app2, *host, importSwapWait, "swapped", "placed") {
1334 fmt.Fprintln(stdout, fmt.Sprintf("the box has not swapped %s after %d minutes. Check carlos instances list, then commit or abort.", *host, int(importSwapWait/time.Minute)))
1335 os.Exit(1)
1336 }
1337 fmt.Fprintln(stdout, fmt.Sprintf("swapped. Until it is committed, %s answers only requests that carry the verify token.", *host))
1338 if *verify == "" {
1339 fmt.Fprintln(stdout, fmt.Sprintf("verify token: %s. It is shown only this once.", token))
1340 fmt.Fprintln(stdout, fmt.Sprintf("commit with: carlos instances import commit --app %s --host %s. Abort with: carlos instances import abort --app %s --host %s.", app2, *host, app2, *host))
1341 return
1342 }
1343 code, err := verifyImport(ctx, &http.Client{Timeout: 2 * time.Minute}, *host, *verify, token)
1344 if err == nil && code >= 200 && code < 300 {
1345 fmt.Fprintln(stdout, fmt.Sprintf("verify passed (%d). Committing.", code))
1346 fmt.Fprintln(stdout, "waiting for the box to finish placing the snapshot")
1347 if !waitImport(ctx, sess, acct, app2, *host, importPlaceWait, "placed", "committed") {
1348 fmt.Fprintln(stdout, fmt.Sprintf("commit with: carlos instances import commit --app %s --host %s. Abort with: carlos instances import abort --app %s --host %s.", app2, *host, app2, *host))
1349 os.Exit(1)
1350 }
1351 if err := sess.importVerb(ctx, acct, app2, *host, "commit"); err != nil {
1352 log.Fatalf("instances import: %v", err)
1353 }
1354 fmt.Fprintln(stdout, fmt.Sprintf("committed. %s is served by the platform now.", *host))
1355 return
1356 }
1357 status := strconv.Itoa(code)
1358 if err != nil {
1359 status = err.Error()
1360 }
1361 fmt.Fprintln(stdout, fmt.Sprintf("verify failed (%s). Aborting the import.", status))
1362 if err := sess.importVerb(ctx, acct, app2, *host, "abort"); err != nil {
1363 log.Fatalf("instances import: %v", err)
1364 }
1365 fmt.Fprintln(stdout, fmt.Sprintf("aborted. The box puts the old route of %s back on its next pass.", *host))
1366 os.Exit(1)
1367}
1368
1369// waitImport polls the record until its seed is in one of states, or the
1370// import was refused (printed, exit 1), or wait runs out (false).
1371func waitImport(ctx context.Context, sess *apiSession, acct apiAcct, app, host string, wait time.Duration, states ...string) bool {
1372 deadline := time.Now().Add(wait)
1373 for time.Now().Before(deadline) {
1374 rec, found, err := sess.instanceGet(ctx, acct, app, host)
1375 if err == nil && found && rec.Seed != nil {
1376 if rec.Seed.State == "refused" {
1377 fmt.Fprintln(stdout, fmt.Sprintf("the box refused the import: %s", rec.Seed.Reason))
1378 os.Exit(1)
1379 }
1380 for _, s := range states {
1381 if rec.Seed.State == s {
1382 return true
1383 }
1384 }
1385 }
1386 time.Sleep(importPoll)
1387 }
1388 return false
1389}
1390
1391func runInstancesImportVerb(verb string, args []string) {
1392 fs := flag.NewFlagSet("instances import "+verb, flag.ExitOnError)
1393 app := appFlag(fs, "app the instance belongs to")
1394 host := fs.String("host", "", "instance host — one DNS label + \".\" + the app's instance domain")
1395 consoleFlag := consoleOption(fs, "console to create through (default: the only logged-in one)")
1396 acctRaw := fs.String("account", "", "account (sqid or name) the app belongs to (default: your only account, or the configured/chosen one)")
1397 acctIDRaw := fs.String("account-id", "", "account sqid, matched as a sqid ONLY — supersedes --account")
1398 fs.Usage = flagUsage(fs, "")
1399 fs.Parse(args)
1400 if *host == "" {
1401 fs.Usage()
1402 os.Exit(2)
1403 }
1404 sess := requireAPISession("import", *consoleFlag)
1405 acct := resolvedAccount(sess, acctRaw, acctIDRaw)
1406 app2 := resolvedApp(sess, acct, *app, instancesRecordsUsage)
1407 if err := sess.importVerb(context.Background(), acct, app2, *host, verb); err != nil {
1408 log.Fatalf("instances import %s: %v", verb, err)
1409 }
1410 if verb == "commit" {
1411 fmt.Fprintln(stdout, fmt.Sprintf("committed. %s is served by the platform now.", *host))
1412 return
1413 }
1414 fmt.Fprintln(stdout, fmt.Sprintf("aborted. The box puts the old route of %s back on its next pass.", *host))
1415}
1416
1417// verifyImport is the verify request through the edge (spec §5.5): the
1418// gate answers 503 with Retry-After while the instance wakes, so a 503 is
1419// retried; any other answer is the verdict.
1420func verifyImport(ctx context.Context, client *http.Client, host, path, token string) (int, error) {
1421 if !strings.HasPrefix(path, "/") {
1422 path = "/" + path
1423 }
1424 return verifyImportURL(ctx, client, "https://"+host+path, token)
1425}
1426
1427func verifyImportURL(ctx context.Context, client *http.Client, url, token string) (int, error) {
1428 for try := 0; ; try++ {
1429 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
1430 if err != nil {
1431 return 0, err
1432 }
1433 req.Header.Set("Carlos-Import-Verify", token)
1434 res, err := client.Do(req)
1435 if err != nil {
1436 return 0, err
1437 }
1438 io.Copy(io.Discard, io.LimitReader(res.Body, 1<<20))
1439 res.Body.Close()
1440 if res.StatusCode != http.StatusServiceUnavailable || try >= importVerifyTries {
1441 return res.StatusCode, nil
1442 }
1443 wait := 3 * time.Second
1444 if n, err := strconv.Atoi(res.Header.Get("Retry-After")); err == nil && n >= 0 && n <= 30 {
1445 wait = time.Duration(n) * time.Second
1446 }
1447 select {
1448 case <-ctx.Done():
1449 return 0, ctx.Err()
1450 case <-time.After(wait):
1451 }
1452 }
1453}
1454```
1455
1456Every flag help string above except `--file`, `--replaces` and `--verify` is `instances create`'s existing text (`instances_cli.go:288-301`), reused byte for byte; `requireAPISession`'s refusal is `main`'s own. `humanBytes(v *int64) string` is `cli.go:3668`.
1457
1458In `apimode.go`:
1459
1460```go
1461// importBegin is the import door's begin: the ordinary create body plus
1462// "import". The verify token comes back once and is returned, never stored.
1463func (s *apiSession) importBegin(ctx context.Context, a apiAcct, app, host, environment, sha string, bytes int64, replaces string) (apiInstanceRecord, string, error) {
1464 in := map[string]any{"host": host, "import": map[string]any{"sha256": sha, "bytes": bytes, "replaces": replaces}}
1465 if environment != "" {
1466 in["environment"] = environment
1467 }
1468 status, body, err := s.postJSON(ctx, apiPath(a, app, "/instances"), in)
1469 if err != nil {
1470 return apiInstanceRecord{}, "", err
1471 }
1472 if status != http.StatusCreated {
1473 return apiInstanceRecord{}, "", apiErrorFromBody(status, body)
1474 }
1475 var out struct {
1476 apiInstanceRecord
1477 VerifyToken string `json:"verify_token"`
1478 }
1479 if err := json.Unmarshal(body, &out); err != nil || out.VerifyToken == "" {
1480 return apiInstanceRecord{}, "", fmt.Errorf("instances import: unreadable response: %v", err)
1481 }
1482 return out.apiInstanceRecord, out.VerifyToken, nil
1483}
1484
1485// importUpload streams the snapshot (spec §5.2) with its own deadline: a
1486// 4 GiB upload outlives any JSON timeout.
1487func (s *apiSession) importUpload(ctx context.Context, a apiAcct, app, host string, f *os.File, size int64) error {
1488 ctx, cancel := context.WithTimeout(ctx, 65*time.Minute)
1489 defer cancel()
1490 res, err := s.c.doStream(ctx, http.MethodPut, apiPath(a, app, "/instances/"+url.PathEscape(host)+"/import"), f, size,
1491 http.Header{"Content-Type": {"application/octet-stream"}})
1492 if err != nil {
1493 return err
1494 }
1495 defer res.Body.Close()
1496 raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
1497 if res.StatusCode != http.StatusOK {
1498 return apiErrorFromBody(res.StatusCode, raw)
1499 }
1500 return nil
1501}
1502
1503// importVerb is stopped, commit or abort.
1504func (s *apiSession) importVerb(ctx context.Context, a apiAcct, app, host, verb string) error {
1505 status, body, err := s.postJSON(ctx, apiPath(a, app, "/instances/"+url.PathEscape(host)+"/import/"+verb), struct{}{})
1506 if err != nil {
1507 return err
1508 }
1509 if status != http.StatusOK {
1510 return apiErrorFromBody(status, body)
1511 }
1512 return nil
1513}
1514```
1515
1516In `cli.go`'s `runInstances` switch: `case "import": runInstancesImport(args[1:]); return`.
1517
1518In `docs/site/cli.md`, under `### carlos instances`, a paragraph with SD-N89's approved text and:
1519
1520````markdown
1521```
1522carlos instances import --app titogo --host acme.go.tito.io --file acme.db --replaces 127.0.0.1:8401 --verify /up
1523carlos instances import commit --app titogo --host acme.go.tito.io
1524carlos instances import abort --app titogo --host acme.go.tito.io
1525```
1526````
1527
1528- [ ] **Step 4: Run the tests to verify they pass**
1529
1530Run: `go test . -run 'TestImport|TestInstances|TestSeeded' -count=1`
1531Expected: PASS.
1532
1533- [ ] **Step 5: Wire SD-N68 to SD-N82, SD-N89, SD-N90 and commit**
1534
1535```bash
1536git add instances_import.go instances_import_test.go cli.go apimode.go docs/site/cli.md approved_seeded_copy_test.go
1537git commit -m "carlos instances import, with --verify, and import commit and abort (Plan 6 Task 6)
1538
1539Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>"
1540```
1541
1542### Task 7: Plan gate
1543
1544- [ ] **Step 1: Cross-compile and run the touched packages under -race**
1545
1546Run:
1547```bash
1548GOOS=darwin go build ./... && GOOS=windows go build ./... && GOOS=linux GOARCH=arm64 go build ./... && \
1549nice go test -race ./internal/console/ ./internal/provision/ . -count=1
1550```
1551Expected: builds clean; tests PASS, including the census and both copy gates.
1552
1553---
1554
1555## Self-review
1556
1557- Spec coverage: §5.1 (Task 1: caller, floor, not a platform record, storage, bytes, token once and hashed), §5.2 (Task 2: reservation and limits, `MaxBytesReader`, hash as it spools, 422s, `CheckDBContext` under 30 minutes, one `PutFrom`, spool removed on every path and at start through Plan 5's `clearSeedScratch`), §5.3 (Task 3), §5.4's commit (Task 3) and gate-clearing hand-off to the box (Plan 7), §5.5 (Task 6's `--verify`), §5.6's abort, run rule, commit/abort race, delete refusal and pre-swap delete, and the console finish (Tasks 4, 5), §6.1's callers (every route), §7's audit rows (`instance-seed`, `import-uploaded`, `import-stopped`, `import-committed`, `import-aborted`).
1558- Moved from Plan 8 to here: `finishSeed`, because the delete door's pre-swap path needs it ("finishes as below"). Plan 8's sweep calls it.
1559- Additions not in the spec: `carlos instances import commit` and `import abort` (the spec's CLI prints "the commit command" without naming it), and SD-N115 (commit of a refused or abandoned import), both in the deck Plan 1 reviews.
1560