feat: attach execution storage to the activation database
10 files changed,
+1,441
−16
internal/equipo/execution.go+49 −0internal/equipo/execution_models.go+184 −0internal/equipo/migrations/0007_execution.sql+151 −0internal/equipo/migrations/schema.sql+184 −7internal/equipo/models.go+1 −1internal/equipo/store.go+10 −2internal/equipo/team/shared.go+268 −0internal/equipo/team/shared_test.go+251 −0internal/equipo/team/store.go+19 −6internal/equipotest/execution_schema_test.go+324 −0
CI failed — run details
diff --git a/internal/equipo/execution.go b/internal/equipo/execution.go| new file mode 100644 |
| index 00000000..ced7cca7 |
| --- /dev/null |
| +++ b/internal/equipo/execution.go |
| @@ -0,0 +1,49 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| +) |
| + |
| +type Execution struct { |
| + Core *team.Store |
| + db *db.DB |
| +} |
| + |
| +// AttachExecution is a startup operation, before serving requests. |
| +// Production boot stays unattached until runner recovery is wired. |
| +func (s *Store) AttachExecution(ctx context.Context, path string, options team.Options) (*Execution, error) { |
| + if s == nil || s.db == nil { |
| + return nil, ErrUnavailable |
| + } |
| + if s.execution != nil { |
| + return nil, ErrConflict |
| + } |
| + core, err := team.OpenShared(ctx, s.db.Writer(), path, options) |
| + if err != nil { |
| + return nil, err |
| + } |
| + x := &Execution{Core: core, db: s.db} |
| + s.execution = x |
| + return x, nil |
| +} |
| + |
| +// Write shares one commit with core SQL and audit records. The callback must |
| +// use its GORM handle throughout and leave commit and rollback to the core. |
| +func (e *Execution) Write(ctx context.Context, fn func(*gorm.DB) error) error { |
| + if e == nil || e.Core == nil || e.db == nil { |
| + return ErrUnavailable |
| + } |
| + return e.Core.WithTransaction(ctx, func(tx *sql.Tx) error { |
| + g := e.db.G.Session(&gorm.Session{NewDB: true, Context: ctx, SkipDefaultTransaction: true, DisableNestedTransaction: true}).Clauses(dbresolver.Write) |
| + g.Statement.ConnPool = tx |
| + g.ConnPool = tx |
| + // A fresh statement prevents an earlier query error leaking into the next. |
| + return fn(g.Session(&gorm.Session{NewDB: true})) |
| + }) |
| +} |
diff --git a/internal/equipo/execution_models.go b/internal/equipo/execution_models.go| new file mode 100644 |
| index 00000000..851249fc |
| --- /dev/null |
| +++ b/internal/equipo/execution_models.go |
| @@ -0,0 +1,184 @@ |
| +package equipo |
| + |
| +// These private models describe columns and named indexes for migration checks. |
| +// SQL owns the unnamed checks, foreign keys and compound unique constraints; |
| +// TestExecutionSchemaParity compares those against the standalone core. |
| + |
| +type executionActions struct { |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null"` |
| + StepID int64 `gorm:"column:step_id;type:integer;not null"` |
| + AttemptID int64 `gorm:"column:attempt_id;type:integer;not null"` |
| + Fence int64 `gorm:"column:fence;type:integer;not null"` |
| + Key string `gorm:"column:key;type:text;not null"` |
| + Operation string `gorm:"column:operation;type:text;not null"` |
| + Class string `gorm:"column:class;type:text;not null"` |
| + PayloadHash string `gorm:"column:payload_hash;type:text;not null"` |
| + Payload []byte `gorm:"column:payload;type:blob;not null"` |
| + State string `gorm:"column:state;type:text;not null;index:actions_state,priority:1"` |
| + ReservationID int64 `gorm:"column:reservation_id;type:integer;not null"` |
| + GrantRef string `gorm:"column:grant_ref;type:text;not null"` |
| + GrantVersion int64 `gorm:"column:grant_version;type:integer;not null"` |
| + GrantEpoch int64 `gorm:"column:grant_epoch;type:integer;not null"` |
| + AdmittedAt string `gorm:"column:admitted_at;type:text;not null"` |
| + AdmissionEnds string `gorm:"column:admission_ends;type:text;not null"` |
| + Receipt string `gorm:"column:receipt;type:text;not null"` |
| + LastError string `gorm:"column:last_error;type:text;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| + UpdatedAt string `gorm:"column:updated_at;type:text;not null"` |
| + AdmittedIncarnation int64 `gorm:"column:admitted_incarnation;type:integer;not null;default:0"` |
| +} |
| + |
| +func (executionActions) TableName() string { return "actions" } |
| + |
| +type executionArtifacts struct { |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null;index:artifacts_job,priority:1"` |
| + StepID int64 `gorm:"column:step_id;type:integer;not null"` |
| + AttemptID int64 `gorm:"column:attempt_id;type:integer;not null"` |
| + Fence int64 `gorm:"column:fence;type:integer;not null"` |
| + Role string `gorm:"column:role;type:text;not null;index:artifacts_job,priority:2"` |
| + Hash string `gorm:"column:hash;type:text;not null"` |
| + MediaType string `gorm:"column:media_type;type:text;not null"` |
| + Size int64 `gorm:"column:size;type:integer;not null"` |
| + Provenance string `gorm:"column:provenance;type:text;not null"` |
| + Payload []byte `gorm:"column:payload;type:blob;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| +} |
| + |
| +func (executionArtifacts) TableName() string { return "artifacts" } |
| + |
| +type executionAttempts struct { |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null;index:attempts_job,priority:1"` |
| + StepID int64 `gorm:"column:step_id;type:integer;not null;uniqueIndex:attempts_one_live,priority:1,where:containment = 'pending'"` |
| + Number int64 `gorm:"column:number;type:integer;not null"` |
| + Runner string `gorm:"column:runner;type:text;not null"` |
| + Workspace string `gorm:"column:workspace;type:text;not null"` |
| + Fence int64 `gorm:"column:fence;type:integer;not null"` |
| + LeaseDeadline string `gorm:"column:lease_deadline;type:text;not null"` |
| + State string `gorm:"column:state;type:text;not null"` |
| + Containment string `gorm:"column:containment;type:text;not null;index:attempts_job,priority:2"` |
| + StopRequested string `gorm:"column:stop_requested;type:text;not null"` |
| + StopAcked string `gorm:"column:stop_acked;type:text;not null"` |
| + Provider string `gorm:"column:provider;type:text;not null"` |
| + Model string `gorm:"column:model;type:text;not null"` |
| + Effort string `gorm:"column:effort;type:text;not null"` |
| + Outcome string `gorm:"column:outcome;type:text;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| + UpdatedAt string `gorm:"column:updated_at;type:text;not null"` |
| +} |
| + |
| +func (executionAttempts) TableName() string { return "attempts" } |
| + |
| +type executionEvents struct { |
| + JobID int64 `gorm:"column:job_id;type:integer;primaryKey;autoIncrement:false;not null"` |
| + Seq int64 `gorm:"column:seq;type:integer;primaryKey;autoIncrement:false;not null"` |
| + Type string `gorm:"column:type;type:text;not null"` |
| + Actor string `gorm:"column:actor;type:text;not null"` |
| + Payload []byte `gorm:"column:payload;type:blob;not null"` |
| + SourceAt string `gorm:"column:source_at;type:text;not null"` |
| +} |
| + |
| +func (executionEvents) TableName() string { return "events" } |
| + |
| +type executionJobs struct { |
| + 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"` |
| + Depth int64 `gorm:"column:depth;type:integer;not null"` |
| + Requester string `gorm:"column:requester;type:text;not null"` |
| + Target string `gorm:"column:target;type:text;not null"` |
| + Evidence string `gorm:"column:evidence;type:text;not null"` |
| + PolicyVersion int64 `gorm:"column:policy_version;type:integer;not null"` |
| + Policy string `gorm:"column:policy;type:text;not null"` |
| + GrantRef string `gorm:"column:grant_ref;type:text;not null"` |
| + GrantVersion int64 `gorm:"column:grant_version;type:integer;not null"` |
| + GrantEpoch int64 `gorm:"column:grant_epoch;type:integer;not null"` |
| + GrantObservedAt string `gorm:"column:grant_observed_at;type:text;not null"` |
| + State string `gorm:"column:state;type:text;not null;index:jobs_account,priority:2"` |
| + Wait string `gorm:"column:wait;type:text;not null"` |
| + Revision int64 `gorm:"column:revision;type:integer;not null"` |
| + Outcome string `gorm:"column:outcome;type:text;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| + UpdatedAt string `gorm:"column:updated_at;type:text;not null"` |
| + ProjectID int64 `gorm:"column:project_id;type:integer;not null;default:0"` |
| +} |
| + |
| +func (executionJobs) TableName() string { return "jobs" } |
| + |
| +type executionPeriodBudgets struct { |
| + Account string `gorm:"column:account;type:text;primaryKey;autoIncrement:false"` |
| + Revision int64 `gorm:"column:revision;type:integer;not null"` |
| + Config string `gorm:"column:config;type:text;not null"` |
| +} |
| + |
| +func (executionPeriodBudgets) TableName() string { return "period_budgets" } |
| + |
| +type executionReservations struct { |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + Account string `gorm:"column:account;type:text;not null;index:reservations_account,priority:1"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null;index:reservations_job,priority:1"` |
| + StepID int64 `gorm:"column:step_id;type:integer;not null"` |
| + AttemptID int64 `gorm:"column:attempt_id;type:integer;not null"` |
| + ActionID int64 `gorm:"column:action_id;type:integer;not null"` |
| + RCalls int64 `gorm:"column:r_calls;type:integer;not null"` |
| + RInput int64 `gorm:"column:r_input;type:integer;not null"` |
| + ROutput int64 `gorm:"column:r_output;type:integer;not null"` |
| + RCost int64 `gorm:"column:r_cost;type:integer;not null"` |
| + SCalls int64 `gorm:"column:s_calls;type:integer;not null"` |
| + SInput int64 `gorm:"column:s_input;type:integer;not null"` |
| + SOutput int64 `gorm:"column:s_output;type:integer;not null"` |
| + SCost int64 `gorm:"column:s_cost;type:integer;not null"` |
| + State string `gorm:"column:state;type:text;not null;index:reservations_job,priority:2;index:reservations_account,priority:2"` |
| + ReceiptID string `gorm:"column:receipt_id;type:text;not null"` |
| + SettledBy string `gorm:"column:settled_by;type:text;not null"` |
| + CreatedAt string `gorm:"column:created_at;type:text;not null"` |
| + SettledAt string `gorm:"column:settled_at;type:text;not null"` |
| +} |
| + |
| +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"` |
| +} |
| + |
| +func (executionService) TableName() string { return "service" } |
| + |
| +type executionSteps struct { |
| + ID int64 `gorm:"column:id;type:integer;primaryKey;autoIncrement:false"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null"` |
| + Key string `gorm:"column:key;type:text;not null"` |
| + Capability string `gorm:"column:capability;type:text;not null"` |
| + Version int64 `gorm:"column:version;type:integer;not null"` |
| + DependsOn string `gorm:"column:depends_on;type:text;not null"` |
| + State string `gorm:"column:state;type:text;not null"` |
| + Fence int64 `gorm:"column:fence;type:integer;not null"` |
| + Holder int64 `gorm:"column:holder;type:integer;not null"` |
| + Attempts int64 `gorm:"column:attempts;type:integer;not null"` |
| +} |
| + |
| +func (executionSteps) TableName() string { return "steps" } |
| + |
| +type executionTimeReservations struct { |
| + 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"` |
| + JobID int64 `gorm:"column:job_id;type:integer;not null"` |
| + Period string `gorm:"column:period;type:text;not null;index:time_reservations_account,priority:4"` |
| + ReservedSeconds int64 `gorm:"column:reserved_seconds;type:integer;not null"` |
| + SettledSeconds int64 `gorm:"column:settled_seconds;type:integer;not null"` |
| + State string `gorm:"column:state;type:text;not null;index:time_reservations_account,priority:3"` |
| + SettledAt string `gorm:"column:settled_at;type:text;not null"` |
| +} |
| + |
| +func (executionTimeReservations) TableName() string { return "time_reservations" } |
| + |
| +var executionModels = []any{&executionActions{}, &executionArtifacts{}, &executionAttempts{}, &executionEvents{}, &executionJobs{}, &executionPeriodBudgets{}, &executionReservations{}, &executionService{}, &executionSteps{}, &executionTimeReservations{}} |
diff --git a/internal/equipo/migrations/0007_execution.sql b/internal/equipo/migrations/0007_execution.sql| new file mode 100644 |
| index 00000000..1f1061b9 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0007_execution.sql |
| @@ -0,0 +1,151 @@ |
| +CREATE TABLE IF NOT EXISTS service ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + schema_version INTEGER NOT NULL, |
| + incarnation INTEGER NOT NULL, |
| + revision INTEGER NOT NULL DEFAULT 0, |
| + restore_uncertain INTEGER NOT NULL DEFAULT 0, |
| + admission_paused INTEGER NOT NULL, |
| + quarantine INTEGER NOT NULL, |
| + quarantine_why TEXT NOT NULL |
| +); |
| +CREATE TABLE IF NOT EXISTS jobs ( |
| + id INTEGER PRIMARY KEY, |
| + account TEXT NOT NULL, |
| + parent INTEGER NOT NULL, |
| + depth INTEGER NOT NULL, |
| + requester TEXT NOT NULL, |
| + target TEXT NOT NULL, |
| + evidence TEXT NOT NULL, |
| + policy_version INTEGER NOT NULL, |
| + policy TEXT NOT NULL, |
| + grant_ref TEXT NOT NULL, |
| + grant_version INTEGER NOT NULL, |
| + grant_epoch INTEGER NOT NULL, |
| + grant_observed_at TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + wait TEXT NOT NULL, |
| + revision INTEGER NOT NULL, |
| + outcome TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL |
| +); |
| +CREATE INDEX IF NOT EXISTS jobs_account ON jobs(account, state); |
| +CREATE TABLE IF NOT EXISTS steps ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + key TEXT NOT NULL, |
| + capability TEXT NOT NULL, |
| + version INTEGER NOT NULL, |
| + depends_on TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + fence INTEGER NOT NULL, |
| + holder INTEGER NOT NULL, |
| + attempts INTEGER NOT NULL, |
| + UNIQUE(job_id, key) |
| +); |
| +CREATE TABLE IF NOT EXISTS attempts ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL REFERENCES steps(id), |
| + number INTEGER NOT NULL, |
| + runner TEXT NOT NULL, |
| + workspace TEXT NOT NULL, |
| + fence INTEGER NOT NULL, |
| + lease_deadline TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + containment TEXT NOT NULL, |
| + stop_requested TEXT NOT NULL, |
| + stop_acked TEXT NOT NULL, |
| + provider TEXT NOT NULL, |
| + model TEXT NOT NULL, |
| + effort TEXT NOT NULL, |
| + outcome TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL, |
| + UNIQUE(job_id, workspace) |
| +); |
| +CREATE UNIQUE INDEX IF NOT EXISTS attempts_one_live ON attempts(step_id) WHERE containment = 'pending'; |
| +CREATE INDEX IF NOT EXISTS attempts_job ON attempts(job_id, containment); |
| +CREATE TABLE IF NOT EXISTS reservations ( |
| + id INTEGER PRIMARY KEY, |
| + account TEXT NOT NULL, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + action_id INTEGER NOT NULL, |
| + r_calls INTEGER NOT NULL, r_input INTEGER NOT NULL, r_output INTEGER NOT NULL, r_cost INTEGER NOT NULL, |
| + s_calls INTEGER NOT NULL, s_input INTEGER NOT NULL, s_output INTEGER NOT NULL, s_cost INTEGER NOT NULL, |
| + state TEXT NOT NULL, |
| + receipt_id TEXT NOT NULL, |
| + settled_by TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + settled_at TEXT NOT NULL |
| +); |
| +CREATE INDEX IF NOT EXISTS reservations_job ON reservations(job_id, state); |
| +CREATE INDEX IF NOT EXISTS reservations_account ON reservations(account, state); |
| +CREATE TABLE IF NOT EXISTS actions ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + fence INTEGER NOT NULL, |
| + key TEXT NOT NULL, |
| + operation TEXT NOT NULL, |
| + class TEXT NOT NULL, |
| + payload_hash TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + state TEXT NOT NULL, |
| + reservation_id INTEGER NOT NULL, |
| + grant_ref TEXT NOT NULL, |
| + grant_version INTEGER NOT NULL, |
| + grant_epoch INTEGER NOT NULL, |
| + admitted_at TEXT NOT NULL, |
| + admission_ends TEXT NOT NULL, |
| + receipt TEXT NOT NULL, |
| + last_error TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL, |
| + admitted_incarnation INTEGER NOT NULL DEFAULT 0, |
| + UNIQUE(job_id, key) |
| +); |
| +CREATE INDEX IF NOT EXISTS actions_state ON actions(state); |
| +CREATE TABLE IF NOT EXISTS events ( |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + seq INTEGER NOT NULL, |
| + type TEXT NOT NULL, |
| + actor TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + source_at TEXT NOT NULL, |
| + PRIMARY KEY(job_id, seq) |
| +); |
| +CREATE TABLE IF NOT EXISTS artifacts ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + fence INTEGER NOT NULL, |
| + role TEXT NOT NULL, |
| + hash TEXT NOT NULL, |
| + media_type TEXT NOT NULL, |
| + size INTEGER NOT NULL, |
| + provenance TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + created_at TEXT NOT NULL |
| +); |
| +CREATE INDEX IF NOT EXISTS artifacts_job ON artifacts(job_id, role); |
| + |
| +ALTER TABLE jobs ADD COLUMN project_id INTEGER NOT NULL DEFAULT 0; |
| + |
| +CREATE TABLE IF NOT EXISTS period_budgets ( |
| + account TEXT PRIMARY KEY, revision INTEGER NOT NULL, config TEXT NOT NULL |
| +); |
| +CREATE TABLE IF NOT EXISTS time_reservations ( |
| + 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, |
| + reserved_seconds INTEGER NOT NULL, settled_seconds INTEGER NOT NULL, |
| + state TEXT NOT NULL, settled_at TEXT NOT NULL |
| +); |
| +CREATE INDEX IF NOT EXISTS time_reservations_account ON time_reservations(account, project_id, state, period); |
| + |
| +INSERT INTO service(id,schema_version,incarnation,admission_paused,quarantine,quarantine_why) VALUES (1,3,0,1,0,''); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 23a4314c..5589b75c 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -1,13 +1,190 @@ |
| -CREATE TABLE teams (id text, name text, roster_epoch integer, PRIMARY KEY (id)); |
| -CREATE TABLE members (address text, role text, revision integer, active numeric, session_epoch integer, PRIMARY KEY (address)); |
| -CREATE TABLE audit_events (id integer PRIMARY KEY AUTOINCREMENT, actor text, kind text, record_id text, at datetime); |
| +-- Generated by rastrillo migration generate; DO NOT EDIT. |
| +-- The schema every migration in this directory adds up to. |
| + |
| CREATE TABLE accounts (id integer PRIMARY KEY AUTOINCREMENT, label text, revision integer); |
| -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 UNIQUE INDEX project_binding ON projects(repository, app_name); |
| + |
| +CREATE TABLE actions ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + fence INTEGER NOT NULL, |
| + key TEXT NOT NULL, |
| + operation TEXT NOT NULL, |
| + class TEXT NOT NULL, |
| + payload_hash TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + state TEXT NOT NULL, |
| + reservation_id INTEGER NOT NULL, |
| + grant_ref TEXT NOT NULL, |
| + grant_version INTEGER NOT NULL, |
| + grant_epoch INTEGER NOT NULL, |
| + admitted_at TEXT NOT NULL, |
| + admission_ends TEXT NOT NULL, |
| + receipt TEXT NOT NULL, |
| + last_error TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL, |
| + admitted_incarnation INTEGER NOT NULL DEFAULT 0, |
| + UNIQUE(job_id, key) |
| +); |
| + |
| +CREATE TABLE artifacts ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + fence INTEGER NOT NULL, |
| + role TEXT NOT NULL, |
| + hash TEXT NOT NULL, |
| + media_type TEXT NOT NULL, |
| + size INTEGER NOT NULL, |
| + provenance TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + created_at TEXT NOT NULL |
| +); |
| + |
| +CREATE TABLE attempts ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL REFERENCES steps(id), |
| + number INTEGER NOT NULL, |
| + runner TEXT NOT NULL, |
| + workspace TEXT NOT NULL, |
| + fence INTEGER NOT NULL, |
| + lease_deadline TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + containment TEXT NOT NULL, |
| + stop_requested TEXT NOT NULL, |
| + stop_acked TEXT NOT NULL, |
| + provider TEXT NOT NULL, |
| + model TEXT NOT NULL, |
| + effort TEXT NOT NULL, |
| + outcome TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL, |
| + UNIQUE(job_id, workspace) |
| +); |
| + |
| +CREATE TABLE audit_events (id integer PRIMARY KEY AUTOINCREMENT, actor text, kind text, record_id text, at datetime); |
| + |
| +CREATE TABLE budget_records (team_id text, revision integer, config text, PRIMARY KEY (team_id)); |
| + |
| CREATE TABLE decision_owners (project_id integer, decision text, address text, PRIMARY KEY (project_id, decision)); |
| -CREATE INDEX idx_decision_owners_address ON decision_owners(address); |
| + |
| +CREATE TABLE events ( |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + seq INTEGER NOT NULL, |
| + type TEXT NOT NULL, |
| + actor TEXT NOT NULL, |
| + payload BLOB NOT NULL, |
| + source_at TEXT NOT NULL, |
| + PRIMARY KEY(job_id, seq) |
| +); |
| + |
| +CREATE TABLE jobs ( |
| + id INTEGER PRIMARY KEY, |
| + account TEXT NOT NULL, |
| + parent INTEGER NOT NULL, |
| + depth INTEGER NOT NULL, |
| + requester TEXT NOT NULL, |
| + target TEXT NOT NULL, |
| + evidence TEXT NOT NULL, |
| + policy_version INTEGER NOT NULL, |
| + policy TEXT NOT NULL, |
| + grant_ref TEXT NOT NULL, |
| + grant_version INTEGER NOT NULL, |
| + grant_epoch INTEGER NOT NULL, |
| + grant_observed_at TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + wait TEXT NOT NULL, |
| + revision INTEGER NOT NULL, |
| + outcome TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + updated_at TEXT NOT NULL |
| +, project_id INTEGER NOT NULL DEFAULT 0); |
| + |
| +CREATE TABLE members (address text, role text, revision integer, active numeric, session_epoch integer, PRIMARY KEY (address)); |
| + |
| +CREATE TABLE period_budgets ( |
| + account TEXT PRIMARY KEY, revision INTEGER NOT NULL, config TEXT NOT NULL |
| +); |
| + |
| CREATE TABLE project_requests (actor text, operation text, request_id text, input_hash text, result text, PRIMARY KEY (actor, operation, request_id)); |
| -CREATE TABLE budget_records (team_id text, revision integer, config text, PRIMARY KEY (team_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 reservations ( |
| + id INTEGER PRIMARY KEY, |
| + account TEXT NOT NULL, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + step_id INTEGER NOT NULL, |
| + attempt_id INTEGER NOT NULL, |
| + action_id INTEGER NOT NULL, |
| + r_calls INTEGER NOT NULL, r_input INTEGER NOT NULL, r_output INTEGER NOT NULL, r_cost INTEGER NOT NULL, |
| + s_calls INTEGER NOT NULL, s_input INTEGER NOT NULL, s_output INTEGER NOT NULL, s_cost INTEGER NOT NULL, |
| + state TEXT NOT NULL, |
| + receipt_id TEXT NOT NULL, |
| + settled_by TEXT NOT NULL, |
| + created_at TEXT NOT NULL, |
| + settled_at TEXT NOT NULL |
| +); |
| + |
| +CREATE TABLE service ( |
| + id INTEGER PRIMARY KEY CHECK (id = 1), |
| + schema_version INTEGER NOT NULL, |
| + incarnation INTEGER NOT NULL, |
| + revision INTEGER NOT NULL DEFAULT 0, |
| + restore_uncertain INTEGER NOT NULL DEFAULT 0, |
| + admission_paused INTEGER NOT NULL, |
| + quarantine INTEGER NOT NULL, |
| + quarantine_why TEXT NOT NULL |
| +); |
| + |
| CREATE TABLE specialists (key text, model_selection text, provider text, model_family text, model text, standing_instructions text, max_concurrent integer, revision integer, PRIMARY KEY (key)); |
| +CREATE TABLE steps ( |
| + id INTEGER PRIMARY KEY, |
| + job_id INTEGER NOT NULL REFERENCES jobs(id), |
| + key TEXT NOT NULL, |
| + capability TEXT NOT NULL, |
| + version INTEGER NOT NULL, |
| + depends_on TEXT NOT NULL, |
| + state TEXT NOT NULL, |
| + fence INTEGER NOT NULL, |
| + holder INTEGER NOT NULL, |
| + attempts INTEGER NOT NULL, |
| + UNIQUE(job_id, key) |
| +); |
| + |
| +CREATE TABLE teams (id text, name text, roster_epoch integer, PRIMARY KEY (id)); |
| + |
| +CREATE TABLE time_reservations ( |
| + 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, |
| + reserved_seconds INTEGER NOT NULL, settled_seconds INTEGER NOT NULL, |
| + state TEXT NOT NULL, settled_at TEXT NOT NULL |
| +); |
| + |
| CREATE UNIQUE INDEX account_label ON accounts(lower(trim(label))); |
| + |
| +CREATE INDEX actions_state ON actions(state); |
| + |
| +CREATE INDEX artifacts_job ON artifacts(job_id, role); |
| + |
| +CREATE INDEX attempts_job ON attempts(job_id, containment); |
| + |
| +CREATE UNIQUE INDEX attempts_one_live ON attempts(step_id) WHERE containment = 'pending'; |
| + |
| +CREATE INDEX idx_decision_owners_address ON decision_owners(address); |
| + |
| +CREATE INDEX jobs_account ON jobs(account, state); |
| + |
| +CREATE UNIQUE INDEX project_binding ON projects(repository, app_name); |
| + |
| +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); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 2b660dc2..53203e9f 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -2,7 +2,7 @@ package equipo |
| import "time" |
| -var Models = []any{&Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}} |
| +var Models = append([]any{&Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}}, executionModels...) |
| type Role string |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index 104174d0..e442e0ef 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -41,7 +41,10 @@ func (e *refusal) Unwrap() error { return e.kind } |
| // Store grants no access by itself. Mutators must check the trusted Actor |
| // against the current roster and append an AuditEvent in their transaction. |
| -type Store struct{ db *db.DB } |
| +type Store struct { |
| + db *db.DB |
| + execution *Execution |
| +} |
| func NewStore(d *db.DB) *Store { return &Store{db: d} } |
| @@ -59,7 +62,12 @@ func (s *Store) write(ctx context.Context, fn func(*gorm.DB) error) error { |
| if s == nil || s.db == nil { |
| return ErrUnavailable |
| } |
| - err := s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| + var err error |
| + if s.execution != nil { |
| + err = s.execution.Write(ctx, fn) |
| + } else { |
| + err = s.db.G.WithContext(ctx).Clauses(dbresolver.Write).Transaction(fn) |
| + } |
| if err == nil || errors.Is(err, ErrForbidden) || errors.Is(err, ErrNotFound) || errors.Is(err, ErrConflict) || errors.Is(err, ErrInvalid) || errors.Is(err, ErrUnavailable) { |
| return err |
| } |
diff --git a/internal/equipo/team/shared.go b/internal/equipo/team/shared.go| new file mode 100644 |
| index 00000000..e83ab080 |
| --- /dev/null |
| +++ b/internal/equipo/team/shared.go |
| @@ -0,0 +1,268 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "path/filepath" |
| +) |
| + |
| +// OpenShared borrows the activation writer after the app has migrated it. |
| +// The path must name that same file so every handle uses the same lock. |
| +func OpenShared(ctx context.Context, writer *sql.DB, path string, o Options) (*Store, error) { |
| + if writer == nil || writer.Stats().MaxOpenConnections != 1 || o.Clock == nil || o.Authority == nil { |
| + return nil, fail(CodeInvalid, "shared open needs one writer, a clock and an authority") |
| + } |
| + path, err := canonicalStorePath(path) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if o.Marker == "" { |
| + o.Marker = path + ".incarnation" |
| + } |
| + o.Marker, err = filepath.Abs(o.Marker) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s := &Store{db: writer, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters, commitHook: o.commitHook} |
| + if s.adapters == nil { |
| + s.adapters = map[Operation]Adapter{} |
| + } |
| + if err := s.checkSharedSchema(ctx); err != nil { |
| + return nil, err |
| + } |
| + if err := s.start(ctx); err != nil { |
| + return nil, err |
| + } |
| + return s, nil |
| +} |
| + |
| +// 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 { |
| + return s.tx(ctx, fn) |
| +} |
| + |
| +func (s *Store) checkSharedSchema(ctx context.Context) error { |
| + return s.withStoreGuard(ctx, func() error { |
| + rows, err := s.db.QueryContext(ctx, `PRAGMA database_list`) |
| + if err != nil { |
| + return err |
| + } |
| + var mainPath string |
| + for rows.Next() { |
| + var seq int |
| + var name, path string |
| + if err = rows.Scan(&seq, &name, &path); err != nil { |
| + break |
| + } |
| + if name == "main" { |
| + mainPath = path |
| + } |
| + } |
| + if err == nil { |
| + err = rows.Err() |
| + } |
| + rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + if mainPath == "" { |
| + return fail(CodeInvalid, "shared writer needs a file database") |
| + } |
| + mainPath, err = canonicalStorePath(mainPath) |
| + if err != nil { |
| + return err |
| + } |
| + if mainPath != s.path { |
| + return fail(CodeInvalid, "shared writer path differs from lock path") |
| + } |
| + var version int |
| + if err := s.db.QueryRowContext(ctx, `SELECT schema_version FROM service WHERE id=1`).Scan(&version); err != nil { |
| + return fail(CodeStaleStore, "shared schema: %v", err) |
| + } |
| + if version != SchemaVersion { |
| + return fail(CodeStaleStore, "shared schema %d, need %d", version, SchemaVersion) |
| + } |
| + for _, query := range sharedSchemaQueries { |
| + rows, err := s.db.QueryContext(ctx, query) |
| + if err != nil { |
| + return fail(CodeStaleStore, "shared schema: %v", err) |
| + } |
| + err = rows.Close() |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + for _, index := range sharedSchemaIndexes { |
| + var count int |
| + if err := s.db.QueryRowContext(ctx, `SELECT count(*) FROM sqlite_master WHERE type='index' AND name=?`, index).Scan(&count); err != nil { |
| + return err |
| + } |
| + if count != 1 { |
| + return fail(CodeStaleStore, "shared schema missing index %s", index) |
| + } |
| + } |
| + return nil |
| + }) |
| +} |
| + |
| +var sharedSchemaQueries = []string{ |
| + `SELECT |
| + actions."id", |
| + actions."job_id", |
| + actions."step_id", |
| + actions."attempt_id", |
| + actions."fence", |
| + actions."key", |
| + actions."operation", |
| + actions."class", |
| + actions."payload_hash", |
| + actions."payload", |
| + actions."state", |
| + actions."reservation_id", |
| + actions."grant_ref", |
| + actions."grant_version", |
| + actions."grant_epoch", |
| + actions."admitted_at", |
| + actions."admission_ends", |
| + actions."receipt", |
| + actions."last_error", |
| + actions."created_at", |
| + actions."updated_at", |
| + actions."admitted_incarnation" |
| + FROM actions LIMIT 0`, |
| + `SELECT |
| + artifacts."id", |
| + artifacts."job_id", |
| + artifacts."step_id", |
| + artifacts."attempt_id", |
| + artifacts."fence", |
| + artifacts."role", |
| + artifacts."hash", |
| + artifacts."media_type", |
| + artifacts."size", |
| + artifacts."provenance", |
| + artifacts."payload", |
| + artifacts."created_at" |
| + FROM artifacts LIMIT 0`, |
| + `SELECT |
| + attempts."id", |
| + attempts."job_id", |
| + attempts."step_id", |
| + attempts."number", |
| + attempts."runner", |
| + attempts."workspace", |
| + attempts."fence", |
| + attempts."lease_deadline", |
| + attempts."state", |
| + attempts."containment", |
| + attempts."stop_requested", |
| + attempts."stop_acked", |
| + attempts."provider", |
| + attempts."model", |
| + attempts."effort", |
| + attempts."outcome", |
| + attempts."created_at", |
| + attempts."updated_at" |
| + FROM attempts LIMIT 0`, |
| + `SELECT |
| + events."job_id", |
| + events."seq", |
| + events."type", |
| + events."actor", |
| + events."payload", |
| + events."source_at" |
| + FROM events LIMIT 0`, |
| + `SELECT |
| + jobs."id", |
| + jobs."account", |
| + jobs."parent", |
| + jobs."depth", |
| + jobs."requester", |
| + jobs."target", |
| + jobs."evidence", |
| + jobs."policy_version", |
| + jobs."policy", |
| + jobs."grant_ref", |
| + jobs."grant_version", |
| + jobs."grant_epoch", |
| + jobs."grant_observed_at", |
| + jobs."state", |
| + jobs."wait", |
| + jobs."revision", |
| + jobs."outcome", |
| + jobs."created_at", |
| + jobs."updated_at", |
| + jobs."project_id" |
| + FROM jobs LIMIT 0`, |
| + `SELECT |
| + period_budgets."account", |
| + period_budgets."revision", |
| + period_budgets."config" |
| + FROM period_budgets LIMIT 0`, |
| + `SELECT |
| + reservations."id", |
| + reservations."account", |
| + reservations."job_id", |
| + reservations."step_id", |
| + reservations."attempt_id", |
| + reservations."action_id", |
| + reservations."r_calls", |
| + reservations."r_input", |
| + reservations."r_output", |
| + reservations."r_cost", |
| + reservations."s_calls", |
| + reservations."s_input", |
| + reservations."s_output", |
| + reservations."s_cost", |
| + reservations."state", |
| + reservations."receipt_id", |
| + reservations."settled_by", |
| + reservations."created_at", |
| + reservations."settled_at" |
| + FROM reservations LIMIT 0`, |
| + `SELECT |
| + service."id", |
| + service."schema_version", |
| + service."incarnation", |
| + service."revision", |
| + service."restore_uncertain", |
| + service."admission_paused", |
| + service."quarantine", |
| + service."quarantine_why" |
| + FROM service LIMIT 0`, |
| + `SELECT |
| + steps."id", |
| + steps."job_id", |
| + steps."key", |
| + steps."capability", |
| + steps."version", |
| + steps."depends_on", |
| + steps."state", |
| + steps."fence", |
| + steps."holder", |
| + steps."attempts" |
| + FROM steps LIMIT 0`, |
| + `SELECT |
| + time_reservations."attempt_id", |
| + time_reservations."account", |
| + time_reservations."project_id", |
| + time_reservations."job_id", |
| + time_reservations."period", |
| + time_reservations."reserved_seconds", |
| + time_reservations."settled_seconds", |
| + time_reservations."state", |
| + time_reservations."settled_at" |
| + FROM time_reservations LIMIT 0`, |
| +} |
| + |
| +var sharedSchemaIndexes = []string{ |
| + "actions_state", |
| + "artifacts_job", |
| + "attempts_job", |
| + "attempts_one_live", |
| + "jobs_account", |
| + "reservations_account", |
| + "reservations_job", |
| + "time_reservations_account", |
| +} |
diff --git a/internal/equipo/team/shared_test.go b/internal/equipo/team/shared_test.go| new file mode 100644 |
| index 00000000..fa86f295 |
| --- /dev/null |
| +++ b/internal/equipo/team/shared_test.go |
| @@ -0,0 +1,251 @@ |
| +package team |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func sharedFixture(t *testing.T) (*env, *sql.DB) { |
| + t.Helper() |
| + e := newEnv(t) |
| + must(t, e.store.Close()) |
| + e.store = nil |
| + writer, err := sql.Open("sqlite", e.path+"?_pragma=foreign_keys(1)") |
| + must(t, err) |
| + writer.SetMaxOpenConns(1) |
| + t.Cleanup(func() { writer.Close() }) |
| + return e, writer |
| +} |
| + |
| +func TestExecutionSharedValidation(t *testing.T) { |
| + for _, scenario := range []string{"pool", "unlimited", "missing schema", "old schema", "new schema", "missing table", "missing column", "missing index", "wrong path", "missing dependencies"} { |
| + t.Run(scenario, func(t *testing.T) { |
| + e, writer := sharedFixture(t) |
| + path, opts := e.path, e.options() |
| + switch scenario { |
| + case "pool": |
| + writer.SetMaxOpenConns(2) |
| + case "unlimited": |
| + writer.SetMaxOpenConns(0) |
| + case "missing schema": |
| + _, err := writer.Exec(`DROP TABLE service`) |
| + must(t, err) |
| + case "old schema": |
| + _, err := writer.Exec(`UPDATE service SET schema_version=2`) |
| + must(t, err) |
| + case "new schema": |
| + _, err := writer.Exec(`UPDATE service SET schema_version=99`) |
| + must(t, err) |
| + case "missing table": |
| + _, err := writer.Exec(`DROP TABLE artifacts`) |
| + must(t, err) |
| + case "missing column": |
| + _, err := writer.Exec(`ALTER TABLE artifacts DROP COLUMN payload`) |
| + must(t, err) |
| + case "missing index": |
| + _, err := writer.Exec(`DROP INDEX attempts_one_live`) |
| + must(t, err) |
| + case "wrong path": |
| + path = filepath.Join(e.dir, "other.db") |
| + case "missing dependencies": |
| + opts.Authority = nil |
| + } |
| + before, err := os.ReadFile(e.path + ".incarnation") |
| + must(t, err) |
| + s, err := OpenShared(e.ctx, writer, path, opts) |
| + if err == nil { |
| + s.Close() |
| + t.Fatal("invalid attachment accepted") |
| + } |
| + must(t, writer.Ping()) |
| + after, err := os.ReadFile(e.path + ".incarnation") |
| + must(t, err) |
| + if string(before) != string(after) { |
| + t.Fatal("failed attachment changed witness") |
| + } |
| + if scenario == "old schema" || scenario == "new schema" { |
| + var version int |
| + must(t, writer.QueryRow(`SELECT schema_version FROM service`).Scan(&version)) |
| + if (scenario == "old schema" && version != 2) || (scenario == "new schema" && version != 99) { |
| + t.Fatal("attachment migrated schema") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestExecutionSharedCommitFailure(t *testing.T) { |
| + for _, stage := range []string{"before_commit", "after_commit", "commit_error", "witness"} { |
| + t.Run(stage, func(t *testing.T) { |
| + e, writer := sharedFixture(t) |
| + s, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + var before int64 |
| + must(t, writer.QueryRow(`SELECT revision FROM service`).Scan(&before)) |
| + injected := errors.New("injected commit failure") |
| + if stage == "witness" { |
| + must(t, os.Mkdir(s.marker+".tmp", 0700)) |
| + } else { |
| + s.commitHook = func(at string) error { |
| + if at == stage { |
| + return injected |
| + } |
| + return nil |
| + } |
| + } |
| + err = s.WithTransaction(e.ctx, func(tx *sql.Tx) error { |
| + if stage == "commit_error" { |
| + _, err := tx.Exec(`PRAGMA defer_foreign_keys=ON; INSERT INTO events VALUES (999,1,'test','test',x'01','')`) |
| + return err |
| + } |
| + _, err := tx.Exec(`UPDATE service SET quarantine_why='committed payload'`) |
| + return err |
| + }) |
| + if err == nil { |
| + t.Fatal("commit failure ignored") |
| + } |
| + s.commitHook = nil |
| + if stage == "witness" { |
| + must(t, os.Remove(s.marker+".tmp")) |
| + } |
| + var after int64 |
| + must(t, writer.QueryRow(`SELECT revision FROM service`).Scan(&after)) |
| + want := before |
| + if stage == "after_commit" || stage == "witness" { |
| + want++ |
| + } |
| + if after != want { |
| + t.Fatalf("revision = %d, want %d", after, want) |
| + } |
| + if stage == "before_commit" { |
| + must(t, s.Close()) |
| + return |
| + } |
| + |
| + // Repairing the witness must not revive a handle whose commit failed. |
| + var incarnation int64 |
| + must(t, writer.QueryRow(`SELECT incarnation FROM service`).Scan(&incarnation)) |
| + must(t, writeMarker(s.marker, incarnation, after, false)) |
| + wantCode(t, s.WithTransaction(e.ctx, func(*sql.Tx) error { t.Fatal("poisoned callback ran"); return nil }), CodeStaleStore) |
| + wantCode(t, s.Close(), CodeStaleStore) |
| + must(t, writer.Ping()) |
| + reopened, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + rr, err := reopened.Resume(e.ctx) |
| + must(t, err) |
| + if !rr.Resumed || rr.Quarantine { |
| + t.Fatalf("gap did not recover: %+v", rr) |
| + } |
| + must(t, reopened.Close()) |
| + }) |
| + } |
| +} |
| + |
| +func TestExecutionSharedCrashHelper(t *testing.T) { |
| + path := os.Getenv("EQUIPO_SHARED_CRASH_PATH") |
| + if path == "" { |
| + return |
| + } |
| + writer, err := sql.Open("sqlite", path) |
| + must(t, err) |
| + writer.SetMaxOpenConns(1) |
| + clock := NewFakeClock(time.Now()) |
| + s, err := OpenShared(context.Background(), writer, path, Options{Clock: clock, Authority: NewFakeAuthority(clock, time.Minute)}) |
| + must(t, err) |
| + s.commitHook = func(stage string) error { |
| + if stage == "after_commit" { |
| + os.Exit(73) |
| + } |
| + return nil |
| + } |
| + must(t, s.WithTransaction(context.Background(), func(tx *sql.Tx) error { |
| + _, err := tx.Exec(`INSERT INTO period_budgets VALUES ('crash-payload', 1, '{}')`) |
| + return err |
| + })) |
| + t.Fatal("crash boundary not reached") |
| +} |
| + |
| +func TestExecutionSharedCrashRecovery(t *testing.T) { |
| + e, writer := sharedFixture(t) |
| + exe, err := os.Executable() |
| + must(t, err) |
| + ctx, cancel := context.WithTimeout(e.ctx, 10*time.Second) |
| + defer cancel() |
| + cmd := exec.CommandContext(ctx, exe, "-test.run=^TestExecutionSharedCrashHelper$") |
| + cmd.Env = append(os.Environ(), "EQUIPO_SHARED_CRASH_PATH="+e.path) |
| + out, err := cmd.CombinedOutput() |
| + var exit *exec.ExitError |
| + if !errors.As(err, &exit) || exit.ExitCode() != 73 { |
| + t.Fatalf("crash helper: %v\n%s", err, out) |
| + } |
| + s, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + var n int |
| + must(t, writer.QueryRow(`SELECT count(*) FROM period_budgets WHERE account='crash-payload'`).Scan(&n)) |
| + if n != 1 { |
| + t.Fatal("SQL commit lost across witness gap") |
| + } |
| + rr, err := s.Resume(e.ctx) |
| + must(t, err) |
| + if !rr.Resumed || rr.Quarantine { |
| + t.Fatalf("crash treated as restored history: %+v", rr) |
| + } |
| + must(t, s.Close()) |
| + must(t, writer.Ping()) |
| +} |
| + |
| +func TestExecutionSharedClosedHandle(t *testing.T) { |
| + standalone := newEnv(t) |
| + owned := standalone.store.db |
| + must(t, standalone.store.Close()) |
| + standalone.store = nil |
| + if err := owned.Ping(); err == nil { |
| + t.Fatal("standalone close left owned pool open") |
| + } |
| + |
| + e, writer := sharedFixture(t) |
| + s, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + must(t, s.Close()) |
| + wantCode(t, s.WithTransaction(e.ctx, func(*sql.Tx) error { t.Fatal("closed shared handle ran a write"); return nil }), CodeStaleStore) |
| + must(t, writer.Ping()) |
| +} |
| + |
| +func TestExecutionSharedGuard(t *testing.T) { |
| + e, writer := sharedFixture(t) |
| + s, err := OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + committed, release, done := make(chan struct{}), make(chan struct{}), make(chan error, 1) |
| + s.commitHook = func(stage string) error { |
| + if stage == "after_commit" { |
| + close(committed) |
| + <-release |
| + } |
| + return nil |
| + } |
| + go func() { done <- s.WithTransaction(e.ctx, func(*sql.Tx) error { return nil }) }() |
| + <-committed |
| + ctx, cancel := context.WithTimeout(e.ctx, 50*time.Millisecond) |
| + replacement, err := OpenShared(ctx, writer, e.path, e.options()) |
| + cancel() |
| + close(release) |
| + must(t, <-done) |
| + s.commitHook = nil |
| + if replacement != nil { |
| + replacement.Close() |
| + t.Fatal("replacement entered commit/witness gap") |
| + } |
| + if !errors.Is(err, context.DeadlineExceeded) { |
| + t.Fatalf("replacement did not wait for guard: %v", err) |
| + } |
| + replacement, err = OpenShared(e.ctx, writer, e.path, e.options()) |
| + must(t, err) |
| + wantCode(t, s.WithTransaction(e.ctx, func(*sql.Tx) error { t.Fatal("stale shared handle ran"); return nil }), CodeStaleStore) |
| + must(t, replacement.Close()) |
| +} |
diff --git a/internal/equipo/team/store.go b/internal/equipo/team/store.go| index 4dec38c5..32a91c41 100644 |
| --- a/internal/equipo/team/store.go |
| +++ b/internal/equipo/team/store.go |
| @@ -50,6 +50,8 @@ type Options struct { |
| // connection. The database, witness and lock live in trusted local storage. |
| type Store struct { |
| db *sql.DB |
| + ownsDB bool |
| + closed bool |
| path string |
| marker string |
| clock Clock |
| @@ -88,7 +90,7 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) { |
| return nil, fail(CodeInvalid, "open: %v", err) |
| } |
| db.SetMaxOpenConns(4) |
| - s := &Store{db: db, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters} |
| + s := &Store{db: db, ownsDB: true, path: path, marker: o.Marker, clock: o.Clock, auth: o.Authority, adapters: o.Adapters} |
| if s.adapters == nil { |
| s.adapters = map[Operation]Adapter{} |
| } |
| @@ -105,15 +107,17 @@ func Open(ctx context.Context, path string, o Options) (*Store, error) { |
| } |
| // Close pauses admission, records a clean shutdown in the marker and |
| -// closes the database. |
| +// closes the database only when Open created the pool. |
| func (s *Store) Close() error { |
| ctx := context.Background() |
| err := s.transact(ctx, true, func(tx *sql.Tx) error { |
| _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1 WHERE id=1`) |
| return err |
| }) |
| - if cerr := s.db.Close(); err == nil { |
| - err = cerr |
| + if s.ownsDB { |
| + if cerr := s.db.Close(); err == nil { |
| + err = cerr |
| + } |
| } |
| return err |
| } |
| @@ -299,9 +303,10 @@ func (s *Store) migrate(ctx context.Context) error { |
| return fail(CodeInvalid, "migration: %v", err) |
| } |
| } |
| - if _, err := tx.ExecContext(ctx, `UPDATE service SET schema_version=? WHERE id=1`, SchemaVersion); err != nil { |
| + if _, err := tx.ExecContext(ctx, `UPDATE service SET schema_version=2 WHERE id=1`); err != nil { |
| return err |
| } |
| + v = 2 |
| case v != 2 && v != SchemaVersion: |
| return fail(CodeStaleStore, "unsupported schema %d", v) |
| } |
| @@ -340,7 +345,9 @@ func (s *Store) migrate(ctx context.Context) error { |
| return err |
| } |
| } |
| - _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=? WHERE id=1`, SchemaVersion) |
| + if v < SchemaVersion { |
| + _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=? WHERE id=1`, SchemaVersion) |
| + } |
| return err |
| }) |
| } |
| @@ -472,6 +479,12 @@ func (s *Store) transact(ctx context.Context, clean bool, fn func(*sql.Tx) error |
| func (s *Store) transaction(ctx context.Context, clean, witnessed bool, fn func(*sql.Tx) error) error { |
| return s.withStoreGuard(ctx, func() error { |
| + if s.closed { |
| + return fail(CodeStaleStore, "store is closed") |
| + } |
| + if clean { |
| + defer func() { s.closed = true }() |
| + } |
| tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return fail(CodeInvalid, "begin: %v", err) |
diff --git a/internal/equipotest/execution_schema_test.go b/internal/equipotest/execution_schema_test.go| new file mode 100644 |
| index 00000000..56353931 |
| --- /dev/null |
| +++ b/internal/equipotest/execution_schema_test.go |
| @@ -0,0 +1,324 @@ |
| +package equipotest |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "database/sql" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "gorm.io/gorm" |
| + "gorm.io/plugin/dbresolver" |
| +) |
| + |
| +func executionMust(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func executionOptions() team.Options { |
| + clock := team.NewFakeClock(time.Date(2026, 11, 2, 12, 0, 0, 0, time.UTC)) |
| + return team.Options{Clock: clock, Authority: team.NewFakeAuthority(clock, time.Minute)} |
| +} |
| +func executionDB(t *testing.T) (*db.DB, string) { |
| + t.Helper() |
| + path := filepath.Join(t.TempDir(), "activation.db") |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + executionMust(t, err) |
| + t.Cleanup(func() { d.Close() }) |
| + _, err = migrate.Apply(context.Background(), d, equipo.BootSchema) |
| + executionMust(t, err) |
| + return d, path |
| +} |
| +func executionRevision(t *testing.T, d *db.DB) int64 { |
| + t.Helper() |
| + var rev int64 |
| + executionMust(t, d.Writer().QueryRow(`SELECT revision FROM service`).Scan(&rev)) |
| + return rev |
| +} |
| + |
| +func TestExecutionSharedPool(t *testing.T) { |
| + d, path := executionDB(t) |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + s := equipo.NewStore(d) |
| + x, err := s.AttachExecution(ctx, path, executionOptions()) |
| + executionMust(t, err) |
| + before := executionRevision(t, d) |
| + executionMust(t, s.Bootstrap(ctx, []string{ownerAddress})) |
| + if executionRevision(t, d) != before+1 { |
| + t.Fatal("app write bypassed witnessed transaction") |
| + } |
| + if _, err := s.AttachExecution(ctx, path, executionOptions()); !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatalf("duplicate attachment: %v", err) |
| + } |
| + executionMust(t, s.SetMember(ctx, equipo.Actor{Address: ownerAddress}, "member@example.com", equipo.RoleMember, true, 0)) |
| + var auditCount int |
| + executionMust(t, d.Writer().QueryRow(`SELECT count(*) FROM audit_events WHERE actor=?`, ownerAddress).Scan(&auditCount)) |
| + if auditCount != 1 { |
| + t.Fatalf("attached roster audit count = %d", auditCount) |
| + } |
| + if err := s.SetMember(ctx, equipo.Actor{Address: "outsider@example.com"}, "other@example.com", equipo.RoleMember, true, 0); !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatalf("attached write lost authority error: %v", err) |
| + } |
| + waits := d.Writer().Stats().WaitCount |
| + abort := errors.New("abort app/core/audit") |
| + before = executionRevision(t, d) |
| + err = x.Write(ctx, func(tx *gorm.DB) error { |
| + if !tx.SkipDefaultTransaction || !tx.DisableNestedTransaction { |
| + t.Fatal("nested transactions enabled") |
| + } |
| + if _, ok := tx.Statement.ConnPool.(*sql.Tx); !ok { |
| + t.Fatal("GORM is not using core SQL transaction") |
| + } |
| + executionMust(t, tx.Create(&equipo.Account{Label: "rollback"}).Error) |
| + executionMust(t, tx.Exec(`INSERT INTO period_budgets VALUES ('rollback',1,'{}')`).Error) |
| + executionMust(t, tx.Create(&equipo.AuditEvent{Actor: ownerAddress, Kind: "rollback", At: time.Now()}).Error) |
| + var count int64 |
| + executionMust(t, tx.Clauses(dbresolver.Read).Model(&equipo.Account{}).Where("label = ?", "rollback").Count(&count).Error) |
| + if count != 1 { |
| + t.Fatal("transaction read escaped to replica") |
| + } |
| + return tx.Transaction(func(nested *gorm.DB) error { return abort }) |
| + }) |
| + if !errors.Is(err, abort) { |
| + t.Fatalf("rollback error = %v", err) |
| + } |
| + for _, q := range []string{`SELECT count(*) FROM accounts WHERE label='rollback'`, `SELECT count(*) FROM period_budgets WHERE account='rollback'`, `SELECT count(*) FROM audit_events WHERE kind='rollback'`} { |
| + var n int |
| + executionMust(t, d.Writer().QueryRow(q).Scan(&n)) |
| + if n != 0 { |
| + t.Fatalf("partial rollback: %s", q) |
| + } |
| + } |
| + if executionRevision(t, d) != before { |
| + t.Fatal("rollback advanced witness revision") |
| + } |
| + executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { return tx.Create(&equipo.Account{Label: "committed"}).Error })) |
| + executionMust(t, x.Core.ConfigureBudgets(ctx, "team", 0, team.BudgetSet{Team: team.PeriodLimits{Calls: 10, InputTokens: 10, OutputTokens: 10, Seconds: 10}})) |
| + if d.Writer().Stats().WaitCount != waits { |
| + t.Fatal("nested writer pool acquisition") |
| + } |
| + executionMust(t, x.Core.Close()) |
| + executionMust(t, d.Writer().PingContext(ctx)) |
| + var committedCount int64 |
| + executionMust(t, d.G.WithContext(ctx).Model(&equipo.Account{}).Where("label = ?", "committed").Count(&committedCount).Error) |
| + if committedCount != 1 || d.G.SkipDefaultTransaction || d.G.DisableNestedTransaction { |
| + t.Fatal("execution changed the app GORM session") |
| + } |
| + if err := s.Bootstrap(ctx, []string{ownerAddress}); !errors.Is(err, equipo.ErrUnavailable) { |
| + t.Fatalf("closed execution allowed app write: %v", err) |
| + } |
| + var paused int |
| + executionMust(t, d.Writer().QueryRow(`SELECT admission_paused FROM service`).Scan(&paused)) |
| + marker, err := os.ReadFile(path + ".incarnation") |
| + executionMust(t, err) |
| + if paused != 1 || !bytes.Contains(marker, []byte("clean=true")) { |
| + t.Fatal("shared close did not publish clean pause") |
| + } |
| +} |
| + |
| +func TestExecutionSchemaParity(t *testing.T) { |
| + ctx := context.Background() |
| + d, path := executionDB(t) |
| + if _, err := d.Writer().Exec(`INSERT INTO service (id,schema_version,incarnation,admission_paused,quarantine,quarantine_why) VALUES (2,3,0,1,0,'')`); err == nil { |
| + t.Fatal("service singleton check missing") |
| + } |
| + expected, err := migrate.Read(ctx, d.Writer()) |
| + executionMust(t, err) |
| + t.Run("foundation upgrade", func(t *testing.T) { |
| + oldPath := filepath.Join(t.TempDir(), "foundation.db") |
| + old, err := db.Open(oldPath, 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/0007_execution" { |
| + before.Add(m) |
| + } |
| + } |
| + _, err = migrate.Apply(ctx, old, before) |
| + executionMust(t, err) |
| + 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"}) { |
| + t.Fatalf("upgrade migrations: %v", result.Applied) |
| + } |
| + var account equipo.Account |
| + executionMust(t, old.G.First(&account).Error) |
| + if account.Label != "existing account" { |
| + t.Fatal("upgrade lost app record") |
| + } |
| + result, err = migrate.Apply(ctx, old, equipo.BootSchema) |
| + executionMust(t, err) |
| + if len(result.Applied) != 0 { |
| + 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} |
| + var appCore migrate.Snapshot |
| + for _, table := range expected.Tables { |
| + if coreNames[table.Name] { |
| + appCore.Tables = append(appCore.Tables, table) |
| + } |
| + } |
| + 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} { |
| + t.Run(fmt.Sprint(version), func(t *testing.T) { |
| + standalonePath := filepath.Join(t.TempDir(), "core.db") |
| + core, err := team.Open(ctx, standalonePath, executionOptions()) |
| + executionMust(t, err) |
| + executionMust(t, core.Close()) |
| + raw, err := sql.Open("sqlite", standalonePath) |
| + executionMust(t, err) |
| + defer raw.Close() |
| + raw.SetMaxOpenConns(1) |
| + executionMust(t, seedExecutionJob(raw)) |
| + 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) |
| + executionMust(t, err) |
| + } |
| + } |
| + if version == 1 { |
| + for _, q := range []string{`ALTER TABLE service DROP COLUMN revision`, `ALTER TABLE service DROP COLUMN restore_uncertain`, `ALTER TABLE actions DROP COLUMN admitted_incarnation`} { |
| + _, err = raw.Exec(q) |
| + executionMust(t, err) |
| + } |
| + } |
| + _, err = raw.Exec(`UPDATE service SET schema_version=?`, version) |
| + executionMust(t, err) |
| + _, err = raw.Exec(`CREATE TRIGGER ordered_schema_bumps BEFORE UPDATE OF schema_version ON service WHEN NEW.schema_version != OLD.schema_version + 1 BEGIN SELECT RAISE(ABORT, 'schema bump skipped or repeated'); END`) |
| + executionMust(t, err) |
| + for reopen := 0; reopen < 3; reopen++ { |
| + core, err = team.Open(ctx, standalonePath, executionOptions()) |
| + executionMust(t, err) |
| + executionMust(t, core.Close()) |
| + got, err := migrate.Read(ctx, raw) |
| + executionMust(t, err) |
| + if diff := appCore.Diff(got); len(diff) != 0 { |
| + t.Fatalf("schema parity: %v", diff) |
| + } |
| + var evidence string |
| + executionMust(t, raw.QueryRow(`SELECT evidence FROM jobs WHERE id=1`).Scan(&evidence)) |
| + if evidence != "preserved evidence" { |
| + t.Fatal("upgrade lost job data") |
| + } |
| + for name := range coreNames { |
| + if !reflect.DeepEqual(executionConstraints(t, d.Writer(), name), executionConstraints(t, raw, name)) { |
| + t.Fatalf("constraints differ for %s", name) |
| + } |
| + } |
| + } |
| + }) |
| + } |
| + for reopen := 0; reopen < 2; reopen++ { |
| + result, err := migrate.Apply(ctx, d, equipo.BootSchema) |
| + executionMust(t, err) |
| + if len(result.Applied) != 0 { |
| + t.Fatalf("second migration applied %v", result.Applied) |
| + } |
| + core, err := team.OpenShared(ctx, d.Writer(), path, executionOptions()) |
| + executionMust(t, err) |
| + executionMust(t, core.Close()) |
| + } |
| + _, err = d.Writer().Exec(`UPDATE service SET schema_version=?`, team.SchemaVersion+1) |
| + executionMust(t, err) |
| + if _, err = team.OpenShared(ctx, d.Writer(), path, executionOptions()); team.CodeOf(err) != team.CodeStaleStore { |
| + t.Fatalf("newer schema accepted: %v", err) |
| + } |
| +} |
| + |
| +func executionConstraints(t *testing.T, d *sql.DB, table string) []string { |
| + t.Helper() |
| + var result []string |
| + for _, q := range []string{`SELECT "from", "table", "to", on_update, on_delete FROM pragma_foreign_key_list(?) ORDER BY "from"`, `SELECT name, "unique", origin, partial FROM pragma_index_list(?) ORDER BY name`, `SELECT il.name, ii.seqno, ii.name FROM pragma_index_list(?) il JOIN pragma_index_info(il.name) ii ORDER BY il.name, ii.seqno`} { |
| + rows, err := d.Query(q, table) |
| + executionMust(t, err) |
| + cols, err := rows.Columns() |
| + executionMust(t, err) |
| + for rows.Next() { |
| + values := make([]any, len(cols)) |
| + dest := make([]any, len(cols)) |
| + for i := range values { |
| + dest[i] = &values[i] |
| + } |
| + executionMust(t, rows.Scan(dest...)) |
| + result = append(result, fmt.Sprint(values)) |
| + } |
| + executionMust(t, rows.Err()) |
| + executionMust(t, rows.Close()) |
| + } |
| + rows, err := d.Query(`SELECT sql FROM sqlite_master WHERE type='index' AND tbl_name=? AND sql IS NOT NULL ORDER BY name`, table) |
| + executionMust(t, err) |
| + for rows.Next() { |
| + var ddl string |
| + executionMust(t, rows.Scan(&ddl)) |
| + result = append(result, migrate.Checksum(ddl)) |
| + } |
| + executionMust(t, rows.Err()) |
| + executionMust(t, rows.Close()) |
| + return result |
| +} |
| + |
| +func seedExecutionJob(d *sql.DB) error { |
| + _, err := d.Exec(`INSERT INTO jobs (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) VALUES (1,'team',0,0,'requester','{}','preserved evidence',1,'{}','grant',1,1,'','queued','',1,'','','')`) |
| + return err |
| +} |
| + |
| +func TestExecutionBackupIncludesArtifacts(t *testing.T) { |
| + d, path := executionDB(t) |
| + ctx := context.Background() |
| + options := executionOptions() |
| + options.Authority.(*team.FakeAuthority).Issue("backup-grant", team.Grant{Account: "team", Operations: map[team.Operation]bool{team.OpJobContinue: true, team.OpAttemptContinue: true}}) |
| + x, err := equipo.NewStore(d).AttachExecution(ctx, path, options) |
| + executionMust(t, err) |
| + defer x.Core.Close() |
| + _, err = x.Core.Resume(ctx) |
| + executionMust(t, err) |
| + job, err := x.Core.CreateJob(ctx, team.JobSpec{ |
| + Account: "team", Requester: ownerAddress, GrantRef: "backup-grant", |
| + Target: team.TargetBinding{Kind: team.TargetRepository, Repository: "example/shop", Ref: "team/backup-test", DefaultRef: "main", BaseRevision: fmt.Sprintf("%064x", 1)}, |
| + Evidence: team.EvidenceRequirement{Predicate: team.PredicateSoftwareFix, ExpectedSymptom: team.FixtureSymptom, CheckDefinitionHash: team.CheckDefinitionHash}, |
| + Policy: team.DefaultPolicy(5_000_000, team.Rates{Version: 1}), Steps: team.SoftwareSteps(false), |
| + }) |
| + executionMust(t, err) |
| + scope := team.Scope{Account: job.Account, Job: job.ID} |
| + handle, err := x.Core.Claim(ctx, scope, "reproduce", "backup-runner", "backup-workspace") |
| + executionMust(t, err) |
| + reproduction := []byte{0, 1, 2, 255, 'r', 'e', 'p', 'r', 'o'} |
| + _, err = x.Core.Register(ctx, scope, handle, team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "application/octet-stream", Payload: reproduction, Provenance: team.Provenance{Producer: "backup-runner", Provider: "offline-fake", Context: "backup-context"}}) |
| + executionMust(t, err) |
| + executionMust(t, x.Write(ctx, func(tx *gorm.DB) error { |
| + return tx.Create(&equipo.Account{Label: "backup account"}).Error |
| + })) |
| + backup := filepath.Join(t.TempDir(), "backup.db") |
| + _, err = d.Writer().Exec(`VACUUM INTO ?`, backup) |
| + executionMust(t, err) |
| + restored, err := sql.Open("sqlite", backup) |
| + executionMust(t, err) |
| + defer restored.Close() |
| + var label, requester string |
| + var payload []byte |
| + executionMust(t, restored.QueryRow(`SELECT label FROM accounts`).Scan(&label)) |
| + executionMust(t, restored.QueryRow(`SELECT requester FROM jobs`).Scan(&requester)) |
| + executionMust(t, restored.QueryRow(`SELECT payload FROM artifacts`).Scan(&payload)) |
| + if label != "backup account" || requester != ownerAddress || !bytes.Equal(payload, reproduction) { |
| + t.Fatal("activation backup lost app, job or reproduction bytes") |
| + } |
| +} |