package host import ( "context" "errors" "slices" "strings" "testing" "github.com/carlosframework/platform/internal/activator" "github.com/carlosframework/platform/internal/genselect" "github.com/carlosframework/platform/internal/hostbox" "github.com/carlosframework/platform/internal/hostclaim" execctl "github.com/carlosframework/platform/internal/hostexec" "github.com/carlosframework/platform/internal/hostrelocate" ) // fakeReleaseReplica is the session's replicator as releaseFinalTXID sees // it: SyncAndWait. type fakeReleaseReplica struct { calls []string syncErr error } func (r *fakeReleaseReplica) SyncAndWait(context.Context) error { r.calls = append(r.calls, "sync") return r.syncErr } // Fix round 1, I2 (N1): an empty listing is not evidence of an empty // database. FinalTXID 0 comes only from writer session 0, a holder no // writer was ever admitted to; an empty listing for any other session (a // wrong bucket, a listing not yet visible) refuses. The listing is read // only after the replicator synced. func TestReleaseFinalTXIDIsZeroOnlyForWriterSessionZero(t *testing.T) { ctx := context.Background() failure := errors.New("s3: access denied") for _, tc := range []struct { name string session uint64 rep fakeReleaseReplica plan *genselect.Plan selErr error want uint64 refuses bool calls []string }{ {name: "the wrong bucket: an empty listing for writer session 6", session: 6, selErr: genselect.ErrEmpty, refuses: true}, {name: "a genuinely empty session-0 database", selErr: genselect.ErrEmpty, want: 0}, {name: "a listing at the database's position", session: 6, plan: &genselect.Plan{MaxTXID: 41, MaxLevel0TXID: 41}, want: 41}, {name: "level 0 behind the database", session: 6, plan: &genselect.Plan{MaxTXID: 41, MaxLevel0TXID: 40}, refuses: true}, {name: "a listing that fails", session: 6, selErr: failure, refuses: true}, {name: "a sync that fails", session: 0, rep: fakeReleaseReplica{syncErr: failure}, refuses: true, calls: []string{"sync"}}, } { t.Run(tc.name, func(t *testing.T) { rep := tc.rep selected := false sel := func(_ context.Context, r genselect.Request) (*genselect.Plan, error) { selected = true if r.Holder.Session != tc.session || r.Host != "shop.example" { t.Fatalf("selected for %+v", r) } return tc.plan, tc.selErr } got, err := releaseFinalTXID(ctx, &rep, sel, genselect.Request{Host: "shop.example", Holder: hostclaim.Holder{Session: tc.session}}) if tc.refuses { if err == nil { t.Fatalf("released at %d", got) } } else if err != nil || got != tc.want { t.Fatalf("got %d %v, want %d", got, err, tc.want) } if !slices.Equal(rep.calls, []string{"sync"}) || selected != (tc.calls == nil) { t.Fatalf("ran %v selected=%v", rep.calls, selected) } }) } } // relocationFlushDB has nothing to flush without the session's replicator: // no wake, no attempt for the host, no data bucket. func TestRelocationFlushDBNeedsTheSessionsReplicator(t *testing.T) { obs := hostclaim.Observed{Host: "shop.example", Claim: &hostclaim.Claim{Host: "shop.example", Holder: &hostclaim.Holder{Session: 0}}} cfg := RelocationAssemblyConfig{Bucket: "data"} for name, a := range map[string]ClaimAssembly{"no wake": {}, "no attempt": {Wake: &ClaimWakeAssembly{}}} { if _, err := a.relocationFlushDB(cfg)(context.Background(), obs); !errors.Is(err, ErrClaimStopUnavailable) { t.Fatalf("%s: %v", name, err) } } if _, err := (ClaimAssembly{Wake: &ClaimWakeAssembly{}}).relocationFlushDB(cfg)(context.Background(), hostclaim.Observed{Host: "shop.example"}); !errors.Is(err, ErrClaimStopUnavailable) { t.Fatalf("no claim: %v", err) } } // relocationRoot is root's isolated launcher as relocationPreflight asks // it: the protocol, then the capability for one kind. type relocationRoot struct { protocol string kindErr error asked []string } func (r *relocationRoot) Capability(context.Context) (string, error) { r.asked = append(r.asked, "protocol") return r.protocol, nil } func (*relocationRoot) Launch(context.Context, hostbox.RoleLaunchRequest) (hostbox.RoleLaunchGrant, error) { return hostbox.RoleLaunchGrant{}, errors.New("unused") } func (*relocationRoot) Stop(context.Context, hostbox.RoleLaunchRequest) error { return nil } func (r *relocationRoot) KindCapability(_ context.Context, kind string) error { r.asked = append(r.asked, "kind "+kind) return r.kindErr } // Fix round 1, M4: relocationPreflight (ruling 48) asks root for the // isolated launch protocol, then for kind relocating; either refusal is // the answer. After P's opening, until claim ask C11, a later attempt is // ErrLaterAttemptUnlaunchable without asking root (ruling 58). func TestRelocationPreflightAsksRootForTheRelocatingKind(t *testing.T) { ctx := context.Background() refused := errors.New("root: no attempt reader for relocating") probing := func(opened bool) hostclaim.Observed { j := map[string]string{"prepared": "P1", "prepared_authority": `{"generation":"P1"}`, "pin": `{"empty":true}`, "probing_since": "2026-10-07T02:00:00Z"} if opened { j["prepared_opened"] = "P1" } return hostclaim.Observed{Host: "shop.example", Claim: &hostclaim.Claim{Host: "shop.example", Holder: &hostclaim.Holder{Session: 7}, Op: hostclaim.Op{Kind: hostclaim.KindRelocating, ID: "rel-1", Phase: hostclaim.PhaseRelocatingProbing, Journal: j}}} } for _, tc := range []struct { name string root *relocationRoot opened bool later bool want error asked []string }{ {name: "root answers both", root: &relocationRoot{protocol: hostbox.RoleLaunchProtocol}, asked: []string{"protocol", "kind relocating"}}, {name: "root speaks another protocol", root: &relocationRoot{protocol: "old"}, want: activator.ErrClaimIsolationUnavailable, asked: []string{"protocol"}}, {name: "root refuses the kind", root: &relocationRoot{protocol: hostbox.RoleLaunchProtocol, kindErr: refused}, want: refused, asked: []string{"protocol", "kind relocating"}}, {name: "a later attempt before C11", root: &relocationRoot{protocol: hostbox.RoleLaunchProtocol}, opened: true, want: hostrelocate.ErrLaterAttemptUnlaunchable}, {name: "a later attempt once C11 is answered", root: &relocationRoot{protocol: hostbox.RoleLaunchProtocol}, opened: true, later: true, asked: []string{"protocol", "kind relocating"}}, } { t.Run(tc.name, func(t *testing.T) { a := ClaimAssembly{Wake: &ClaimWakeAssembly{Roles: &ClaimRoleAssembly{Root: tc.root}}} err := a.relocationPreflight(RelocationAssemblyConfig{LaterProbeAttempts: tc.later})(ctx, probing(tc.opened)) if (tc.want == nil && err != nil) || (tc.want != nil && !errors.Is(err, tc.want)) { t.Fatalf("err = %v, want %v", err, tc.want) } if !slices.Equal(tc.root.asked, tc.asked) { t.Fatalf("asked root %v, want %v", tc.root.asked, tc.asked) } }) } if err := (ClaimAssembly{}).relocationPreflight(RelocationAssemblyConfig{})(ctx, probing(false)); !errors.Is(err, activator.ErrClaimIsolationUnavailable) { t.Fatalf("no roles: %v", err) } } // Fix round 1, M4 (D5d): Acknowledge's one binding check. Main's // controller must be for exactly the observed op, incarnation and host; // any other is ErrLost, never an acknowledgement. func TestRelocationAcknowledgeBindsTheObservedOperation(t *testing.T) { ctx := context.Background() e, obs, _, _ := effectsFixture(t) ack, err := e.Acknowledge(ctx, obs) if err != nil || ack.Op != "rel-1" || ack.ControllerID != "c9" || ack.LeaseETag != "lease-1" || ack.Enrollment != "enr" || ack.BootID != "boot" { t.Fatalf("the bound acknowledgement: %+v %v", ack, err) } for name, change := range map[string]func(*execctl.State){ "another op": func(s *execctl.State) { s.Op = "rel-0" }, "another incarnation": func(s *execctl.State) { s.Incarnation = "inc-0" }, "another host": func(s *execctl.State) { s.Host = "other.example" }, } { e, obs, _, _ := effectsFixture(t) inner := e.Participation e.Participation = func(ctx context.Context, o hostclaim.Observed) (execctl.State, error) { st, err := inner(ctx, o) change(&st) return st, err } if ack, err := e.Acknowledge(ctx, obs); !errors.Is(err, execctl.ErrLost) { t.Fatalf("%s: acknowledged %+v %v", name, ack, err) } if err := e.Ready(ctx, obs); !errors.Is(err, execctl.ErrLost) { t.Fatalf("%s: ready %v", name, err) } } } // Fix round 1, M4: validOpID is the one op-id check for a name under the // data root. Release positions refuse every id it refuses. func TestValidOpIDRefusesEveryPathThatIsNotOneName(t *testing.T) { for _, op := range []string{"", ".", "..", "a/b", `a\b`, "a\x00b", "../rel-1", "rel-1/.."} { if validOpID(op) { t.Errorf("%q accepted", op) } f := ReleasePositionsFile{Dir: t.TempDir()} r := StopRequest{Host: "shop.example", OperationID: op} if err := f.Record(context.Background(), ReleasePosition{Request: r, PID: 1, ProcessStart: "1"}); !errors.Is(err, ErrClaimStopUnavailable) { t.Errorf("%q recorded: %v", op, err) } if _, _, err := f.Recorded(context.Background(), r); !errors.Is(err, ErrClaimStopUnavailable) { t.Errorf("%q read: %v", op, err) } } for _, op := range []string{"rel-1", ".rel", "rel..1", "a.b"} { if !validOpID(op) { t.Errorf("%q refused", op) } } } // Fix round 1, M4: the release's Collect provider is a recovery request // (StopRequest.Recover) exactly when the release offers the recovery // drain, after a restart; the process that flushed asks with its own // producers and no Recover. func TestRelocationCollectRecoversAfterARestart(t *testing.T) { ctx := context.Background() e, obs, _, _ := effectsFixture(t) var asked []StopRequest a := ClaimAssembly{collectStop: func(ctx context.Context, r StopRequest, d StopDrainer) (StopResult, error) { asked = append(asked, r) if !r.Recover { if _, err := d.DrainClaim(ctx, r, "fence"); err != nil { return StopResult{}, err } } return StopResult{Key: "control/hosts/shop.example/evidence/rel-1/src/r.json", Digest: strings.Repeat("a", 64)}, nil }} e.Collect = a.RelocationEffects(RelocationAssemblyConfig{}, nil).Collect if _, err := e.Release(ctx, obs); err != nil { t.Fatal(err) } e.Identity = func(context.Context) (RelocationIdentity, error) { return RelocationIdentity{Actor: hostbox.Actor{Box: "src", Enrollment: "enr", Revision: 4, Binding: "4"}, BootID: "boot-2", ControllerID: "ctl-2", PID: 200, ProcessStart: "9000"}, nil } if _, err := e.Release(ctx, obs); err != nil { t.Fatal(err) } if len(asked) != 2 || asked[0].Recover || !asked[1].Recover || asked[1].BootID != "boot" || asked[1].ControllerID != "ctl" { t.Fatalf("asked root %+v", asked) } }