feat: reconcile and release execution quarantine
32 files changed,
+1,790
−96
.rastrillo/budgets.txt+1 −1internal/equipo/authority.go+4 −1internal/equipo/budgets.go+10 −0internal/equipo/execution.go+33 −0internal/equipo/execution_models.go+46 −9internal/equipo/migrations/0008_recovery.sql+13 −0internal/equipo/migrations/schema.sql+12 −1internal/equipo/models.go+1 −0internal/equipo/projects.go+22 −1internal/equipo/recovery.go+119 −0internal/equipo/roster.go+7 −2internal/equipo/team/actions.go+7 −4internal/equipo/team/authority.go+1 −0internal/equipo/team/budget.go+3 −3internal/equipo/team/evidence.go+2 −2internal/equipo/team/harness_test.go+9 −0internal/equipo/team/jobs.go+20 −6internal/equipo/team/periodbudget.go+96 −19internal/equipo/team/periodbudget_test.go+2 −0internal/equipo/team/recovery.go+74 −15internal/equipo/team/recovery_release.go+205 −0internal/equipo/team/recovery_release_test.go+311 −0internal/equipo/team/review_regression_test.go+1 −0internal/equipo/team/scheduler.go+16 −2internal/equipo/team/scheduler_test.go+10 −4internal/equipo/team/settletime_test.go+8 −3internal/equipo/team/shared.go+8 −0internal/equipo/team/stop.go+243 −0internal/equipo/team/store.go+53 −15internal/equipotest/authority_test.go+9 −4internal/equipotest/execution_schema_test.go+42 −4internal/equipotest/recovery_test.go+402 −0
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 2e79f527..854391ed 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -9,7 +9,7 @@ |
| # time <dir> <duration> <reason> |
| # perf <METHOD> <path> <duration>|skip <reason> |
| # boot <duration> <reason> |
| -size internal/equipo/team 6500 - Preserve the copied transactional core; this budget extension covers its existing 5,243 source lines without splitting the store. |
| +size internal/equipo/team 7000 - Preserve the plan-mandated core layout; Task 2 adds quarantine release, recovery charges, grant fencing and conservative clock accounting to the copied transactional core. |
| perf GET /* skip Unknown private paths render 404; this fallback contains no screens. |
| time internal/equipo/team 15s Copied core crash, recovery and concurrency tests take about 7.7s idle and 13.6s on the loaded shared machine. |
| time internal/equipotest 15s Real NoProof sign-in ceremonies wait 3s each; the package takes about 9.3s. |
diff --git a/internal/equipo/authority.go b/internal/equipo/authority.go| index f814ad63..6dafe67a 100644 |
| --- a/internal/equipo/authority.go |
| +++ b/internal/equipo/authority.go |
| @@ -70,6 +70,9 @@ func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequ |
| if err != nil { |
| return team.Admission{}, err |
| } |
| + if req.Project != team.ProjectID(grant.ProjectID) { |
| + return team.Admission{}, team.ErrGrantRevoked |
| + } |
| switch req.Operation { |
| case team.OpJobContinue, team.OpAttemptContinue, team.OpProviderCall, team.OpForgePublish: |
| default: |
| @@ -127,7 +130,7 @@ func (a *RosterAuthority) Introspect(ctx context.Context, req team.AdmissionRequ |
| } |
| } |
| now := a.clock.Now() |
| - admission = team.Admission{Grant: req.Grant, Version: project.Revision, Epoch: instance.RosterEpoch, IssuedAt: now, ExpiresAt: now.Add(5 * time.Second)} |
| + admission = team.Admission{Grant: req.Grant, Version: project.GrantVersion, Epoch: instance.RosterEpoch, IssuedAt: now, ExpiresAt: now.Add(5 * time.Second)} |
| return nil |
| }, &sql.TxOptions{ReadOnly: true}) |
| if err != nil { |
diff --git a/internal/equipo/budgets.go b/internal/equipo/budgets.go| index fae57617..955c9a3e 100644 |
| --- a/internal/equipo/budgets.go |
| +++ b/internal/equipo/budgets.go |
| @@ -72,6 +72,16 @@ func (s *Store) SaveBudgets(ctx context.Context, actor Actor, config BudgetConfi |
| return ErrConflict |
| } |
| } |
| + if s.execution != nil { |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + b.Revision = config.Revision |
| + if err = s.execution.Core.SyncBudgetsTx(ctx, raw, team.AccountID(instance.ID), b); err != nil { |
| + return err |
| + } |
| + } |
| return appendAudit(tx, actor, "budget.save", instance.ID) |
| }) |
| } |
diff --git a/internal/equipo/execution.go b/internal/equipo/execution.go| index ced7cca7..fccb0328 100644 |
| --- a/internal/equipo/execution.go |
| +++ b/internal/equipo/execution.go |
| @@ -3,6 +3,8 @@ package equipo |
| import ( |
| "context" |
| "database/sql" |
| + "encoding/json" |
| + "errors" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/rastrillo/rastrillo/db" |
| @@ -29,6 +31,37 @@ func (s *Store) AttachExecution(ctx context.Context, path string, options team.O |
| return nil, err |
| } |
| x := &Execution{Core: core, db: s.db} |
| + if err := x.Write(ctx, func(tx *gorm.DB) error { |
| + var instance Team |
| + if err := tx.First(&instance).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + return err |
| + } |
| + var row budgetRecord |
| + if err := tx.Where("team_id = ?", instance.ID).First(&row).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return nil |
| + } |
| + return err |
| + } |
| + var config BudgetConfig |
| + if err := json.Unmarshal([]byte(row.Config), &config); err != nil { |
| + return err |
| + } |
| + if row.Revision != config.Revision { |
| + return ErrUnavailable |
| + } |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + return core.SyncBudgetsTx(ctx, raw, team.AccountID(instance.ID), team.BudgetSet{Revision: config.Revision, Team: config.Team, Projects: config.Projects}) |
| + }); err != nil { |
| + core.Close() |
| + return nil, err |
| + } |
| s.execution = x |
| return x, nil |
| } |
diff --git a/internal/equipo/execution_models.go b/internal/equipo/execution_models.go| index 851249fc..9edd55ae 100644 |
| --- a/internal/equipo/execution_models.go |
| +++ b/internal/equipo/execution_models.go |
| @@ -83,6 +83,7 @@ type executionEvents struct { |
| func (executionEvents) TableName() string { return "events" } |
| type executionJobs struct { |
| + GrantStale int64 `gorm:"type:integer;not null;default:0"` |
| ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| Account string `gorm:"column:account;type:text;not null;index:jobs_account,priority:1"` |
| Parent int64 `gorm:"column:parent;type:integer;not null"` |
| @@ -140,14 +141,18 @@ type executionReservations struct { |
| func (executionReservations) TableName() string { return "reservations" } |
| type executionService struct { |
| - ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| - SchemaVersion int64 `gorm:"column:schema_version;type:integer;not null"` |
| - Incarnation int64 `gorm:"column:incarnation;type:integer;not null"` |
| - Revision int64 `gorm:"column:revision;type:integer;not null;default:0"` |
| - RestoreUncertain int64 `gorm:"column:restore_uncertain;type:integer;not null;default:0"` |
| - AdmissionPaused int64 `gorm:"column:admission_paused;type:integer;not null"` |
| - Quarantine int64 `gorm:"column:quarantine;type:integer;not null"` |
| - QuarantineWhy string `gorm:"column:quarantine_why;type:text;not null"` |
| + ReleaseRequired int64 `gorm:"type:integer;not null;default:0"` |
| + RecoveryRevision int64 `gorm:"type:integer;not null;default:0"` |
| + ReconciledRevision int64 `gorm:"type:integer;not null;default:-1"` |
| + ClockHighWater string `gorm:"type:text;not null;default:''"` |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + SchemaVersion int64 `gorm:"column:schema_version;type:integer;not null"` |
| + Incarnation int64 `gorm:"column:incarnation;type:integer;not null"` |
| + Revision int64 `gorm:"column:revision;type:integer;not null;default:0"` |
| + RestoreUncertain int64 `gorm:"column:restore_uncertain;type:integer;not null;default:0"` |
| + AdmissionPaused int64 `gorm:"column:admission_paused;type:integer;not null"` |
| + Quarantine int64 `gorm:"column:quarantine;type:integer;not null"` |
| + QuarantineWhy string `gorm:"column:quarantine_why;type:text;not null"` |
| } |
| func (executionService) TableName() string { return "service" } |
| @@ -168,6 +173,7 @@ type executionSteps struct { |
| func (executionSteps) TableName() string { return "steps" } |
| type executionTimeReservations struct { |
| + ElapsedUnknown int64 `gorm:"type:integer;not null;default:0"` |
| AttemptID int64 `gorm:"column:attempt_id;type:integer;primaryKey;autoIncrement:false"` |
| Account string `gorm:"column:account;type:text;not null;index:time_reservations_account,priority:1"` |
| ProjectID int64 `gorm:"column:project_id;type:integer;not null;index:time_reservations_account,priority:2"` |
| @@ -181,4 +187,35 @@ type executionTimeReservations struct { |
| func (executionTimeReservations) TableName() string { return "time_reservations" } |
| -var executionModels = []any{&executionActions{}, &executionArtifacts{}, &executionAttempts{}, &executionEvents{}, &executionJobs{}, &executionPeriodBudgets{}, &executionReservations{}, &executionService{}, &executionSteps{}, &executionTimeReservations{}} |
| +var executionModels = []any{&executionGrantFences{}, &executionRecoveryCharges{}, &executionRecoveryEvents{}, &executionActions{}, &executionArtifacts{}, &executionAttempts{}, &executionEvents{}, &executionJobs{}, &executionPeriodBudgets{}, &executionReservations{}, &executionService{}, &executionSteps{}, &executionTimeReservations{}} |
| + |
| +type executionGrantFences struct { |
| + Ref string `gorm:"type:text;primaryKey"` |
| + Version int64 `gorm:"type:integer;not null"` |
| + Epoch int64 `gorm:"type:integer;not null"` |
| +} |
| + |
| +func (executionGrantFences) TableName() string { return "grant_fences" } |
| + |
| +type executionRecoveryCharges struct { |
| + Key string `gorm:"type:text;primaryKey"` |
| + Account string `gorm:"type:text;not null"` |
| + ProjectID int64 `gorm:"type:integer;not null"` |
| + Reserved string `gorm:"type:text;not null"` |
| + Actor string `gorm:"type:text;not null"` |
| + Reason string `gorm:"type:text;not null"` |
| + Incarnation int64 `gorm:"type:integer;not null"` |
| + CreatedAt string `gorm:"type:text;not null"` |
| +} |
| + |
| +func (executionRecoveryCharges) TableName() string { return "recovery_charges" } |
| + |
| +type executionRecoveryEvents struct { |
| + Revision int64 `gorm:"type:integer;primaryKey;autoIncrement:false"` |
| + Kind string `gorm:"type:text;not null"` |
| + Actor string `gorm:"type:text;not null"` |
| + Reason string `gorm:"type:text;not null"` |
| + SnapshotHash string `gorm:"type:text;not null"` |
| +} |
| + |
| +func (executionRecoveryEvents) TableName() string { return "recovery_events" } |
diff --git a/internal/equipo/migrations/0008_recovery.sql b/internal/equipo/migrations/0008_recovery.sql| new file mode 100644 |
| index 00000000..b9a5192b |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0008_recovery.sql |
| @@ -0,0 +1,13 @@ |
| + |
| +ALTER TABLE service ADD COLUMN release_required INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE service ADD COLUMN recovery_revision INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE service ADD COLUMN reconciled_revision INTEGER NOT NULL DEFAULT -1; |
| +ALTER TABLE service ADD COLUMN clock_high_water TEXT NOT NULL DEFAULT ""; |
| +ALTER TABLE jobs ADD COLUMN grant_stale INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE time_reservations ADD COLUMN elapsed_unknown INTEGER NOT NULL DEFAULT 0; |
| +CREATE TABLE grant_fences (ref TEXT PRIMARY KEY, version INTEGER NOT NULL, epoch INTEGER NOT NULL); |
| +CREATE TABLE recovery_charges (key TEXT PRIMARY KEY, account TEXT NOT NULL, project_id INTEGER NOT NULL, reserved TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, incarnation INTEGER NOT NULL, created_at TEXT NOT NULL); |
| +CREATE TABLE recovery_events (revision INTEGER PRIMARY KEY, kind TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, snapshot_hash TEXT NOT NULL); |
| +UPDATE service SET schema_version=4 WHERE id=1; |
| +ALTER TABLE projects ADD COLUMN grant_version INTEGER NOT NULL DEFAULT 1; |
| +UPDATE projects SET grant_version=revision; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 5589b75c..cc8259d4 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -83,6 +83,7 @@ CREATE TABLE events ( |
| ); |
| CREATE TABLE jobs ( |
| + grant_stale INTEGER NOT NULL DEFAULT 0, |
| id INTEGER PRIMARY KEY, |
| account TEXT NOT NULL, |
| parent INTEGER NOT NULL, |
| @@ -112,7 +113,8 @@ CREATE TABLE period_budgets ( |
| CREATE TABLE project_requests (actor text, operation text, request_id text, input_hash text, result text, PRIMARY KEY (actor, operation, request_id)); |
| -CREATE TABLE projects (id integer PRIMARY KEY AUTOINCREMENT, account_id integer, name text, repository text NOT NULL, app_name text NOT NULL, default_branch text, kind text, revision integer); |
| +CREATE TABLE projects ( |
| + grant_version INTEGER NOT NULL DEFAULT 1,id integer PRIMARY KEY AUTOINCREMENT, account_id integer, name text, repository text NOT NULL, app_name text NOT NULL, default_branch text, kind text, revision integer); |
| CREATE TABLE reservations ( |
| id INTEGER PRIMARY KEY, |
| @@ -131,6 +133,10 @@ CREATE TABLE reservations ( |
| ); |
| CREATE TABLE service ( |
| + release_required INTEGER NOT NULL DEFAULT 0, |
| + recovery_revision INTEGER NOT NULL DEFAULT 0, |
| + reconciled_revision INTEGER NOT NULL DEFAULT -1, |
| + clock_high_water TEXT NOT NULL DEFAULT "", |
| id INTEGER PRIMARY KEY CHECK (id = 1), |
| schema_version INTEGER NOT NULL, |
| incarnation INTEGER NOT NULL, |
| @@ -160,6 +166,7 @@ CREATE TABLE steps ( |
| CREATE TABLE teams (id text, name text, roster_epoch integer, PRIMARY KEY (id)); |
| CREATE TABLE time_reservations ( |
| + elapsed_unknown INTEGER NOT NULL DEFAULT 0, |
| attempt_id INTEGER PRIMARY KEY REFERENCES attempts(id), |
| account TEXT NOT NULL, project_id INTEGER NOT NULL, |
| job_id INTEGER NOT NULL REFERENCES jobs(id), period TEXT NOT NULL, |
| @@ -188,3 +195,7 @@ CREATE INDEX reservations_account ON reservations(account, state); |
| CREATE INDEX reservations_job ON reservations(job_id, state); |
| CREATE INDEX time_reservations_account ON time_reservations(account, project_id, state, period); |
| + |
| +CREATE TABLE grant_fences (ref TEXT PRIMARY KEY, version INTEGER NOT NULL, epoch INTEGER NOT NULL); |
| +CREATE TABLE recovery_charges (key TEXT PRIMARY KEY, account TEXT NOT NULL, project_id INTEGER NOT NULL, reserved TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, incarnation INTEGER NOT NULL, created_at TEXT NOT NULL); |
| +CREATE TABLE recovery_events (revision INTEGER PRIMARY KEY, kind TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, snapshot_hash TEXT NOT NULL); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 53203e9f..2d28eb79 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -51,6 +51,7 @@ const ( |
| ) |
| type Project struct { |
| + GrantVersion int64 `gorm:"not null;default:1"` |
| ID int64 |
| AccountID int64 |
| Name string |
diff --git a/internal/equipo/projects.go b/internal/equipo/projects.go| index 373399ba..411b2c0c 100644 |
| --- a/internal/equipo/projects.go |
| +++ b/internal/equipo/projects.go |
| @@ -246,13 +246,29 @@ func (s *Store) SaveProject(ctx context.Context, actor Actor, project Project, o |
| if duplicates != 0 { |
| return ErrBindingInUse |
| } |
| + changed := old.ID == 0 || old.Repository != project.Repository || old.AppName != project.AppName || old.DefaultBranch != project.DefaultBranch || old.Kind != project.Kind |
| + if old.ID != 0 { |
| + var priorWork DecisionOwner |
| + if err := tx.Where("project_id = ? AND decision = ?", old.ID, "work").First(&priorWork).Error; err != nil { |
| + return storeError(err) |
| + } |
| + for _, owner := range owners { |
| + if owner.Decision == "work" && owner.Address != priorWork.Address { |
| + changed = true |
| + } |
| + } |
| + } |
| + project.GrantVersion = old.GrantVersion |
| + if changed { |
| + project.GrantVersion++ |
| + } |
| project.Revision++ |
| if project.ID == 0 { |
| if err := tx.Create(&project).Error; err != nil { |
| return storeError(err) |
| } |
| } else { |
| - result := tx.Model(&Project{}).Where("id = ? AND revision = ?", project.ID, old.Revision).Select("AccountID", "Name", "Repository", "AppName", "DefaultBranch", "Kind", "Revision").Updates(&project) |
| + result := tx.Model(&Project{}).Where("id = ? AND revision = ?", project.ID, old.Revision).Select("AccountID", "Name", "Repository", "AppName", "DefaultBranch", "Kind", "Revision", "GrantVersion").Updates(&project) |
| if result.Error != nil { |
| return storeError(result.Error) |
| } |
| @@ -269,6 +285,11 @@ func (s *Store) SaveProject(ctx context.Context, actor Actor, project Project, o |
| if err := tx.Create(&owners).Error; err != nil { |
| return storeError(err) |
| } |
| + if changed { |
| + if err := s.fenceAuthority(ctx, tx, project.ID); err != nil { |
| + return err |
| + } |
| + } |
| if err := appendAudit(tx, actor, "project.save", strconv.FormatInt(project.ID, 10)); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/recovery.go b/internal/equipo/recovery.go| new file mode 100644 |
| index 00000000..7620c6ab |
| --- /dev/null |
| +++ b/internal/equipo/recovery.go |
| @@ -0,0 +1,119 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "gorm.io/gorm" |
| +) |
| + |
| +func executionTx(tx *gorm.DB) (*sql.Tx, error) { |
| + raw, ok := tx.Statement.ConnPool.(*sql.Tx) |
| + if !ok { |
| + return nil, ErrUnavailable |
| + } |
| + return raw, nil |
| +} |
| + |
| +func (s *Store) ReleaseExecution(ctx context.Context, actor Actor, expectedRevision int64, reason, snapshotHash string) error { |
| + if s == nil || s.execution == nil { |
| + return ErrUnavailable |
| + } |
| + return s.write(ctx, func(tx *gorm.DB) error { |
| + if err := requireOwner(tx, actor); err != nil { |
| + return err |
| + } |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + if err = s.execution.Core.ReleaseQuarantineTx(ctx, raw, expectedRevision, normalizeAddress(actor.Address), reason, snapshotHash); err != nil { |
| + return err |
| + } |
| + return appendAudit(tx, actor, "execution.release", strconv.FormatInt(expectedRevision, 10)) |
| + }) |
| +} |
| + |
| +func (s *Store) RecordRecoveryCharge(ctx context.Context, actor Actor, charge team.RecoveryCharge, reason string) error { |
| + if s == nil || s.execution == nil { |
| + return ErrUnavailable |
| + } |
| + return s.write(ctx, func(tx *gorm.DB) error { |
| + if err := requireOwner(tx, actor); err != nil { |
| + return err |
| + } |
| + var instance Team |
| + if err := tx.First(&instance).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if charge.Account != team.AccountID(instance.ID) { |
| + return ErrInvalid |
| + } |
| + var project Project |
| + if err := tx.First(&project, int64(charge.Project)).Error; err != nil { |
| + return storeError(err) |
| + } |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + var prior int64 |
| + if err = tx.Raw("SELECT count(*) FROM recovery_charges WHERE key=?", charge.Key).Scan(&prior).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err = s.execution.Core.RecordRecoveryChargeTx(ctx, raw, charge, normalizeAddress(actor.Address), reason); err != nil { |
| + return err |
| + } |
| + if prior > 0 { |
| + return nil |
| + } |
| + return appendAudit(tx, actor, "execution.recovery_charge", charge.Key) |
| + }) |
| +} |
| + |
| +func (s *Store) fenceAuthority(ctx context.Context, tx *gorm.DB, projectID int64) error { |
| + if s.execution == nil { |
| + return nil |
| + } |
| + raw, err := executionTx(tx) |
| + if err != nil { |
| + return err |
| + } |
| + var instance Team |
| + if err = tx.First(&instance).Error; err != nil { |
| + return storeError(err) |
| + } |
| + var projects []Project |
| + q := tx |
| + if projectID != 0 { |
| + q = q.Where("id = ?", projectID) |
| + } |
| + if err = q.Find(&projects).Error; err != nil { |
| + return storeError(err) |
| + } |
| + var members []Member |
| + if err = tx.Find(&members).Error; err != nil { |
| + return storeError(err) |
| + } |
| + var changes []team.GrantChange |
| + var revoked []string |
| + for _, p := range projects { |
| + var work DecisionOwner |
| + if err = tx.Where("project_id = ? AND decision = ?", p.ID, "work").First(&work).Error; err != nil { |
| + return storeError(err) |
| + } |
| + for _, m := range members { |
| + ref := GrantRef(p.ID, m.Address) |
| + changes = append(changes, team.GrantChange{Ref: ref, Version: p.GrantVersion, Epoch: instance.RosterEpoch}) |
| + if !m.Active || (m.Role != RoleOwner && (m.Role != RoleMember || work.Address != m.Address)) { |
| + revoked = append(revoked, ref) |
| + } |
| + } |
| + } |
| + if err = s.execution.Core.FenceGrantsTx(ctx, raw, changes); err != nil { |
| + return err |
| + } |
| + return s.execution.Core.RevokeGrantsTx(ctx, raw, revoked) |
| +} |
diff --git a/internal/equipo/roster.go b/internal/equipo/roster.go| index b0a3af25..56bc332e 100644 |
| --- a/internal/equipo/roster.go |
| +++ b/internal/equipo/roster.go |
| @@ -151,8 +151,13 @@ func (s *Store) SetMember(ctx context.Context, actor Actor, address string, role |
| return storeError(err) |
| } |
| } |
| - if err := tx.Model(&Team{}).Where("1 = 1").Update("roster_epoch", gorm.Expr("roster_epoch + 1")).Error; err != nil { |
| - return storeError(err) |
| + if !exists || old.Role != role || old.Active != active { |
| + if err := tx.Model(&Team{}).Where("1 = 1").Update("roster_epoch", gorm.Expr("roster_epoch + 1")).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err := s.fenceAuthority(ctx, tx, 0); err != nil { |
| + return err |
| + } |
| } |
| return appendAudit(tx, actor, "roster.set", address) |
| }) |
diff --git a/internal/equipo/team/actions.go b/internal/equipo/team/actions.go| index 02fd87ef..314a8d58 100644 |
| --- a/internal/equipo/team/actions.go |
| +++ b/internal/equipo/team/actions.go |
| @@ -263,7 +263,7 @@ func checkPublication(ctx context.Context, tx *sql.Tx, j jobRow, payload []byte) |
| func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, error) { |
| var pre Action |
| var job jobRow |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| j, err := loadJob(ctx, tx, scope) |
| if err != nil { |
| return err |
| @@ -281,13 +281,16 @@ func (s *Store) Admit(ctx context.Context, scope Scope, id ActionID) (Dispatch, |
| if pre.State != ActionIntent { |
| return Dispatch{}, fail(CodeState, "action %d is %s", id, pre.State) |
| } |
| - adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Target: job.Target, Operation: pre.Operation}) |
| + adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Project: job.Project, Target: job.Target, Operation: pre.Operation}) |
| if err != nil { |
| if errors.Is(err, ErrGrantRevoked) { |
| s.revoke(ctx, scope, "admit: "+err.Error()) |
| } |
| return Dispatch{}, err |
| } |
| + if err := s.fenceObserved(ctx, job.Grant, adm); err != nil { |
| + return Dispatch{}, err |
| + } |
| var d Dispatch |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| if err := admissionOpen(ctx, tx); err != nil { |
| @@ -530,7 +533,7 @@ func (s *Store) Reconcile(ctx context.Context, scope Scope, id ActionID) (Action |
| // GetAction reads one action. |
| func (s *Store) GetAction(ctx context.Context, scope Scope, id ActionID) (Action, error) { |
| var a Action |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| j, err := loadJob(ctx, tx, scope) |
| if err != nil { |
| return err |
| @@ -544,7 +547,7 @@ func (s *Store) GetAction(ctx context.Context, scope Scope, id ActionID) (Action |
| // Actions lists the job's actions. |
| func (s *Store) Actions(ctx context.Context, scope Scope) ([]Action, error) { |
| var out []Action |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/authority.go b/internal/equipo/team/authority.go| index 2db66bdb..a4f71907 100644 |
| --- a/internal/equipo/team/authority.go |
| +++ b/internal/equipo/team/authority.go |
| @@ -10,6 +10,7 @@ import ( |
| // operation for an account. The store builds it from stored job fields, |
| // never from a worker's arguments. |
| type AdmissionRequest struct { |
| + Project ProjectID |
| Grant string |
| Account AccountID |
| Target TargetBinding |
diff --git a/internal/equipo/team/budget.go b/internal/equipo/team/budget.go| index 4cc0faa7..dd5de755 100644 |
| --- a/internal/equipo/team/budget.go |
| +++ b/internal/equipo/team/budget.go |
| @@ -242,7 +242,7 @@ func (s *Store) SettleAudited(ctx context.Context, scope Scope, id ReservationID |
| // Ledger summarises the job's reservations (its own and its children's). |
| func (s *Store) Ledger(ctx context.Context, scope Scope) (LedgerSummary, error) { |
| var sum LedgerSummary |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
| @@ -259,7 +259,7 @@ func (s *Store) AccountLedger(ctx context.Context, account AccountID) (LedgerSum |
| return LedgerSummary{}, fail(CodeScope, "empty account") |
| } |
| var sum LedgerSummary |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| var err error |
| sum, err = ledgerSum(ctx, tx, `account=?`, string(account)) |
| return err |
| @@ -270,7 +270,7 @@ func (s *Store) AccountLedger(ctx context.Context, account AccountID) (LedgerSum |
| // Reservations lists the job's ledger rows. |
| func (s *Store) Reservations(ctx context.Context, scope Scope) ([]Reservation, error) { |
| var out []Reservation |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/evidence.go b/internal/equipo/team/evidence.go| index 16a836bc..ee7a2e46 100644 |
| --- a/internal/equipo/team/evidence.go |
| +++ b/internal/equipo/team/evidence.go |
| @@ -483,7 +483,7 @@ func itoa(n int) string { |
| // Artifacts lists the job's artifacts without payloads. |
| func (s *Store) Artifacts(ctx context.Context, scope Scope) ([]Artifact, error) { |
| var out []Artifact |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
| @@ -508,7 +508,7 @@ func (s *Store) Artifacts(ctx context.Context, scope Scope) ([]Artifact, error) |
| // Artifact reads one artifact with its payload. |
| func (s *Store) Artifact(ctx context.Context, scope Scope, id ArtifactID) (Artifact, error) { |
| var out Artifact |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/harness_test.go b/internal/equipo/team/harness_test.go| index 9be517a2..46b708c3 100644 |
| --- a/internal/equipo/team/harness_test.go |
| +++ b/internal/equipo/team/harness_test.go |
| @@ -2,6 +2,7 @@ package team |
| import ( |
| "context" |
| + "database/sql" |
| "errors" |
| "path/filepath" |
| "testing" |
| @@ -162,3 +163,11 @@ func (e *env) hasEvent(scope Scope, typ string) bool { |
| } |
| var _ = errors.Is |
| + |
| +func dropRecoverySchema(t *testing.T, db *sql.DB) { |
| + t.Helper() |
| + for _, q := range []string{`DROP TABLE recovery_events`, `DROP TABLE recovery_charges`, `DROP TABLE grant_fences`, `ALTER TABLE service DROP COLUMN release_required`, `ALTER TABLE service DROP COLUMN recovery_revision`, `ALTER TABLE service DROP COLUMN reconciled_revision`, `ALTER TABLE service DROP COLUMN clock_high_water`, `ALTER TABLE jobs DROP COLUMN grant_stale`, `ALTER TABLE time_reservations DROP COLUMN elapsed_unknown`} { |
| + _, err := db.Exec(q) |
| + must(t, err) |
| + } |
| +} |
diff --git a/internal/equipo/team/jobs.go b/internal/equipo/team/jobs.go| index 59745732..51c3bc88 100644 |
| --- a/internal/equipo/team/jobs.go |
| +++ b/internal/equipo/team/jobs.go |
| @@ -111,7 +111,14 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err := spec.validate(); err != nil { |
| return Job{}, err |
| } |
| - adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: spec.GrantRef, Account: spec.Account, Target: spec.Target, Operation: OpJobContinue}) |
| + if spec.Parent != 0 && spec.Project == 0 { |
| + parent, err := s.GetJob(ctx, Scope{spec.Account, spec.Parent}) |
| + if err != nil { |
| + return Job{}, err |
| + } |
| + spec.Project = parent.Project |
| + } |
| + adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: spec.GrantRef, Account: spec.Account, Project: spec.Project, Target: spec.Target, Operation: OpJobContinue}) |
| if err != nil { |
| return Job{}, err |
| } |
| @@ -124,6 +131,9 @@ func (s *Store) CreateJob(ctx context.Context, spec JobSpec) (Job, error) { |
| if err := admissionOpen(ctx, tx); err != nil { |
| return err |
| } |
| + if err := checkGrantFence(ctx, tx, adm); err != nil { |
| + return err |
| + } |
| account, err := accountPolicy(ctx, tx, spec.Account) |
| if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| return err |
| @@ -210,11 +220,12 @@ func accountPolicy(ctx context.Context, tx *sql.Tx, account AccountID) (Policy, |
| // jobRow is a Job plus the depth column used for nesting checks. |
| type jobRow struct { |
| + grantStale bool |
| Job |
| depth int |
| } |
| -const jobColumns = `id, project_id, account, parent, depth, requester, target, evidence, policy_version, policy, grant_ref, grant_version, grant_epoch, grant_observed_at, state, wait, revision, outcome, created_at, updated_at` |
| +const jobColumns = `grant_stale, id, project_id, account, parent, depth, requester, target, evidence, policy_version, policy, grant_ref, grant_version, grant_epoch, grant_observed_at, state, wait, revision, outcome, created_at, updated_at` |
| type rowScanner interface { |
| Scan(dest ...any) error |
| @@ -224,7 +235,7 @@ func scanJob(r rowScanner) (jobRow, error) { |
| var j jobRow |
| var target, evidence, policy, state, wait, observed, created, updated string |
| var parent int64 |
| - err := r.Scan(&j.ID, &j.Project, &j.Account, &parent, &j.depth, &j.Requester, &target, &evidence, &j.PolicyVersion, &policy, |
| + err := r.Scan(&j.grantStale, &j.ID, &j.Project, &j.Account, &parent, &j.depth, &j.Requester, &target, &evidence, &j.PolicyVersion, &policy, |
| &j.Grant.Ref, &j.Grant.Version, &j.Grant.Epoch, &observed, &state, &wait, &j.Revision, &j.Outcome, &created, &updated) |
| if err != nil { |
| return j, err |
| @@ -275,7 +286,7 @@ func loadJob(ctx context.Context, tx *sql.Tx, scope Scope) (jobRow, error) { |
| // GetJob reads a job. |
| func (s *Store) GetJob(ctx context.Context, scope Scope) (Job, error) { |
| var job Job |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| j, err := loadJob(ctx, tx, scope) |
| job = j.Job |
| return err |
| @@ -307,6 +318,9 @@ func bumpJob(ctx context.Context, tx *sql.Tx, j jobRow, state JobState, wait Wai |
| // appendEvent writes the next event of the job's log inside tx. |
| func appendEvent(ctx context.Context, tx *sql.Tx, scope Scope, typ, actor string, payload any, now time.Time) error { |
| + if err := advanceRecovery(ctx, tx); err != nil { |
| + return err |
| + } |
| raw, err := json.Marshal(payload) |
| if err != nil { |
| return fail(CodeInvalid, "event payload: %v", err) |
| @@ -325,7 +339,7 @@ func appendEvent(ctx context.Context, tx *sql.Tx, scope Scope, typ, actor string |
| // Events returns the job's log after seq, in order. |
| func (s *Store) Events(ctx context.Context, scope Scope, after int64) ([]Event, error) { |
| var out []Event |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
| @@ -403,7 +417,7 @@ func loadStep(ctx context.Context, tx *sql.Tx, job JobID, id StepID) (Step, erro |
| // Steps lists the job's steps. |
| func (s *Store) Steps(ctx context.Context, scope Scope) ([]Step, error) { |
| var out []Step |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/periodbudget.go b/internal/equipo/team/periodbudget.go| index da1f256c..c4bbf522 100644 |
| --- a/internal/equipo/team/periodbudget.go |
| +++ b/internal/equipo/team/periodbudget.go |
| @@ -110,36 +110,74 @@ func loadBudgets(ctx context.Context, tx *sql.Tx, account AccountID) (BudgetSet, |
| return b, true, nil |
| } |
| func (s *Store) ConfigureBudgets(ctx context.Context, account AccountID, expectedRevision int64, budgets BudgetSet) error { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| + return s.tx(ctx, func(tx *sql.Tx) error { return s.ConfigureBudgetsTx(ctx, tx, account, expectedRevision, budgets) }) |
| +} |
| + |
| +func (s *Store) ConfigureBudgetsTx(ctx context.Context, tx *sql.Tx, account AccountID, expectedRevision int64, budgets BudgetSet) error { |
| if account == "" || expectedRevision < 0 || budgets.Revision != expectedRevision { |
| return fail(CodeInvalid, "budget account or revision") |
| } |
| if err := budgets.Validate(); err != nil { |
| return err |
| } |
| - return s.tx(ctx, func(tx *sql.Tx) error { |
| - old, _, err := loadBudgets(ctx, tx, account) |
| - if err != nil { |
| - return err |
| - } |
| - if old.Revision != expectedRevision { |
| - return fail(CodeRevision, "budget revision changed") |
| - } |
| - budgets.Revision, err = addChecked(expectedRevision, 1) |
| - if err != nil { |
| - return err |
| - } |
| - raw, err := json.Marshal(budgets) |
| - if err != nil { |
| - return err |
| - } |
| - _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config) VALUES(?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision, config=excluded.config`, string(account), budgets.Revision, string(raw)) |
| + |
| + old, _, err := loadBudgets(ctx, tx, account) |
| + if err != nil { |
| return err |
| - }) |
| + } |
| + if old.Revision != expectedRevision { |
| + return fail(CodeRevision, "budget revision changed") |
| + } |
| + budgets.Revision, err = addChecked(expectedRevision, 1) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(budgets) |
| + if err != nil { |
| + return err |
| + } |
| + _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config) VALUES(?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision, config=excluded.config`, string(account), budgets.Revision, string(raw)) |
| + if err != nil { |
| + return err |
| + } |
| + return advanceRecovery(ctx, tx) |
| } |
| + |
| func period(at time.Time) string { return at.UTC().Format("2006-01") } |
| func periodSum(ctx context.Context, tx *sql.Tx, account AccountID, project ProjectID, at time.Time) (PeriodUsage, error) { |
| var sum PeriodUsage |
| + charges, err := tx.QueryContext(ctx, `SELECT reserved FROM recovery_charges WHERE account=? AND (?=0 OR project_id=?)`, string(account), project, project) |
| + if err != nil { |
| + return sum, err |
| + } |
| + for charges.Next() { |
| + var raw string |
| + var r PeriodLimits |
| + if err = charges.Scan(&raw); err != nil { |
| + break |
| + } |
| + if err = json.Unmarshal([]byte(raw), &r); err != nil { |
| + break |
| + } |
| + if r.Calls < 0 || r.InputTokens < 0 || r.OutputTokens < 0 || r.Seconds < 0 { |
| + err = fail(CodeInvalid, "negative recovery charge") |
| + break |
| + } |
| + sum.Reserved, err = sum.Reserved.add(r) |
| + if err != nil { |
| + break |
| + } |
| + } |
| + if err == nil { |
| + err = charges.Err() |
| + } |
| + charges.Close() |
| + if err != nil { |
| + return sum, err |
| + } |
| rows, err := tx.QueryContext(ctx, `SELECT r.state,r.created_at,r.r_calls,r.r_input,r.r_output,r.s_calls,r.s_input,r.s_output FROM reservations r JOIN jobs j ON j.id=r.job_id WHERE r.account=? AND (?=0 OR j.project_id=?)`, string(account), project, project) |
| if err != nil { |
| return sum, err |
| @@ -212,7 +250,7 @@ func (s *Store) PeriodUsage(ctx context.Context, account AccountID, project Proj |
| if account == "" || project < 0 || at.IsZero() { |
| return sum, fail(CodeInvalid, "period usage scope") |
| } |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| b, configured, err := loadBudgets(ctx, tx, account) |
| if err != nil { |
| return err |
| @@ -276,6 +314,14 @@ func settleTime(ctx context.Context, tx *sql.Tx, a Attempt, now time.Time) error |
| if a.CreatedAt.IsZero() { |
| return fail(CodeInvalid, "invalid containment time") |
| } |
| + var unknown int |
| + if err := tx.QueryRowContext(ctx, `SELECT elapsed_unknown FROM time_reservations WHERE attempt_id=? AND state='open'`, a.ID).Scan(&unknown); err != nil { |
| + return fail(CodeState, "attempt has no open time reservation") |
| + } |
| + if unknown != 0 || now.Before(a.CreatedAt) { |
| + _, err := tx.ExecContext(ctx, `UPDATE time_reservations SET elapsed_unknown=1 WHERE attempt_id=?`, a.ID) |
| + return err |
| + } |
| seconds := max(int64(0), now.Unix()-a.CreatedAt.Unix()) |
| if !now.Before(a.CreatedAt) && now.Nanosecond() > a.CreatedAt.Nanosecond() { |
| var err error |
| @@ -346,3 +392,34 @@ func migrateTimeReservations(ctx context.Context, tx *sql.Tx) error { |
| } |
| return nil |
| } |
| + |
| +func (s *Store) SyncBudgetsTx(ctx context.Context, tx *sql.Tx, account AccountID, budgets BudgetSet) error { |
| + if account == "" || budgets.Revision <= 0 { |
| + return fail(CodeInvalid, "budget account or revision") |
| + } |
| + if err := budgets.Validate(); err != nil { |
| + return err |
| + } |
| + old, exists, err := loadBudgets(ctx, tx, account) |
| + if err != nil { |
| + return err |
| + } |
| + raw, err := json.Marshal(budgets) |
| + if err != nil { |
| + return err |
| + } |
| + if exists && old.Revision >= budgets.Revision { |
| + previous, err := json.Marshal(old) |
| + if err != nil { |
| + return err |
| + } |
| + if string(previous) == string(raw) { |
| + return nil |
| + } |
| + return fail(CodeRevision, "budget revision changed") |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO period_budgets(account,revision,config) VALUES(?,?,?) ON CONFLICT(account) DO UPDATE SET revision=excluded.revision,config=excluded.config`, string(account), budgets.Revision, string(raw)); err != nil { |
| + return err |
| + } |
| + return advanceRecovery(ctx, tx) |
| +} |
diff --git a/internal/equipo/team/periodbudget_test.go b/internal/equipo/team/periodbudget_test.go| index 9cfea33b..b8f18de1 100644 |
| --- a/internal/equipo/team/periodbudget_test.go |
| +++ b/internal/equipo/team/periodbudget_test.go |
| @@ -407,6 +407,7 @@ func TestProjectBudgetMigration(t *testing.T) { |
| e.store = nil |
| db, err := sql.Open("sqlite", e.path) |
| must(t, err) |
| + dropRecoverySchema(t, db) |
| for _, q := range []string{"DROP TABLE time_reservations", "DROP TABLE period_budgets", "ALTER TABLE jobs DROP COLUMN project_id", "UPDATE service SET schema_version=2 WHERE id=1"} { |
| _, err = db.Exec(q) |
| must(t, err) |
| @@ -495,6 +496,7 @@ func TestProjectBudgetMigrationKeepsUncontainedTime(t *testing.T) { |
| e.store = nil |
| db, err := sql.Open("sqlite", e.path) |
| must(t, err) |
| + dropRecoverySchema(t, db) |
| for _, q := range []string{"DROP TABLE time_reservations", "DROP TABLE period_budgets", "ALTER TABLE jobs DROP COLUMN project_id", "UPDATE service SET schema_version=2 WHERE id=1"} { |
| _, err = db.Exec(q) |
| must(t, err) |
diff --git a/internal/equipo/team/recovery.go b/internal/equipo/team/recovery.go| index b0dde202..31a13eca 100644 |
| --- a/internal/equipo/team/recovery.go |
| +++ b/internal/equipo/team/recovery.go |
| @@ -28,16 +28,16 @@ type ResumeReport struct { |
| // reconciled through its adapter; what stays uncertain keeps its job |
| // waiting. After an unclean shutdown, all uncertain actions need receipts |
| // or conservative audited charges before admission reopens. Missing or |
| -// mismatched external history stays quarantined: this prototype has no |
| -// operator recovery API for a restored snapshot. |
| +// mismatched external history stays quarantined until an owner releases it. |
| func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| s.recoveryMu.Lock() |
| defer s.recoveryMu.Unlock() |
| var rep ResumeReport |
| type jobRef struct { |
| - scope Scope |
| - grant GrantSnapshot |
| - tgt TargetBinding |
| + scope Scope |
| + grant GrantSnapshot |
| + tgt TargetBinding |
| + project ProjectID |
| } |
| var jobs []jobRef |
| err := s.tx(ctx, func(tx *sql.Tx) error { |
| @@ -45,8 +45,15 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| if err := tx.QueryRowContext(ctx, `SELECT admission_paused, restore_uncertain FROM service WHERE id=1`).Scan(&paused, &restore); err != nil { |
| return err |
| } |
| + |
| if paused == 0 { |
| - return fail(CodeState, "recovery requires paused admission") |
| + var stale int |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE grant_stale=1 AND state NOT IN ('succeeded','failed','cancelled')`).Scan(&stale); err != nil { |
| + return err |
| + } |
| + if stale == 0 { |
| + return fail(CodeState, "recovery requires paused admission or stale grants") |
| + } |
| } |
| // An old snapshot's intents may have executed after the backup. |
| // Classify them before revocation can otherwise release their budgets. |
| @@ -65,7 +72,7 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| if err != nil { |
| return err |
| } |
| - jobs = append(jobs, jobRef{Scope{j.Account, j.ID}, j.Grant, j.Target}) |
| + jobs = append(jobs, jobRef{Scope{j.Account, j.ID}, j.Grant, j.Target, j.Project}) |
| } |
| return rows.Err() |
| }) |
| @@ -74,15 +81,28 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| } |
| rep.Jobs = len(jobs) |
| for _, jr := range jobs { |
| - adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: jr.grant.Ref, Account: jr.scope.Account, Target: jr.tgt, Operation: OpJobContinue}) |
| + adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: jr.grant.Ref, Account: jr.scope.Account, Project: jr.project, Target: jr.tgt, Operation: OpJobContinue}) |
| switch { |
| case errors.Is(err, ErrGrantRevoked): |
| - s.revoke(ctx, jr.scope, "resume: "+err.Error()) |
| + if err := s.tx(ctx, func(tx *sql.Tx) error { |
| + j, err := loadJob(ctx, tx, jr.scope) |
| + if err != nil { |
| + return err |
| + } |
| + if j.State.Terminal() { |
| + return nil |
| + } |
| + _, err = terminate(ctx, tx, j, JobCancelled, "authority", "grant revoked during recovery", s.clock.Now()) |
| + return err |
| + }); err != nil { |
| + return rep, err |
| + } |
| rep.Cancelled = append(rep.Cancelled, jr.scope.Job) |
| continue |
| case err != nil: |
| return rep, err |
| } |
| + refreshed := false |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| j, err := loadJob(ctx, tx, jr.scope) |
| if err != nil { |
| @@ -91,11 +111,35 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| if j.State.Terminal() { |
| return nil |
| } |
| + checked := j |
| + checked.grantStale = false |
| + checked.Grant.Version = adm.Version |
| + checked.Grant.Epoch = adm.Epoch |
| + if err := checkAdmission(checked, adm, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + if adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch { |
| + if err := s.FenceGrantsTx(ctx, tx, []GrantChange{{Ref: adm.Grant, Version: adm.Version, Epoch: adm.Epoch}}); err != nil { |
| + return err |
| + } |
| + j.grantStale = true |
| + } |
| + if err := checkGrantFence(ctx, tx, adm); err != nil { |
| + return err |
| + } |
| + var pending int |
| + if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM attempts WHERE job_id=? AND containment='pending'`, j.ID).Scan(&pending); err != nil { |
| + return err |
| + } |
| + if j.grantStale && pending > 0 { |
| + return nil |
| + } |
| now := s.clock.Now() |
| - if _, err := tx.ExecContext(ctx, `UPDATE jobs SET grant_version=?, grant_epoch=?, grant_observed_at=? WHERE id=?`, adm.Version, adm.Epoch, ts(now), int64(j.ID)); err != nil { |
| + if _, err := tx.ExecContext(ctx, `UPDATE jobs SET grant_stale=0, grant_version=?, grant_epoch=?, grant_observed_at=? WHERE id=?`, adm.Version, adm.Epoch, ts(now), int64(j.ID)); err != nil { |
| return fail(CodeInvalid, "snapshot: %v", err) |
| } |
| - if adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch { |
| + refreshed = true |
| + if j.grantStale || adm.Version != j.Grant.Version || adm.Epoch != j.Grant.Epoch { |
| return appendEvent(ctx, tx, jr.scope, "grant.revalidated", "resume", map[string]any{"from": j.Grant.Version, "to": adm.Version, "epoch": adm.Epoch}, now) |
| } |
| return nil |
| @@ -103,7 +147,9 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| if err != nil { |
| return rep, err |
| } |
| - rep.Revalidated = append(rep.Revalidated, jr.scope.Job) |
| + if refreshed { |
| + rep.Revalidated = append(rep.Revalidated, jr.scope.Job) |
| + } |
| } |
| // Actions the dead incarnation had admitted may have run: treat them as |
| // uncertain and ask the adapters. |
| @@ -174,12 +220,25 @@ func (s *Store) Resume(ctx context.Context) (ResumeReport, error) { |
| return fail(CodeInvalid, "expire: %v", err) |
| } |
| } |
| - var quarantine, restore int |
| + var quarantine, restore, releaseRequired int |
| var why string |
| - if err := tx.QueryRowContext(ctx, `SELECT quarantine, quarantine_why, restore_uncertain FROM service WHERE id=1`).Scan(&quarantine, &why, &restore); err != nil { |
| + if err := tx.QueryRowContext(ctx, `SELECT quarantine, quarantine_why, restore_uncertain, release_required FROM service WHERE id=1`).Scan(&quarantine, &why, &restore, &releaseRequired); err != nil { |
| return fail(CodeInvalid, "service: %v", err) |
| } |
| - if restore != 0 || (quarantine != 0 && len(rep.Unresolved) > 0) { |
| + if err := recoveryEvent(ctx, tx, "reconcile", "resume", "reconciliation completed", ""); err != nil { |
| + return err |
| + } |
| + snap, err := recoverySnapshot(ctx, tx) |
| + if err != nil { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE recovery_events SET snapshot_hash=? WHERE revision=?`, snap.Hash, snap.Revision); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE service SET reconciled_revision=recovery_revision WHERE id=1`); err != nil { |
| + return err |
| + } |
| + if restore != 0 || (quarantine != 0 && (releaseRequired != 0 || len(rep.Unresolved) > 0)) { |
| rep.Quarantine, rep.Why = true, why+"; "+itoa(len(rep.Unresolved))+" actions unresolved" |
| if restore != 0 { |
| rep.Why = "restored history requires operator recovery; missing post-snapshot work cannot be inferred" |
diff --git a/internal/equipo/team/recovery_release.go b/internal/equipo/team/recovery_release.go| new file mode 100644 |
| index 00000000..6519462b |
| --- /dev/null |
| +++ b/internal/equipo/team/recovery_release.go |
| @@ -0,0 +1,205 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "strings" |
| +) |
| + |
| +const recoverySchema = ` |
| +ALTER TABLE service ADD COLUMN release_required INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE service ADD COLUMN recovery_revision INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE service ADD COLUMN reconciled_revision INTEGER NOT NULL DEFAULT -1; |
| +ALTER TABLE service ADD COLUMN clock_high_water TEXT NOT NULL DEFAULT ""; |
| +ALTER TABLE jobs ADD COLUMN grant_stale INTEGER NOT NULL DEFAULT 0; |
| +ALTER TABLE time_reservations ADD COLUMN elapsed_unknown INTEGER NOT NULL DEFAULT 0; |
| +CREATE TABLE grant_fences (ref TEXT PRIMARY KEY, version INTEGER NOT NULL, epoch INTEGER NOT NULL); |
| +CREATE TABLE recovery_charges (key TEXT PRIMARY KEY, account TEXT NOT NULL, project_id INTEGER NOT NULL, reserved TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, incarnation INTEGER NOT NULL, created_at TEXT NOT NULL); |
| +CREATE TABLE recovery_events (revision INTEGER PRIMARY KEY, kind TEXT NOT NULL, actor TEXT NOT NULL, reason TEXT NOT NULL, snapshot_hash TEXT NOT NULL); |
| +` |
| + |
| +type RecoverySnapshot struct { |
| + Revision, Incarnation int64 |
| + Hash string |
| + Unresolved []ActionID |
| + Uncontained []AttemptID |
| +} |
| + |
| +type RecoveryCharge struct { |
| + Key string |
| + Account AccountID |
| + Project ProjectID |
| + Reserved PeriodLimits |
| +} |
| + |
| +func advanceRecovery(ctx context.Context, tx *sql.Tx) error { |
| + _, err := tx.ExecContext(ctx, `UPDATE service SET recovery_revision=recovery_revision+1 WHERE id=1`) |
| + return err |
| +} |
| + |
| +func recoveryEvent(ctx context.Context, tx *sql.Tx, kind, actor, reason, hash string) error { |
| + if err := advanceRecovery(ctx, tx); err != nil { |
| + return err |
| + } |
| + _, err := tx.ExecContext(ctx, `INSERT INTO recovery_events(revision,kind,actor,reason,snapshot_hash) SELECT recovery_revision,?,?,?,? FROM service WHERE id=1`, kind, actor, reason, hash) |
| + return err |
| +} |
| + |
| +func (s *Store) Pause(ctx context.Context, reason string) error { |
| + if strings.TrimSpace(reason) == "" { |
| + return fail(CodeInvalid, "pause needs a reason") |
| + } |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| + return s.tx(ctx, func(tx *sql.Tx) error { |
| + if _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1,quarantine=1,release_required=1,quarantine_why=? WHERE id=1`, reason); err != nil { |
| + return err |
| + } |
| + return recoveryEvent(ctx, tx, "pause", "service", reason, "") |
| + }) |
| +} |
| + |
| +func recoverySnapshot(ctx context.Context, tx *sql.Tx) (RecoverySnapshot, error) { |
| + var snap RecoverySnapshot |
| + if err := tx.QueryRowContext(ctx, `SELECT recovery_revision,incarnation FROM service WHERE id=1`).Scan(&snap.Revision, &snap.Incarnation); err != nil { |
| + return snap, err |
| + } |
| + rows, err := tx.QueryContext(ctx, `SELECT id FROM actions WHERE state IN ('dispatching','uncertain') ORDER BY id`) |
| + if err != nil { |
| + return snap, err |
| + } |
| + for rows.Next() { |
| + var id ActionID |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + snap.Unresolved = append(snap.Unresolved, id) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return snap, err |
| + } |
| + rows, err = tx.QueryContext(ctx, `SELECT id FROM attempts WHERE containment='pending' ORDER BY id`) |
| + if err != nil { |
| + return snap, err |
| + } |
| + for rows.Next() { |
| + var id AttemptID |
| + if err = rows.Scan(&id); err != nil { |
| + break |
| + } |
| + snap.Uncontained = append(snap.Uncontained, id) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return snap, err |
| + } |
| + raw, err := json.Marshal(snap) |
| + if err != nil { |
| + return snap, err |
| + } |
| + snap.Hash = hashBytes(raw) |
| + return snap, nil |
| +} |
| + |
| +func (s *Store) RecoverySnapshot(ctx context.Context) (RecoverySnapshot, error) { |
| + var snap RecoverySnapshot |
| + err := s.read(ctx, func(tx *sql.Tx) error { var err error; snap, err = recoverySnapshot(ctx, tx); return err }) |
| + return snap, err |
| +} |
| + |
| +func (s *Store) ReleaseQuarantine(ctx context.Context, expectedRevision int64, actor, reason, reconciliationHash string) error { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| + return s.tx(ctx, func(tx *sql.Tx) error { |
| + return s.ReleaseQuarantineTx(ctx, tx, expectedRevision, actor, reason, reconciliationHash) |
| + }) |
| +} |
| + |
| +// The app verifies the owner in this transaction before calling the core. |
| +func (s *Store) ReleaseQuarantineTx(ctx context.Context, tx *sql.Tx, expectedRevision int64, actor, reason, reconciliationHash string) error { |
| + if strings.TrimSpace(actor) == "" || strings.TrimSpace(reason) == "" || reconciliationHash == "" { |
| + return fail(CodeInvalid, "release needs actor, reason and reconciliation") |
| + } |
| + snap, err := recoverySnapshot(ctx, tx) |
| + if err != nil { |
| + return err |
| + } |
| + if expectedRevision != snap.Revision || reconciliationHash != snap.Hash { |
| + return fail(CodeRevision, "recovery snapshot changed") |
| + } |
| + var reconciled int64 |
| + var quarantine, restore int |
| + if err = tx.QueryRowContext(ctx, `SELECT reconciled_revision,quarantine,restore_uncertain FROM service WHERE id=1`).Scan(&reconciled, &quarantine, &restore); err != nil { |
| + return err |
| + } |
| + if quarantine == 0 || reconciled != snap.Revision { |
| + return fail(CodeState, "current quarantine has not been reconciled") |
| + } |
| + if len(snap.Uncontained) > 0 { |
| + return fail(CodeContainment, "recovery still has uncontained attempts") |
| + } |
| + if restore != 0 { |
| + var charges int |
| + if err = tx.QueryRowContext(ctx, `SELECT count(*) FROM recovery_charges WHERE incarnation=?`, snap.Incarnation).Scan(&charges); err != nil { |
| + return err |
| + } |
| + if charges == 0 { |
| + return fail(CodeState, "missing history needs an attested recovery charge") |
| + } |
| + } |
| + if _, err = tx.ExecContext(ctx, `UPDATE service SET quarantine=0,release_required=0,quarantine_why='',restore_uncertain=0,admission_paused=1 WHERE id=1 AND recovery_revision=?`, expectedRevision); err != nil { |
| + return err |
| + } |
| + return recoveryEvent(ctx, tx, "release", actor, reason, reconciliationHash) |
| +} |
| + |
| +func (s *Store) RecordRecoveryCharge(ctx context.Context, charge RecoveryCharge, actor, reason string) error { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| + return s.tx(ctx, func(tx *sql.Tx) error { return s.RecordRecoveryChargeTx(ctx, tx, charge, actor, reason) }) |
| +} |
| + |
| +func (s *Store) RecordRecoveryChargeTx(ctx context.Context, tx *sql.Tx, charge RecoveryCharge, actor, reason string) error { |
| + if strings.TrimSpace(charge.Key) == "" || charge.Account == "" || charge.Project <= 0 || strings.TrimSpace(actor) == "" || strings.TrimSpace(reason) == "" || charge.Reserved == (PeriodLimits{}) { |
| + return fail(CodeInvalid, "invalid recovery charge") |
| + } |
| + if charge.Reserved.Calls < 0 || charge.Reserved.InputTokens < 0 || charge.Reserved.OutputTokens < 0 || charge.Reserved.Seconds < 0 { |
| + return fail(CodeInvalid, "negative recovery charge") |
| + } |
| + raw, err := json.Marshal(charge.Reserved) |
| + if err != nil { |
| + return err |
| + } |
| + var account, reserved string |
| + var project ProjectID |
| + err = tx.QueryRowContext(ctx, `SELECT account,project_id,reserved FROM recovery_charges WHERE key=?`, charge.Key).Scan(&account, &project, &reserved) |
| + if err == nil { |
| + if account != string(charge.Account) || project != charge.Project || reserved != string(raw) { |
| + return fail(CodeConflict, "recovery key has different content") |
| + } |
| + return nil |
| + } |
| + if !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + var quarantine int |
| + if err = tx.QueryRowContext(ctx, `SELECT quarantine FROM service WHERE id=1`).Scan(&quarantine); err != nil { |
| + return err |
| + } |
| + if quarantine == 0 { |
| + return fail(CodeState, "recovery charge requires quarantine") |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO recovery_charges(key,account,project_id,reserved,actor,reason,incarnation,created_at) VALUES(?,?,?,?,?,?,?,?)`, charge.Key, string(charge.Account), charge.Project, string(raw), actor, reason, s.incarnation, ts(s.clock.Now())); err != nil { |
| + return err |
| + } |
| + return recoveryEvent(ctx, tx, "charge", actor, reason, charge.Key) |
| +} |
diff --git a/internal/equipo/team/recovery_release_test.go b/internal/equipo/team/recovery_release_test.go| new file mode 100644 |
| index 00000000..18204f56 |
| --- /dev/null |
| +++ b/internal/equipo/team/recovery_release_test.go |
| @@ -0,0 +1,311 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "os" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func TestRecoveryReleaseKeepsUnknownCharged(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + scope, h := periodJob(e, 1) |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("unknown", Usage{InputTokens: 10})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Lost(e.ctx, scope, id, "lost reply")) |
| + must(t, e.store.StopAttempt(e.ctx, scope, h, "recover")) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + must(t, e.store.Pause(e.ctx, "unknown work")) |
| + before := periodUsage(e, 1) |
| + snapshot, err := e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + if err := e.store.ReleaseQuarantine(e.ctx, snapshot.Revision, "owner", "reviewed", snapshot.Hash); err == nil { |
| + t.Fatal("release without reconciliation") |
| + } |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + snapshot, err = e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + if len(snapshot.Unresolved) != 1 { |
| + t.Fatalf("unknown work missing: %+v", snapshot) |
| + } |
| + must(t, e.store.ReleaseQuarantine(e.ctx, snapshot.Revision, "owner", "reviewed unknown charge", snapshot.Hash)) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + if got := periodUsage(e, 1); got != before { |
| + t.Fatalf("release refunded unknown work: before=%+v after=%+v", before, got) |
| + } |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionUncertain || a.Receipt != nil { |
| + t.Fatalf("release invented result: %+v", a) |
| + } |
| + if _, err := e.store.Admit(e.ctx, scope, id); err == nil { |
| + t.Fatal("release replayed unknown action") |
| + } |
| +} |
| + |
| +func TestContainAfterClockRollback(t *testing.T) { |
| + for _, back := range []time.Duration{5 * time.Second, 30 * time.Second} { |
| + t.Run(back.String(), func(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + scope, h := periodJob(e, 1) |
| + e.clock.Advance(10 * time.Second) |
| + _, err := e.store.Renew(e.ctx, scope, h) |
| + must(t, err) |
| + wrong := h |
| + wrong.Runner = "other" |
| + wantCode(t, e.store.StopAttempt(e.ctx, scope, wrong, "wrong handle"), CodeFence) |
| + e.clock.Advance(-back) |
| + must(t, e.store.StopAttempt(e.ctx, scope, h, "clock rollback")) |
| + steps, err := e.store.Steps(e.ctx, scope) |
| + must(t, err) |
| + if steps[0].Fence <= h.Fence { |
| + t.Fatal("stop did not advance fence") |
| + } |
| + if _, err := e.store.Renew(e.ctx, scope, h); err == nil { |
| + t.Fatal("stopped handle renewed") |
| + } |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "physical cleanup complete")) |
| + if _, err := e.store.Renew(e.ctx, scope, h); err == nil { |
| + t.Fatal("contained handle renewed") |
| + } |
| + usage := periodUsage(e, 1) |
| + if usage.Reserved.Seconds != int64(testPolicy().AttemptSeconds) { |
| + t.Fatalf("rollback refunded unknown elapsed time: %+v", usage) |
| + } |
| + e.clock.Advance(time.Hour) |
| + if got := periodUsage(e, 1); got != usage { |
| + t.Fatalf("read refunded unknown time: %+v", got) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityEditFencesOnlyChangedGrants(t *testing.T) { |
| + e := newEnv(t) |
| + e.auth.Issue("grant-b", Grant{Account: acctA, Operations: map[Operation]bool{OpJobContinue: true, OpAttemptContinue: true, OpProviderCall: true}}) |
| + spec := softwareSpec(SoftwareSteps(false)) |
| + _, a := e.createJob(spec) |
| + ha := e.claim(a, "reproduce", "a", "a") |
| + spec.GrantRef = "grant-b" |
| + _, b := e.createJob(spec) |
| + hb := e.claim(b, "reproduce", "b", "b") |
| + ia, err := e.store.Intend(e.ctx, a, ha, intent("a", Usage{})) |
| + must(t, err) |
| + ib, err := e.store.Intend(e.ctx, b, hb, intent("b", Usage{})) |
| + must(t, err) |
| + e.auth.Amend(grant) |
| + must(t, e.store.WithTransaction(e.ctx, func(tx *sql.Tx) error { |
| + return e.store.FenceGrantsTx(e.ctx, tx, []GrantChange{{Ref: grant, Version: 2, Epoch: 1}}) |
| + })) |
| + if _, err := e.store.Renew(e.ctx, a, ha); err == nil { |
| + t.Fatal("changed grant renewed") |
| + } |
| + if _, err := e.store.Admit(e.ctx, a, ia); err == nil { |
| + t.Fatal("changed grant admitted") |
| + } |
| + action, err := e.store.GetAction(e.ctx, a, ia) |
| + must(t, err) |
| + if action.State != ActionRevoked { |
| + t.Fatal("changed grant retained undispatched intent") |
| + } |
| + reservations, err := e.store.Reservations(e.ctx, a) |
| + must(t, err) |
| + if reservations[0].State != ReservationReleased { |
| + t.Fatal("undispatched reservation retained") |
| + } |
| + if _, err := e.store.Claim(e.ctx, a, "reproduce", "new", "new"); err == nil { |
| + t.Fatal("stale grant claimed") |
| + } |
| + _, err = e.store.Renew(e.ctx, b, hb) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, b, ib) |
| + must(t, err) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + if _, err := e.store.Claim(e.ctx, a, "reproduce", "new", "new"); err == nil { |
| + t.Fatal("resume skipped containment") |
| + } |
| + must(t, e.store.Contain(e.ctx, a, ha.Attempt, "supervisor")) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + _, err = e.store.Claim(e.ctx, a, "reproduce", "new", "new") |
| + must(t, err) |
| +} |
| + |
| +func TestRuntimeAuthorityObservedDriftFencesBeforeResume(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "runner", "workspace") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("pending", Usage{})) |
| + must(t, err) |
| + e.auth.Amend(grant) |
| + _, err = e.store.Renew(e.ctx, scope, h) |
| + wantCode(t, err, CodeGrantStale) |
| + attempts, err := e.store.Attempts(e.ctx, scope) |
| + must(t, err) |
| + if attempts[0].State != AttemptStopping { |
| + t.Fatal("observed drift did not stop attempt") |
| + } |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionRevoked { |
| + t.Fatal("observed drift kept undispatched intent") |
| + } |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + if _, err = e.store.Renew(e.ctx, scope, h); err == nil { |
| + t.Fatal("resume revived stale handle") |
| + } |
| +} |
| + |
| +func TestRecoveryReleaseReceiptInvalidatesSnapshot(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "runner", "workspace") |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("pending", Usage{InputTokens: 10, OutputTokens: 10})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Lost(e.ctx, scope, id, "unknown")) |
| + must(t, e.store.StopAttempt(e.ctx, scope, h, "cleanup")) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + must(t, e.store.Pause(e.ctx, "recover")) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + snapshot, err := e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + must(t, e.store.Record(e.ctx, scope, id, Receipt{ID: "receipt", Outcome: OutcomeSuccess, Usage: &Usage{Calls: 1, InputTokens: 1, CostMicros: 1003}})) |
| + wantCode(t, e.store.ReleaseQuarantine(e.ctx, snapshot.Revision, "owner", "reviewed", snapshot.Hash), CodeRevision) |
| + next, err := e.store.RecoverySnapshot(e.ctx) |
| + must(t, err) |
| + wantCode(t, e.store.ReleaseQuarantine(e.ctx, next.Revision, "owner", "reviewed", next.Hash), CodeState) |
| +} |
| + |
| +func TestContainAfterClockRollbackReopen(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + scope, h := periodJob(e, 1) |
| + e.clock.Advance(10 * time.Second) |
| + _, err := e.store.Renew(e.ctx, scope, h) |
| + must(t, err) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + e.clock.Advance(-5 * time.Second) |
| + e.openNoResume() |
| + must(t, e.store.StopAttempt(e.ctx, scope, h, "physical cleanup")) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + if got := periodUsage(e, 1); got.Reserved.Seconds != int64(testPolicy().AttemptSeconds) { |
| + t.Fatalf("reopen lost clock high water: %+v", got) |
| + } |
| +} |
| + |
| +type recoveryBlockedAdapter struct { |
| + Adapter |
| + entered, release chan struct{} |
| +} |
| + |
| +func (a recoveryBlockedAdapter) Reconcile(ctx context.Context, d Dispatch) (ReconcileResult, error) { |
| + close(a.entered) |
| + <-a.release |
| + return a.Adapter.Reconcile(ctx, d) |
| +} |
| + |
| +func TestRecoveryReleaseSerializesBudgetAndContain(t *testing.T) { |
| + e := newEnv(t) |
| + must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| + scope, h := periodJob(e, 1) |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("blocked", Usage{})) |
| + must(t, err) |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Lost(e.ctx, scope, id, "unknown")) |
| + must(t, e.store.StopAttempt(e.ctx, scope, h, "cleanup")) |
| + must(t, e.store.Pause(e.ctx, "reconcile")) |
| + entered, release := make(chan struct{}), make(chan struct{}) |
| + e.store.adapters[OpProviderCall] = recoveryBlockedAdapter{e.store.adapters[OpProviderCall], entered, release} |
| + resumed := make(chan error, 1) |
| + go func() { _, err := e.store.Resume(e.ctx); resumed <- err }() |
| + <-entered |
| + results := make(chan error, 2) |
| + started := make(chan struct{}, 2) |
| + go func() { |
| + started <- struct{}{} |
| + b := periodSet() |
| + b.Revision = 1 |
| + results <- e.store.ConfigureBudgets(e.ctx, acctA, 1, b) |
| + }() |
| + go func() { started <- struct{}{}; results <- e.store.Contain(e.ctx, scope, h.Attempt, "supervisor") }() |
| + <-started |
| + <-started |
| + early := false |
| + select { |
| + case <-results: |
| + early = true |
| + case <-time.After(30 * time.Millisecond): |
| + } |
| + close(release) |
| + must(t, <-resumed) |
| + count := 2 |
| + if early { |
| + count-- |
| + } |
| + for range count { |
| + must(t, <-results) |
| + } |
| + if early { |
| + t.Fatal("budget or containment overlapped reconciliation") |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityResumeObservesFurtherEdit(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "runner", "workspace") |
| + e.auth.Amend(grant) |
| + _, err := e.store.Renew(e.ctx, scope, h) |
| + wantCode(t, err, CodeGrantStale) |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + e.auth.Amend(grant) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + if got := e.job(scope).Grant.Version; got != 3 { |
| + t.Fatalf("resume retained obsolete grant %d", got) |
| + } |
| + e.claim(scope, "reproduce", "new", "new") |
| +} |
| + |
| +func TestRecoveryReleaseRestoreAndClockRollbackKeepsIntentCharged(t *testing.T) { |
| + e := newEnv(t) |
| + _, scope := e.createJob(softwareSpec(SoftwareSteps(false))) |
| + h := e.claim(scope, "reproduce", "runner", "workspace") |
| + e.clock.Advance(10 * time.Second) |
| + id, err := e.store.Intend(e.ctx, scope, h, intent("saved", Usage{InputTokens: 10})) |
| + must(t, err) |
| + backup := e.snapshot() |
| + _, err = e.store.Admit(e.ctx, scope, id) |
| + must(t, err) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + raw, err := os.ReadFile(backup) |
| + must(t, err) |
| + must(t, os.WriteFile(e.path, raw, 0600)) |
| + e.clock.Advance(-5 * time.Second) |
| + e.openNoResume() |
| + a, err := e.store.GetAction(e.ctx, scope, id) |
| + must(t, err) |
| + if a.State != ActionUncertain { |
| + t.Fatalf("restore plus rollback lost unknown intent: %s", a.State) |
| + } |
| + ledger, err := e.store.Ledger(e.ctx, scope) |
| + must(t, err) |
| + if ledger.Reserved.Calls != 1 { |
| + t.Fatalf("restore plus rollback refunded unknown action: %+v", ledger) |
| + } |
| +} |
diff --git a/internal/equipo/team/review_regression_test.go b/internal/equipo/team/review_regression_test.go| index 9b93aead..ab44cafc 100644 |
| --- a/internal/equipo/team/review_regression_test.go |
| +++ b/internal/equipo/team/review_regression_test.go |
| @@ -314,6 +314,7 @@ func TestVersionOneMigrationPreservesJobsAndQuarantinesHistory(t *testing.T) { |
| e.store = nil |
| db, err := sql.Open("sqlite", e.path) |
| must(t, err) |
| + dropRecoverySchema(t, db) |
| for _, q := range []string{ |
| `ALTER TABLE service DROP COLUMN revision`, |
| `ALTER TABLE service DROP COLUMN restore_uncertain`, |
diff --git a/internal/equipo/team/scheduler.go b/internal/equipo/team/scheduler.go| index 5e70f9f9..34b9cf39 100644 |
| --- a/internal/equipo/team/scheduler.go |
| +++ b/internal/equipo/team/scheduler.go |
| @@ -53,6 +53,9 @@ func current(ctx context.Context, tx *sql.Tx, scope Scope, h Handle, now time.Ti |
| if err != nil { |
| return holder{}, err |
| } |
| + if j.grantStale { |
| + return holder{}, fail(CodeGrantStale, "job grant needs reconciliation") |
| + } |
| if a.Runner != h.Runner || a.Fence != h.Fence { |
| return holder{}, fail(CodeFence, "handle does not match attempt %d", a.ID) |
| } |
| @@ -94,6 +97,9 @@ func (s *Store) Claim(ctx context.Context, scope Scope, stepKey, runner, workspa |
| if err != nil { |
| return err |
| } |
| + if j.grantStale { |
| + return fail(CodeGrantStale, "job grant needs reconciliation") |
| + } |
| switch { |
| case j.State.Terminal(): |
| return fail(CodeState, "job %d is %s", j.ID, j.State) |
| @@ -208,13 +214,16 @@ func (s *Store) Renew(ctx context.Context, scope Scope, h Handle) (time.Time, er |
| if err != nil { |
| return time.Time{}, err |
| } |
| - adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Target: job.Target, Operation: OpAttemptContinue}) |
| + adm, err := s.auth.Introspect(ctx, AdmissionRequest{Grant: job.Grant.Ref, Account: job.Account, Project: job.Project, Target: job.Target, Operation: OpAttemptContinue}) |
| if err != nil { |
| if errors.Is(err, ErrGrantRevoked) { |
| s.revoke(ctx, scope, "renew: "+err.Error()) |
| } |
| return time.Time{}, err |
| } |
| + if err := s.fenceObserved(ctx, job.Grant, adm); err != nil { |
| + return time.Time{}, err |
| + } |
| var deadline time.Time |
| err = s.tx(ctx, func(tx *sql.Tx) error { |
| if err := admissionOpen(ctx, tx); err != nil { |
| @@ -245,6 +254,9 @@ func (s *Store) Renew(ctx context.Context, scope Scope, h Handle) (time.Time, er |
| // snapshot and the admission window. Version or epoch drift is ErrGrantStale: |
| // only Resume moves the snapshot, after its own online check. |
| func checkAdmission(j jobRow, adm Admission, now time.Time) error { |
| + if j.grantStale { |
| + return fail(CodeGrantStale, "job grant needs reconciliation") |
| + } |
| if adm.Grant != j.Grant.Ref { |
| return fail(CodeGrantStale, "admission for grant %q, job holds %q", adm.Grant, j.Grant.Ref) |
| } |
| @@ -373,6 +385,8 @@ func revokeIntents(ctx context.Context, tx *sql.Tx, attempt AttemptID, now time. |
| // expired or finished attempt and, for an expired or stopped attempt on a |
| // still-pending step, clears the holder so a fresh claim may follow. |
| func (s *Store) Contain(ctx context.Context, scope Scope, id AttemptID, supervisor string) error { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| return s.tx(ctx, func(tx *sql.Tx) error { |
| now := s.clock.Now() |
| j, err := loadJob(ctx, tx, scope) |
| @@ -418,7 +432,7 @@ func (s *Store) Contain(ctx context.Context, scope Scope, id AttemptID, supervis |
| // Attempts lists the job's attempts. |
| func (s *Store) Attempts(ctx context.Context, scope Scope) ([]Attempt, error) { |
| var out []Attempt |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| if _, err := loadJob(ctx, tx, scope); err != nil { |
| return err |
| } |
diff --git a/internal/equipo/team/scheduler_test.go b/internal/equipo/team/scheduler_test.go| index ab0fcaaa..ebab45bb 100644 |
| --- a/internal/equipo/team/scheduler_test.go |
| +++ b/internal/equipo/team/scheduler_test.go |
| @@ -204,9 +204,15 @@ func TestRenewRechecksAuthority(t *testing.T) { |
| // Only Resume moves the snapshot, after its own online check. |
| must(t, e.store.Close()) |
| e.open() |
| - if _, err := e.store.Renew(e.ctx, scope, h); err != nil { |
| - t.Fatal(err) |
| + if _, err := e.store.Renew(e.ctx, scope, h); err == nil { |
| + t.Fatal("resume revived an uncontained stale handle") |
| } |
| + must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| + _, err = e.store.Resume(e.ctx) |
| + must(t, err) |
| + h = e.claim(scope, "reproduce", "runner-a", "ws-2") |
| + _, err = e.store.Renew(e.ctx, scope, h) |
| + must(t, err) |
| e.auth.RotateEpoch() |
| _, err = e.store.Renew(e.ctx, scope, h) |
| wantCode(t, err, CodeGrantStale) |
| @@ -221,8 +227,8 @@ func TestRenewRechecksAuthority(t *testing.T) { |
| t.Fatal("no cancel event") |
| } |
| atts, _ := e.store.Attempts(e.ctx, scope) |
| - if atts[0].State != AttemptStopping { |
| - t.Fatalf("attempt %+v", atts[0]) |
| + if atts[len(atts)-1].State != AttemptStopping { |
| + t.Fatalf("attempt %+v", atts[len(atts)-1]) |
| } |
| } |
diff --git a/internal/equipo/team/settletime_test.go b/internal/equipo/team/settletime_test.go| index ed02c349..67305567 100644 |
| --- a/internal/equipo/team/settletime_test.go |
| +++ b/internal/equipo/team/settletime_test.go |
| @@ -22,7 +22,11 @@ func TestContainTimeAfterClockStep(t *testing.T) { |
| e.clock.Advance(tc.elapsed) |
| must(t, e.store.Contain(e.ctx, scope, h.Attempt, "supervisor")) |
| usage := periodUsage(e, 1) |
| - if usage.Reserved.Seconds != 0 || usage.Spent.Seconds != tc.seconds { |
| + reserved := int64(0) |
| + if tc.elapsed < 0 { |
| + reserved = int64(testPolicy().AttemptSeconds) |
| + } |
| + if usage.Reserved.Seconds != reserved || usage.Spent.Seconds != tc.seconds { |
| t.Fatalf("settled %+v, want %d seconds", usage, tc.seconds) |
| } |
| e.clock.Advance(time.Hour) |
| @@ -73,6 +77,7 @@ func TestTimeMigrationAfterClockStep(t *testing.T) { |
| defer db.Close() |
| _, err = db.Exec("UPDATE attempts SET stop_acked=? WHERE id=?", ts(e.clock.Now().Add(-time.Minute)), h.Attempt) |
| must(t, err) |
| + dropRecoverySchema(t, db) |
| for _, q := range []string{"DROP TABLE time_reservations", "DROP TABLE period_budgets", "ALTER TABLE jobs DROP COLUMN project_id", "UPDATE service SET schema_version=2 WHERE id=1"} { |
| _, err = db.Exec(q) |
| must(t, err) |
| @@ -80,13 +85,13 @@ func TestTimeMigrationAfterClockStep(t *testing.T) { |
| must(t, db.Close()) |
| e.open() |
| must(t, e.store.ConfigureBudgets(e.ctx, acctA, 0, periodSet())) |
| - if usage := periodUsage(e, 0); usage != (PeriodUsage{}) { |
| + if usage := periodUsage(e, 0); usage.Reserved.Seconds != int64(testPolicy().AttemptSeconds) || usage.Spent.Seconds != 0 { |
| t.Fatal("migrated backwards time", usage) |
| } |
| var state string |
| var seconds int64 |
| must(t, e.store.db.QueryRow("SELECT state, settled_seconds FROM time_reservations WHERE attempt_id=?", h.Attempt).Scan(&state, &seconds)) |
| - if state != "settled" || seconds != 0 { |
| + if state != "open" || seconds != 0 { |
| t.Fatal("migrated settlement missing", state, seconds) |
| } |
| must(t, e.store.Contain(e.ctx, scope, h.Attempt, "s")) |
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go| index e83ab080..80bd7e7b 100644 |
| --- a/internal/equipo/team/shared.go |
| +++ b/internal/equipo/team/shared.go |
| @@ -39,6 +39,8 @@ func OpenShared(ctx context.Context, writer *sql.DB, path string, o Options) (*S |
| // WithTransaction keeps SQL commit and witness publication under the core guard. |
| // Use the supplied transaction throughout; do not call Store methods inside fn. |
| func (s *Store) WithTransaction(ctx context.Context, fn func(*sql.Tx) error) error { |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| return s.tx(ctx, fn) |
| } |
| @@ -107,6 +109,12 @@ func (s *Store) checkSharedSchema(ctx context.Context) error { |
| } |
| var sharedSchemaQueries = []string{ |
| + `SELECT release_required,recovery_revision,reconciled_revision,clock_high_water FROM service LIMIT 0`, |
| + `SELECT grant_stale FROM jobs LIMIT 0`, |
| + `SELECT elapsed_unknown FROM time_reservations LIMIT 0`, |
| + `SELECT ref,version,epoch FROM grant_fences LIMIT 0`, |
| + `SELECT key,account,project_id,reserved,actor,reason,incarnation,created_at FROM recovery_charges LIMIT 0`, |
| + `SELECT revision,kind,actor,reason,snapshot_hash FROM recovery_events LIMIT 0`, |
| `SELECT |
| actions."id", |
| actions."job_id", |
diff --git a/internal/equipo/team/stop.go b/internal/equipo/team/stop.go| new file mode 100644 |
| index 00000000..4c69ad07 |
| --- /dev/null |
| +++ b/internal/equipo/team/stop.go |
| @@ -0,0 +1,243 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "strings" |
| + "time" |
| +) |
| + |
| +type GrantRef = string |
| + |
| +type GrantChange struct { |
| + Ref GrantRef |
| + Version, Epoch int64 |
| +} |
| + |
| +func (s *Store) StopAttempt(ctx context.Context, scope Scope, h Handle, reason string) error { |
| + if strings.TrimSpace(reason) == "" { |
| + return fail(CodeInvalid, "stop needs a reason") |
| + } |
| + s.recoveryMu.Lock() |
| + defer s.recoveryMu.Unlock() |
| + return s.tx(ctx, func(tx *sql.Tx) error { |
| + if _, err := loadJob(ctx, tx, scope); err != nil { |
| + return err |
| + } |
| + a, err := loadAttempt(ctx, tx, scope.Job, h.Attempt) |
| + if err != nil { |
| + return err |
| + } |
| + if a.Runner != h.Runner || a.Fence != h.Fence { |
| + return fail(CodeFence, "stop handle differs") |
| + } |
| + if a.Containment == ContainmentContained { |
| + return fail(CodeFence, "attempt already contained") |
| + } |
| + if a.State == AttemptStopping { |
| + return nil |
| + } |
| + if err = stopAttempt(ctx, tx, a, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + return appendEvent(ctx, tx, scope, "attempt.stop_requested", h.Runner, map[string]any{"attempt": a.ID, "reason": reason}, s.clock.Now()) |
| + }) |
| +} |
| + |
| +func stopAttempt(ctx context.Context, tx *sql.Tx, a Attempt, now time.Time) error { |
| + if _, err := tx.ExecContext(ctx, `UPDATE attempts SET state='stopping',stop_requested=?,updated_at=? WHERE id=? AND containment='pending'`, ts(now), ts(now), a.ID); err != nil { |
| + return err |
| + } |
| + if _, err := tx.ExecContext(ctx, `UPDATE steps SET fence=fence+1 WHERE id=? AND holder=? AND fence=?`, a.Step, a.ID, a.Fence); err != nil { |
| + return err |
| + } |
| + return revokeIntents(ctx, tx, a.ID, now) |
| +} |
| + |
| +func (s *Store) FenceGrantsTx(ctx context.Context, tx *sql.Tx, changes []GrantChange) error { |
| + for _, change := range changes { |
| + if change.Ref == "" || change.Version <= 0 || change.Epoch <= 0 { |
| + return fail(CodeInvalid, "invalid grant change") |
| + } |
| + var priorVersion, priorEpoch int64 |
| + err := tx.QueryRowContext(ctx, `SELECT version,epoch FROM grant_fences WHERE ref=?`, change.Ref).Scan(&priorVersion, &priorEpoch) |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if change.Version < priorVersion || change.Epoch < priorEpoch { |
| + return fail(CodeGrantStale, "grant fence cannot move backwards") |
| + } |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO grant_fences(ref,version,epoch) VALUES(?,?,?) ON CONFLICT(ref) DO UPDATE SET version=excluded.version,epoch=excluded.epoch`, change.Ref, change.Version, change.Epoch); err != nil { |
| + return err |
| + } |
| + rows, err := tx.QueryContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE grant_ref=? AND grant_stale=0 AND (grant_version<>? OR grant_epoch<>?) AND state NOT IN ('succeeded','failed','cancelled')`, change.Ref, change.Version, change.Epoch) |
| + if err != nil { |
| + return err |
| + } |
| + var jobs []jobRow |
| + for rows.Next() { |
| + j, e := scanJob(rows) |
| + if e != nil { |
| + err = e |
| + break |
| + } |
| + jobs = append(jobs, j) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + for _, j := range jobs { |
| + if _, err = tx.ExecContext(ctx, `UPDATE jobs SET grant_stale=1 WHERE id=?`, j.ID); err != nil { |
| + return err |
| + } |
| + rows, err := tx.QueryContext(ctx, `SELECT `+attemptColumns+` FROM attempts WHERE job_id=? AND containment='pending'`, j.ID) |
| + if err != nil { |
| + return err |
| + } |
| + var attempts []Attempt |
| + for rows.Next() { |
| + a, e := scanAttempt(rows) |
| + if e != nil { |
| + err = e |
| + break |
| + } |
| + attempts = append(attempts, a) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + for _, a := range attempts { |
| + if err = stopAttempt(ctx, tx, a, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + } |
| + if err = appendEvent(ctx, tx, Scope{j.Account, j.ID}, "grant.stale", "authority", change, s.clock.Now()); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func checkGrantFence(ctx context.Context, tx *sql.Tx, adm Admission) error { |
| + var version, epoch int64 |
| + err := tx.QueryRowContext(ctx, `SELECT version,epoch FROM grant_fences WHERE ref=?`, adm.Grant).Scan(&version, &epoch) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return nil |
| + } |
| + if err != nil { |
| + return err |
| + } |
| + if version != adm.Version || epoch != adm.Epoch { |
| + return fail(CodeGrantStale, "grant changed during admission") |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Store) observeClock(ctx context.Context, tx *sql.Tx) error { |
| + var high string |
| + if err := tx.QueryRowContext(ctx, `SELECT clock_high_water FROM service WHERE id=1`).Scan(&high); err != nil { |
| + return err |
| + } |
| + now := s.clock.Now() |
| + if high != "" && now.Before(parseTS(high)) { |
| + changed, err := tx.ExecContext(ctx, `UPDATE time_reservations SET elapsed_unknown=1 WHERE state='open' AND elapsed_unknown=0`) |
| + if err != nil { |
| + return err |
| + } |
| + unknown, err := changed.RowsAffected() |
| + if err != nil { |
| + return err |
| + } |
| + // Stop remains possible even when wall time precedes the old lease. |
| + rows, err := tx.QueryContext(ctx, `SELECT `+attemptColumns+` FROM attempts WHERE state='active' AND containment='pending'`) |
| + if err != nil { |
| + return err |
| + } |
| + var attempts []Attempt |
| + for rows.Next() { |
| + a, e := scanAttempt(rows) |
| + if e != nil { |
| + err = e |
| + break |
| + } |
| + attempts = append(attempts, a) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + for _, a := range attempts { |
| + if err = stopAttempt(ctx, tx, a, now); err != nil { |
| + return err |
| + } |
| + } |
| + if len(attempts) > 0 || unknown > 0 { |
| + if _, err = tx.ExecContext(ctx, `UPDATE service SET admission_paused=1,quarantine=1,release_required=1,quarantine_why='clock rollback' WHERE id=1`); err != nil { |
| + return err |
| + } |
| + return recoveryEvent(ctx, tx, "clock_rollback", "service", high, "") |
| + } |
| + return nil |
| + } |
| + _, err := tx.ExecContext(ctx, `UPDATE service SET clock_high_water=? WHERE id=1`, ts(now)) |
| + return err |
| +} |
| + |
| +func (s *Store) RevokeGrantsTx(ctx context.Context, tx *sql.Tx, refs []GrantRef) error { |
| + for _, ref := range refs { |
| + rows, err := tx.QueryContext(ctx, `SELECT `+jobColumns+` FROM jobs WHERE grant_ref=? AND state NOT IN ('succeeded','failed','cancelled')`, ref) |
| + if err != nil { |
| + return err |
| + } |
| + var jobs []jobRow |
| + for rows.Next() { |
| + j, e := scanJob(rows) |
| + if e != nil { |
| + err = e |
| + break |
| + } |
| + jobs = append(jobs, j) |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + for _, j := range jobs { |
| + if _, err = terminate(ctx, tx, j, JobCancelled, "authority", "grant revoked", s.clock.Now()); err != nil { |
| + return err |
| + } |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Store) fenceObserved(ctx context.Context, grant GrantSnapshot, adm Admission) error { |
| + if adm.Grant != grant.Ref { |
| + return fail(CodeGrantStale, "admission names a different grant") |
| + } |
| + if adm.Version == grant.Version && adm.Epoch == grant.Epoch { |
| + return nil |
| + } |
| + if err := s.WithTransaction(ctx, func(tx *sql.Tx) error { |
| + return s.FenceGrantsTx(ctx, tx, []GrantChange{{Ref: adm.Grant, Version: adm.Version, Epoch: adm.Epoch}}) |
| + }); err != nil { |
| + return err |
| + } |
| + return fail(CodeGrantStale, "observed authority change needs reconciliation") |
| +} |
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go| index 32a91c41..dd3dce57 100644 |
| --- a/internal/equipo/team/store.go |
| +++ b/internal/equipo/team/store.go |
| @@ -19,7 +19,7 @@ import ( |
| // SchemaVersion is the one schema this binary writes. A database with a |
| // newer version is refused (ErrStaleStore): the binary would not know the |
| // rows it was reading. |
| -const SchemaVersion = 3 |
| +const SchemaVersion = 4 |
| // Adapter executes one operation class against an external system. Execute |
| // runs an admitted dispatch and returns its receipt; an error from Execute |
| @@ -111,6 +111,9 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) { |
| func (s *Store) Close() error { |
| ctx := context.Background() |
| err := s.transact(ctx, true, func(tx *sql.Tx) error { |
| + if err := s.observeClock(ctx, tx); err != nil { |
| + return err |
| + } |
| _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1 WHERE id=1`) |
| return err |
| }) |
| @@ -126,7 +129,7 @@ func (s *Store) Close() error { |
| func (s *Store) Status(ctx context.Context) (Status, error) { |
| var st Status |
| var paused, quarantine int |
| - err := s.tx(ctx, func(tx *sql.Tx) error { |
| + err := s.read(ctx, func(tx *sql.Tx) error { |
| return tx.QueryRowContext(ctx, `SELECT schema_version, incarnation, admission_paused, quarantine, quarantine_why FROM service WHERE id=1`). |
| Scan(&st.SchemaVersion, &st.Incarnation, &paused, &quarantine, &st.QuarantineWhy) |
| }) |
| @@ -285,7 +288,7 @@ func (s *Store) migrate(ctx context.Context) error { |
| err := tx.QueryRowContext(ctx, `SELECT schema_version FROM service WHERE id=1`).Scan(&v) |
| switch { |
| case errors.Is(err, sql.ErrNoRows): |
| - _, err = tx.ExecContext(ctx, `INSERT INTO service(id, schema_version, incarnation, admission_paused, quarantine, quarantine_why) VALUES (1, ?, 0, 1, 0, '')`, SchemaVersion) |
| + _, err = tx.ExecContext(ctx, `INSERT INTO service(id, schema_version, incarnation, admission_paused, quarantine, quarantine_why) VALUES (1, ?, 0, 1, 0, '')`, 3) |
| if err != nil { |
| return fail(CodeInvalid, "service row: %v", err) |
| } |
| @@ -307,7 +310,7 @@ func (s *Store) migrate(ctx context.Context) error { |
| return err |
| } |
| v = 2 |
| - case v != 2 && v != SchemaVersion: |
| + case v != 2 && v != 3 && v != SchemaVersion: |
| return fail(CodeStaleStore, "unsupported schema %d", v) |
| } |
| rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`) |
| @@ -340,13 +343,21 @@ func (s *Store) migrate(ctx context.Context) error { |
| if _, err := tx.ExecContext(ctx, periodSchema); err != nil { |
| return err |
| } |
| - if v < 3 { |
| - if err := migrateTimeReservations(ctx, tx); err != nil { |
| + if v > 0 && v < 3 { |
| + if _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=3 WHERE id=1`); err != nil { |
| return err |
| } |
| } |
| - if v < SchemaVersion { |
| - _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=? WHERE id=1`, SchemaVersion) |
| + if v < 4 { |
| + if _, err = tx.ExecContext(ctx, recoverySchema); err != nil { |
| + return err |
| + } |
| + if v < 3 { |
| + if err := migrateTimeReservations(ctx, tx); err != nil { |
| + return err |
| + } |
| + } |
| + _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=4 WHERE id=1`) |
| } |
| return err |
| }) |
| @@ -358,11 +369,15 @@ func (s *Store) start(ctx context.Context) error { |
| var next int64 |
| err := s.transaction(ctx, false, true, func(tx *sql.Tx) error { |
| var inc, revision int64 |
| - var previousRestore int |
| - if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision, restore_uncertain FROM service WHERE id=1`).Scan(&inc, &revision, &previousRestore); err != nil { |
| + var previousRestore, previousQuarantine int |
| + var previousWhy string |
| + if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision, restore_uncertain, quarantine, quarantine_why FROM service WHERE id=1`).Scan(&inc, &revision, &previousRestore, &previousQuarantine, &previousWhy); err != nil { |
| return err |
| } |
| why, restore := "", previousRestore |
| + if previousQuarantine != 0 { |
| + why = previousWhy |
| + } |
| mInc, mRevision, clean, markerErr := readMarker(s.marker) |
| if inc == 0 { |
| // Establish an empty predecessor before the first commit. A |
| @@ -401,16 +416,28 @@ func (s *Store) start(ctx context.Context) error { |
| if err != nil { |
| return err |
| } |
| - q := 0 |
| - if why != "" { |
| - q = 1 |
| - } |
| if restore != 0 { |
| if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='restored intent may have executed after snapshot' WHERE state='intent'`); err != nil { |
| return err |
| } |
| } |
| - _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, q, why, restore) |
| + // Classify restored intents before clock rollback can revoke live intents. |
| + if err := s.observeClock(ctx, tx); err != nil { |
| + return err |
| + } |
| + var clockQuarantine int |
| + var clockWhy string |
| + if err := tx.QueryRowContext(ctx, `SELECT quarantine,quarantine_why FROM service WHERE id=1`).Scan(&clockQuarantine, &clockWhy); err != nil { |
| + return err |
| + } |
| + if why == "" && clockQuarantine != 0 { |
| + why = clockWhy |
| + } |
| + q := 0 |
| + if why != "" { |
| + q = 1 |
| + } |
| + _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, recovery_revision=recovery_revision+1, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, q, why, restore) |
| return err |
| }) |
| if err == nil { |
| @@ -470,6 +497,17 @@ func writeMarker(path string, inc, revision int64, clean bool) error { |
| // unpublished commit; start repairs that gap before advancing again. |
| // Reads also advance the position in this bounded prototype. |
| func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| + return s.transact(ctx, false, func(tx *sql.Tx) error { |
| + if s.incarnation != 0 { |
| + if err := s.observeClock(ctx, tx); err != nil { |
| + return err |
| + } |
| + } |
| + return fn(tx) |
| + }) |
| +} |
| + |
| +func (s *Store) read(ctx context.Context, fn func(*sql.Tx) error) error { |
| return s.transact(ctx, false, fn) |
| } |
diff --git a/internal/equipotest/authority_test.go b/internal/equipotest/authority_test.go| index 35f63a5d..87acb438 100644 |
| --- a/internal/equipotest/authority_test.go |
| +++ b/internal/equipotest/authority_test.go |
| @@ -29,7 +29,7 @@ func authorityFixture(t *testing.T) (*equipo.Store, *db.DB, equipo.Project, *tea |
| } |
| clock := team.NewFakeClock(time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)) |
| auth := equipo.NewAuthority(s, clock) |
| - req := team.AdmissionRequest{Grant: equipo.GrantRef(p.ID, "member@example.com"), Account: team.AccountID(id), Operation: team.OpJobContinue, |
| + req := team.AdmissionRequest{Project: team.ProjectID(p.ID), Grant: equipo.GrantRef(p.ID, "member@example.com"), Account: team.AccountID(id), Operation: team.OpJobContinue, |
| Target: team.TargetBinding{Kind: team.TargetRepository, Repository: p.Repository, App: p.AppName, Ref: "review/task-6", DefaultRef: p.DefaultBranch, BaseRevision: "base"}} |
| return s, d, p, clock, auth, req |
| } |
| @@ -114,7 +114,10 @@ func TestAuthorityRejectsMismatchedTarget(t *testing.T) { |
| change func(*team.AdmissionRequest) |
| }{ |
| {"unknown project", func(r *team.AdmissionRequest) { r.Grant = equipo.GrantRef(999, ownerAddress) }}, |
| - {"another project grant", func(r *team.AdmissionRequest) { r.Grant = equipo.GrantRef(other.ID, ownerAddress) }}, |
| + {"another project grant", func(r *team.AdmissionRequest) { |
| + r.Project = team.ProjectID(other.ID) |
| + r.Grant = equipo.GrantRef(other.ID, ownerAddress) |
| + }}, |
| {"wrong team", func(r *team.AdmissionRequest) { r.Account = "another-team" }}, |
| {"label account", func(r *team.AdmissionRequest) { r.Account = team.AccountID(fmt.Sprint(p.AccountID)) }}, |
| {"wrong repository", func(r *team.AdmissionRequest) { r.Target.Repository = other.Repository }}, |
| @@ -238,7 +241,7 @@ func TestAuthoritySnapshotChanges(t *testing.T) { |
| p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "revision") |
| clock.Advance(time.Second) |
| second := requireAdmission(t, auth, req) |
| - if second.Version != p.Revision || second.Version != first.Version+1 || second.Epoch != first.Epoch || second.IssuedAt != clock.Now() || second.ExpiresAt.Sub(second.IssuedAt) != 5*time.Second { |
| + if second.Version != p.GrantVersion || second.Version != first.Version || second.Epoch != first.Epoch || second.IssuedAt != clock.Now() || second.ExpiresAt.Sub(second.IssuedAt) != 5*time.Second { |
| t.Fatalf("project edit snapshot: %+v", second) |
| } |
| setMember(t, s, "new@example.com", equipo.RoleMember, true) |
| @@ -307,7 +310,8 @@ func TestAuthorityCoreIntegration(t *testing.T) { |
| want := team.ErrGrantStale |
| switch change { |
| case "project revision": |
| - p.Name = "Changed" |
| + p.DefaultBranch = "trunk" |
| + want = team.ErrGrantRevoked |
| saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "edit") |
| case "roster epoch": |
| setMember(t, s, "new@example.com", equipo.RoleMember, true) |
| @@ -353,6 +357,7 @@ func TestAuthorityProjectKinds(t *testing.T) { |
| other.Kind, other.AppName = kind, "" |
| other = saveProject(t, s, other, projectOwners(), string(kind)) |
| r := req |
| + r.Project = team.ProjectID(other.ID) |
| r.Grant = equipo.GrantRef(other.ID, ownerAddress) |
| r.Target.Repository, r.Target.App = other.Repository, "" |
| for _, op := range authorityOps { |
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go| index 56353931..e6bea07c 100644 |
| --- a/internal/equipotest/execution_schema_test.go |
| +++ b/internal/equipotest/execution_schema_test.go |
| @@ -145,7 +145,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer old.Close() |
| before := &migrate.Set{} |
| for _, m := range equipo.BootSchema.All() { |
| - if m.ID != "equipo/0007_execution" { |
| + if m.ID != "equipo/0007_execution" && m.ID != "equipo/0008_recovery" { |
| before.Add(m) |
| } |
| } |
| @@ -154,7 +154,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| executionMust(t, old.G.Create(&equipo.Account{Label: "existing account"}).Error) |
| result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| executionMust(t, err) |
| - if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution"}) { |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0007_execution", "equipo/0008_recovery"}) { |
| t.Fatalf("upgrade migrations: %v", result.Applied) |
| } |
| var account equipo.Account |
| @@ -168,7 +168,39 @@ func TestExecutionSchemaParity(t *testing.T) { |
| t.Fatal("upgrade repeated") |
| } |
| }) |
| - coreNames := map[string]bool{"service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} |
| + t.Run("task one upgrade", func(t *testing.T) { |
| + old, err := db.Open(filepath.Join(t.TempDir(), "task1.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + executionMust(t, err) |
| + defer old.Close() |
| + before := &migrate.Set{} |
| + for _, m := range equipo.BootSchema.All() { |
| + if m.ID != "equipo/0008_recovery" { |
| + before.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, old, before) |
| + executionMust(t, err) |
| + executionMust(t, seedExecutionJob(old.Writer())) |
| + _, err = old.Writer().Exec(`INSERT INTO projects(id,repository,app_name,revision) VALUES(1,'amadan.net/oficina/shop','shop',7)`) |
| + executionMust(t, err) |
| + result, err := migrate.Apply(ctx, old, equipo.BootSchema) |
| + executionMust(t, err) |
| + if !reflect.DeepEqual(result.Applied, []string{"equipo/0008_recovery"}) { |
| + t.Fatalf("task one upgrade migrations: %v", result.Applied) |
| + } |
| + var evidence string |
| + executionMust(t, old.Writer().QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) |
| + if evidence != "preserved evidence" || scalar(t, old, "SELECT grant_version FROM projects WHERE id=1") != 7 { |
| + t.Fatal("task one upgrade lost data or grant version") |
| + } |
| + got, err := migrate.Read(ctx, old.Writer()) |
| + executionMust(t, err) |
| + if diff := expected.Diff(got); len(diff) != 0 { |
| + t.Fatalf("task one upgrade schema: %v", diff) |
| + } |
| + }) |
| + |
| + coreNames := map[string]bool{"grant_fences": true, "recovery_charges": true, "recovery_events": true, "service": true, "jobs": true, "steps": true, "attempts": true, "reservations": true, "actions": true, "events": true, "artifacts": true, "period_budgets": true, "time_reservations": true} |
| var appCore migrate.Snapshot |
| for _, table := range expected.Tables { |
| if coreNames[table.Name] { |
| @@ -178,7 +210,7 @@ func TestExecutionSchemaParity(t *testing.T) { |
| if len(appCore.Tables) != len(coreNames) { |
| t.Fatalf("execution tables = %d, want %d", len(appCore.Tables), len(coreNames)) |
| } |
| - for _, version := range []int{1, 2, 3} { |
| + for _, version := range []int{1, 2, 3, 4} { |
| t.Run(fmt.Sprint(version), func(t *testing.T) { |
| standalonePath := filepath.Join(t.TempDir(), "core.db") |
| core, err := team.Open(ctx, standalonePath, executionOptions()) |
| @@ -189,6 +221,12 @@ func TestExecutionSchemaParity(t *testing.T) { |
| defer raw.Close() |
| raw.SetMaxOpenConns(1) |
| executionMust(t, seedExecutionJob(raw)) |
| + if version < 4 { |
| + for _, q := range []string{`DROP TABLE recovery_events`, `DROP TABLE recovery_charges`, `DROP TABLE grant_fences`, `ALTER TABLE service DROP COLUMN release_required`, `ALTER TABLE service DROP COLUMN recovery_revision`, `ALTER TABLE service DROP COLUMN reconciled_revision`, `ALTER TABLE service DROP COLUMN clock_high_water`, `ALTER TABLE jobs DROP COLUMN grant_stale`, `ALTER TABLE time_reservations DROP COLUMN elapsed_unknown`} { |
| + _, err = raw.Exec(q) |
| + executionMust(t, err) |
| + } |
| + } |
| if version < 3 { |
| for _, q := range []string{`DROP TABLE time_reservations`, `DROP TABLE period_budgets`, `ALTER TABLE jobs DROP COLUMN project_id`} { |
| _, err = raw.Exec(q) |
diff --git a/internal/equipotest/recovery_test.go b/internal/equipotest/recovery_test.go| new file mode 100644 |
| index 00000000..89231e9a |
| --- /dev/null |
| +++ b/internal/equipotest/recovery_test.go |
| @@ -0,0 +1,402 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "context" |
| + "errors" |
| + "gorm.io/gorm" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| +) |
| + |
| +func TestRecoveryReleaseOwnerAndRevision(t *testing.T) { |
| + d, path := executionDB(t) |
| + ctx := context.Background() |
| + s := equipo.NewStore(d) |
| + executionMust(t, s.Bootstrap(ctx, []string{ownerAddress})) |
| + executionMust(t, s.SetMember(ctx, equipo.Actor{Address: ownerAddress}, "member@example.com", equipo.RoleMember, true, 0)) |
| + x, err := s.AttachExecution(ctx, path, executionOptions()) |
| + executionMust(t, err) |
| + defer x.Core.Close() |
| + executionMust(t, x.Core.Pause(ctx, "restore review")) |
| + snap, err := x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + if err = s.ReleaseExecution(ctx, equipo.Actor{Address: "member@example.com"}, snap.Revision, "reviewed", snap.Hash); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatalf("member release: %v", err) |
| + } |
| + if err = s.ReleaseExecution(ctx, equipo.Actor{Address: ownerAddress}, snap.Revision, "reviewed", snap.Hash); err == nil { |
| + t.Fatal("missing reconciliation accepted") |
| + } |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + snap, err = x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + for _, bad := range []struct { |
| + rev int64 |
| + hash, reason string |
| + }{{snap.Revision - 1, snap.Hash, "reviewed"}, {snap.Revision, "wrong", "reviewed"}, {snap.Revision, snap.Hash, ""}} { |
| + if err = s.ReleaseExecution(ctx, equipo.Actor{Address: ownerAddress}, bad.rev, bad.reason, bad.hash); err == nil { |
| + t.Fatal("invalid release accepted") |
| + } |
| + } |
| + _, err = x.Core.Status(ctx) |
| + executionMust(t, err) |
| + same, err := x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + if snap.Revision != same.Revision || snap.Hash != same.Hash { |
| + t.Fatal("read changed recovery snapshot") |
| + } |
| + executionMust(t, s.ReleaseExecution(ctx, equipo.Actor{Address: ownerAddress}, snap.Revision, "reviewed", snap.Hash)) |
| + st, err := x.Core.Status(ctx) |
| + executionMust(t, err) |
| + if st.Quarantine || !st.AdmissionPaused { |
| + t.Fatalf("release reopened admission: %+v", st) |
| + } |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + if scalar(t, d, "SELECT count(*) FROM audit_events WHERE kind='execution.release'") != 1 || scalar(t, d, "SELECT count(*) FROM recovery_events WHERE kind='release'") != 1 { |
| + t.Fatal("release audit missing") |
| + } |
| +} |
| + |
| +func TestProjectGrantChargeAgreement(t *testing.T) { |
| + _, _, p, clock, auth, req := authorityFixture(t) |
| + req.Project = team.ProjectID(p.ID) + 1 |
| + requireRevoked(t, auth, req) |
| + req.Project = team.ProjectID(p.ID) |
| + core, err := team.Open(context.Background(), t.TempDir()+"/core.db", team.Options{Clock: clock, Authority: auth}) |
| + executionMust(t, err) |
| + defer core.Close() |
| + _, err = core.Resume(context.Background()) |
| + executionMust(t, err) |
| + spec := team.JobSpec{Account: req.Account, Project: req.Project + 1, Requester: "member@example.com", GrantRef: req.Grant, Target: req.Target, Policy: team.DefaultPolicy(5000000, team.Rates{Version: 1}), Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, Steps: team.SoftwareSteps(false)} |
| + if _, err = core.CreateJob(context.Background(), spec); !errors.Is(err, team.ErrGrantRevoked) { |
| + t.Fatalf("wrong project created: %v", err) |
| + } |
| +} |
| + |
| +func recoveryRuntime(t *testing.T) (*equipo.Store, *db.DB, *equipo.Execution, equipo.Project, *team.FakeClock, team.AdmissionRequest) { |
| + t.Helper() |
| + s, d, p, clock, auth, req := authorityFixture(t) |
| + var seq int |
| + var name, path string |
| + executionMust(t, d.Writer().QueryRow(`PRAGMA database_list`).Scan(&seq, &name, &path)) |
| + x, err := s.AttachExecution(context.Background(), path, team.Options{Clock: clock, Authority: auth, Adapters: map[team.Operation]team.Adapter{team.OpProviderCall: team.NewFakeProvider("fake", "model", map[string]string{})}}) |
| + executionMust(t, err) |
| + t.Cleanup(func() { x.Core.Close() }) |
| + _, err = x.Core.Resume(context.Background()) |
| + executionMust(t, err) |
| + return s, d, x, p, clock, req |
| +} |
| + |
| +func recoveryJob(t *testing.T, x *equipo.Execution, req team.AdmissionRequest, key string) (team.Scope, team.Handle, team.ActionID) { |
| + t.Helper() |
| + ctx := context.Background() |
| + job, err := x.Core.CreateJob(ctx, team.JobSpec{Account: req.Account, Project: req.Project, Requester: "member@example.com", GrantRef: req.Grant, Target: req.Target, Policy: team.DefaultPolicy(5000000, team.Rates{Version: 1}), Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, Steps: team.SoftwareSteps(false)}) |
| + executionMust(t, err) |
| + scope := team.Scope{Account: job.Account, Job: job.ID} |
| + h, err := x.Core.Claim(ctx, scope, "reproduce", key, key) |
| + executionMust(t, err) |
| + id, err := x.Core.Intend(ctx, scope, h, team.IntentSpec{Key: key, Operation: team.OpProviderCall, Payload: []byte(`{"task":"implement","prompt":"test"}`), Reserve: team.Usage{InputTokens: 10}}) |
| + executionMust(t, err) |
| + return scope, h, id |
| +} |
| + |
| +func TestProjectGrantChargeAgreementRenewAndAdmit(t *testing.T) { |
| + for _, operation := range []string{"renew", "admit"} { |
| + t.Run(operation, func(t *testing.T) { |
| + _, _, x, _, _, req := recoveryRuntime(t) |
| + scope, h, id := recoveryJob(t, x, req, operation) |
| + ctx := context.Background() |
| + executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { |
| + return tx.Exec(`UPDATE jobs SET project_id=project_id+1 WHERE id=?`, scope.Job).Error |
| + })) |
| + var err error |
| + if operation == "renew" { |
| + _, err = x.Core.Renew(ctx, scope, h) |
| + } else { |
| + _, err = x.Core.Admit(ctx, scope, id) |
| + } |
| + if !errors.Is(err, team.ErrGrantRevoked) { |
| + t.Fatalf("wrong project %s: %v", operation, err) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityEditFencesOnlyChangedGrants(t *testing.T) { |
| + s, d, x, p, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + owner := equipo.Actor{Address: ownerAddress} |
| + other := p |
| + other.ID = 0 |
| + other.Revision = 0 |
| + other.Repository = "amadan.net/oficina/second" |
| + other = saveProject(t, s, other, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "second") |
| + rb := req |
| + rb.Project = team.ProjectID(other.ID) |
| + rb.Grant = equipo.GrantRef(other.ID, "member@example.com") |
| + rb.Target.Repository = other.Repository |
| + a, ha, ia := recoveryJob(t, x, req, "a") |
| + b, hb, ib := recoveryJob(t, x, rb, "b") |
| + // Labels and non-work routing do not alter execution authority. |
| + p.Name = "Renamed" |
| + p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: "member@example.com"}}, "label") |
| + var account equipo.Account |
| + executionMust(t, d.G.First(&account, p.AccountID).Error) |
| + account.Label = "Renamed account" |
| + _, err := s.SaveAccount(ctx, owner, account) |
| + executionMust(t, err) |
| + _, err = x.Core.Renew(ctx, a, ha) |
| + executionMust(t, err) |
| + _, err = x.Core.Renew(ctx, b, hb) |
| + executionMust(t, err) |
| + if scalar(t, d, "SELECT count(*) FROM jobs WHERE grant_stale<>0") != 0 { |
| + t.Fatal("metadata edit staled grants") |
| + } |
| + // The target changes only A, leaving B's admission and renewal live. |
| + p.DefaultBranch = "trunk" |
| + p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "target") |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + if _, err = x.Core.Renew(ctx, a, ha); err == nil { |
| + t.Fatal("target edit did not fence A") |
| + } |
| + if _, err = x.Core.Admit(ctx, a, ia); err == nil { |
| + t.Fatal("target edit did not revoke A intent") |
| + } |
| + _, err = x.Core.Renew(ctx, b, hb) |
| + executionMust(t, err) |
| + _, err = x.Core.Admit(ctx, b, ib) |
| + executionMust(t, err) |
| + job, err := x.Core.GetJob(ctx, a) |
| + executionMust(t, err) |
| + if job.State != team.JobCancelled { |
| + t.Fatal("target-changed job not cancelled") |
| + } |
| + // A roster epoch change stales all remaining grants, even unrelated people. |
| + executionMust(t, s.SetMember(ctx, owner, "new@example.com", equipo.RoleMember, true, 0)) |
| + if scalar(t, d, "SELECT count(*) FROM attempts WHERE state='active'") != 0 { |
| + t.Fatal("roster commit left active attempts") |
| + } |
| + if _, err = x.Core.Renew(ctx, b, hb); err == nil { |
| + t.Fatal("roster epoch did not fence B") |
| + } |
| + attempts, err := x.Core.Attempts(ctx, b) |
| + executionMust(t, err) |
| + if attempts[0].State != team.AttemptStopping { |
| + t.Fatal("roster change did not request stop") |
| + } |
| + executionMust(t, x.Core.Contain(ctx, b, hb.Attempt, "supervisor")) |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + _, err = x.Core.Claim(ctx, b, "reproduce", "new", "new") |
| + executionMust(t, err) |
| +} |
| + |
| +func TestRuntimeAuthorityBudgetSyncAndRemoval(t *testing.T) { |
| + s, d, x, p, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + owner := equipo.Actor{Address: ownerAddress} |
| + l := team.PeriodLimits{Calls: 100, InputTokens: 10000, OutputTokens: 10000, Seconds: 10000} |
| + executionMust(t, s.SaveBudgets(ctx, owner, equipo.BudgetConfig{Team: l, Projects: map[team.ProjectID]team.PeriodLimits{req.Project: l}})) |
| + scope, h, _ := recoveryJob(t, x, req, "budget") |
| + l.Calls = 90 |
| + executionMust(t, s.SaveBudgets(ctx, owner, equipo.BudgetConfig{Revision: 1, Team: l, Projects: map[team.ProjectID]team.PeriodLimits{req.Project: l}})) |
| + _, err := x.Core.Renew(ctx, scope, h) |
| + executionMust(t, err) |
| + if scalar(t, d, "SELECT count(*) FROM period_budgets WHERE revision=2") != 1 || scalar(t, d, "SELECT count(*) FROM jobs WHERE grant_stale<>0") != 0 { |
| + t.Fatal("budget edit did not synchronize independently") |
| + } |
| + // An owner need not be a decision owner to have a grant; removal cancels it. |
| + executionMust(t, s.SetMember(ctx, owner, "second@example.com", equipo.RoleOwner, true, 0)) |
| + r := req |
| + r.Grant = equipo.GrantRef(p.ID, "second@example.com") |
| + removed, rh, _ := recoveryJob(t, x, r, "removed") |
| + executionMust(t, s.SetMember(ctx, owner, "second@example.com", equipo.RoleOwner, false, 1)) |
| + job, err := x.Core.GetJob(ctx, removed) |
| + executionMust(t, err) |
| + if job.State != team.JobCancelled { |
| + t.Fatal("member removal did not cancel work") |
| + } |
| + attempts, err := x.Core.Attempts(ctx, removed) |
| + executionMust(t, err) |
| + if attempts[0].State != team.AttemptStopping { |
| + t.Fatal("member removal omitted stop") |
| + } |
| + if _, err = x.Core.Renew(ctx, removed, rh); err == nil { |
| + t.Fatal("removed member renewed") |
| + } |
| +} |
| + |
| +func TestRecoveryReleaseUncontainedAndAtomicAudit(t *testing.T) { |
| + s, d, x, _, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + owner := equipo.Actor{Address: ownerAddress} |
| + scope, h, _ := recoveryJob(t, x, req, "release") |
| + executionMust(t, x.Core.Pause(ctx, "owner review")) |
| + _, err := x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + snap, err := x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + if err = s.ReleaseExecution(ctx, owner, snap.Revision, "reviewed", snap.Hash); err == nil { |
| + t.Fatal("uncontained release accepted") |
| + } |
| + executionMust(t, x.Core.StopAttempt(ctx, scope, h, "cleanup")) |
| + executionMust(t, x.Core.Contain(ctx, scope, h.Attempt, "supervisor")) |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + snap, err = x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + _, err = d.Writer().Exec(`CREATE TRIGGER reject_release_audit BEFORE INSERT ON audit_events WHEN NEW.kind='execution.release' BEGIN SELECT RAISE(ABORT,'audit unavailable'); END`) |
| + executionMust(t, err) |
| + if err = s.ReleaseExecution(ctx, owner, snap.Revision, "reviewed", snap.Hash); err == nil { |
| + t.Fatal("release survived failed audit") |
| + } |
| + st, err := x.Core.Status(ctx) |
| + executionMust(t, err) |
| + if !st.Quarantine || scalar(t, d, "SELECT count(*) FROM recovery_events WHERE kind='release'") != 0 { |
| + t.Fatal("release partially committed") |
| + } |
| + _, err = d.Writer().Exec(`DROP TRIGGER reject_release_audit`) |
| + executionMust(t, err) |
| + executionMust(t, s.ReleaseExecution(ctx, owner, snap.Revision, "reviewed", snap.Hash)) |
| +} |
| + |
| +func TestRecoveryReleaseMissingHistoryCharge(t *testing.T) { |
| + s, d, x, _, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + owner := equipo.Actor{Address: ownerAddress} |
| + l := team.PeriodLimits{Calls: 100, InputTokens: 10000, OutputTokens: 10000, Seconds: 10000} |
| + executionMust(t, s.SaveBudgets(ctx, owner, equipo.BudgetConfig{Team: l, Projects: map[team.ProjectID]team.PeriodLimits{req.Project: l}})) |
| + executionMust(t, x.Core.Pause(ctx, "missing history")) |
| + executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Exec(`UPDATE service SET restore_uncertain=1`).Error })) |
| + _, err := x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + snap, err := x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + if err = s.ReleaseExecution(ctx, owner, snap.Revision, "attest missing work", snap.Hash); err == nil { |
| + t.Fatal("missing history released without charge") |
| + } |
| + charge := team.RecoveryCharge{Key: "restore-1", Account: req.Account, Project: req.Project, Reserved: team.PeriodLimits{Calls: 10, Seconds: 100}} |
| + if err = s.RecordRecoveryCharge(ctx, equipo.Actor{Address: "member@example.com"}, charge, "attest"); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatalf("member recovery charge: %v", err) |
| + } |
| + executionMust(t, s.RecordRecoveryCharge(ctx, owner, charge, "attest missing work and conservative reserve")) |
| + executionMust(t, s.RecordRecoveryCharge(ctx, owner, charge, "retry")) |
| + if scalar(t, d, "SELECT count(*) FROM recovery_charges") != 1 { |
| + t.Fatal("recovery charge duplicated") |
| + } |
| + altered := charge |
| + altered.Reserved.Calls++ |
| + if err = s.RecordRecoveryCharge(ctx, owner, altered, "changed"); err == nil { |
| + t.Fatal("recovery key content changed") |
| + } |
| + if err = s.ReleaseExecution(ctx, owner, snap.Revision, "reviewed", snap.Hash); err == nil { |
| + t.Fatal("charge did not invalidate reconciliation") |
| + } |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + snap, err = x.Core.RecoverySnapshot(ctx) |
| + executionMust(t, err) |
| + executionMust(t, s.ReleaseExecution(ctx, owner, snap.Revision, "attest missing history has been conservatively charged", snap.Hash)) |
| + usage, err := x.Core.PeriodUsage(ctx, req.Account, req.Project, time.Now()) |
| + executionMust(t, err) |
| + if usage.Reserved != charge.Reserved || scalar(t, d, "SELECT count(*) FROM actions WHERE receipt<>''") != 0 { |
| + t.Fatalf("charge lost or fabricated receipt: %+v", usage) |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityAttachSavedBudgets(t *testing.T) { |
| + s, d, p, clock, auth, req := authorityFixture(t) |
| + ctx := context.Background() |
| + owner := equipo.Actor{Address: ownerAddress} |
| + l := team.PeriodLimits{Calls: 100, InputTokens: 10000, OutputTokens: 10000, Seconds: 10000} |
| + config := equipo.BudgetConfig{Team: l, Projects: map[team.ProjectID]team.PeriodLimits{team.ProjectID(p.ID): l}} |
| + executionMust(t, s.SaveBudgets(ctx, owner, config)) |
| + config.Revision = 1 |
| + executionMust(t, s.SaveBudgets(ctx, owner, config)) |
| + var seq int |
| + var name, path string |
| + executionMust(t, d.Writer().QueryRow(`PRAGMA database_list`).Scan(&seq, &name, &path)) |
| + x, err := s.AttachExecution(ctx, path, team.Options{Clock: clock, Authority: auth}) |
| + executionMust(t, err) |
| + defer x.Core.Close() |
| + if scalar(t, d, "SELECT count(*) FROM period_budgets WHERE revision=2") != 1 { |
| + t.Fatal("attachment lost existing budgets") |
| + } |
| + config.Revision = 2 |
| + executionMust(t, s.SaveBudgets(ctx, owner, config)) |
| + usage, err := x.Core.PeriodUsage(ctx, req.Account, req.Project, clock.Now()) |
| + executionMust(t, err) |
| + if usage != (team.PeriodUsage{}) { |
| + t.Fatalf("fresh budget usage: %+v", usage) |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityAdmissionRacesEdit(t *testing.T) { |
| + s, d, x, p, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + changed := false |
| + executionMust(t, d.G.Callback().Query().After("gorm:query").Register("race_grant_creation", func(tx *gorm.DB) { |
| + if tx.Statement.Table != "projects" || changed { |
| + return |
| + } |
| + changed = true |
| + p.DefaultBranch = "trunk" |
| + p = saveProject(t, s, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "race") |
| + })) |
| + defer d.G.Callback().Query().Remove("race_grant_creation") |
| + _, err := x.Core.CreateJob(ctx, team.JobSpec{Account: req.Account, Project: req.Project, Requester: "member@example.com", GrantRef: req.Grant, Target: req.Target, Policy: team.DefaultPolicy(5000000, team.Rates{Version: 1}), Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, Steps: team.SoftwareSteps(false)}) |
| + if !changed || !errors.Is(err, team.ErrGrantStale) { |
| + t.Fatalf("stale creation raced edit: changed=%v err=%v", changed, err) |
| + } |
| + if scalar(t, d, "SELECT count(*) FROM jobs") != 0 { |
| + t.Fatal("stale creation committed") |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityEditAuditRollback(t *testing.T) { |
| + s, d, x, p, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + scope, h, id := recoveryJob(t, x, req, "rollback") |
| + _, err := d.Writer().Exec(`CREATE TRIGGER reject_project_audit BEFORE INSERT ON audit_events WHEN NEW.kind='project.save' BEGIN SELECT RAISE(ABORT,'audit unavailable'); END`) |
| + executionMust(t, err) |
| + p.DefaultBranch = "trunk" |
| + if _, err = s.SaveProject(ctx, equipo.Actor{Address: ownerAddress}, p, []equipo.DecisionOwner{{Decision: "work", Address: "member@example.com"}, {Decision: "merge", Address: ownerAddress}}, "rollback"); err == nil { |
| + t.Fatal("project edit survived audit failure") |
| + } |
| + _, err = x.Core.Renew(ctx, scope, h) |
| + executionMust(t, err) |
| + _, err = x.Core.Admit(ctx, scope, id) |
| + executionMust(t, err) |
| + if scalar(t, d, "SELECT count(*) FROM jobs WHERE grant_stale<>0") != 0 { |
| + t.Fatal("failed project edit committed fence") |
| + } |
| +} |
| + |
| +func TestRuntimeAuthorityLookupFailureDenies(t *testing.T) { |
| + _, d, x, _, _, req := recoveryRuntime(t) |
| + ctx := context.Background() |
| + scope, h, id := recoveryJob(t, x, req, "lookup") |
| + executionMust(t, d.G.Callback().Query().Before("gorm:query").Register("failed_roster_lookup", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "members" { |
| + tx.AddError(errors.New("roster lookup unavailable")) |
| + } |
| + })) |
| + defer d.G.Callback().Query().Remove("failed_roster_lookup") |
| + if _, err := x.Core.Renew(ctx, scope, h); !errors.Is(err, team.ErrAuthorityUnavailable) { |
| + t.Fatalf("lookup failure renewed: %v", err) |
| + } |
| + if _, err := x.Core.Admit(ctx, scope, id); !errors.Is(err, team.ErrAuthorityUnavailable) { |
| + t.Fatalf("lookup failure admitted: %v", err) |
| + } |
| + job, err := x.Core.GetJob(ctx, scope) |
| + executionMust(t, err) |
| + if job.State == team.JobCancelled { |
| + t.Fatal("lookup error became revocation") |
| + } |
| +} |