console: owner ties an unlabelled fleet record to its serving box
Task 4 of fleet record labels (#1008 option B), the first task of M2
(release B). provision.SetRecordFirstFleetBox is the typed first-label
writer: every check runs inside updateRecord on each CAS attempt, and it
writes FleetBox, FleetBoxAt and FleetBoxMoved (R2). The owner-only door
POST /api/cli/apps/{account}/{app}/instances/{host}/label ties a record
only to the box the binding and the hub stamp agree on (spec §4), under
the fleet lock, from a complete view, with every fleet box and the console
at the new release.FleetRecordLabelFloor (v0.35.4, provisional).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
docs/parity.md+3 −2internal/console/instancelabel.go+465 −0internal/console/instancelabel_test.go+663 −0internal/console/routedecls.go+4 −0internal/console/server.go+6 −0internal/provision/fleetbox.go+86 −0internal/provision/fleetbox_first_test.go+306 −0internal/provision/provision.go+3 −2internal/release/layoutintent.go+12 −0internal/release/layoutintent_test.go+13 −0parity/parity.tsv+1 −0
CI failed — run details
Intent
<paseo-system version="1" kind="agent-message" source-agent-id="8a3d302a-eac7-407c-b61c-f5ccc66b5544" message-id="dd332ab2-fdbc-4cf2-966d-957d37625f91"> Agent manager 8a3d302: v0.35.4 stands. v0.35.3 was cut at 6b03bef2 before M1, so M1 first ships in v0.35.4. </paseo-system>
Attributed to this commit: 13.7 g CO₂e (1,631,531 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on fleet-record-labels-m2, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/docs/parity.md b/docs/parity.md| index ac1e801e5..01212fed9 100644 |
| --- a/docs/parity.md |
| +++ b/docs/parity.md |
| @@ -13,9 +13,9 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | both | 44 | |
| | partial | 9 | |
| | gap | 63 | |
| -| cli-only | 15 | |
| +| cli-only | 16 | |
| | console-only | 17 | |
| -| Total | 148 | |
| +| Total | 149 | |
| ## account |
| @@ -156,6 +156,7 @@ CLI rows are checked against the command registry (`parity/cli.tsv`). |
| | instances-update | both | `instances update` | `POST /a/{sqid}/apps/{app}/instances/{host}/updates/install` | | | |
| | instances-retry | both | `instances retry` | `POST /a/{sqid}/apps/{app}/instances/{host}/retry` | | | |
| | instances-backups | both | `instances backups` | `GET /a/{sqid}/apps/{app}/instances/{host}` | | | |
| +| instances-label | cli-only | `instances label [--box, --dry-run]` | | | Ties an instance on a fleet to the box serving it now; owner only. The console has no labelling action yet (fleet record labels spec, out of scope). | |
| | steering | gap | `steering` | | [wp-instances](#wp-instances) | | |
| | routes | partial | `routes` | `GET /a/{sqid}/apps/{app}/instances`<br>`GET /a/{sqid}/apps/{app}/settings/{section}` | | The console shows host and channel but no environment or replication column. | |
| | restart | partial | `restart` | `POST /a/{sqid}/apps/{app}/restart`<br>`POST /a/{sqid}/apps/{app}/instances/{host}/restart` | | The console has no environment scope and no dry-run list. | |
diff --git a/internal/console/instancelabel.go b/internal/console/instancelabel.go| new file mode 100644 |
| index 000000000..1a4fe48a6 |
| --- /dev/null |
| +++ b/internal/console/instancelabel.go |
| @@ -0,0 +1,465 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/version" |
| +) |
| + |
| +// The owner's label door (fleet record labels spec §4 and §5, #1008 option |
| +// B): POST /api/cli/apps/{account}/{app}/instances/{host}/label, body |
| +// {"box", "dry_run"}, behind `carlos instances label`. It is the only way an |
| +// unlabelled fleet record gets its first label: the relabel worker writes |
| +// none (D2), and create labels only new records. |
| +// |
| +// The owner may tie a record only to the box the evidence names as serving |
| +// it now: the box's binding (written for this fleet and host after the |
| +// record's CreatedAt) and the hub's forward-row stamp must name the same |
| +// box. The evidence is not proof (spec §2); if it is wrong, R1 and R2 make |
| +// the label a safe move, which is why every active box of the fleet and the |
| +// console must be at release.FleetRecordLabelFloor (R4). |
| +// |
| +// Every answer past the gate has one shape, instanceLabelAnswer, with a 200: |
| +// applied is true only after the record write committed. why_not is a code |
| +// the CLI renders in its own copy (spec §9). Without a box, or with |
| +// dry_run, nothing is written. |
| +// |
| +// What is not atomic (spec §5): the registry mark and the record write are |
| +// two writes, made safe by the fresh registry read and the fleet's lock |
| +// under one console process; a mark outlives a failed record write; a |
| +// failed serial bump is only logged. |
| + |
| +// labelBinding is the binding the door read, as the answer shows it. |
| +// AfterCreate is whether it was written at or after the record's creation |
| +// (in milliseconds), the only binding that counts as evidence. |
| +type labelBinding struct { |
| + Box string `json:"box"` |
| + BoundAt int64 `json:"bound_at"` |
| + AfterCreate bool `json:"after_create"` |
| +} |
| + |
| +// instanceLabelAnswer is every answer of the door past its gate. Label is |
| +// the record's box label ("" when unlabelled; after a write, the label |
| +// written; after a competing write, the label that won). Binding is nil when |
| +// there is none for this fleet and host. ServingBox is set only when Agree. |
| +// Box is the named box, or with none named the serving box the door would |
| +// accept. Eligible is true exactly when WhyNot is "". |
| +type instanceLabelAnswer struct { |
| + Host string `json:"host"` |
| + Fleet string `json:"fleet"` |
| + Label string `json:"label"` |
| + Binding *labelBinding `json:"binding"` |
| + HubBox string `json:"hub_box"` |
| + Agree bool `json:"agree"` |
| + ServingBox string `json:"serving_box"` |
| + Box string `json:"box"` |
| + Eligible bool `json:"eligible"` |
| + WhyNot string `json:"why_not"` |
| + Applied bool `json:"applied"` |
| +} |
| + |
| +// The door's why_not codes, each one copy key in the CLI (plan T5/T7). |
| +const ( |
| + labelWhyNotFleet = "not_fleet" |
| + labelWhyLabelled = "labelled" |
| + labelWhyAssigned = "assigned" |
| + labelWhyMove = "move" |
| + labelWhyImport = "import" |
| + labelWhyCoordinated = "coordinated" |
| + labelWhyNotActive = "not_active" |
| + labelWhyDraining = "draining" |
| + labelWhyStale = "stale" |
| + labelWhyRuntime = "runtime" |
| + labelWhyFloor = "floor" |
| + labelWhyNotServing = "not_serving" |
| + labelWhyDisagree = "disagree" |
| + labelWhyNoEvidence = "no_evidence" |
| + labelWhyUnmovable = "unmovable:" // + static, addr, always_on, unit, ha or demo |
| + labelWhySidecars = "sidecars" |
| + labelWhyIncomplete = "incomplete" |
| + labelWhyChanged = "changed" |
| + labelWhyMarkFailed = "mark_failed" |
| +) |
| + |
| +// labelOwnerPurpose completes apiOwnerAccountFor's 403: "only an account |
| +// owner can tie an instance to a box". |
| +const labelOwnerPurpose = "tie an instance to a box" // draft for copy review (C18) |
| + |
| +// claimInstanceLabelUnsupportedMsg is the door's answer on a host-claim |
| +// console, where the relabel worker is off and no claim operation gates |
| +// the record write. |
| +const claimInstanceLabelUnsupportedMsg = "tying instances to boxes is not available on this console" // draft for copy review (C33) |
| + |
| +// msgLabelReadFailed is the door's answer when it cannot read the app, the |
| +// record or the fleet before it has an answer to give. |
| +const msgLabelReadFailed = "could not read the instance and its fleet, so it was not tied. try again" // draft for copy review (C37) |
| + |
| +// msgLabelUnknown is the door's answer when the record write failed in a |
| +// way that does not say whether it landed. |
| +func msgLabelUnknown(app, host string) string { |
| + return fmt.Sprintf("the result is unknown: the console did not answer in time. run carlos instances label --app %s %s to see whether it is tied", app, host) // draft for copy review (C38) |
| +} |
| + |
| +// labelDoorTimeout bounds one request: the fleet view reads each heartbeat |
| +// prefix of the deployment. |
| +const labelDoorTimeout = 30 * time.Second |
| + |
| +// handleAPIInstanceLabel is the door. The order is spec §5's: the owner |
| +// gate, the app, a judged record read and the fleet's owner, then, under |
| +// the fleet's lock, the view, the evidence, the record's eligibility and |
| +// the write. |
| +func (s *Server) handleAPIInstanceLabel(w http.ResponseWriter, r *http.Request) { |
| + p, acct, ok := s.apiOwnerAccountFor(w, r, labelOwnerPurpose) |
| + if !ok { |
| + return |
| + } |
| + app := r.PathValue("app") |
| + found, err := s.store.HasAppIn(acct.ID, app) |
| + if err != nil { |
| + log.Printf("console: api instance label %s/%s: has-app: %v", acct.Sqid, app, err) |
| + jsonError(w, http.StatusBadGateway, msgLabelReadFailed) |
| + return |
| + } |
| + if !found { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if s.refuseLinkedJSON(w, r, acct, app) { |
| + return |
| + } |
| + if !s.allowWrite(p, time.Now()) { |
| + jsonError(w, http.StatusTooManyRequests, "too many requests. wait a minute and try again") |
| + return |
| + } |
| + if s.cfg.HostClaim { |
| + jsonError(w, http.StatusConflict, claimInstanceLabelUnsupportedMsg) |
| + return |
| + } |
| + if s.cfg.Releases == nil { |
| + jsonError(w, http.StatusServiceUnavailable, mainGateCopy().noBucket) |
| + return |
| + } |
| + host := r.PathValue("host") |
| + if !provision.ValidHostShape(host) { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + var req struct { |
| + Box string `json:"box"` |
| + DryRun bool `json:"dry_run"` |
| + } |
| + if !readJSON(w, r, &req) { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), labelDoorTimeout) |
| + defer cancel() |
| + |
| + rec, _, err := s.readRecord(ctx, acct.Sqid, app, host) |
| + switch { |
| + case errors.Is(err, os.ErrNotExist): |
| + http.NotFound(w, r) // unknown and retired are one answer |
| + return |
| + case err != nil: |
| + log.Printf("console: api instance label %s/%s/%s: read: %v", acct.Sqid, app, host, err) |
| + jsonError(w, http.StatusBadGateway, msgLabelReadFailed) |
| + return |
| + case rec.Retired: |
| + http.NotFound(w, r) |
| + return |
| + } |
| + if s.labelAfterRead != nil { |
| + s.labelAfterRead(host) |
| + } |
| + ans := instanceLabelAnswer{Host: host, Label: rec.FleetBox, Box: req.Box} |
| + fleet, onFleet := registry.FleetPlacement(rec.Region) |
| + if !onFleet { |
| + ans.WhyNot = labelWhyNotFleet |
| + writeJSON(w, http.StatusOK, ans) |
| + return |
| + } |
| + reg, err := s.openPassRegistry() |
| + if err != nil { |
| + log.Printf("console: api instance label %s/%s/%s: registry: %v", acct.Sqid, app, host, err) |
| + jsonError(w, http.StatusBadGateway, msgLabelReadFailed) |
| + return |
| + } |
| + f, err := reg.GetFleet(fleet) |
| + if err != nil { |
| + log.Printf("console: api instance label %s/%s/%s: fleet %s: %v", acct.Sqid, app, host, fleet, err) |
| + jsonError(w, http.StatusBadGateway, msgLabelReadFailed) |
| + return |
| + } |
| + if f == nil || f.Account != acct.Sqid { |
| + // The owner gate checks the account, not the record: a record placed |
| + // on a fleet another account owns is the same 404 as no record. |
| + http.NotFound(w, r) |
| + return |
| + } |
| + ans.Fleet = fleet |
| + if why := firstLabelRecordRefusal(*rec); why != "" { |
| + ans.WhyNot = why |
| + writeJSON(w, http.StatusOK, ans) |
| + return |
| + } |
| + |
| + unlock := s.lockFleet(fleet) |
| + defer unlock() |
| + write := req.Box != "" && !req.DryRun |
| + s.judgeLabel(ctx, reg, *rec, fleet, &ans) |
| + ans.Eligible = ans.WhyNot == "" |
| + if !ans.Eligible || !write { |
| + writeJSON(w, http.StatusOK, ans) |
| + return |
| + } |
| + |
| + if s.labelBeforeMark != nil { |
| + s.labelBeforeMark(host) |
| + } |
| + // The mark first, so a box that holds a labelled record is always marked |
| + // (MarkFleetBoxLabelled refuses a detached box). It outlives a failed |
| + // record write (spec §5). |
| + if err := reg.MarkFleetBoxLabelled(fleet, ans.Box, time.Now().UnixNano()); err != nil { |
| + log.Printf("console: api instance label %s/%s/%s: mark %s/%s labelled: %v", acct.Sqid, app, host, fleet, ans.Box, err) |
| + refuseLabel(&ans, labelWhyMarkFailed) |
| + writeJSON(w, http.StatusOK, ans) |
| + return |
| + } |
| + want := provision.FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt} |
| + out, err := provision.SetRecordFirstFleetBox(ctx, s.cfg.Releases, acct.Sqid, app, host, want, ans.Box, time.Now()) |
| + switch { |
| + case errors.Is(err, provision.ErrFleetBoxNotFirst): |
| + refuseLabel(&ans, labelWhyLabelled) // C34: another change tied it first |
| + if out != nil { |
| + ans.Label = out.FleetBox |
| + } |
| + case errors.Is(err, provision.ErrFleetBoxAssigned): |
| + refuseLabel(&ans, labelWhyAssigned) |
| + case errors.Is(err, provision.ErrFleetBoxMoveInFlight): |
| + refuseLabel(&ans, labelWhyMove) |
| + // ErrFleetBoxImportInFlight wraps a *SeedMoveError: told apart by |
| + // errors.Is on the sentinel. |
| + case errors.Is(err, provision.ErrFleetBoxImportInFlight): |
| + refuseLabel(&ans, labelWhyImport) |
| + case errors.Is(err, provision.ErrFleetBoxCoordinated): |
| + refuseLabel(&ans, labelWhyCoordinated) |
| + case errors.Is(err, provision.ErrFleetBoxMoved), errors.Is(err, os.ErrNotExist): |
| + refuseLabel(&ans, labelWhyChanged) |
| + case err != nil: |
| + log.Printf("console: api instance label %s/%s/%s: write: %v", acct.Sqid, app, host, err) |
| + jsonError(w, http.StatusBadGateway, msgLabelUnknown(app, host)) |
| + return |
| + default: |
| + ans.Applied, ans.Label = true, ans.Box |
| + s.auditActivity(acct, app, auditActor(p, acct), Activity{Action: "instance-label", TargetType: "instance", Target: host, |
| + Detail: "tied " + host + " to " + fleet + "/" + ans.Box + " (cli)"}) |
| + // A box-consumed write: the other boxes stop carrying the record |
| + // once they converge on it. |
| + s.bumpSerial(ctx) |
| + } |
| + writeJSON(w, http.StatusOK, ans) |
| +} |
| + |
| +// refuseLabel sets why on a, which is then not eligible. |
| +func refuseLabel(a *instanceLabelAnswer, why string) { |
| + a.WhyNot, a.Eligible = why, false |
| +} |
| + |
| +// firstLabelRecordRefusal is the record's own refusal, from the judged |
| +// read, before the fleet is read: a record a first label is never written |
| +// to. SetRecordFirstFleetBox asks the same of the record it writes; these |
| +// are early answers, not the gate. |
| +func firstLabelRecordRefusal(rec provision.Record) string { |
| + switch { |
| + case rec.FleetBox != "": |
| + return labelWhyLabelled |
| + case rec.ReplicaAssignment != nil: |
| + return labelWhyAssigned |
| + case rec.Move != nil: |
| + return labelWhyMove |
| + case rec.Seed.MoveBlock() != "": |
| + return labelWhyImport |
| + case !fleetLabelsRecord(rec): |
| + return labelWhyUnmovable + "static" |
| + } |
| + return "" |
| +} |
| + |
| +// judgeLabel fills a's evidence and its first refusal, if any, for rec on |
| +// fleet. The caller holds the fleet's lock. In order: the complete view |
| +// (R4), the fleet's sidecars, the box (the named one, or the serving one), |
| +// the floors, the evidence (§4), the record's verified eligibility (R3) and |
| +// its coordinator. Anything that cannot be read is incomplete. |
| +func (s *Server) judgeLabel(ctx context.Context, reg consoleRegistry, rec provision.Record, fleet string, a *instanceLabelAnswer) { |
| + now := time.Now() |
| + v, verr := s.loadFleetViewRequiredAt(ctx, fleet, now, true) |
| + if verr != nil { |
| + log.Printf("console: api instance label %s: fleet %s view: %v", rec.Host, fleet, verr) |
| + } |
| + b, bok, berr := s.readFleetBinding(ctx, fleet, rec.Host) |
| + if berr != nil { |
| + log.Printf("console: api instance label %s: binding: %v", rec.Host, berr) |
| + } |
| + // The binding counts only if it is this fleet's, for this host, naming |
| + // a box, and written at or after the record's creation (a binding left |
| + // by an earlier record at the same host names a box that served other |
| + // data). |
| + if bok && b.Fleet == fleet && b.Host == rec.Host && registry.ValidTunnelName(b.Box) { |
| + a.Binding = &labelBinding{Box: b.Box, BoundAt: b.BoundAt, AfterCreate: b.BoundAt >= rec.CreatedAt.UnixMilli()} |
| + } |
| + // The hub row is the registry's forward row for the host on this fleet; |
| + // none, or one that is not this fleet's forward row, has no box. |
| + rt, herr := reg.Get(rec.Host) |
| + if herr != nil { |
| + log.Printf("console: api instance label %s: hub row: %v", rec.Host, herr) |
| + } |
| + if rt != nil && rt.IsForward() && rt.Region == registry.PlacementTarget(fleet) { |
| + a.HubBox = rt.FleetBox |
| + } |
| + evidence := a.Binding != nil && a.Binding.AfterCreate && a.HubBox != "" |
| + if evidence && a.Binding.Box == a.HubBox { |
| + a.Agree, a.ServingBox = true, a.HubBox |
| + } |
| + if a.Box == "" { |
| + a.Box = a.ServingBox |
| + } |
| + |
| + switch { |
| + case verr != nil || berr != nil || herr != nil || !v.Complete: |
| + a.WhyNot = labelWhyIncomplete |
| + return |
| + case v.HasSidecars: |
| + a.WhyNot = labelWhySidecars |
| + return |
| + case a.Box == "" && !evidence: |
| + a.WhyNot = labelWhyNoEvidence |
| + return |
| + case a.Box == "": |
| + a.WhyNot = labelWhyDisagree |
| + return |
| + } |
| + |
| + // The named box, read fresh from the registry under the lock, then as |
| + // the view's heartbeats see it. |
| + row, err := findFleetBox(reg, fleet, a.Box) |
| + if err != nil { |
| + log.Printf("console: api instance label %s: box %s/%s: %v", rec.Host, fleet, a.Box, err) |
| + a.WhyNot = labelWhyIncomplete |
| + return |
| + } |
| + if row == nil || row.Status != "active" { |
| + a.WhyNot = labelWhyNotActive |
| + return |
| + } |
| + if row.DrainingSince != 0 { |
| + a.WhyNot = labelWhyDraining |
| + return |
| + } |
| + var box *fleetBoxView |
| + for i := range v.Boxes { |
| + if v.Boxes[i].Label == a.Box { |
| + box = &v.Boxes[i] |
| + } |
| + } |
| + rootfs := rec.Runtime == provision.RuntimeRootfsV1 |
| + switch { |
| + case box == nil: |
| + a.WhyNot = labelWhyNotActive |
| + return |
| + case box.Draining: |
| + a.WhyNot = labelWhyDraining |
| + return |
| + case !box.Fresh: |
| + a.WhyNot = labelWhyStale |
| + return |
| + case !box.AtLabelFloor || !s.fleetAtRecordFloor(v): |
| + a.WhyNot = labelWhyFloor |
| + return |
| + case !box.destinationFor(rootfs): |
| + a.WhyNot = labelWhyRuntime // a rootfs record on a box not rootfs-ready at the rootfs floor |
| + return |
| + } |
| + |
| + switch { |
| + case !evidence: |
| + a.WhyNot = labelWhyNoEvidence |
| + return |
| + case !a.Agree: |
| + a.WhyNot = labelWhyDisagree |
| + return |
| + case a.Box != a.ServingBox: |
| + a.WhyNot = labelWhyNotServing |
| + return |
| + } |
| + |
| + ok, stateless, err := s.movableVerified(ctx, rec) |
| + switch { |
| + case err != nil: |
| + log.Printf("console: api instance label %s: its manifest cannot be verified: %v", rec.Host, err) |
| + a.WhyNot = labelWhyIncomplete |
| + return |
| + case !ok: |
| + a.WhyNot = labelWhyUnmovable + unmovableReason(rec) |
| + return |
| + case stateless && !atStatelessRuntimeFloor(box.Release): |
| + a.WhyNot = labelWhyRuntime |
| + return |
| + } |
| + if c := rec.Coordinator; c != nil && c.Box != a.Box && (c.ExpiresAt.IsZero() || now.Before(c.ExpiresAt)) { |
| + a.WhyNot = labelWhyCoordinated |
| + } |
| +} |
| + |
| +// unmovableReason is why movableVerified refused rec, in movable's order: |
| +// a demo, an address the platform does not manage, an HA record, a system |
| +// unit, and otherwise an always-on binary whose selected release is not |
| +// stateless. |
| +func unmovableReason(rec provision.Record) string { |
| + switch { |
| + case rec.Demo != nil: |
| + return "demo" |
| + case rec.Addr != "" || len(rec.Addrs) > 0: |
| + return "addr" |
| + case rec.HA: |
| + return "ha" |
| + case rec.Unit != "": |
| + return "unit" |
| + } |
| + return "always_on" |
| +} |
| + |
| +// atRecordLabelFloor reports whether a platform release parses at or above |
| +// release.FleetRecordLabelFloor. Missing or unparseable is false. |
| +func atRecordLabelFloor(rel string) bool { |
| + v, ok := release.ParseReleaseVersion(rel) |
| + floor, _ := release.ParseReleaseVersion(release.FleetRecordLabelFloor) |
| + return ok && v.Compare(floor) >= 0 |
| +} |
| + |
| +// fleetAtRecordFloor is R4: the deployment is at the label floor |
| +// (DeploymentCurrent, which also needs every active box of the fleet to |
| +// have reported), and every active box of the fleet and this console are at |
| +// the record label floor. |
| +func (s *Server) fleetAtRecordFloor(v fleetView) bool { |
| + build := s.consoleBuild |
| + if build == "" { |
| + build = version.Build |
| + } |
| + if !v.DeploymentCurrent || !atRecordLabelFloor(build) { |
| + return false |
| + } |
| + for _, b := range v.Boxes { |
| + if !atRecordLabelFloor(b.Release) { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/console/instancelabel_test.go b/internal/console/instancelabel_test.go| new file mode 100644 |
| index 000000000..e0d65d505 |
| --- /dev/null |
| +++ b/internal/console/instancelabel_test.go |
| @@ -0,0 +1,663 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/seeds" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| +) |
| + |
| +// Fleet record labels (#1008 option B), spec §4 and §5: the owner's door |
| +// that ties an unlabelled fleet record to the box serving it now. App shop |
| +// in bab, fleet pi, boxes pi-1, pi-2, ..., hosts under example.com. Every |
| +// box and the console report FleetRecordLabelFloor unless a test says |
| +// otherwise. |
| + |
| +const labelHost = "a.example.com" |
| + |
| +// labelWorld is fleetBoxWorld with every box beating now at the record |
| +// label floor, the console at it too, and shop's unlabelled record of |
| +// labelHost created an hour ago. It answers the record's stored creation |
| +// time. |
| +func labelWorld(t *testing.T, code string, boxes ...string) (*consoleFixture, string, *registry.Registry, time.Time) { |
| + t.Helper() |
| + fx, token, reg := fleetBoxWorld(t, code, boxes...) |
| + for _, b := range boxes { |
| + piBeat(t, fx, b, true, time.Now(), release.FleetRecordLabelFloor) |
| + } |
| + fx.srv.consoleBuild = release.FleetRecordLabelFloor |
| + putFleetRecord(t, fx, "shop", labelHost, func(r *provision.Record) { r.CreatedAt = time.Now().UTC().Add(-time.Hour) }) |
| + return fx, token, reg, shopRec(t, fx, labelHost).CreatedAt |
| +} |
| + |
| +// hubRow writes the hub's forward row for host on fleet pi, unlabelled, |
| +// stamped with box as the bindings pass stamps it. |
| +func hubRow(t *testing.T, fx *consoleFixture, reg *registry.Registry, host, box string) { |
| + t.Helper() |
| + if err := reg.PutForward(registry.Route{Host: host, Kind: registry.KindForward, Slug: strings.TrimSuffix(host, ".example.com"), |
| + App: "shop", Account: fx.sqid, Region: "fleet/pi", Channel: "edge"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + if ok, err := reg.SetFleetBoxIf(host, "pi", box); err != nil || !ok { |
| + t.Fatalf("stamp %s with %s: %v, %v", host, box, ok, err) |
| + } |
| +} |
| + |
| +// servingEvidence writes agreeing evidence: box's binding, a second after the |
| +// record's creation, and the hub's stamp naming box. |
| +func servingEvidence(t *testing.T, fx *consoleFixture, reg *registry.Registry, created time.Time, box string) { |
| + t.Helper() |
| + bindTo(t, fx, labelHost, box, created.Add(time.Second)) |
| + hubRow(t, fx, reg, labelHost, box) |
| +} |
| + |
| +func labelURL(fx *consoleFixture, host string) string { |
| + return fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/shop/instances/" + host + "/label" |
| +} |
| + |
| +// labelBody is the door's request body. |
| +func labelBody(box string, dryRun bool) string { |
| + raw, _ := json.Marshal(map[string]any{"box": box, "dry_run": dryRun}) |
| + return string(raw) |
| +} |
| + |
| +// labelPost asks the door about labelHost and decodes a 200's answer. |
| +func labelPost(t *testing.T, fx *consoleFixture, token, box string, dryRun bool) instanceLabelAnswer { |
| + t.Helper() |
| + code, _, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), token, labelBody(box, dryRun)) |
| + if code != http.StatusOK { |
| + t.Fatalf("label = %d %s; want 200", code, raw) |
| + } |
| + var a instanceLabelAnswer |
| + if err := json.Unmarshal([]byte(raw), &a); err != nil { |
| + t.Fatalf("answer %s: %v", raw, err) |
| + } |
| + return a |
| +} |
| + |
| +// wantRefused fails unless the answer refuses with why and wrote nothing |
| +// to the record. |
| +func wantRefused(t *testing.T, fx *consoleFixture, a instanceLabelAnswer, why string) { |
| + t.Helper() |
| + if a.WhyNot != why || a.Eligible || a.Applied { |
| + t.Fatalf("answer %+v; want refused with %q", a, why) |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| +} |
| + |
| +// editShop changes shop's stored record of labelHost with mut, as another |
| +// writer would. |
| +func editShop(t *testing.T, fx *consoleFixture, mut func(*provision.Record)) { |
| + t.Helper() |
| + ctx := context.Background() |
| + key := provision.RecordKey(fx.sqid, "shop", labelHost) |
| + raw, etag, err := fx.rel.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, err := provision.DecodeRecord(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mut(&rec) |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.rel.Put(ctx, key, body, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// --- authorization --- |
| + |
| +func TestLabelDoorOwnerOnly(t *testing.T) { |
| + fx, _, reg, created := labelWorld(t, "code-ld-owner", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + if err := fx.st.AddMember(OpsAccountID, "alice@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + member := cliToken(t, fx, "alice@keymail.dev", "code-ld-member") |
| + code, _, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), member, labelBody("pi-1", false)) |
| + if code != http.StatusForbidden || errorOf(t, raw) != "only an account owner can tie an instance to a box" { |
| + t.Fatalf("member = %d %s; want 403 with C18", code, raw) |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("a member's request marked pi-1") |
| + } |
| +} |
| + |
| +func TestLabelDoorNonMemberIs404(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-stranger", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + stranger := cliToken(t, fx, "eve@keymail.dev", "code-ld-eve") |
| + want := canonicalNotFound(t) |
| + code, h, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), stranger, labelBody("pi-1", false)) |
| + assertNotFound(t, "a non-member", want, code, h, raw) |
| + unknown := fx.ts.URL + "/api/cli/apps/" + fx.sqid + "/ghost/instances/" + labelHost + "/label" |
| + code, h, raw = rawReq(t, http.MethodPost, unknown, token, labelBody("pi-1", false)) |
| + assertNotFound(t, "the owner, an unknown app", want, code, h, raw) |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| +} |
| + |
| +func TestLabelDoorRefusesServiceRoles(t *testing.T) { |
| + fx, _, reg, created := labelWorld(t, "code-ld-roles", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + for _, role := range []svcrole.Role{svcrole.Admin, svcrole.Service, svcrole.Instance, svcrole.Operate} { |
| + tok := serviceToken(t, fx.st, OpsAccountID, "bot-"+strings.ToLower(string(role)), "shop", role) |
| + code, _, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), tok, labelBody("pi-1", false)) |
| + if code != http.StatusForbidden { |
| + t.Errorf("%s credential = %d %s; want 403", role, code, raw) |
| + } |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("a service credential's request marked pi-1") |
| + } |
| +} |
| + |
| +// A fleet box's bearer, presented with the tunnel's channel header as a |
| +// box presents it, is not a CLI principal (spec §5). |
| +func TestLabelDoorRefusesAFleetBoxToken(t *testing.T) { |
| + fx, _, reg, created := labelWorld(t, "code-ld-boxtoken", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + tok, hash, err := mintFleetToken() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := reg.SetFleetBoxToken("pi", "pi-1", hash); err != nil { |
| + t.Fatal(err) |
| + } |
| + code, _, raw := rawReqHeader(t, http.MethodPost, labelURL(fx, labelHost), tok, labelBody("pi-1", false), |
| + map[string]string{"Carlos-Tunnel-Name": "pi/pi-1"}) |
| + if code != http.StatusUnauthorized { |
| + t.Fatalf("a fleet box token = %d %s; want 401", code, raw) |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("a fleet box token's request marked pi-1") |
| + } |
| +} |
| + |
| +// A record the owner's account does not hold, and the owner's record on a |
| +// fleet another account owns, are both the family's 404. |
| +func TestLabelDoorWrongAccountRecordIs404(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-wrongacct", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + fskAway(t, fx) // bob's account cdef, with fleet away |
| + want := canonicalNotFound(t) |
| + |
| + code, h, raw := rawReq(t, http.MethodPost, labelURL(fx, "b.example.com"), token, labelBody("pi-1", false)) |
| + assertNotFound(t, "a host with no record in this account", want, code, h, raw) |
| + |
| + editShop(t, fx, func(r *provision.Record) { r.Region = "fleet/away" }) |
| + code, h, raw = rawReq(t, http.MethodPost, labelURL(fx, labelHost), token, labelBody("pi-1", false)) |
| + assertNotFound(t, "a record placed on another account's fleet", want, code, h, raw) |
| + if r := shopRec(t, fx, labelHost); r.FleetBox != "" { |
| + t.Fatalf("labelled %q", r.FleetBox) |
| + } |
| +} |
| + |
| +func TestLabelDoorWrongFleetBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-otherfleet", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + if st, body := postJSON(t, fleetsURL(fx, fx.sqid)+"/new", map[string]string{"name": "ox", "bucket": "ox-fleet-data"}, token); st != http.StatusOK { |
| + t.Fatalf("create fleet ox = %d %v", st, body) |
| + } |
| + registerFleetBox(t, reg, "ox", "ox-1") |
| + writeFleetBoxOn(t, fx, "ox", "ox-1", "", true, time.Now(), release.FleetRecordLabelFloor) |
| + a := labelPost(t, fx, token, "ox-1", false) |
| + wantRefused(t, fx, a, "not_active") |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("pi-1 was marked") |
| + } |
| +} |
| + |
| +// --- records --- |
| + |
| +func TestLabelDoorRetiredRecordIs404(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-retired", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + editShop(t, fx, func(r *provision.Record) { r.Retired = true }) |
| + code, h, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), token, labelBody("pi-1", false)) |
| + assertNotFound(t, "a retired record", canonicalNotFound(t), code, h, raw) |
| +} |
| + |
| +func TestLabelDoorRefusesMoveAndAssignment(t *testing.T) { |
| + for _, c := range []struct { |
| + why string |
| + mut func(*provision.Record) |
| + }{ |
| + {"move", func(r *provision.Record) { r.Move = &provision.MoveState{ID: "mv_1", To: "eu"} }}, |
| + {"assigned", func(r *provision.Record) { |
| + r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}} |
| + }}, |
| + {"import", func(r *provision.Record) { |
| + id, _ := seeds.NewID() |
| + r.Seed = &provision.SeedSource{ID: id, Kind: seeds.KindImport, State: seeds.StateSwapped, SHA256: strings.Repeat("a", 64), Bytes: 10, |
| + Replaces: "127.0.0.1:8401", VerifyHash: strings.Repeat("b", 64), By: "t", At: time.Now()} |
| + }}, |
| + {"coordinated", func(r *provision.Record) { |
| + r.Coordinator = &replicas.Coordinator{Term: "t1", Box: "pi-2", BootID: "b", ExpiresAt: time.Now().Add(time.Hour)} |
| + }}, |
| + } { |
| + t.Run(c.why, func(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-rec-"+c.why, "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + editShop(t, fx, c.mut) |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), c.why) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("pi-1 was marked") |
| + } |
| + }) |
| + } |
| + t.Run("labelled", func(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-rec-labelled", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + labelOn(t, fx, reg, labelHost, "pi-2") |
| + a := labelPost(t, fx, token, "pi-1", false) |
| + if a.WhyNot != "labelled" || a.Label != "pi-2" || a.Applied { |
| + t.Fatalf("answer %+v; want labelled, naming pi-2", a) |
| + } |
| + }) |
| +} |
| + |
| +// --- boxes --- |
| + |
| +func TestLabelDoorDetachedBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-detached", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-2") |
| + if err := reg.SetFleetBoxStatus("pi", "pi-2", "detached"); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-2", false), "not_active") |
| +} |
| + |
| +func TestLabelDoorDrainingBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-draining", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-2") |
| + if _, err := reg.SetFleetBoxDraining("pi", "pi-2", time.Now().UnixNano()); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-2", false), "draining") |
| + if b := boxRow(t, reg, "pi-2"); b.LabelledAt != 0 { |
| + t.Fatal("a draining box was marked") |
| + } |
| +} |
| + |
| +func TestLabelDoorStaleBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-stale", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-2") |
| + piBeat(t, fx, "pi-2", true, time.Now().Add(-time.Hour), release.FleetRecordLabelFloor) |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-2", false), "stale") |
| +} |
| + |
| +// A rootfs record needs a box that is rootfs-ready. |
| +func TestLabelDoorRootfsNeedsARootfsReadyBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-rootfs", "pi-1", "pi-2") |
| + editShop(t, fx, func(r *provision.Record) { r.Runtime = provision.RuntimeRootfsV1 }) |
| + servingEvidence(t, fx, reg, created, "pi-2") |
| + piBeat(t, fx, "pi-2", false, time.Now(), release.FleetRecordLabelFloor) |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-2", false), "runtime") |
| +} |
| + |
| +func TestLabelDoorFloor(t *testing.T) { |
| + t.Run("a box below the floor", func(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-floor-box", "pi-1", "pi-2", "pi-3") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + piBeat(t, fx, "pi-3", true, time.Now(), release.StatelessReplicasFloor) // above the label floor, below the record floor |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "floor") |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("pi-1 was marked below the floor") |
| + } |
| + }) |
| + t.Run("the console below the floor", func(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-floor-console", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + fx.srv.consoleBuild = release.StatelessReplicasFloor |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "floor") |
| + }) |
| +} |
| + |
| +// A deployment heartbeat that cannot be read leaves the view incomplete |
| +// with no error: the door refuses, whatever the rest says. |
| +func TestLabelDoorIncompleteView(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-incomplete", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + writeFleetBoxOn(t, fx, "", "box-1", "", true, time.Now(), release.FleetRecordLabelFloor) |
| + fx.srv.cfg.Releases = &failGetStore{Store: fx.srv.cfg.Releases, key: "status/boxes/box-1.json"} |
| + v, err := fx.srv.loadFleetViewRequiredAt(context.Background(), "pi", time.Now(), true) |
| + if err != nil || v.Complete { |
| + t.Fatalf("view complete %v, %v; want incomplete with no error", v.Complete, err) |
| + } |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "incomplete") |
| +} |
| + |
| +// --- evidence --- |
| + |
| +func TestLabelDoorLabelsTheServingBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-serving", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + cs := newCountStore(fx.srv.cfg.Releases) |
| + fx.srv.cfg.Releases = cs |
| + |
| + // No box: the dry run names the box it would accept. |
| + a := labelPost(t, fx, token, "", false) |
| + if a.Host != labelHost || a.Fleet != "pi" || a.Label != "" || a.Binding == nil || a.Binding.Box != "pi-1" || !a.Binding.AfterCreate || |
| + a.HubBox != "pi-1" || !a.Agree || a.ServingBox != "pi-1" || a.Box != "pi-1" || !a.Eligible || a.WhyNot != "" || a.Applied { |
| + t.Fatalf("no-box answer %+v; want the evidence, pi-1 eligible, nothing applied", a) |
| + } |
| + if cs.recordPuts() != 0 || cs.puts[release.SerialKey] != 0 || boxRow(t, reg, "pi-1").LabelledAt != 0 { |
| + t.Fatal("a call without --box wrote") |
| + } |
| + |
| + a = labelPost(t, fx, token, "pi-1", false) |
| + if !a.Applied || !a.Eligible || a.WhyNot != "" || a.Label != "pi-1" || a.Box != "pi-1" { |
| + t.Fatalf("answer %+v; want applied to pi-1", a) |
| + } |
| + rec := shopRec(t, fx, labelHost) |
| + at, err := time.Parse(time.RFC3339Nano, rec.FleetBoxAt) |
| + if rec.FleetBox != "pi-1" || !rec.FleetBoxMoved || err != nil || time.Since(at) > time.Minute { |
| + t.Fatalf("record %+v; want labelled pi-1 now, moved", rec) |
| + } |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt == 0 { |
| + t.Fatal("pi-1 was not marked labelled") |
| + } |
| + if cs.puts[release.SerialKey] == 0 { |
| + t.Fatal("the serial was not bumped") |
| + } |
| +} |
| + |
| +func TestLabelDoorRefusesAnotherBox(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-another", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + a := labelPost(t, fx, token, "pi-2", false) |
| + wantRefused(t, fx, a, "not_serving") |
| + if a.ServingBox != "pi-1" || !a.Agree || a.Box != "pi-2" { |
| + t.Fatalf("answer %+v; want pi-1 named serving", a) |
| + } |
| + if b := boxRow(t, reg, "pi-2"); b.LabelledAt != 0 { |
| + t.Fatal("pi-2 was marked") |
| + } |
| +} |
| + |
| +func TestLabelDoorRefusesDisagreement(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-disagree", "pi-1", "pi-2") |
| + bindTo(t, fx, labelHost, "pi-1", created.Add(time.Second)) |
| + hubRow(t, fx, reg, labelHost, "pi-2") |
| + for _, box := range []string{"pi-1", "pi-2", ""} { |
| + a := labelPost(t, fx, token, box, false) |
| + wantRefused(t, fx, a, "disagree") |
| + if a.Agree || a.ServingBox != "" || a.HubBox != "pi-2" || a.Binding == nil || a.Binding.Box != "pi-1" { |
| + t.Fatalf("--box %q: answer %+v; want the disagreement shown", box, a) |
| + } |
| + } |
| +} |
| + |
| +// A binding written before the record was created is an earlier record's |
| +// at the same host: it is not evidence (the removed worker's test, spec |
| +// §4). |
| +func TestBindingDatedBeforeCreateIsNoEvidence(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-early", "pi-1", "pi-2") |
| + bindTo(t, fx, labelHost, "pi-1", created.Add(-time.Second)) |
| + hubRow(t, fx, reg, labelHost, "pi-1") |
| + a := labelPost(t, fx, token, "pi-1", false) |
| + wantRefused(t, fx, a, "no_evidence") |
| + if a.Binding == nil || a.Binding.AfterCreate || a.Agree || a.ServingBox != "" { |
| + t.Fatalf("answer %+v; want the binding shown as before the record", a) |
| + } |
| + // The same millisecond as the creation counts. |
| + bindTo(t, fx, labelHost, "pi-1", time.UnixMilli(created.UnixMilli())) |
| + if a := labelPost(t, fx, token, "pi-1", true); !a.Eligible || !a.Binding.AfterCreate { |
| + t.Fatalf("a binding at the creation millisecond: %+v; want evidence", a) |
| + } |
| +} |
| + |
| +func TestMissingHubRowIsNoEvidence(t *testing.T) { |
| + fx, token, _, created := labelWorld(t, "code-ld-nohub", "pi-1", "pi-2") |
| + bindTo(t, fx, labelHost, "pi-1", created.Add(time.Second)) |
| + a := labelPost(t, fx, token, "pi-1", false) |
| + wantRefused(t, fx, a, "no_evidence") |
| + if a.HubBox != "" || a.Binding == nil || a.Binding.Box != "pi-1" { |
| + t.Fatalf("answer %+v; want the binding and no hub box", a) |
| + } |
| +} |
| + |
| +// --- the rest --- |
| + |
| +func TestLabelDoorDryRunWritesNothing(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-dry", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + cs := newCountStore(fx.srv.cfg.Releases) |
| + fx.srv.cfg.Releases = cs |
| + a := labelPost(t, fx, token, "pi-1", true) |
| + if !a.Eligible || a.Applied || a.WhyNot != "" || a.Box != "pi-1" { |
| + t.Fatalf("dry run %+v; want eligible, not applied", a) |
| + } |
| + if n := cs.recordPuts(); n != 0 { |
| + t.Fatalf("a dry run wrote %d records", n) |
| + } |
| + if n := cs.puts[release.SerialKey]; n != 0 { |
| + t.Fatalf("a dry run wrote the serial %d times", n) |
| + } |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("a dry run marked pi-1") |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| +} |
| + |
| +func TestLabelDoorOneBoxFleet(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-onebox", "pi-1") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + if a := labelPost(t, fx, token, "pi-1", false); !a.Applied { |
| + t.Fatalf("answer %+v; want applied", a) |
| + } |
| + if r := shopRec(t, fx, labelHost); r.FleetBox != "pi-1" || !r.FleetBoxMoved { |
| + t.Fatalf("record %+v; want labelled pi-1", r) |
| + } |
| +} |
| + |
| +func TestLabelDoorUnmovable(t *testing.T) { |
| + off := false |
| + for _, c := range []struct { |
| + why string |
| + mut func(*provision.Record) |
| + }{ |
| + {"static", func(r *provision.Record) { r.Kind = "static" }}, |
| + {"addr", func(r *provision.Record) { r.Kind = "instance"; r.Addr = "127.0.0.1:9000" }}, |
| + {"always_on", func(r *provision.Record) { r.Hibernate = &off }}, |
| + {"unit", func(r *provision.Record) { r.Hibernate = &off; r.Unit = "shop.service" }}, |
| + {"ha", func(r *provision.Record) { r.HA = true }}, |
| + {"demo", func(r *provision.Record) { |
| + r.Demo = &demo.Descriptor{ID: "AAAAAAAAAAAAAAAAAAAAAA", Host: labelHost, Lifetime: "1h", ExpiresAt: time.Now().Add(time.Hour).Unix()} |
| + }}, |
| + } { |
| + t.Run(c.why, func(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-unmovable-"+c.why, "pi-1", "pi-2") |
| + shipVersion(t, fx, "shop", "v1") // a binary, not stateless |
| + seedChannel(t, fx, "shop", "edge", "v1") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + editShop(t, fx, c.mut) |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "unmovable:"+c.why) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt != 0 { |
| + t.Fatal("pi-1 was marked") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// An always-on binary whose selected release is stateless is labelled |
| +// (R3's verified eligibility). |
| +func TestLabelDoorLabelsAnAlwaysOnStatelessRecord(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-stateless", "pi-1", "pi-2") |
| + shipStatelessFloorRelease(t, fx, "shop", "v1") |
| + seedChannel(t, fx, "shop", "edge", "v1") |
| + editShop(t, fx, func(r *provision.Record) { r.Hibernate = new(bool) }) |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + if a := labelPost(t, fx, token, "pi-1", false); !a.Applied { |
| + t.Fatalf("answer %+v; want applied", a) |
| + } |
| +} |
| + |
| +func TestLabelDoorSidecars(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-sidecars", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + if err := provision.CreateSidecarRecord(context.Background(), fx.rel, provision.SidecarRecord{Schema: 1, Name: "bot", |
| + Host: provision.SidecarHost("bot", "shop", fx.sqid), App: "shop", Account: fx.sqid, Region: "fleet/pi", |
| + Channel: "edge", CreatedAt: time.Now().UTC()}); err != nil { |
| + t.Fatal(err) |
| + } |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "sidecars") |
| +} |
| + |
| +func TestLabelDoorHostClaimConsole(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-claim", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + fx.srv.cfg.HostClaim = true |
| + code, _, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), token, labelBody("pi-1", false)) |
| + if code != http.StatusConflict || errorOf(t, raw) != "tying instances to boxes is not available on this console" { |
| + t.Fatalf("host-claim console = %d %s; want 409 with C33", code, raw) |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| +} |
| + |
| +// The box is detached after the door read the registry and before the |
| +// mark: MarkFleetBoxLabelled refuses a detached box, so nothing is written |
| +// to the record. |
| +func TestLabelDoorDetachedBetweenCheckAndWrite(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-race-detach", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + fx.srv.labelBeforeMark = func(host string) { |
| + if err := reg.SetFleetBoxStatus("pi", "pi-1", "detached"); err != nil { |
| + t.Error(err) |
| + } |
| + } |
| + wantRefused(t, fx, labelPost(t, fx, token, "pi-1", false), "mark_failed") |
| +} |
| + |
| +// putFailStore fails every Put of key. |
| +type putFailStore struct { |
| + release.Store |
| + key string |
| +} |
| + |
| +func (p putFailStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + if key == p.key { |
| + return "", errors.New("injected put failure") |
| + } |
| + return p.Store.Put(ctx, key, body, ifMatch) |
| +} |
| + |
| +// Spec §5, what is not atomic: a record write that fails after the mark |
| +// leaves the box marked. The answer is not applied. |
| +func TestLabelDoorMarkSurvivesFailedWrite(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-failwrite", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + fx.srv.cfg.Releases = putFailStore{Store: fx.srv.cfg.Releases, key: provision.RecordKey(fx.sqid, "shop", labelHost)} |
| + code, _, raw := rawReq(t, http.MethodPost, labelURL(fx, labelHost), token, labelBody("pi-1", false)) |
| + want := fmt.Sprintf("the result is unknown: the console did not answer in time. run carlos instances label --app shop %s to see whether it is tied", labelHost) |
| + if code != http.StatusBadGateway || errorOf(t, raw) != want { |
| + t.Fatalf("a failed write = %d %s; want 502 with C38", code, raw) |
| + } |
| + if strings.Contains(raw, `"applied":true`) { |
| + t.Fatalf("a failed write answered applied: %s", raw) |
| + } |
| + wantNoLabel(t, shopRec(t, fx, labelHost)) |
| + if b := boxRow(t, reg, "pi-1"); b.LabelledAt == 0 { |
| + t.Fatal("the mark did not survive the failed write") |
| + } |
| +} |
| + |
| +// labelPostAsync is labelPost for a goroutine: it reports instead of |
| +// failing the test. |
| +func labelPostAsync(fx *consoleFixture, token, box string) (instanceLabelAnswer, error) { |
| + var a instanceLabelAnswer |
| + req, err := http.NewRequest(http.MethodPost, labelURL(fx, labelHost), strings.NewReader(labelBody(box, false))) |
| + if err != nil { |
| + return a, err |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + res, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + return a, err |
| + } |
| + defer res.Body.Close() |
| + if res.StatusCode != http.StatusOK { |
| + return a, fmt.Errorf("label = %d", res.StatusCode) |
| + } |
| + return a, json.NewDecoder(res.Body).Decode(&a) |
| +} |
| + |
| +// Two owners' requests both read the unlabelled record before either takes |
| +// the fleet's lock (a barrier holds each after its read until both have |
| +// read). One label is written; the other request is refused by the writer |
| +// and names the label that won (C34). |
| +func TestLabelDoorConcurrentLabels(t *testing.T) { |
| + fx, token, reg, created := labelWorld(t, "code-ld-concurrent", "pi-1", "pi-2") |
| + servingEvidence(t, fx, reg, created, "pi-1") |
| + arrived := make(chan struct{}, 2) |
| + release := make(chan struct{}) |
| + fx.srv.labelAfterRead = func(string) { |
| + arrived <- struct{}{} |
| + <-release |
| + } |
| + answers := make([]instanceLabelAnswer, 2) |
| + errs := make([]error, 2) |
| + done := make(chan struct{}, 2) |
| + var wg sync.WaitGroup |
| + for i := range answers { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + defer func() { done <- struct{}{} }() |
| + answers[i], errs[i] = labelPostAsync(fx, token, "pi-1") |
| + }() |
| + } |
| + for n := 0; n < 2; { |
| + select { |
| + case <-arrived: |
| + n++ |
| + case <-done: |
| + // A request answered before reaching the barrier: no second |
| + // request can be held there with it. |
| + close(release) |
| + wg.Wait() |
| + t.Fatalf("a request answered before both had read: %+v, %v", answers, errs) |
| + } |
| + } |
| + close(release) |
| + wg.Wait() |
| + if err := errors.Join(errs...); err != nil { |
| + t.Fatal(err) |
| + } |
| + applied, lost := 0, 0 |
| + for _, a := range answers { |
| + switch { |
| + case a.Applied && a.Label == "pi-1": |
| + applied++ |
| + case !a.Applied && a.WhyNot == "labelled" && a.Label == "pi-1": |
| + lost++ |
| + } |
| + } |
| + if applied != 1 || lost != 1 { |
| + t.Fatalf("answers %+v; want one applied and one labelled naming pi-1", answers) |
| + } |
| + if r := shopRec(t, fx, labelHost); r.FleetBox != "pi-1" || !r.FleetBoxMoved { |
| + t.Fatalf("record %+v; want labelled pi-1", r) |
| + } |
| +} |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index dbc1872b7..08a49bf87 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -746,6 +746,10 @@ var routeDecls = []routeDecl{ |
| // `carlos instances retry <host>` (apiretry.go): the operate family's, as |
| // restart is. The {host} wildcard and the 404 are the instance family's. |
| {Pattern: "POST /api/cli/apps/{account}/{app}/instances/{host}/retry", Kind: kindCLIScoped, Allow: svcrole.Allow(svcrole.Operate), Target: scopeHost, Handler: (*Server).handleAPIInstanceRetry}, |
| + // The owner's first label (fleet record labels spec §5, instancelabel.go): |
| + // ties an unlabelled fleet record to the box serving it now. Owner-gated |
| + // inside, and closed to every service role, as the fleet doors. |
| + {Pattern: "POST /api/cli/apps/{account}/{app}/instances/{host}/label", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPIInstanceLabel}, |
| // The `carlos db` replica door (apidb.go; spec 2026-09-02 §6): an |
| // instance's replicated LTX files, by coordinate, for a member to |
| // restore on their own machine. The zero Set, deliberately: the payload |
diff --git a/internal/console/server.go b/internal/console/server.go| index 5b95478fd..fe795acc9 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1087,6 +1087,12 @@ type Server struct { |
| // detachBeforeLock, when set, runs in both detach doors just before |
| // they take the fleet's lock (tests only: an interleaving seam). |
| detachBeforeLock func(fleet, label string) |
| + // labelAfterRead and labelBeforeMark, when set, run in the owner's |
| + // label door (instancelabel.go): the first after its judged record read, |
| + // before it takes the fleet's lock, the second after every check passed |
| + // and before MarkFleetBoxLabelled (tests only: interleaving seams). |
| + labelAfterRead func(host string) |
| + labelBeforeMark func(host string) |
| // consoleBuild, when set, is the release this console reports to the |
| // fleet label gate instead of version.Build (tests only). |
| consoleBuild string |
diff --git a/internal/provision/fleetbox.go b/internal/provision/fleetbox.go| index a5251f6d4..288627ae2 100644 |
| --- a/internal/provision/fleetbox.go |
| +++ b/internal/provision/fleetbox.go |
| @@ -6,6 +6,7 @@ import ( |
| "fmt" |
| "time" |
| + "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/release" |
| ) |
| @@ -77,3 +78,88 @@ func SetRecordFleetBox(ctx context.Context, s release.Store, acct, app, host str |
| }) |
| return err |
| } |
| + |
| +// The first label's refusals (fleet record labels spec §5). Each is |
| +// SetRecordFirstFleetBox's answer when the record it read, on any attempt, |
| +// is no longer one a first label may be written to. |
| +var ( |
| + // ErrFleetBoxNotFirst: the record already carries a label. The writer |
| + // answers the record as read with it, so the caller can name the label |
| + // that won. |
| + ErrFleetBoxNotFirst = errors.New("provision: the record is already tied to a box") |
| + // ErrFleetBoxAssigned: the record has a replica assignment; placement |
| + // chooses its boxes. |
| + ErrFleetBoxAssigned = errors.New("provision: the record has a replica assignment") |
| + // ErrFleetBoxMoveInFlight: the record has a move journal (Move). |
| + ErrFleetBoxMoveInFlight = errors.New("provision: the record has a move in flight") |
| + // ErrFleetBoxCoordinated: an unexpired replica coordinator names a box |
| + // other than the one being written. |
| + ErrFleetBoxCoordinated = errors.New("provision: another box coordinates the record") |
| +) |
| + |
| +// firstLabelBeforeWrite, when set, runs in SetRecordFirstFleetBox's |
| +// mutation after the record it read passed every check and before the |
| +// write's CAS (tests only: an interleaving seam). Nil in production. |
| +var firstLabelBeforeWrite func(host string) |
| + |
| +// SetRecordFirstFleetBox writes the first label of an unlabelled |
| +// fleet-placed record (fleet record labels spec §5, R2): FleetBox is label, |
| +// FleetBoxAt is at (RFC 3339 nanoseconds, UTC) and FleetBoxMoved is true, |
| +// so the named box restores the record's last saved copy and never starts |
| +// it empty. It shares updateRecord, which keeps the protected-field checks, |
| +// and every check below runs inside each attempt, CAS retries included, so |
| +// a retry is judged against the record the retry read. It refuses, writing |
| +// nothing, unless: |
| +// |
| +// - label is a valid box label; |
| +// - the record is not retired, and its Region and CreatedAt equal want's, |
| +// and want.Label is "" (otherwise ErrFleetBoxMoved); |
| +// - FleetBox is "" (ErrFleetBoxNotFirst, answered with the record read, |
| +// whose FleetBox names the label that won); |
| +// - ReplicaAssignment is nil (ErrFleetBoxAssigned); |
| +// - Move is nil (ErrFleetBoxMoveInFlight); |
| +// - the seed does not block a move (ErrFleetBoxImportInFlight, wrapping a |
| +// *SeedMoveError); |
| +// - no unexpired Coordinator names another box (ErrFleetBoxCoordinated). |
| +// A coordinator with no expiry counts as unexpired. |
| +// |
| +// It answers the record as written. |
| +func SetRecordFirstFleetBox(ctx context.Context, s release.Store, acct, app, host string, want FleetBoxExpect, label string, at time.Time) (*Record, error) { |
| + var current *Record |
| + rec, err := updateRecord(ctx, s, acct, app, host, func(rec *Record) error { |
| + if !registry.ValidTunnelName(label) { |
| + return fmt.Errorf("provision: invalid box label %q", label) |
| + } |
| + if rec.Retired || want.Label != "" || rec.Region != want.Region || !rec.CreatedAt.Equal(want.CreatedAt) { |
| + return ErrFleetBoxMoved |
| + } |
| + if rec.FleetBox != "" { |
| + c := *rec |
| + current = &c |
| + return ErrFleetBoxNotFirst |
| + } |
| + if rec.ReplicaAssignment != nil { |
| + return ErrFleetBoxAssigned |
| + } |
| + if rec.Move != nil { |
| + return ErrFleetBoxMoveInFlight |
| + } |
| + if b := rec.Seed.MoveBlock(); b != "" { |
| + return fmt.Errorf("%w: %w", ErrFleetBoxImportInFlight, &SeedMoveError{Block: b}) |
| + } |
| + if c := rec.Coordinator; c != nil && c.Box != label && (c.ExpiresAt.IsZero() || time.Now().Before(c.ExpiresAt)) { |
| + return ErrFleetBoxCoordinated |
| + } |
| + rec.FleetBox = label |
| + rec.FleetBoxAt = at.UTC().Format(time.RFC3339Nano) |
| + rec.FleetBoxMoved = true |
| + if firstLabelBeforeWrite != nil { |
| + firstLabelBeforeWrite(host) |
| + } |
| + return nil |
| + }) |
| + if errors.Is(err, ErrFleetBoxNotFirst) { |
| + return current, err |
| + } |
| + return rec, err |
| +} |
diff --git a/internal/provision/fleetbox_first_test.go b/internal/provision/fleetbox_first_test.go| new file mode 100644 |
| index 000000000..daca95184 |
| --- /dev/null |
| +++ b/internal/provision/fleetbox_first_test.go |
| @@ -0,0 +1,306 @@ |
| +package provision |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/replicas" |
| + "github.com/carlosframework/platform/internal/seeds" |
| +) |
| + |
| +// Fleet record labels (#1008 option B), spec §5: SetRecordFirstFleetBox is |
| +// the owner's door's only writer. It writes a first label, with the write |
| +// time and FleetBoxMoved (R2), and refuses on every attempt, CAS retries |
| +// included, unless the record is still the unlabelled, unassigned, unmoved, |
| +// unretired one the door read. Record shop/web.shop.example.com in acme, on |
| +// fleet pi (fleetBoxFixture). |
| + |
| +// firstLabelWant is the expectation the door reads off fleetBoxFixture's |
| +// record. |
| +func firstLabelWant(rec Record) FleetBoxExpect { |
| + return FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt} |
| +} |
| + |
| +// firstLabelEdit changes the stored record with mut, as another writer |
| +// would, straight through the store. |
| +func firstLabelEdit(t *testing.T, s release.Store, mut func(*Record)) { |
| + t.Helper() |
| + ctx := context.Background() |
| + key := RecordKey("acme", "shop", "web.shop.example.com") |
| + raw, etag, err := s.Get(ctx, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + rec, err := DecodeRecord(raw) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mut(&rec) |
| + body, err := json.Marshal(rec) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := s.Put(ctx, key, body, etag); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// wantUnlabelled fails unless the stored record carries no label. |
| +func wantUnlabelled(t *testing.T, s release.Store) *Record { |
| + t.Helper() |
| + got, _, _, err := GetRecordRaw(context.Background(), s, "acme", "shop", "web.shop.example.com") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if got.FleetBox != "" || got.FleetBoxAt != "" || got.FleetBoxMoved { |
| + t.Fatalf("a refused first label wrote: box %q at %q moved %v", got.FleetBox, got.FleetBoxAt, got.FleetBoxMoved) |
| + } |
| + return got |
| +} |
| + |
| +func TestFirstLabelWritesMovedAndAt(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + at := time.Date(2026, 11, 14, 10, 0, 0, 5, time.FixedZone("x", 3600)) |
| + out, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", at) |
| + if err != nil { |
| + t.Fatalf("first label: %v", err) |
| + } |
| + want := at.UTC().Format(time.RFC3339Nano) |
| + got := fleetBoxGet(t, s) |
| + if got.FleetBox != "pi-1" || got.FleetBoxAt != want || !got.FleetBoxMoved { |
| + t.Fatalf("stored: box %q at %q moved %v; want pi-1 at %s, moved", got.FleetBox, got.FleetBoxAt, got.FleetBoxMoved, want) |
| + } |
| + if out == nil || out.FleetBox != "pi-1" || out.FleetBoxAt != want || !out.FleetBoxMoved { |
| + t.Fatalf("returned record %+v; want the written label", out) |
| + } |
| + if got.Region != rec.Region || got.Channel != rec.Channel || !got.CreatedAt.Equal(rec.CreatedAt) || got.CreatedBy != rec.CreatedBy { |
| + t.Fatalf("the first label changed other fields: %+v", got) |
| + } |
| +} |
| + |
| +func TestFirstLabelRefusesALabelledRecord(t *testing.T) { |
| + ctx := context.Background() |
| + s, rec := fleetBoxFixture(t) |
| + if err := SetRecordFleetBox(ctx, s, "acme", "shop", rec.Host, FleetBoxExpect{Region: rec.Region, CreatedAt: rec.CreatedAt}, "pi-2", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + before := fleetBoxGet(t, s) |
| + out, err := SetRecordFirstFleetBox(ctx, s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !errors.Is(err, ErrFleetBoxNotFirst) { |
| + t.Fatalf("err = %v, want ErrFleetBoxNotFirst", err) |
| + } |
| + if out == nil || out.FleetBox != "pi-2" { |
| + t.Fatalf("refusal's record = %+v; want the label it already has, pi-2", out) |
| + } |
| + if got := fleetBoxGet(t, s); got.FleetBox != "pi-2" || got.FleetBoxAt != before.FleetBoxAt || got.FleetBoxMoved { |
| + t.Fatalf("a refused first label wrote: %+v", got) |
| + } |
| +} |
| + |
| +func TestFirstLabelRefusesAnAssignment(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + firstLabelEdit(t, s, func(r *Record) { |
| + r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-1"}} |
| + }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !errors.Is(err, ErrFleetBoxAssigned) { |
| + t.Fatalf("err = %v, want ErrFleetBoxAssigned", err) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRefusesAMove(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + firstLabelEdit(t, s, func(r *Record) { r.Move = &MoveState{ID: "mv_1", To: "eu"} }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !errors.Is(err, ErrFleetBoxMoveInFlight) { |
| + t.Fatalf("err = %v, want ErrFleetBoxMoveInFlight", err) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +// blockingSeed is an import not yet committed: its seed blocks a move. |
| +func blockingSeed() *SeedSource { |
| + id, _ := seeds.NewID() |
| + return &SeedSource{ID: id, Kind: seeds.KindImport, State: seeds.StateSwapped, SHA256: strings.Repeat("a", 64), Bytes: 10, |
| + Replaces: "127.0.0.1:8401", VerifyHash: strings.Repeat("b", 64), By: "t", At: time.Now()} |
| +} |
| + |
| +func TestFirstLabelRefusesABlockingSeed(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + firstLabelEdit(t, s, func(r *Record) { r.Seed = blockingSeed() }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + var sme *SeedMoveError |
| + if !errors.Is(err, ErrFleetBoxImportInFlight) || !errors.As(err, &sme) { |
| + t.Fatalf("err = %v, want ErrFleetBoxImportInFlight wrapping a *SeedMoveError", err) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRefusesALiveCoordinatorElsewhere(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + firstLabelEdit(t, s, func(r *Record) { |
| + r.Coordinator = &replicas.Coordinator{Term: "t1", Box: "pi-2", BootID: "b", ExpiresAt: time.Now().Add(time.Hour)} |
| + }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !errors.Is(err, ErrFleetBoxCoordinated) { |
| + t.Fatalf("err = %v, want ErrFleetBoxCoordinated", err) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelAllowsAnExpiredCoordinator(t *testing.T) { |
| + for _, c := range []struct { |
| + what string |
| + co replicas.Coordinator |
| + }{ |
| + {"expired, on another box", replicas.Coordinator{Term: "t1", Box: "pi-2", BootID: "b", ExpiresAt: time.Now().Add(-time.Minute)}}, |
| + {"live, on the named box", replicas.Coordinator{Term: "t1", Box: "pi-1", BootID: "b", ExpiresAt: time.Now().Add(time.Hour)}}, |
| + } { |
| + t.Run(c.what, func(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + co := c.co |
| + firstLabelEdit(t, s, func(r *Record) { r.Coordinator = &co }) |
| + if _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()); err != nil { |
| + t.Fatalf("first label: %v", err) |
| + } |
| + if got := fleetBoxGet(t, s); got.FleetBox != "pi-1" { |
| + t.Fatalf("box %q, want pi-1", got.FleetBox) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestFirstLabelRefusesARetiredRecord(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + firstLabelEdit(t, s, func(r *Record) { r.Retired = true }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !errors.Is(err, ErrFleetBoxMoved) { |
| + t.Fatalf("err = %v, want ErrFleetBoxMoved", err) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +// The expectation: another region, another creation time (a later record |
| +// at the same host) or a caller that read a label is refused. |
| +func TestFirstLabelRefusesAnotherExpectation(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + for _, want := range []FleetBoxExpect{ |
| + {Region: "fleet/other", CreatedAt: rec.CreatedAt}, |
| + {Region: rec.Region, CreatedAt: rec.CreatedAt.Add(time.Nanosecond)}, |
| + {Region: rec.Region, Label: "pi-2", CreatedAt: rec.CreatedAt}, |
| + } { |
| + if _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, want, "pi-1", time.Now()); !errors.Is(err, ErrFleetBoxMoved) { |
| + t.Fatalf("expectation %+v: err = %v, want ErrFleetBoxMoved", want, err) |
| + } |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRefusesABadLabel(t *testing.T) { |
| + s, rec := fleetBoxFixture(t) |
| + for _, label := range []string{"", "PI-1", "pi_1", "../pi-1", "pi-1/x", strings.Repeat("a", 33)} { |
| + if _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), label, time.Now()); err == nil { |
| + t.Fatalf("label %q was accepted", label) |
| + } |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +// conflictStore counts the CAS conflicts its Puts answer. |
| +type conflictStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + conflicts int |
| +} |
| + |
| +func (c *conflictStore) Put(ctx context.Context, key string, body []byte, ifMatch string) (string, error) { |
| + etag, err := c.Store.Put(ctx, key, body, ifMatch) |
| + if errors.Is(err, release.ErrCASConflict) { |
| + c.mu.Lock() |
| + c.conflicts++ |
| + c.mu.Unlock() |
| + } |
| + return etag, err |
| +} |
| + |
| +// firstLabelRetry arms firstLabelBeforeWrite to make change once, after |
| +// the writer's first read passed every check and before its CAS: the first |
| +// PUT then meets a store conflict, and the retry reads the changed record. |
| +// It answers the writer's error and how many conflicts the store saw. |
| +func firstLabelRetry(t *testing.T, change func(*Record)) (release.Store, error, int) { |
| + t.Helper() |
| + inner, rec := fleetBoxFixture(t) |
| + s := &conflictStore{Store: inner} |
| + var once sync.Once |
| + ran := false |
| + firstLabelBeforeWrite = func(host string) { |
| + once.Do(func() { |
| + if host != rec.Host { |
| + t.Errorf("seam ran for %q", host) |
| + } |
| + firstLabelEdit(t, inner, change) |
| + ran = true |
| + }) |
| + } |
| + t.Cleanup(func() { firstLabelBeforeWrite = nil }) |
| + _, err := SetRecordFirstFleetBox(context.Background(), s, "acme", "shop", rec.Host, firstLabelWant(rec), "pi-1", time.Now()) |
| + if !ran { |
| + t.Fatal("the seam never ran: the first attempt was refused before its CAS") |
| + } |
| + return inner, err, s.conflicts |
| +} |
| + |
| +func TestFirstLabelRetryRefusesRetirement(t *testing.T) { |
| + s, err, conflicts := firstLabelRetry(t, func(r *Record) { r.Retired = true }) |
| + if conflicts != 1 || !errors.Is(err, ErrFleetBoxMoved) { |
| + t.Fatalf("err = %v after %d conflicts; want ErrFleetBoxMoved on the retry", err, conflicts) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRetryRefusesSeedBlock(t *testing.T) { |
| + s, err, conflicts := firstLabelRetry(t, func(r *Record) { r.Seed = blockingSeed() }) |
| + if conflicts != 1 || !errors.Is(err, ErrFleetBoxImportInFlight) { |
| + t.Fatalf("err = %v after %d conflicts; want ErrFleetBoxImportInFlight on the retry", err, conflicts) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRetryRefusesAssignment(t *testing.T) { |
| + s, err, conflicts := firstLabelRetry(t, func(r *Record) { |
| + r.ReplicaAssignment = &replicas.Assignment{Revision: 1, Desired: 1, Boxes: []string{"pi-2"}} |
| + }) |
| + if conflicts != 1 || !errors.Is(err, ErrFleetBoxAssigned) { |
| + t.Fatalf("err = %v after %d conflicts; want ErrFleetBoxAssigned on the retry", err, conflicts) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRetryRefusesCoordinator(t *testing.T) { |
| + s, err, conflicts := firstLabelRetry(t, func(r *Record) { |
| + r.Coordinator = &replicas.Coordinator{Term: "t1", Box: "pi-2", BootID: "b", ExpiresAt: time.Now().Add(time.Hour)} |
| + }) |
| + if conflicts != 1 || !errors.Is(err, ErrFleetBoxCoordinated) { |
| + t.Fatalf("err = %v after %d conflicts; want ErrFleetBoxCoordinated on the retry", err, conflicts) |
| + } |
| + wantUnlabelled(t, s) |
| +} |
| + |
| +func TestFirstLabelRetryRefusesCompetingLabel(t *testing.T) { |
| + s, err, conflicts := firstLabelRetry(t, func(r *Record) { |
| + r.FleetBox, r.FleetBoxAt, r.FleetBoxMoved = "pi-2", "2026-11-14T09:00:00Z", true |
| + }) |
| + if conflicts != 1 || !errors.Is(err, ErrFleetBoxNotFirst) { |
| + t.Fatalf("err = %v after %d conflicts; want ErrFleetBoxNotFirst on the retry", err, conflicts) |
| + } |
| + if got := fleetBoxGet(t, s); got.FleetBox != "pi-2" || got.FleetBoxAt != "2026-11-14T09:00:00Z" { |
| + t.Fatalf("the competing label was overwritten: %+v", got) |
| + } |
| +} |
diff --git a/internal/provision/provision.go b/internal/provision/provision.go| index 5a8d307ef..dca5353a2 100644 |
| --- a/internal/provision/provision.go |
| +++ b/internal/provision/provision.go |
| @@ -68,8 +68,9 @@ type Record struct { |
| // FleetBox is the label of the fleet box this instance is assigned to, |
| // FleetBoxAt when it was assigned (RFC 3339 nanoseconds, UTC), and |
| // FleetBoxMoved whether a relabel ever took it from one box to another. |
| - // Written only through SetRecordFleetBox (fleetbox.go) and cleared, the |
| - // first two, by a region change in SetRecordRegion. Additive and |
| + // Written only through SetRecordFleetBox and SetRecordFirstFleetBox |
| + // (fleetbox.go) and cleared, the first two, by a region change in |
| + // SetRecordRegion. Additive and |
| // omitempty: every record written before them reads as unassigned. |
| FleetBox string `json:"fleet_box,omitempty"` |
| FleetBoxAt string `json:"fleet_box_at,omitempty"` |
diff --git a/internal/release/layoutintent.go b/internal/release/layoutintent.go| index e4a4f0dd7..1f51e1f08 100644 |
| --- a/internal/release/layoutintent.go |
| +++ b/internal/release/layoutintent.go |
| @@ -276,6 +276,18 @@ var RegionalDomainsFloor = SemVer{Major: 0, Minor: 31, Patch: 0} |
| // or does not parse counts as below. TestFleetBoxLabelFloorIsPinned pins it. |
| const FleetBoxLabelFloor = "v0.33.0" |
| +// FleetRecordLabelFloor is the first platform release whose fleet boxes |
| +// carry the fleet record labels slice's box behaviour (#1008 option B, spec |
| +// R1-R4): the stale unlabelled wake fence, the proven final checkpoint and |
| +// stateless eligibility wherever a label is acted on. The owner's label door |
| +// (console/instancelabel.go) ties a record to a box only while every active |
| +// box of the record's fleet, and the console itself, report a release at or |
| +// above it. It is above StatelessRuntimeFloor and FleetBoxLabelFloor, and it |
| +// must be at least the release that carries R1-R3 (release A). Provisional |
| +// (controller ruling, 2026-11-14): confirmed before the merge. |
| +// TestFleetRecordLabelFloorIsPinned pins it. |
| +const FleetRecordLabelFloor = "v0.35.4" |
| + |
| // RootfsFloorOverrideFlag is the override's flag name, on `carlos system |
| // update`, `carlos system rollback` and `carlos system apply`. |
| const RootfsFloorOverrideFlag = "allow-below-rootfs-floor" |
diff --git a/internal/release/layoutintent_test.go b/internal/release/layoutintent_test.go| index d8c59919b..dd43e2df2 100644 |
| --- a/internal/release/layoutintent_test.go |
| +++ b/internal/release/layoutintent_test.go |
| @@ -161,6 +161,19 @@ func TestFleetBoxLabelFloorIsPinned(t *testing.T) { |
| } |
| } |
| +func TestFleetRecordLabelFloorIsPinned(t *testing.T) { |
| + v, ok := ParseReleaseVersion(FleetRecordLabelFloor) |
| + if !ok || v != (SemVer{Major: 0, Minor: 35, Patch: 4}) { |
| + t.Fatalf("FleetRecordLabelFloor = %q, want v0.35.4", FleetRecordLabelFloor) |
| + } |
| + for _, below := range []string{FleetBoxLabelFloor, StatelessRuntimeFloor} { |
| + b, _ := ParseReleaseVersion(below) |
| + if v.Compare(b) <= 0 { |
| + t.Fatalf("FleetRecordLabelFloor %s is not above %s", FleetRecordLabelFloor, below) |
| + } |
| + } |
| +} |
| + |
| // RootfsFloorAllows is the box-side rule by version alone (Task 15 round |
| // 3): a box below the floor, or whose own version does not parse, installs |
| // anything; one at or above it only a parseable candidate at or above it. |
diff --git a/parity/parity.tsv b/parity/parity.tsv| index 8484364a8..0b417ed8e 100644 |
| --- a/parity/parity.tsv |
| +++ b/parity/parity.tsv |
| @@ -72,6 +72,7 @@ instances-updates instances both instances set [--updates,--major,--pin] POST /a |
| instances-update instances both instances update POST /a/{sqid}/apps/{app}/instances/{host}/updates/install |
| instances-retry instances both instances retry POST /a/{sqid}/apps/{app}/instances/{host}/retry |
| instances-backups instances both instances backups GET /a/{sqid}/apps/{app}/instances/{host} |
| +instances-label instances cli-only instances label [--box, --dry-run] Ties an instance on a fleet to the box serving it now; owner only. The console has no labelling action yet (fleet record labels spec, out of scope). |
| steering instances gap steering wp-instances |
| routes instances partial routes GET /a/{sqid}/apps/{app}/instances ; GET /a/{sqid}/apps/{app}/settings/{section} The console shows host and channel but no environment or replication column. |
| restart instances partial restart POST /a/{sqid}/apps/{app}/restart ; POST /a/{sqid}/apps/{app}/instances/{host}/restart The console has no environment scope and no dry-run list. |