package store import ( "context" "crypto/sha256" "path/filepath" "testing" "time" rvboxv1 "github.com/rvbox/rvbox/gen/go/rvbox/v1" ) func TestReconcileTombstonesStillValidateAndInterrupt_REC_RECONCILE_09(t *testing.T) { for _, scenario := range []string{"missing", "terminal", "running", "hash-mismatch"} { t.Run(scenario, func(t *testing.T) { ctx := context.Background() opened, err := Open(ctx, Options{DataDir: filepath.Join(t.TempDir(), "state"), BusyTimeout: time.Second}) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = opened.Close() }) now := time.Now().UTC() if _, err := opened.RegisterClientSession(ctx, ClientRegistration{ClientID: "tombstone-client", Platform: 3, Architecture: "amd64", DaemonVersion: "test", DaemonCWD: `C:\`, SupportedShells: []byte{1}, ClientInstanceID: [16]byte{1}, SessionID: [16]byte{2}, ConnectedAt: now}); err != nil { t.Fatal(err) } issue := mustReconcileIssue(t, "019c46f1-1d02-7000-8000-0000000000d2") hash := sha256.Sum256([]byte("terminal command")) if scenario != "missing" { if _, err := opened.QueueCommand(ctx, QueueCommandInput{IssueUUID: issue, ClientID: "tombstone-client", IssueTime: now, ReceiptTime: now, ImmutableSHA256: hash, ExecutionSpec: []byte("opaque")}); err != nil { t.Fatal(err) } phase := rvboxv1.CommandLifecycle_COMMAND_SUCCEEDED if scenario == "running" { phase = rvboxv1.CommandLifecycle_COMMAND_RUNNING } // Seed only the metadata being reconciled; no execution is involved. if _, err := opened.DB().ExecContext(ctx, `UPDATE commands SET lifecycle = ?, terminal_time = CASE WHEN ? >= 5 THEN ? ELSE NULL END WHERE issue_uuid = ?`, phase, phase, now.UnixNano(), issue[:]); err != nil { t.Fatal(err) } } if scenario == "hash-mismatch" { hash[0] ^= 0xff } result, err := opened.ReconcileClientSnapshotForSession(ctx, "tombstone-client", 1, &rvboxv1.ReconcileSnapshot{RetainedCommands: []*rvboxv1.ReconcileCommandState{{ IssueUuid: issue.String(), CommandRevision: 1, Lifecycle: rvboxv1.CommandLifecycle_COMMAND_SUCCEEDED, Tombstoned: true, ImmutableRequestSha256: hash[:], }}}) if err != nil { t.Fatal(err) } if len(result.GetDiscardLocalTerminalIssueUuids()) != 0 || len(result.GetTerminateLocalIssueUuids()) != 0 { t.Fatalf("already compacted tombstone needs no local action: %v", result) } var incidents int if err := opened.DB().QueryRowContext(ctx, `SELECT count(*) FROM storage_incidents`).Scan(&incidents); err != nil { t.Fatal(err) } wantIncidents := 0 if scenario == "running" || scenario == "hash-mismatch" { wantIncidents = 1 } if incidents != wantIncidents { t.Fatalf("incidents=%d, want %d", incidents, wantIncidents) } if scenario == "running" { view, err := opened.GetCommandView(ctx, "tombstone-client", issue) if err != nil || view.Lifecycle != uint32(rvboxv1.CommandLifecycle_COMMAND_INTERRUPTED) { t.Fatalf("tombstone must still interrupt contradictory running state: %+v, %v", view, err) } } }) } }