carlos / platform Public

claim-empty-cohort-done: backfill-done, collecting straight to done for an empty cohort

Claim trial Option B (Paul's D1 of 2026-10-20): leo stays empty, the dev
console stays claims-off through the window, and a new signer phase closes
the collecting plan as done. No adoption, no abandon or recover, no plan
fields, no #312 code, no inventory code; backfill-adopt is unchanged.

- hostops Backfill.Done refuses, each condition separately: the etag is not
  the collecting plan's; the envelope does not verify; the phase is not
  collecting; the live record listing is not the plan's hosts by key, etag
  and acquisition; control/hosts/ lists anything; an app has admission.json;
  a roster box with a census key lacks a report that verifies as the census
  verifies it, captured no earlier than the plan, listing no installation.
  Keyless boxes are returned as unreported; no keyed report at all refuses.
  It writes done under If-Match with the reporting boxes' digests, reads it
  back and requires CheckCreateFreeze to pass. ProductionAuthority.census
  (accepted-legacy) is untouched: Done uses a line-for-line copy of its
  per-box check, held to it by TestDoneVerifiesReportsAsTheCensusDoes.
- carlos system claims run backfill-done, mirroring backfill-adopt with a
  dry run. One new refusal: "backfill refused: a census report lists
  installations; this phase is for an empty cohort" (pending Paul's copy
  review); the plan and records refusals are reused.
- A zero-host plan (the trial deletes every dev record first) is
  "hosts":{} and passes collect, the migration census, journal-migrate
  --window and done.

Tests: Done's pass, zero-host and 20 refusal cases, each refusal
mutation-checked (19 mutants killed); TestBackfillPhases gains done (zero
and two hosts, dry run, If-Match, second done refused); the empty-leo census
on leo's real tree; ruling 6 pins the new call sites. Root runner
20261020T011116-f8e45f: the step 8 witnesses including the new empty-leo
flows (zero and two hosts) pass.

Census overlay and 9B8 addendum extended, still PROPOSED
(docs/superpowers/notes/census-proposal-claim-step8-readiness.md,
"backfill-done").
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 26dd5bb11e62a2dcc93b7bf341a0bb09eaccafbe parent 232baff
13 files changed, +1,283 −16
  • docs/site/cli.md +2 −0
  • docs/superpowers/notes/census-proposal-claim-step8-readiness.md +20 −0
  • internal/claimactivation/backfill.go +59 −1
  • internal/claimactivation/backfill_test.go +126 −0
  • internal/claimactivation/runner.go +7 −2
  • internal/host/claimstep8_emptyleo_linux_test.go +112 −0
  • internal/host/claimstep8_ruling6_test.go +75 −0
  • internal/host/claimstep8_witness_rootrunner_linux_test.go +128 −7
  • internal/host/rootmigration_routes_linux_test.go +54 −0
  • internal/hostops/backfill_done_test.go +470 −0
  • internal/hostops/backfill_publish.go +218 −1
  • internal/provision/claim_step8_readiness_census_test.go +7 −1
  • internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv +5 −4

CI cancelled — superseded by a newer push — run details

diff --git a/docs/site/cli.md b/docs/site/cli.md
index 2943d2fb6..bd5d3a309 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -2162,6 +2162,8 @@ Two `run` phases make the files `carlos system guard-arm` takes. `sign-policy` s
Two more `run` phases make the backfill that `carlos system journal-migrate` and claim adoption read. Each takes the plan's `backfill.id`, and prints the signed plan as read back. `backfill-collect` freezes every instance record the bucket lists in a new signed plan. While that plan is in place, claim-mode record writes are refused. `backfill-adopt` runs once every roster box has published its census for the plan. It gives each host to the box that reported it, and a host no box reported is never adopted.
+`backfill-done` is for a cohort with nothing to adopt. It closes a collecting plan as done, and claim-mode record writes are allowed again. It refuses unless the records are still the ones the plan froze, no host claim or app admission exists, and every roster box with a census key has published a census for the plan that lists no installation. A box with no census key is not asked, and is listed as unreported.
+
`install-console` copies the console build that the published identity names into `/opt/carlos/system/console/console` and `console.prev`, owned by root. It refuses a source whose bytes don't match the identity, and it doesn't touch `console.service`. Pass that path to `guard-arm --console`.
After starting the guarded console, run `console-report` on its box as root. It checks the signed roster, guard, systemd process and running executable, then records that process in the existing private box report. It refuses stale box evidence and leaves the report’s timestamp unchanged. Run it again after a console restart and immediately before floor publication; the next agent report may replace the process entry.
diff --git a/docs/superpowers/notes/census-proposal-claim-step8-readiness.md b/docs/superpowers/notes/census-proposal-claim-step8-readiness.md
index aed77e8f5..8600aee41 100644
--- a/docs/superpowers/notes/census-proposal-claim-step8-readiness.md
+++ b/docs/superpowers/notes/census-proposal-claim-step8-readiness.md
@@ -42,3 +42,23 @@ Envelopes re-pinned: `internal/claimactivation`, `internal/host`, `internal/host
## Rows carried over
Every re-pinned row keeps its class and task exactly; only the bases add what changed.
+
+## backfill-done
+
+Status: PROPOSED to platform-1e, in the same overlay and 9B8 addendum (no new file, no new seal). Claim trial Option B (Paul's D1 of 2026-10-20): leo stays empty, the dev console stays claims-off through the window, and a new signer phase goes straight from `collecting` to `done`. No adoption, no abandon or recover phase, no plan fields, no #312 code, no inventory code. `backfill-adopt` stays in the binary unchanged.
+
+- `carlos system claims run` gains `backfill-done` (`Runner.backfillDone`, mirroring `backfillAdopt`, dry run included). It refuses up front through `backfillReady` and the plan check, then calls the new `hostops.Backfill.Done` under the plan's etag.
+- `Backfill.Done` refuses, each condition separately: the etag is not `collectingETag`; the envelope does not verify; the phase is not `collecting`; the live record listing (`Apps`, `Records`) is not the plan's hosts by key, etag and acquisition; `control/hosts/` lists anything; any listed app has `admission.json`; any roster box with a census key lacks a report for the reservation that verifies as the census verifies it, captured no earlier than the plan, listing zero installations. Boxes with no census key are skipped and returned as unreported. With no keyed report at all it refuses. It then fills the reporting boxes' digests, writes `done` under If-Match, reads it back byte for byte, and requires `CheckCreateFreeze` to return nil.
+- `ProductionAuthority.census` is accepted-legacy and is not touched. Done uses `verifyCensusReport`, a line-for-line copy of census's per-box check; `TestDoneVerifiesReportsAsTheCensusDoes` holds the two together over 18 report variants.
+- A zero-host plan (the trial deletes every dev record before the window) is `"hosts":{}` and passes collect, the migration census, journal-migrate `--window` and done.
+
+Ruling 6: the phase is reached only from `claims run` on the trusted signer. `TestStep8CensusChangesReachOnlyClaimMode` now also scans the module's non-test sources and pins `Backfill.Done` (a three-argument `Done` call) to `Runner.backfillDone`, `backfillDone` to `Runner.Run`, and `verifyCensusReport` to `Backfill.Done`. No box, console or agent path calls them, and a claims-off or no-census box sees no change.
+
+| Unit | Change | Class | Executing identity |
+|---|---|---|---|
+| `internal/claimactivation/runner.go` `Runner.Run` | re-pinned: the `backfill-done` case and its one allowed key, `control/hosts-backfill.json` | authority F,G,J4 (unchanged) | `carlos system claims run`, explicit operator CLI, uid 0 on the trusted signing host |
+| `internal/hostops/backfill_publish.go` `Backfill.Done` | new | authority F,G,J4 | the same signer CLI, its only caller. Reads the plan, roster, record listing, `control/hosts/`, admissions and keyed census reports; one If-Match write of the plan as done; adopts and installs nothing |
+
+Envelopes re-pinned: `internal/claimactivation`, `internal/hostops`. New helpers with no read site of their own (`Runner.backfillDone`, `verifyCensusReport`) are envelope only. `internal/host` changes are tests only.
+
+9B8: `internal/hostops/backfill_publish.go` `Backfill.Done`, nonrecord (new). Its one Put is the backfill manifest rewritten as done under the collecting etag, through the runner's checkedStore; it reads records, claims, admissions and census reports and writes none of them.
diff --git a/internal/claimactivation/backfill.go b/internal/claimactivation/backfill.go
index c53239f3f..aa8d9545e 100644
--- a/internal/claimactivation/backfill.go
+++ b/internal/claimactivation/backfill.go
@@ -14,7 +14,7 @@ import (
"github.com/carlosframework/platform/internal/release"
)
-// BackfillInput is backfill-collect's and backfill-adopt's plan: the
+// BackfillInput is the backfill phases' plan: the
// reservation id the boxes' census reports are published under
// (control/host-census/<id>/<box>.json). Nothing else is typed: the hosts
// come from the bucket's own record listing, and each host's box and region
@@ -41,6 +41,9 @@ type BackfillSummary struct {
// Unowned lists the hosts no box reported. They keep no box and are
// never adopted. Adopting only.
Unowned []string `json:"unowned,omitempty"`
+ // Unreported lists the roster boxes with no census key, which
+ // backfill-done did not ask to report. Done only.
+ Unreported []string `json:"unreported,omitempty"`
}
var (
@@ -56,6 +59,10 @@ var (
// ErrBackfillPlan is backfill-adopt's refusal when the plan is not the
// named reservation, still collecting, at this roster revision.
ErrBackfillPlan = errors.New("backfill refused: the plan must be the named reservation, still collecting, at this roster revision")
+ // ErrBackfillInstallations is backfill-done's refusal when a box's
+ // census report lists an installation: done is for an empty cohort,
+ // and there is no override.
+ ErrBackfillInstallations = errors.New("backfill refused: a census report lists installations; this phase is for an empty cohort")
)
// backfillReady is both phases' refusal up front: a published roster with a
@@ -218,6 +225,57 @@ func (r Runner) backfillAdopt(ctx context.Context, d hostactors.Directory, o hos
return nil
}
+// backfillDone closes the named collecting plan straight to done, for an
+// empty cohort (claim trial Option B, Paul's D1 of 2026-10-20), through
+// hostops' Backfill.Done under the plan's own etag (If-Match). Done adopts
+// nothing: it refuses unless the records are the plan's, no host claim or
+// app admission exists, and every roster box with a census key reports no
+// installation. Boxes with no key are listed as unreported. The plan is then
+// read back as done.
+func (r Runner) backfillDone(ctx context.Context, d hostactors.Directory, o hostactors.Observed, in BackfillInput, result *Result) error {
+ if !validBackfillID(in.ID) {
+ return ErrActivation
+ }
+ if err := backfillReady(ctx, d, o); err != nil {
+ return err
+ }
+ p, tag, err := readSignedPlan(ctx, d)
+ if err != nil {
+ return err
+ }
+ if p.ID != in.ID || p.Phase != "collecting" || p.DirectoryRevision != o.Roster.Revision {
+ return ErrBackfillPlan
+ }
+ b := &hostops.Backfill{Store: d.Store, Directory: d}
+ unreported, err := b.Done(ctx, r.Signer, tag)
+ switch {
+ case errors.Is(err, hostops.ErrDoneInstallations):
+ return errors.Join(ErrBackfillInstallations, err)
+ case errors.Is(err, hostops.ErrDoneRecords):
+ return errors.Join(ErrBackfillRecords, err)
+ case errors.Is(err, hostops.ErrDoneETag), errors.Is(err, hostops.ErrDoneEnvelope), errors.Is(err, hostops.ErrDonePhase):
+ return errors.Join(ErrBackfillPlan, err)
+ case err != nil:
+ return err
+ }
+ got, _, err := readSignedPlan(ctx, d)
+ if err != nil {
+ return err
+ }
+ if got.ID != in.ID || got.Phase != "done" || got.DirectoryRevision != o.Roster.Revision || len(got.Hosts) != len(p.Hosts) {
+ return ErrBackfillPlan
+ }
+ for host, h := range p.Hosts {
+ if got.Hosts[host] != h {
+ return ErrBackfillPlan
+ }
+ }
+ summary := backfillSummary(got)
+ summary.Unreported = unreported
+ result.Backfill = &summary
+ return nil
+}
+
// validBackfillID keeps the reservation id one safe path segment.
func validBackfillID(id string) bool {
if id == "" || len(id) > 64 || id == "." || id == ".." {
diff --git a/internal/claimactivation/backfill_test.go b/internal/claimactivation/backfill_test.go
index c2d662e72..3eafede34 100644
--- a/internal/claimactivation/backfill_test.go
+++ b/internal/claimactivation/backfill_test.go
@@ -1,11 +1,13 @@
package claimactivation
import (
+ "bytes"
"context"
"crypto/ed25519"
"crypto/rand"
"errors"
"os"
+ "slices"
"strings"
"testing"
"time"
@@ -211,6 +213,130 @@ func TestBackfillPhases(t *testing.T) {
if _, err := b.r.Run(ctx, b.plan(t, "backfill-adopt"), false); !errors.Is(err, ErrBackfillPlan) {
t.Fatalf("second adopt = %v", err)
}
+ // done is only ever from collecting.
+ if _, err := b.r.Run(ctx, b.plan(t, "backfill-done"), false); !errors.Is(err, ErrBackfillPlan) {
+ t.Fatalf("done over an adopting plan = %v", err)
+ }
+
+ // backfill-done, the empty cohort (claim trial Option B): records are
+ // deleted before the window (all of them, as the trial does; or only
+ // leo's, the two-host shape), sophie has no census key, leo reports
+ // nothing. done writes done under If-Match and lifts the create freeze;
+ // a dry run writes nothing; a second done is refused.
+ for name, keep := range map[string][]string{"zero hosts": nil, "two hosts": {"rollcheck.example.com", "wakecheck.example.com"}} {
+ t.Run(name, func(t *testing.T) {
+ ctx := t.Context()
+ e := newBackfillDeployment(t, false)
+ e.deleteRecordsExcept(t, keep...)
+ dry, err := e.r.Run(ctx, e.plan(t, "backfill-collect"), true)
+ if err != nil || len(dry.Writes) != 1 || len(dry.Backfill.Hosts) != len(keep) {
+ t.Fatalf("collect dry run = %+v, %v", dry, err)
+ }
+ if len(keep) == 0 && !bytes.Contains(dry.Writes[0].Payload, []byte(`"hosts":{}`)) {
+ t.Fatalf("zero-host plan payload = %s; want \"hosts\":{}", dry.Writes[0].Payload)
+ }
+ if _, err := e.r.Run(ctx, e.plan(t, "backfill-collect"), false); err != nil {
+ t.Fatal(err)
+ }
+ collecting := readPlan(t, e.r)
+ if collecting.Hosts == nil || len(collecting.Hosts) != len(keep) {
+ t.Fatalf("collecting hosts = %#v", collecting.Hosts)
+ }
+ _, collectingTag, err := e.r.Directory.Store.Get(ctx, hostops.BackfillKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Leo has not reported yet.
+ if _, err := e.r.Run(ctx, e.plan(t, "backfill-done"), false); !errors.Is(err, os.ErrNotExist) {
+ t.Fatalf("done before leo's report = %v", err)
+ }
+ e.report(t, "leo-climbing")
+ wrong := e.plan(t, "backfill-done")
+ wrong.Backfill.ID = "other"
+ if _, err := e.r.Run(ctx, wrong, false); !errors.Is(err, ErrBackfillPlan) {
+ t.Fatalf("done for another reservation = %v", err)
+ }
+ dry, err = e.r.Run(ctx, e.plan(t, "backfill-done"), true)
+ if err != nil || len(dry.Writes) != 1 || dry.Writes[0].Key != hostops.BackfillKey || dry.Writes[0].BeforeETag != collectingTag || dry.Backfill.Phase != "done" {
+ t.Fatalf("done dry run = %+v, %v", dry, err)
+ }
+ if readPlan(t, e.r).Phase != "collecting" {
+ t.Fatal("dry run moved the plan")
+ }
+ if err := hostops.CheckCreateFreeze(ctx, e.r.Directory.Store, e.r.Directory.PublicKey); !errors.Is(err, hostops.ErrPending) {
+ t.Fatalf("freeze after a dry run = %v", err)
+ }
+ got, err := e.r.Run(ctx, e.plan(t, "backfill-done"), false)
+ if err != nil || got.Backfill.Phase != "done" || len(got.Backfill.Hosts) != len(keep) || len(got.Backfill.Reports) != 1 || got.Backfill.Reports["leo-climbing"] == "" ||
+ len(got.Backfill.Unreported) != 1 || got.Backfill.Unreported[0] != "sophie-knitting" || len(got.Backfill.Unowned) != 0 {
+ t.Fatalf("done = %+v, %v", got.Backfill, err)
+ }
+ if len(got.Writes) != 1 || got.Writes[0].BeforeETag != collectingTag {
+ t.Fatalf("done wrote %+v; want one If-Match write over the collecting plan", got.Writes)
+ }
+ done := readPlan(t, e.r)
+ if done.Phase != "done" || done.Hosts == nil || len(done.Hosts) != len(keep) {
+ t.Fatalf("done plan = %#v", done)
+ }
+ if err := hostops.CheckCreateFreeze(ctx, e.r.Directory.Store, e.r.Directory.PublicKey); err != nil {
+ t.Fatalf("freeze after done = %v", err)
+ }
+ if _, err := e.r.Run(ctx, e.plan(t, "backfill-done"), false); !errors.Is(err, ErrBackfillPlan) {
+ t.Fatalf("second done = %v", err)
+ }
+ })
+ }
+}
+
+func (b *backfillDeployment) deleteRecordsExcept(t *testing.T, keep ...string) {
+ t.Helper()
+ for host, r := range b.records {
+ if slices.Contains(keep, host) {
+ continue
+ }
+ if err := release.DeleteIfMatch(t.Context(), b.r.Directory.Store, r.Holder.Key, r.ETag); err != nil {
+ t.Fatal(err)
+ }
+ delete(b.records, host)
+ }
+}
+
+// backfill-done is fail-closed on installations, with no override: leo's
+// report still lists claimtrial (B1 skipped), so done refuses with the
+// empty-cohort refusal and the plan stays collecting. A record that changed
+// since collect refuses with the records refusal.
+func TestBackfillDoneRefusesAPopulatedCohort(t *testing.T) {
+ ctx := t.Context()
+ b := newBackfillDeployment(t, false)
+ if _, err := b.r.Run(ctx, b.plan(t, "backfill-collect"), false); err != nil {
+ t.Fatal(err)
+ }
+ b.report(t, "leo-climbing", "claimtrial.example.com")
+ if _, err := b.r.Run(ctx, b.plan(t, "backfill-done"), true); !errors.Is(err, ErrBackfillInstallations) || !errors.Is(err, hostops.ErrDoneInstallations) {
+ t.Fatalf("done dry run over an installation = %v", err)
+ }
+ if _, err := b.r.Run(ctx, b.plan(t, "backfill-done"), false); !errors.Is(err, ErrBackfillInstallations) {
+ t.Fatalf("done over an installation = %v", err)
+ }
+ if readPlan(t, b.r).Phase != "collecting" {
+ t.Fatal("plan moved")
+ }
+
+ m := newBackfillDeployment(t, false)
+ if _, err := m.r.Run(ctx, m.plan(t, "backfill-collect"), false); err != nil {
+ t.Fatal(err)
+ }
+ m.report(t, "leo-climbing")
+ r := m.records["wakecheck.example.com"]
+ if _, err := m.r.Directory.Store.Put(ctx, r.Holder.Key, append(append([]byte(nil), r.Body...), '\n'), r.ETag); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := m.r.Run(ctx, m.plan(t, "backfill-done"), false); !errors.Is(err, ErrBackfillRecords) {
+ t.Fatalf("done over a changed record = %v", err)
+ }
+ if readPlan(t, m.r).Phase != "collecting" {
+ t.Fatal("plan moved")
+ }
}
// The dev roster at step 8: sophie is a roster box with no census key, so
diff --git a/internal/claimactivation/runner.go b/internal/claimactivation/runner.go
index 32fc38a05..15674bec1 100644
--- a/internal/claimactivation/runner.go
+++ b/internal/claimactivation/runner.go
@@ -92,7 +92,7 @@ type Result struct {
Release *release.SystemRelease `json:"release,omitempty"`
OutputSHA256 string `json:"output_sha256,omitempty"`
Output []byte `json:"-"`
- // backfill-collect and backfill-adopt only: the signed plan as read
+ // The backfill phases only: the signed plan as read
// back after the write (on a dry run, the plan that would be written).
Backfill *BackfillSummary `json:"backfill,omitempty"`
}
@@ -167,7 +167,7 @@ func (r Runner) Run(ctx context.Context, p Plan, dry bool) (Result, error) {
}
case "sign-policy":
// Writes nothing: the policy goes to the operator's file.
- case "backfill-collect", "backfill-adopt":
+ case "backfill-collect", "backfill-adopt", "backfill-done":
allowed[hostops.BackfillKey] = true
}
store := &checkedStore{allowed: allowed, Store: d.Store, pub: d.PublicKey, bucket: d.Bucket, expected: o.ETag, dry: dry, overlay: map[string]overlayObject{}, writes: &result.Writes}
@@ -301,6 +301,11 @@ func (r Runner) Run(ctx context.Context, p Plan, dry bool) (Result, error) {
return result, ErrActivation
}
err = r.backfillAdopt(ctx, d, o, *p.Backfill, &result)
+ case "backfill-done":
+ if p.Backfill == nil {
+ return result, ErrActivation
+ }
+ err = r.backfillDone(ctx, d, o, *p.Backfill, &result)
default:
return result, ErrActivation
}
diff --git a/internal/host/claimstep8_emptyleo_linux_test.go b/internal/host/claimstep8_emptyleo_linux_test.go
new file mode 100644
index 000000000..15e20de91
--- /dev/null
+++ b/internal/host/claimstep8_emptyleo_linux_test.go
@@ -0,0 +1,112 @@
+//go:build linux
+
+package host
+
+import (
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/hostbox"
+ "github.com/carlosframework/platform/internal/hostops"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/registry"
+)
+
+// step8MovedAside is B2: claimtrial's and wakecheck's instance directories,
+// program files and live links, moved out of leo's census roots. Their
+// certificates stay (the certificate cache is box state).
+func step8MovedAside(r leoRow) bool {
+ for _, h := range []string{leoClaimtrial, leoWakecheck} {
+ switch r.Root {
+ case "/data":
+ for _, dir := range []string{"instances/" + h, ".instances/" + h} {
+ if r.Path == dir || strings.HasPrefix(r.Path, dir+"/") {
+ return true
+ }
+ }
+ if r.Path == "programs/"+h+".json" {
+ return true
+ }
+ case "/opt/carlos":
+ if r.Path == "live/"+h {
+ return true
+ }
+ }
+ }
+ return false
+}
+
+// newEmptyLeoCensusTree is leo's tree for the empty-leo flow (Option B):
+// claimtrial's row gone (B1), the records keep left in the bucket, and, when
+// movedAside, claimtrial's and wakecheck's leftovers moved out (B2). Leo
+// reports zero installations.
+func newEmptyLeoCensusTree(t *testing.T, keep []string, movedAside bool) *leoCensusTree {
+ t.Helper()
+ base := t.TempDir()
+ roots := map[string]string{"data": filepath.Join(base, "data"), "opt": filepath.Join(base, "opt"), "units": filepath.Join(base, "units")}
+ for _, dir := range roots {
+ if err := os.Mkdir(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ buildLeoTree(t, leoTreeRows(t, true), leoTreeOptions{
+ Roots: map[string]string{"/data": roots["data"], "/opt/carlos": roots["opt"], "/etc/systemd/system": roots["units"]},
+ Skip: func(r leoRow) bool {
+ if movedAside && step8MovedAside(r) {
+ return true
+ }
+ return r.Root == "/etc/systemd/system" && r.Type == "l" && (strings.HasPrefix(r.Target, "/usr/lib/") || strings.HasPrefix(r.Target, "/lib/"))
+ },
+ })
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { reg.Close() })
+ c := &leoCensusTree{roots: roots, r: ClaimRuntimeResources{Mode: "instance-control", Registry: reg, DataDir: roots["data"], OptDir: roots["opt"], UnitsDir: roots["units"]}}
+ c.snap.Report.Installations = []hostops.CensusInstallation{}
+ for _, r := range leoRecords(t) {
+ if !slices.Contains(keep, r.Holder.Host) {
+ continue
+ }
+ var rec provision.Record
+ if err := json.Unmarshal(r.Body, &rec); err != nil {
+ t.Fatal(err)
+ }
+ c.snap.Records = append(c.snap.Records, rec)
+ }
+ return c
+}
+
+// The empty-leo flow's census on leo's real tree, under the window's masks:
+// with B1 and B2 done it accepts, whether the bucket keeps no record (the
+// trial's ruling) or rollcheck's and wakecheck's. Without B2, and with
+// wakecheck's record deleted, wakecheck's leftovers refuse, naming them; so
+// do claimtrial's, whose record is gone whatever B1 kept.
+func TestMigrationCensusClassifiesEmptyLeo(t *testing.T) {
+ for name, keep := range map[string][]string{"zero hosts": nil, "two hosts": {leoRollcheck, leoWakecheck}} {
+ t.Run(name, func(t *testing.T) {
+ c := newEmptyLeoCensusTree(t, keep, true)
+ if err := c.check(t, allWindowUnits()); err != nil {
+ t.Fatalf("empty leo under the window's masks: %v", err)
+ }
+ if err := c.check(t, nil); !errors.Is(err, hostbox.ErrTypedInventory) || !strings.Contains(err.Error(), "units entry") {
+ t.Fatalf("masks without --window = %v", err)
+ }
+ c = newEmptyLeoCensusTree(t, keep, false)
+ err := c.check(t, allWindowUnits())
+ if !errors.Is(err, hostbox.ErrTypedInventory) {
+ t.Fatalf("leftovers not moved aside = %v, want a refusal", err)
+ }
+ if !strings.Contains(err.Error(), "claimtrial") && !strings.Contains(err.Error(), "wakecheck") {
+ t.Fatalf("leftovers refusal does not name them: %v", err)
+ }
+ t.Logf("without B2: %v", err)
+ })
+ }
+}
diff --git a/internal/host/claimstep8_ruling6_test.go b/internal/host/claimstep8_ruling6_test.go
index 69812bb94..1669cbca9 100644
--- a/internal/host/claimstep8_ruling6_test.go
+++ b/internal/host/claimstep8_ruling6_test.go
@@ -4,7 +4,9 @@ import (
"go/ast"
"go/parser"
"go/token"
+ "io/fs"
"os"
+ "path/filepath"
"slices"
"sort"
"strings"
@@ -79,6 +81,79 @@ func TestStep8CensusChangesReachOnlyClaimMode(t *testing.T) {
t.Errorf("%s is called from %v, want %v", name, got, w)
}
}
+ checkBackfillDoneCallers(t)
+}
+
+// Ruling 6 for backfill-done (claim trial Option B): the new signer phase is
+// reached only through carlos system claims run on the trusted signer, and
+// its copy of the census's report check is reached only by Done.
+// The whole module's non-test sources are scanned, so a call from a box,
+// console or agent path fails here first. Backfill.Done is matched as a
+// three-argument Done call (ctx, signer, etag): context's Done takes none.
+func checkBackfillDoneCallers(t *testing.T) {
+ t.Helper()
+ callers := map[string][]string{}
+ fset := token.NewFileSet()
+ for _, root := range []string{"../..", "../../cmd", "../../internal"} {
+ err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ if path != root && (root == "../.." || strings.HasPrefix(d.Name(), ".") || d.Name() == "testdata" || d.Name() == "vendor") {
+ return filepath.SkipDir
+ }
+ return nil
+ }
+ if !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
+ return nil
+ }
+ f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
+ if err != nil {
+ return err
+ }
+ rel, _ := filepath.Rel("../..", filepath.Dir(path))
+ for _, decl := range f.Decls {
+ fn, ok := decl.(*ast.FuncDecl)
+ if !ok || fn.Body == nil {
+ continue
+ }
+ name := rel + " " + fn.Name.Name
+ ast.Inspect(fn.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ switch f := call.Fun.(type) {
+ case *ast.Ident:
+ if f.Name == "verifyCensusReport" {
+ callers[f.Name] = append(callers[f.Name], name)
+ }
+ case *ast.SelectorExpr:
+ if f.Sel.Name == "backfillDone" || (f.Sel.Name == "Done" && len(call.Args) == 3) {
+ callers[f.Sel.Name] = append(callers[f.Sel.Name], name)
+ }
+ }
+ return true
+ })
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := map[string][]string{
+ "Done": {"internal/claimactivation backfillDone"},
+ "backfillDone": {"internal/claimactivation Run"},
+ "verifyCensusReport": {"internal/hostops Done"},
+ }
+ for name, w := range want {
+ got := slices.Compact(sortedCopy(callers[name]))
+ if !slices.Equal(got, w) {
+ t.Errorf("%s is called from %v, want %v", name, got, w)
+ }
+ }
}
func sortedCopy(s []string) []string {
diff --git a/internal/host/claimstep8_witness_rootrunner_linux_test.go b/internal/host/claimstep8_witness_rootrunner_linux_test.go
index 22ef5f120..37c3c9e44 100644
--- a/internal/host/claimstep8_witness_rootrunner_linux_test.go
+++ b/internal/host/claimstep8_witness_rootrunner_linux_test.go
@@ -66,9 +66,53 @@ import (
// witness uses); the root floor history and guard binary (guard-arm,
// step 6); claimtrial's registry row (leo-routes.tsv); and, in the second
// test only, sophie's census report, which nothing on dev can produce.
-func TestRootStep8WindowWitnessDevRoster(t *testing.T) { rootStep8Witness(t, false) }
+//
+// On the dev roster, after step 4, backfill-done is also run against leo's
+// real report: it names claimtrial, so done refuses (fail-closed on
+// installations).
+func TestRootStep8WindowWitnessDevRoster(t *testing.T) { rootStep8Witness(t, step8Shape{}) }
+
+func TestRootStep8WindowWitnessSophieReported(t *testing.T) {
+ rootStep8Witness(t, step8Shape{sophieReports: true})
+}
+
+// The empty-leo flow (claim trial Option B, Paul's D1 of 2026-10-20): the
+// dev records are deleted before the window (B1; all of them, as the
+// controller ruled after the live precheck, or all but rollcheck-0261 and
+// wakecheck, the two-host shape), and claimtrial's and wakecheck's leftovers
+// on leo are moved aside out of /data and /opt/carlos (B2). Leo's real tree
+// then runs without claimtrial's registry row and without those leftovers,
+// under 8.1's masks:
+//
+// 1. 8.1's masks, as above;
+// 2. backfill-collect freezes the records left (zero, or two);
+// 3. journal-migrate without --window still refuses the masks;
+// 4. journal-migrate --window under umask 077 completes, and leo's signed
+// census report lists zero installations;
+// 5. backfill-done, dry run then apply: done under If-Match over the
+// collecting plan, sophie (no census key) unreported, and the
+// production CheckCreateFreeze accepts the plan; the console's adoption
+// pass is a no-op on it and gives no host a claim.
+//
+// Scaffold writes are those above less claimtrial's registry row, less the
+// deleted records and their domain claims, and with no stand-in report for
+// sophie. Nothing on the window's path (the plan in both phases, leo's
+// census report, the migration, the masks) is hand-made.
+func TestRootStep8WindowWitnessEmptyLeoZeroHosts(t *testing.T) {
+ rootStep8Witness(t, step8Shape{empty: true})
+}
-func TestRootStep8WindowWitnessSophieReported(t *testing.T) { rootStep8Witness(t, true) }
+func TestRootStep8WindowWitnessEmptyLeoTwoHosts(t *testing.T) {
+ rootStep8Witness(t, step8Shape{empty: true, keep: []string{leoRollcheck, leoWakecheck}})
+}
+
+type step8Shape struct {
+ // sophieReports gives sophie a census key and a stand-in report.
+ sophieReports bool
+ // empty is Option B: B1 and B2 done, and keep the records B1 left.
+ empty bool
+ keep []string
+}
const (
step8Window = "/etc/carlos/claim-window-cohort1-20261021T0900Z"
@@ -78,7 +122,8 @@ const (
step8ID = "cohort1-20261021"
)
-func rootStep8Witness(t *testing.T, sophieReports bool) {
+func rootStep8Witness(t *testing.T, shape step8Shape) {
+ sophieReports := shape.sophieReports
if os.Geteuid() != 0 {
t.Fatal("designated runner must execute as root")
}
@@ -136,6 +181,9 @@ func rootStep8Witness(t *testing.T, sophieReports bool) {
if r.Root == "/data" && strings.HasPrefix(r.Path, "registry.db") {
return true
}
+ if shape.empty && step8MovedAside(r) {
+ return true
+ }
return r.Root == "/opt/carlos" && (r.Path == "system" || strings.HasPrefix(r.Path, "system/") || r.Path == "carlos" || strings.HasPrefix(r.Path, "carlos.prev"))
},
})
@@ -216,6 +264,9 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
}
records := map[string]hostops.Record{}
for _, r := range leoRecords(t) {
+ if shape.empty && !slices.Contains(shape.keep, r.Holder.Host) {
+ continue // deleted at B1
+ }
if _, err := store.Put(ctx, r.Holder.Key, r.Body, ""); err != nil {
t.Fatal(err)
}
@@ -229,14 +280,17 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
t.Fatal(err)
}
}
- // Leo's registry: its one route (leo-routes.tsv), owned as on leo.
+ // Leo's registry: its one route (leo-routes.tsv), owned as on leo; none
+ // once B1 has retired claimtrial.
reg, err := registry.Open(filepath.Join(data, "registry.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { reg.Close() })
- if err := reg.Upsert(leoRoute(data)); err != nil {
- t.Fatal(err)
+ if !shape.empty {
+ if err := reg.Upsert(leoRoute(data)); err != nil {
+ t.Fatal(err)
+ }
}
for _, suffix := range []string{"", "-wal", "-shm"} {
if err := os.Lchown(filepath.Join(data, "registry.db"+suffix), uid, gid); err != nil && !os.IsNotExist(err) {
@@ -283,7 +337,7 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
// 2. backfill-collect, dry run then apply.
runner := claimactivation.Runner{Directory: directory, Signer: signer}
collect := claimactivation.Plan{Phase: "backfill-collect", Bucket: step8Bucket, ExpectedRevision: 9, Backfill: &claimactivation.BackfillInput{ID: step8ID}}
- if res, err := runner.Run(ctx, collect, true); err != nil || len(res.Backfill.Hosts) != 3 {
+ if res, err := runner.Run(ctx, collect, true); err != nil || len(res.Backfill.Hosts) != len(records) {
t.Fatalf("backfill-collect dry run: %+v %v", res.Backfill, err)
}
res, err := runner.Run(ctx, collect, false)
@@ -336,6 +390,14 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
if err := json.Unmarshal(reportRaw, &envelope); err != nil {
t.Fatal(err)
}
+ if shape.empty {
+ if envelope.Report.Installations == nil || len(envelope.Report.Installations) != 0 {
+ t.Fatalf("leo's census report: %+v", envelope.Report.Installations)
+ }
+ t.Logf("journal-migrate --window: complete; leo's report lists zero installations (%d hosts frozen)", len(records))
+ rootStep8Done(t, store, directory, runner, shape)
+ return
+ }
inc, _ := records[leoClaimtrial].Incarnation()
if len(envelope.Report.Installations) != 1 || envelope.Report.Installations[0] != (hostops.CensusInstallation{Host: leoClaimtrial, Account: "bab", App: "claimtrial", Family: "instance", Key: records[leoClaimtrial].Holder.Key, Incarnation: inc, Route: true}) {
t.Fatalf("leo's census report: %+v", envelope.Report.Installations)
@@ -345,6 +407,14 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
// 5. backfill-adopt.
adopt := claimactivation.Plan{Phase: "backfill-adopt", Bucket: step8Bucket, ExpectedRevision: 9, Backfill: &claimactivation.BackfillInput{ID: step8ID}}
if !sophieReports {
+ // backfill-done over leo's real report, which names claimtrial
+ // (B1 skipped): fail-closed, the plan stays collecting.
+ done := claimactivation.Plan{Phase: "backfill-done", Bucket: step8Bucket, ExpectedRevision: 9, Backfill: &claimactivation.BackfillInput{ID: step8ID}}
+ if _, doneErr := runner.Run(ctx, done, false); !errors.Is(doneErr, claimactivation.ErrBackfillInstallations) {
+ t.Fatalf("backfill-done over leo's report naming claimtrial = %v, want the installations refusal", doneErr)
+ } else {
+ t.Logf("backfill-done refused over leo's report naming claimtrial: %v", doneErr)
+ }
_, err := runner.Run(ctx, adopt, false)
if !errors.Is(err, os.ErrNotExist) {
t.Fatalf("backfill-adopt on the dev roster = %v, want sophie's missing census report refused", err)
@@ -420,6 +490,57 @@ systemctl show "${UNITS[@]}" -p Id -p LoadState -p ActiveState
t.Logf("STOP S4: root refuses the adopted legacy host before any seed admission: %v", err)
}
+// rootStep8Done is the empty-leo flow's step 5: backfill-done, dry run then
+// apply, through the production runner, then the console's own readers.
+func rootStep8Done(t *testing.T, store release.Store, directory hostactors.Directory, runner claimactivation.Runner, shape step8Shape) {
+ t.Helper()
+ ctx := t.Context()
+ _, collectingTag, err := store.Get(ctx, hostops.BackfillKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ done := claimactivation.Plan{Phase: "backfill-done", Bucket: step8Bucket, ExpectedRevision: 9, Backfill: &claimactivation.BackfillInput{ID: step8ID}}
+ dry, err := runner.Run(ctx, done, true)
+ if err != nil || len(dry.Writes) != 1 || dry.Writes[0].BeforeETag != collectingTag || dry.Backfill.Phase != "done" {
+ t.Fatalf("backfill-done dry run: %+v %v", dry, err)
+ }
+ if _, tag, err := store.Get(ctx, hostops.BackfillKey); err != nil || tag != collectingTag {
+ t.Fatalf("backfill-done dry run wrote the plan: %v", err)
+ }
+ if err := hostops.CheckCreateFreeze(ctx, store, directory.PublicKey); !errors.Is(err, hostops.ErrPending) {
+ t.Fatalf("freeze while collecting = %v", err)
+ }
+ res, err := runner.Run(ctx, done, false)
+ if err != nil {
+ t.Fatal("backfill-done", err)
+ }
+ if res.Backfill.Phase != "done" || len(res.Backfill.Hosts) != len(shape.keep) || !slices.Equal(res.Backfill.Unreported, []string{step8Sophie}) || len(res.Backfill.Reports) != 1 || res.Backfill.Reports[step8Leo] == "" {
+ t.Fatalf("backfill-done: %+v", res.Backfill)
+ }
+ if len(res.Writes) != 1 || res.Writes[0].Key != hostops.BackfillKey || res.Writes[0].BeforeETag != collectingTag {
+ t.Fatalf("backfill-done writes: %+v", res.Writes)
+ }
+ var plan hostops.BackfillPlan
+ raw, _, err := store.Get(ctx, hostops.BackfillKey)
+ if err != nil || release.VerifyRootEnvelope(directory.PublicKey, raw, &plan) != nil || plan.Phase != "done" || plan.Hosts == nil || len(plan.Hosts) != len(shape.keep) {
+ t.Fatalf("the done plan: %+v %v", plan, err)
+ }
+ if err := hostops.CheckCreateFreeze(ctx, store, directory.PublicKey); err != nil {
+ t.Fatalf("CheckCreateFreeze after done = %v", err)
+ }
+ t.Logf("backfill-done: done under If-Match; %d hosts; unreported %v; CheckCreateFreeze nil", len(plan.Hosts), res.Backfill.Unreported)
+ // The console's adoption pass, as production builds it, does nothing.
+ serial := 0
+ controller := hostops.NewBackfillController(store, directory, time.Now, func() string { serial++; return "witness-op-" + strconv.Itoa(serial) })
+ if err := controller.ReconcileClaims(ctx); err != nil {
+ t.Fatalf("adoption pass over the done plan = %v", err)
+ }
+ if keys, err := store.List(ctx, "control/hosts/"); err != nil || len(keys) != 0 {
+ t.Fatalf("host claims after the adoption pass: %v %v", keys, err)
+ }
+ t.Logf("adoption pass over the done plan: no-op, no host claim")
+}
+
// installLeoUnits writes leo's carlos units, drop-ins and enablement links
// into this runner's /etc/systemd/system: unit files with the embedded
// bytes leo's were installed from, drop-ins with a minimal body, and the
diff --git a/internal/host/rootmigration_routes_linux_test.go b/internal/host/rootmigration_routes_linux_test.go
index 40b211d13..4d8d52fdc 100644
--- a/internal/host/rootmigration_routes_linux_test.go
+++ b/internal/host/rootmigration_routes_linux_test.go
@@ -105,3 +105,57 @@ func TestRootMigrationCensusReportsLegacyRoutes(t *testing.T) {
})
}
}
+
+// The dev trial deletes every instance record before the window, so the
+// collecting plan freezes zero hosts ("hosts":{}). The migration census
+// accepts it on a box with no route rows, reports zero installations, and
+// the signer's backfill-done closes it over that report.
+func TestRootMigrationCensusAcceptsAZeroHostPlan(t *testing.T) {
+ store, _, owners, _ := fix4JournalFixture(t)
+ actor, err := owners.Identity.Verify(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
+ signer := release.RootSigner(key)
+ directory := owners.RetirementAuthority.Directory
+ roster, err := directory.Read(t.Context())
+ if err != nil {
+ t.Fatal(err)
+ }
+ plan := hostops.BackfillPlan{V: 1, ID: "migration", Phase: "collecting", DirectoryRevision: roster.Roster.Revision, CreatedAt: time.Now().Add(-time.Minute), Hosts: map[string]hostops.BackfillHost{}}
+ raw, err := release.SignRootEnvelope(signer, plan)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tag, err := store.Put(t.Context(), hostops.BackfillKey, raw, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ c := rootMigrationCollector{store: store, directory: directory, identity: rootMigrationIdentity{Deployment: actor.ControlBucket, Box: actor.Box, Enrollment: actor.Enrollment, Generation: 1},
+ seeds: &migrationSeeds{}, installations: func(context.Context) ([]hostguard.FenceView, error) { return nil, nil }, launches: func(context.Context) ([]hostbox.LaunchInventory, error) { return nil, nil },
+ reservations: func(context.Context) ([]release.GenerationReservation, error) { return nil, nil }, boot: func() (string, error) { return "boot", nil },
+ routes: func() ([]registry.Route, error) { return nil, nil }, dataDir: t.TempDir()}
+ s, err := c.collect(t.Context())
+ if err != nil {
+ t.Fatal("collect over a zero-host plan:", err)
+ }
+ if err := s.preflight(c.identity); err != nil {
+ t.Fatal(err)
+ }
+ if s.Report.Installations == nil || len(s.Report.Installations) != 0 || len(s.Records) != 0 || len(s.Items) != 0 {
+ t.Fatalf("zero-host census = %+v", s)
+ }
+ if err := hostops.PublishCensusReport(t.Context(), store, directory, s.Report, owners.EvidenceKey); err != nil {
+ t.Fatal(err)
+ }
+ b := &hostops.Backfill{Store: store, Directory: directory}
+ unreported, err := b.Done(t.Context(), signer, tag)
+ if err != nil {
+ t.Fatal("done over the zero-host census:", err)
+ }
+ if err := hostops.CheckCreateFreeze(t.Context(), store, directory.PublicKey); err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("done over zero hosts; unreported %v", unreported)
+}
diff --git a/internal/hostops/backfill_done_test.go b/internal/hostops/backfill_done_test.go
new file mode 100644
index 000000000..17b48a3d6
--- /dev/null
+++ b/internal/hostops/backfill_done_test.go
@@ -0,0 +1,470 @@
+package hostops
+
+import (
+ "bytes"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "slices"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/hostclaim"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const (
+ doneOne = "one.shop.example.com"
+ doneTwo = "two.shop.example.com"
+)
+
+// doneOtherKey signs the plan a wrong signer wrote. Fixed, so a mutation
+// check can name it.
+var doneOtherKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{9}, ed25519.SeedSize))
+
+// keyless re-signs the roster with these boxes' census keys removed: the dev
+// roster's shape, where sophie has no key.
+func (a *activation) keyless(refs ...string) {
+ a.t.Helper()
+ for _, ref := range refs {
+ box := a.roster.Boxes[ref]
+ box.CensusPublicKey = nil
+ a.roster.Boxes[ref] = box
+ }
+ _, tag, err := a.f.store.Get(a.ctx, "control/host-actors.json")
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ raw, err := release.SignRootEnvelope(a.sg, a.roster)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if _, err := a.f.store.Put(a.ctx, "control/host-actors.json", raw, tag); err != nil {
+ a.t.Fatal(err)
+ }
+}
+
+// collecting writes backfill-collect's plan over the records (no box, no
+// region), edited by edit when it is not nil, signed by signer.
+func (a *activation) collecting(signer release.Signer, edit func(*BackfillPlan)) string {
+ a.t.Helper()
+ p := BackfillPlan{V: 1, ID: "backfill", Phase: "collecting", DirectoryRevision: 1, CreatedAt: a.f.now, Hosts: map[string]BackfillHost{}}
+ for _, r := range a.records {
+ p.Hosts[r.Holder.Host] = BackfillHost{Key: r.Holder.Key, ETag: r.ETag, Acquisition: r.Holder.Acquisition}
+ }
+ if edit != nil {
+ edit(&p)
+ }
+ raw, err := release.SignRootEnvelope(signer, p)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ _, before, err := a.f.store.Get(a.ctx, BackfillKey)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ a.t.Fatal(err)
+ }
+ tag, err := a.f.store.Put(a.ctx, BackfillKey, raw, before)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ return tag
+}
+
+// emptyReport is a box's complete census report for the reservation, as
+// the migration census writes it on an empty box.
+func (a *activation) emptyReport(ref string) CensusReport {
+ return CensusReport{Box: ref, Enrollment: a.roster.Boxes[ref].Enrollment, BootID: "boot", Reservation: "backfill", DirectoryRevision: 1,
+ CapturedAt: a.f.now, Complete: true, Installations: []CensusInstallation{}, Seeds: &CensusSeeds{Journaled: []string{}, Gated: []string{}}}
+}
+
+// rawReport signs report with key and writes it at the box's report key,
+// bypassing PublishCensusReport's own checks, as a broken box could.
+func (a *activation) rawReport(report CensusReport, key ed25519.PrivateKey) {
+ a.t.Helper()
+ canonical, err := json.Marshal(report)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ raw, err := json.Marshal(CensusEnvelope{Report: report, Signature: ed25519.Sign(key, canonical)})
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ k, err := reportKey("backfill", report.Box)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if _, err := a.f.store.Put(a.ctx, k, raw, ""); err != nil {
+ a.t.Fatal(err)
+ }
+}
+
+func (a *activation) installation(host string) CensusInstallation {
+ a.t.Helper()
+ for _, r := range a.records {
+ if r.Holder.Host == host {
+ inc, err := r.Incarnation()
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ return CensusInstallation{Host: host, Account: r.Holder.Account, App: r.Holder.App, Family: r.Holder.Family, Key: r.Holder.Key, Incarnation: inc, Route: true}
+ }
+ }
+ a.t.Fatalf("no record for %s", host)
+ return CensusInstallation{}
+}
+
+// The empty cohort: two records frozen, box-a (keyed) reports nothing,
+// box-b has no census key. Done writes done under If-Match with box-a's
+// digest only, returns box-b as unreported, and lifts the create freeze.
+// The console's adoption pass is a no-op on a done plan, adoption refuses
+// it, and a second done is refused.
+func TestBackfillDoneClosesAnEmptyCohort(t *testing.T) {
+ a := newActivation(t)
+ a.record(doneOne, nil)
+ a.record(doneTwo, nil)
+ a.keyless("box-b")
+ tag := a.collecting(a.sg, nil)
+ if err := CheckCreateFreeze(a.ctx, a.f.store, a.d.PublicKey); !errors.Is(err, ErrPending) {
+ t.Fatalf("freeze while collecting = %v", err)
+ }
+ if err := PublishCensusReport(a.ctx, a.f.store, a.d, a.emptyReport("box-a"), a.boxKeys["box-a"]); err != nil {
+ t.Fatal(err)
+ }
+ before := a.plan()
+ b := &Backfill{Store: a.f.store, Directory: a.d}
+ unreported, err := b.Done(a.ctx, a.sg, tag)
+ if err != nil || !slices.Equal(unreported, []string{"box-b"}) {
+ t.Fatalf("Done = %v, %v; want box-b unreported", unreported, err)
+ }
+ p := a.plan()
+ key, _ := reportKey("backfill", "box-a")
+ body, _, err := a.f.store.Get(a.ctx, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum := sha256.Sum256(body)
+ if p.Phase != "done" || len(p.Reports) != 1 || p.Reports["box-a"] != hex.EncodeToString(sum[:]) || p.ID != before.ID || !p.CreatedAt.Equal(before.CreatedAt) || p.DirectoryRevision != before.DirectoryRevision {
+ t.Fatalf("done plan = %+v", p)
+ }
+ for host, h := range before.Hosts {
+ if p.Hosts[host] != h {
+ t.Fatalf("%s changed: %+v -> %+v", host, h, p.Hosts[host])
+ }
+ }
+ if len(p.Hosts) != 2 {
+ t.Fatalf("hosts = %+v", p.Hosts)
+ }
+ if err := CheckCreateFreeze(a.ctx, a.f.store, a.d.PublicKey); err != nil {
+ t.Fatalf("freeze after done = %v", err)
+ }
+ serial := 0
+ c := NewBackfillController(a.f.store, a.d, func() time.Time { return a.f.now }, func() string { serial++; return fmt.Sprintf("op-%d", serial) })
+ if err := c.ReconcileClaims(a.ctx); err != nil {
+ t.Fatalf("adoption pass over a done plan = %v", err)
+ }
+ for _, host := range []string{doneOne, doneTwo} {
+ if obs, err := hostclaim.Read(a.ctx, a.f.store, host); err != nil || !obs.Absent {
+ t.Fatalf("%s gained a claim: %+v %v", host, obs.Claim, err)
+ }
+ }
+ if _, _, _, _, err := b.Adoption(a.ctx, a.records[0]); !errors.Is(err, ErrContract) {
+ t.Fatalf("Adoption on a done plan = %v", err)
+ }
+ _, doneTag, err := a.f.store.Get(a.ctx, BackfillKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := b.Done(a.ctx, a.sg, doneTag); !errors.Is(err, ErrDonePhase) {
+ t.Fatalf("second Done = %v", err)
+ }
+}
+
+// The dev trial's real shape: every instance record deleted before the
+// window, so the collecting plan freezes zero hosts. Its hosts are an empty
+// object, never null, and Done accepts an empty listing against it.
+func TestBackfillDoneWithZeroHosts(t *testing.T) {
+ a := newActivation(t)
+ a.keyless("box-b")
+ tag := a.collecting(a.sg, nil)
+ raw, _, err := a.f.store.Get(a.ctx, BackfillKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var wire struct {
+ Payload string `json:"payload"`
+ }
+ if err := json.Unmarshal(raw, &wire); err != nil {
+ t.Fatal(err)
+ }
+ payload, err := base64.StdEncoding.DecodeString(wire.Payload)
+ if err != nil || !bytes.Contains(payload, []byte(`"hosts":{}`)) {
+ t.Fatalf("zero-host plan payload = %s, %v; want \"hosts\":{}", payload, err)
+ }
+ if p := a.plan(); p.Hosts == nil || len(p.Hosts) != 0 {
+ t.Fatalf("zero-host plan hosts = %#v", p.Hosts)
+ }
+ if err := PublishCensusReport(a.ctx, a.f.store, a.d, a.emptyReport("box-a"), a.boxKeys["box-a"]); err != nil {
+ t.Fatal(err)
+ }
+ b := &Backfill{Store: a.f.store, Directory: a.d}
+ unreported, err := b.Done(a.ctx, a.sg, tag)
+ if err != nil || !slices.Equal(unreported, []string{"box-b"}) {
+ t.Fatalf("Done over zero hosts = %v, %v", unreported, err)
+ }
+ if p := a.plan(); p.Phase != "done" || p.Hosts == nil || len(p.Hosts) != 0 || len(p.Reports) != 1 {
+ t.Fatalf("done plan = %#v", p)
+ }
+ if err := CheckCreateFreeze(a.ctx, a.f.store, a.d.PublicKey); err != nil {
+ t.Fatal(err)
+ }
+ // A record that appears after a zero-host collect is refused.
+ b2 := newActivation(t)
+ b2.keyless("box-b")
+ tag = b2.collecting(b2.sg, nil)
+ if err := PublishCensusReport(b2.ctx, b2.f.store, b2.d, b2.emptyReport("box-a"), b2.boxKeys["box-a"]); err != nil {
+ t.Fatal(err)
+ }
+ b2.record(doneOne, nil)
+ if _, err := (&Backfill{Store: b2.f.store, Directory: b2.d}).Done(b2.ctx, b2.sg, tag); !errors.Is(err, ErrDoneRecords) {
+ t.Fatalf("Done with a record the zero-host plan does not name = %v", err)
+ }
+}
+
+// Every condition is its own refusal, and a refusal writes nothing: the
+// plan stays collecting, byte for byte, and creates stay frozen.
+func TestBackfillDoneRefusals(t *testing.T) {
+ type setup struct {
+ keyless []string // boxes with no census key (default box-b)
+ edit func(*BackfillPlan) // the collecting plan
+ signer bool // sign the plan with doneOtherKey
+ reports func(a *activation) // default: box-a's empty report
+ after func(a *activation) // changes after the reports
+ tag func(t string) string // the etag Done is given
+ }
+ for name, c := range map[string]struct {
+ s setup
+ want []error
+ }{
+ "etag": {setup{tag: func(string) string { return "other" }}, []error{ErrDoneETag}},
+ "envelope": {setup{signer: true}, []error{ErrDoneEnvelope}},
+ "phase": {setup{edit: func(p *BackfillPlan) { p.Phase = "adopting"; p.Reports = map[string]string{} }}, []error{ErrDonePhase}},
+ "record etag": {setup{after: func(a *activation) {
+ r := a.records[0]
+ if _, err := a.f.store.Put(a.ctx, r.Holder.Key, append(append([]byte(nil), r.Body...), '\n'), r.ETag); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneRecords}},
+ "record added": {setup{after: func(a *activation) { a.record("three.shop.example.com", nil) }}, []error{ErrDoneRecords}},
+ "record gone": {setup{after: func(a *activation) {
+ if err := release.DeleteIfMatch(a.ctx, a.f.store, a.records[1].Holder.Key, a.records[1].ETag); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneRecords}},
+ "acquisition": {setup{edit: func(p *BackfillPlan) {
+ h := p.Hosts[doneOne]
+ h.Acquisition = "other"
+ p.Hosts[doneOne] = h
+ }}, []error{ErrDoneRecords}},
+ "claim": {setup{after: func(a *activation) {
+ key, err := hostclaim.Key(doneOne)
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if _, err := a.f.store.Put(a.ctx, key, []byte(`{}`), ""); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneClaims}},
+ "admission": {setup{after: func(a *activation) {
+ key, err := AdmissionKey("bab", "shop")
+ if err != nil {
+ a.t.Fatal(err)
+ }
+ if _, err := a.f.store.Put(a.ctx, key, []byte(`{}`), ""); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneAdmission}},
+ "no report": {setup{reports: func(*activation) {}}, []error{ErrDoneReport, os.ErrNotExist}},
+ "keyed box without a report": {setup{keyless: []string{}}, []error{ErrDoneReport, os.ErrNotExist}},
+ "no keyed box": {setup{keyless: []string{"box-a", "box-b"}, reports: func(*activation) {}}, []error{ErrDoneReport}},
+ "report signature": {setup{reports: func(a *activation) { a.rawReport(a.emptyReport("box-a"), a.boxKeys["box-b"]) }}, []error{ErrDoneReport}},
+ "report revision": {setup{reports: func(a *activation) {
+ r := a.emptyReport("box-a")
+ r.DirectoryRevision = 2
+ a.rawReport(r, a.boxKeys["box-a"])
+ }}, []error{ErrDoneReport}},
+ "report reservation": {setup{reports: func(a *activation) {
+ r := a.emptyReport("box-a")
+ r.Reservation = "other"
+ a.rawReport(r, a.boxKeys["box-a"])
+ }}, []error{ErrDoneReport}},
+ "report incomplete": {setup{reports: func(a *activation) {
+ r := a.emptyReport("box-a")
+ r.Complete = false
+ a.rawReport(r, a.boxKeys["box-a"])
+ }}, []error{ErrDoneReport}},
+ "report captured before the plan": {setup{reports: func(a *activation) {
+ r := a.emptyReport("box-a")
+ r.CapturedAt = a.f.now.Add(-time.Second)
+ if err := PublishCensusReport(a.ctx, a.f.store, a.d, r, a.boxKeys["box-a"]); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneStale}},
+ "installations": {setup{reports: func(a *activation) {
+ r := a.emptyReport("box-a")
+ r.Installations = []CensusInstallation{a.installation(doneOne)}
+ if err := PublishCensusReport(a.ctx, a.f.store, a.d, r, a.boxKeys["box-a"]); err != nil {
+ a.t.Fatal(err)
+ }
+ }}, []error{ErrDoneInstallations}},
+ "roster moved": {setup{after: func(a *activation) {
+ a.roster.Revision = 2
+ a.keyless()
+ }}, []error{ErrPending}},
+ } {
+ t.Run(name, func(t *testing.T) {
+ a := newActivation(t)
+ a.record(doneOne, nil)
+ a.record(doneTwo, nil)
+ keyless := []string{"box-b"}
+ if c.s.keyless != nil {
+ keyless = c.s.keyless
+ }
+ a.keyless(keyless...)
+ signer := a.sg
+ if c.s.signer {
+ signer = release.RootSigner(doneOtherKey)
+ }
+ tag := a.collecting(signer, c.s.edit)
+ if c.s.reports != nil {
+ c.s.reports(a)
+ } else if err := PublishCensusReport(a.ctx, a.f.store, a.d, a.emptyReport("box-a"), a.boxKeys["box-a"]); err != nil {
+ t.Fatal(err)
+ }
+ if c.s.after != nil {
+ c.s.after(a)
+ }
+ if c.s.tag != nil {
+ tag = c.s.tag(tag)
+ }
+ before, beforeTag, err := a.f.store.Get(a.ctx, BackfillKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b := &Backfill{Store: a.f.store, Directory: a.d}
+ unreported, err := b.Done(a.ctx, a.sg, tag)
+ for _, want := range c.want {
+ if !errors.Is(err, want) {
+ t.Fatalf("Done = %v, %v; want %v", unreported, err, want)
+ }
+ }
+ after, afterTag, err := a.f.store.Get(a.ctx, BackfillKey)
+ if err != nil || !bytes.Equal(before, after) || beforeTag != afterTag {
+ t.Fatalf("a refused Done changed the plan (%v)", err)
+ }
+ if err := CheckCreateFreeze(a.ctx, a.f.store, a.d.PublicKey); err == nil {
+ t.Fatal("a refused Done lifted the create freeze")
+ }
+ })
+ }
+}
+
+// Done's copy of the census's per-box report check must accept and refuse
+// exactly what ProductionAuthority.census does (census is accepted-legacy
+// and stays untouched). Each variant is box-a's report; box-b's is valid.
+func TestDoneVerifiesReportsAsTheCensusDoes(t *testing.T) {
+ for name, c := range map[string]struct {
+ edit func(a *activation, r *CensusReport)
+ key string // signing box key (default box-a)
+ }{
+ "valid": {},
+ "valid with a host": {edit: func(a *activation, r *CensusReport) { r.Installations = []CensusInstallation{a.installation(doneOne)} }},
+ "other box's key": {key: "box-b"},
+ "other box": {edit: func(_ *activation, r *CensusReport) { r.Box = "box-b" }},
+ "other enrollment": {edit: func(_ *activation, r *CensusReport) { r.Enrollment = "x" }},
+ "other reservation": {edit: func(_ *activation, r *CensusReport) { r.Reservation = "other" }},
+ "other revision": {edit: func(_ *activation, r *CensusReport) { r.DirectoryRevision = 2 }},
+ "no boot": {edit: func(_ *activation, r *CensusReport) { r.BootID = "" }},
+ "no capture time": {edit: func(_ *activation, r *CensusReport) { r.CapturedAt = time.Time{} }},
+ "nil installations": {edit: func(_ *activation, r *CensusReport) { r.Installations = nil }},
+ "incomplete": {edit: func(_ *activation, r *CensusReport) { r.Complete = false }},
+ "unknown host": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Host = "x.example.com"
+ r.Installations = []CensusInstallation{i}
+ }},
+ "host twice": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ r.Installations = []CensusInstallation{i, i}
+ }},
+ "neither route nor local": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Route = false
+ r.Installations = []CensusInstallation{i}
+ }},
+ "other account": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Account = "zzz"
+ r.Installations = []CensusInstallation{i}
+ }},
+ "other key": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Key = "apps/x"
+ r.Installations = []CensusInstallation{i}
+ }},
+ "other family": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Family = "sidecar"
+ r.Installations = []CensusInstallation{i}
+ }},
+ "other incarnation": {edit: func(a *activation, r *CensusReport) {
+ i := a.installation(doneOne)
+ i.Incarnation = "x"
+ r.Installations = []CensusInstallation{i}
+ }},
+ } {
+ t.Run(name, func(t *testing.T) {
+ a := newActivation(t)
+ a.record(doneOne, nil)
+ a.collecting(a.sg, nil)
+ if err := PublishCensusReport(a.ctx, a.f.store, a.d, a.emptyReport("box-b"), a.boxKeys["box-b"]); err != nil {
+ t.Fatal(err)
+ }
+ r := a.emptyReport("box-a")
+ if c.edit != nil {
+ c.edit(a, &r)
+ }
+ key := a.boxKeys["box-a"]
+ if c.key != "" {
+ key = a.boxKeys[c.key]
+ }
+ k, _ := reportKey("backfill", "box-a")
+ canonical, _ := json.Marshal(r)
+ raw, _ := json.Marshal(CensusEnvelope{Report: r, Signature: ed25519.Sign(key, canonical)})
+ tag, err := a.f.store.Put(a.ctx, k, raw, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, censusErr := ProductionAuthority{Store: a.f.store, Directory: a.d}.census(a.ctx, "", "", "backfill", 0, nil)
+ records := map[string]Record{}
+ for _, rec := range a.records {
+ records[rec.Holder.Host] = rec
+ }
+ _, doneErr := verifyCensusReport(raw, tag, "box-a", a.roster.Boxes["box-a"], "backfill", a.roster.Revision, records)
+ if (censusErr == nil) != (doneErr == nil) {
+ t.Fatalf("census = %v, Done's check = %v", censusErr, doneErr)
+ }
+ if name == "valid" || name == "valid with a host" {
+ if doneErr != nil {
+ t.Fatalf("valid report refused: %v", doneErr)
+ }
+ } else if doneErr == nil {
+ t.Fatal("variant accepted")
+ }
+ })
+ }
+}
diff --git a/internal/hostops/backfill_publish.go b/internal/hostops/backfill_publish.go
index 547d12e2f..ada309d0e 100644
--- a/internal/hostops/backfill_publish.go
+++ b/internal/hostops/backfill_publish.go
@@ -8,8 +8,11 @@ import (
"encoding/hex"
"encoding/json"
"errors"
- "github.com/carlosframework/platform/internal/hostactors"
+ "fmt"
+ "os"
+ "sort"
+ "github.com/carlosframework/platform/internal/hostactors"
"github.com/carlosframework/platform/internal/release"
)
@@ -101,6 +104,220 @@ func (b *Backfill) Publish(ctx context.Context, signer release.Signer, collectin
return err
}
+// Backfill.Done's refusals, one per condition. They are diagnostics: the
+// claims run phase puts its own refusal in front of the ones an operator
+// acts on (the plan, the records, the installations).
+var (
+ ErrDoneETag = fmt.Errorf("%w: backfill done: the plan's etag is not the collecting plan's", ErrContract)
+ ErrDoneEnvelope = fmt.Errorf("%w: backfill done: the plan does not verify", ErrContract)
+ ErrDonePhase = fmt.Errorf("%w: backfill done: the plan is not collecting", ErrContract)
+ ErrDoneRecords = fmt.Errorf("%w: backfill done: the record listing is not the plan's", ErrIdentity)
+ ErrDoneClaims = fmt.Errorf("%w: backfill done: control/hosts/ lists a claim", ErrIdentity)
+ ErrDoneAdmission = fmt.Errorf("%w: backfill done: an app admission exists", ErrIdentity)
+ ErrDoneReport = fmt.Errorf("%w: backfill done: a keyed box's census report does not verify", ErrIdentity)
+ ErrDoneStale = fmt.Errorf("%w: backfill done: a census report was captured before the plan", ErrIdentity)
+ ErrDoneInstallations = fmt.Errorf("%w: backfill done: a census report lists installations", ErrIdentity)
+)
+
+// Done closes an empty cohort's collecting plan straight to done (claim
+// trial Option B, Paul's D1 of 2026-10-20). It adopts nothing, so it needs
+// no report from a box that cannot report: what it proves is that every box
+// that can report owns nothing, not that the others own everything else.
+//
+// Each of these is its own refusal, and a refusal writes nothing:
+// - the plan's etag is collectingETag;
+// - its root envelope verifies;
+// - it is collecting;
+// - the live record listing (Apps, Records) is the plan's hosts, by key,
+// etag and acquisition;
+// - control/hosts/ lists nothing;
+// - no app has an admission.json;
+// - every roster box with a census key has a report for the reservation
+// that verifies exactly as the census verifies it, captured no earlier
+// than the plan, listing no installation.
+//
+// Boxes with no census key are skipped and returned as unreported. The plan
+// is then written as done under If-Match, with the reporting boxes' digests,
+// read back, and CheckCreateFreeze must accept it.
+func (b *Backfill) Done(ctx context.Context, signer release.Signer, collectingETag string) ([]string, error) {
+ raw, tag, err := b.Store.Get(ctx, BackfillKey)
+ if err != nil {
+ return nil, err
+ }
+ if tag == "" || tag != collectingETag {
+ return nil, ErrDoneETag
+ }
+ var p BackfillPlan
+ if release.VerifyRootEnvelope(b.Directory.PublicKey, raw, &p) != nil || p.V != 1 || !safeSegment(p.ID) || p.CreatedAt.IsZero() || p.Hosts == nil {
+ return nil, ErrDoneEnvelope
+ }
+ if p.Phase != "collecting" {
+ return nil, ErrDonePhase
+ }
+ roster, err := b.Directory.Read(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if roster.Roster.Revision != p.DirectoryRevision {
+ return nil, ErrPending
+ }
+
+ // The live record listing, as the census and collect list it.
+ apps, err := Apps(ctx, b.Store)
+ if err != nil {
+ return nil, err
+ }
+ records := map[string]Record{}
+ for _, app := range apps {
+ rs, err := Records(ctx, b.Store, app.Account, app.Name)
+ if err != nil {
+ return nil, err
+ }
+ for _, r := range rs {
+ if _, dup := records[r.Holder.Host]; dup {
+ return nil, ErrDoneRecords
+ }
+ records[r.Holder.Host] = r
+ }
+ }
+ if len(records) != len(p.Hosts) {
+ return nil, ErrDoneRecords
+ }
+ for host, r := range records {
+ frozen, ok := p.Hosts[host]
+ if !ok || frozen.Key != r.Holder.Key || frozen.ETag != r.ETag || frozen.Acquisition == "" || frozen.Acquisition != r.Holder.Acquisition {
+ return nil, ErrDoneRecords
+ }
+ }
+
+ // No host claim, under the prefix the migration census lists.
+ claims, err := b.Store.List(ctx, "control/hosts/")
+ if err != nil {
+ return nil, err
+ }
+ if len(claims) != 0 {
+ return nil, ErrDoneClaims
+ }
+
+ // No app admission (apps/<account>/<app>/admission.json).
+ for _, app := range apps {
+ key, err := AdmissionKey(app.Account, app.Name)
+ if err != nil {
+ return nil, err
+ }
+ if _, _, err := b.Store.Get(ctx, key); err == nil {
+ return nil, ErrDoneAdmission
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return nil, err
+ }
+ }
+
+ // Every keyed box reports, and reports nothing.
+ refs := make([]string, 0, len(roster.Roster.Boxes))
+ for ref := range roster.Roster.Boxes {
+ refs = append(refs, ref)
+ }
+ sort.Strings(refs)
+ unreported := []string{}
+ p.Reports = map[string]string{}
+ for _, ref := range refs {
+ box := roster.Roster.Boxes[ref]
+ if len(box.CensusPublicKey) == 0 {
+ unreported = append(unreported, ref)
+ continue
+ }
+ key, err := reportKey(p.ID, ref)
+ if err != nil {
+ return nil, err
+ }
+ body, reportTag, err := b.Store.Get(ctx, key)
+ if err != nil {
+ return nil, errors.Join(ErrDoneReport, err)
+ }
+ report, err := verifyCensusReport(body, reportTag, ref, box, p.ID, roster.Roster.Revision, records)
+ if err != nil {
+ return nil, errors.Join(ErrDoneReport, err)
+ }
+ if report.CapturedAt.Before(p.CreatedAt) {
+ return nil, ErrDoneStale
+ }
+ if len(report.Installations) != 0 {
+ return nil, ErrDoneInstallations
+ }
+ sum := sha256.Sum256(body)
+ p.Reports[ref] = hex.EncodeToString(sum[:])
+ }
+ // A done with no report at all would prove nothing.
+ if len(p.Reports) == 0 {
+ return nil, ErrDoneReport
+ }
+ fresh, err := b.Directory.Read(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if fresh.ETag != roster.ETag {
+ return nil, ErrPending
+ }
+
+ p.Phase = "done"
+ body, err := release.SignRootEnvelope(signer, p)
+ if err != nil {
+ return nil, err
+ }
+ if _, err = b.Store.Put(ctx, BackfillKey, body, tag); err != nil {
+ return nil, err
+ }
+ got, _, err := b.Store.Get(ctx, BackfillKey)
+ if err != nil {
+ return nil, err
+ }
+ if !bytes.Equal(got, body) {
+ return nil, ErrContract
+ }
+ if err := CheckCreateFreeze(ctx, b.Store, b.Directory.PublicKey); err != nil {
+ return nil, err
+ }
+ return unreported, nil
+}
+
+// verifyCensusReport is the census's acceptance of one roster box's report
+// for the reservation, for Backfill.Done: the envelope verifies under the
+// box's enrolled census key, the report is complete and names this box,
+// enrollment, reservation and roster revision, and every installation names
+// a listed record, once. It is ProductionAuthority.census's per-box check
+// line for line; census is an accepted-legacy unit and is left untouched,
+// and TestDoneVerifiesReportsAsTheCensusDoes holds the two together.
+func verifyCensusReport(raw []byte, tag, ref string, box hostactors.Box, reservation string, revision uint64, records map[string]Record) (CensusReport, error) {
+ var envelope CensusEnvelope
+ if decode(raw, &envelope) != nil {
+ return CensusReport{}, ErrIdentity
+ }
+ report := envelope.Report
+ canonical, e := json.Marshal(report)
+ if e != nil || len(box.CensusPublicKey) != ed25519.PublicKeySize || !ed25519.Verify(box.CensusPublicKey, canonical, envelope.Signature) {
+ return CensusReport{}, ErrIdentity
+ }
+ if tag == "" || !report.Complete || report.Box != ref || report.Enrollment != box.Enrollment || report.Reservation != reservation || report.DirectoryRevision != revision || report.BootID == "" || report.CapturedAt.IsZero() || report.Installations == nil {
+ return CensusReport{}, ErrIdentity
+ }
+ seen := map[string]bool{}
+ for _, i := range report.Installations {
+ if i.Host == "" || seen[i.Host] || (!i.Route && !i.Local) {
+ return CensusReport{}, ErrIdentity
+ }
+ seen[i.Host] = true
+ r, ok := records[i.Host]
+ if !ok || i.Account != r.Holder.Account || i.App != r.Holder.App || i.Key != r.Holder.Key || i.Family != r.Holder.Family {
+ return CensusReport{}, ErrIdentity
+ }
+ inc, err := r.Incarnation()
+ if err != nil || (i.Incarnation != "" && i.Incarnation != inc) {
+ return CensusReport{}, ErrIdentity
+ }
+ }
+ return report, nil
+}
+
// VerifyAdopting is the adopters' own acceptance of a published plan, run
// by the signer as readback after Publish: the signed plan reads adopting,
// and the complete census it froze verifies against its report digests, as
diff --git a/internal/provision/claim_step8_readiness_census_test.go b/internal/provision/claim_step8_readiness_census_test.go
index 63a782644..86bd1d5eb 100644
--- a/internal/provision/claim_step8_readiness_census_test.go
+++ b/internal/provision/claim_step8_readiness_census_test.go
@@ -14,12 +14,17 @@ package provision
// checkedStore, whose allow-list admits only that key for the phase. It
// reads records (hostops.Apps, hostops.Records) and writes none. Hence
// nonrecord.
+// - Backfill.Done, new (backfill-done, the empty cohort): its one Put is
+// the backfill manifest rewritten as done under the collecting etag
+// (If-Match), reached only from Runner.backfillDone through the
+// runner's checkedStore. It reads records, claims, admissions and
+// census reports and writes none of them. Hence nonrecord.
// - hostInstallationPaths, new: the "instances" literal names a host's
// nested data directory under the box's data root, for the migration
// census's classification. It builds no record key. Hence key-site.
func plan14ClaimStep8ReadinessWriteCensusInventory() []censusEntry {
entries := plan14ClaimStep6ArtifactsWriteCensusInventory()
- kept := make([]censusEntry, 0, len(entries)+3)
+ kept := make([]censusEntry, 0, len(entries)+4)
for _, e := range entries {
if e.File == "internal/hostops/backfill_publish.go" && e.Unit == "Backfill.Publish" {
continue
@@ -29,6 +34,7 @@ func plan14ClaimStep8ReadinessWriteCensusInventory() []censusEntry {
return append(kept,
censusEntry{"internal/hostops/backfill_publish.go", "Backfill.Publish", "nonrecord", "sel:Put", "92754dcc02c07fecaab58ef014bfb381c49ee5d90d5f5ca256bbfe275087d8b9"},
censusEntry{"internal/claimactivation/backfill.go", "Runner.backfillCollect", "nonrecord", "sel:Put", "ac53546891b2c6f982c0316595f86ff6b550250a3a4edcbc16d51d84fd18b06a"},
+ censusEntry{"internal/hostops/backfill_publish.go", "Backfill.Done", "nonrecord", "sel:Put", "9a5baeea4eace87c960d1df2a4b01487980b6b2b3f2aaf761835ae475ec34f4f"},
censusEntry{"internal/host/claimcensus_migration_linux.go", "hostInstallationPaths", "key-site", "lit:instances", "e697ca40c82911d63a5f8b401f61fee7e9e20552a2530ed358e55c4b8d827370"},
)
}
diff --git a/internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv b/internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv
index 2534d5041..8c683253d 100644
--- a/internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv
+++ b/internal/provision/testdata/plan14-root-reads-claim-step8-readiness.tsv
@@ -1,10 +1,11 @@
# Census overlay claim-step8-readiness (dev cohort-1 step 8 readiness: the backfill phases, leo's migration census classes, journal-migrate's window masks and umask, and the absent legacy directory), loaded LAST, after claim-guard-umask. Every row is PROPOSED to platform-1e as census owner; the proposal is docs/superpowers/notes/census-proposal-claim-step8-readiness.md.
-# Existing units keep their class and task exactly; their bases add what changed. New units: backfillReady (signer), legacyRouteRow, claimMigrationSharedPaths, verifyMigrationWindow and rootPrivateEntry (journal-migrate). It adds no accepted-legacy row, so the seal stands.
-@coverage internal/claimactivation 798e0c4e47cef053d27f7e0c476e2b1fa1e4ce62905a7886a2fb20fb26a2e623
+# Existing units keep their class and task exactly; their bases add what changed. New units: backfillReady and Backfill.Done (signer), legacyRouteRow, claimMigrationSharedPaths, verifyMigrationWindow and rootPrivateEntry (journal-migrate). It adds no accepted-legacy row, so the seal stands.
+@coverage internal/claimactivation fbb4d4d615bdb5c9aa7dece8c4cab680f0edf31aaf606b5f05ea50d4066f821f
@coverage internal/host 7af2df2472fe86811814416b977dbd5d782fd813636eaeafd143ef7025f228ad
@coverage internal/hostbox 46f97aa29603b9fcd9ee1f32fea80669c00df36601437eb5871b0cd83507e305
-@coverage internal/hostops 29aeb7672fc3fec094a15a3b378821f32832ca41858afeb5a25dfe841ee4d239
-internal/claimactivation/runner.go Runner.Run authority F,G,J4 rev3=PROPOSED-claim-step8-readiness;identity=explicit operator CLI uid 0 on the trusted signing host;basis=unchanged phases as ruled for claim-step6-artifacts; adds backfill-collect and backfill-adopt, whose only writable key is control/hosts-backfill.json, each write verified and read back, the dry-run overlay never calling backing Put file:Read@310,file:Read@6305,file:Read@7208 de4a7b1cbde996a1ea3ed4af10e9e15c97aa1118554f786d53a3b565df1e49b7
+@coverage internal/hostops 71bc9fe23edb5356320359700ce04409a4744214c796546c9856ca5d0c458368
+internal/claimactivation/runner.go Runner.Run authority F,G,J4 rev3=PROPOSED-claim-step8-readiness;identity=explicit operator CLI uid 0 on the trusted signing host;basis=unchanged phases as ruled for claim-step6-artifacts; adds backfill-collect, backfill-adopt and backfill-done, whose only writable key is control/hosts-backfill.json, each write verified and read back, the dry-run overlay never calling backing Put file:Read@310,file:Read@6322,file:Read@7365 2e16f7bcb0879a116f5b8ead539d424cd167cec3e8bb22bcb9c9d26568ca959d
+internal/hostops/backfill_publish.go Backfill.Done authority F,G,J4 rev3=PROPOSED-claim-step8-readiness;identity=explicit operator CLI uid 0 on the trusted signing host (carlos system claims run backfill-done, the only caller);basis=new: reads the signed collecting plan, the roster, the record listing, control/hosts/, each app's admission and each keyed box's signed census report, refusing unless the listing is the plan's, no claim or admission exists and every keyed report verifies as the census verifies it and lists no installation; its one write is the plan as done under the collecting etag (If-Match), read back and checked by CheckCreateFreeze; it adopts and installs nothing file:Read@3107,file:Read@544 9a5baeea4eace87c960d1df2a4b01487980b6b2b3f2aaf761835ae475ec34f4f
internal/claimactivation/backfill.go backfillReady authority F,G,J4 rev3=PROPOSED-claim-step8-readiness;identity=explicit operator CLI uid 0 on the trusted signing host;basis=refusal up front only: the signed roster must be published with a home region, and the published floor must verify under the release key to the roster's floor digest; it reads and grants nothing else file:Read@240 ebbb04dde23cff468ca19227aa30ba6f3de738d3de173c809b95c5bb438d5885
internal/host/claimjournal_migration.go RunSystemJournalMigrate authority G,J4 rev3=PROPOSED-claim-step8-readiness;identity=carlos system journal-migrate, offline operator CLI, uid 0;basis=explicit offline root operator entry requests full G2 bootstrap after verified claim owner setup; --window is checked before anything is written and only lets the census accept the named window's own masks 2e9b7b851f6aba29dcdcd607d950ab5ae26c6a4291becfa35ff91e05d443cd8c
internal/host/rootmigration_census.go rootMigrationCollector.collect authority G,J4 rev3=PROPOSED-claim-step8-readiness;identity=carlos system journal-migrate, offline operator CLI, uid 0;basis=signed collecting manifest and actor directory bound complete records/claims census; registry Seeds are refusal-only; with the agent stopped and masked, a legacy route row is reported as a route installation only when legacyRouteRow matches it to its frozen record, which only nominates this box for that record's adoption (checked again by the adopter against the signed census and the committed domain claim) and installs nothing; any other row refuses file:Exec@4684,file:Read@2868,file:Read@689,registry:Host@6224,registry:Host@6376,registry:Host@6578,registry:Host@6710,whole:Route@6193,whole:Route@6415 d1348e630d27e62d90643b9d73ee4ac0a1f11af720410430f23d113aa69f390d