feat: persist runner events and reconcile measured usage
18 files changed,
+2,156
−31
.rastrillo/budgets.txt+2 −2internal/equipo/migrations/0015_runner_events.sql+7 −0internal/equipo/migrations/schema.sql+8 −0internal/equipo/models.go+1 −1internal/equipo/runner_events.go+292 −0internal/equipo/runner_mutations.go+14 −19internal/equipo/runner_provenance.go+3 −0internal/equipotest/runner_api_test.go+7 −4internal/equipotest/runner_events_test.go+478 −0internal/runner/events.go+247 −0internal/runner/journal.go+273 −0internal/runner/journal_test.go+392 −0internal/runner/paseo/client.go+6 −2internal/runner/paseo/client_test.go+27 −0internal/runner/usage.go+176 −0internal/runner/usage_test.go+125 −0internal/runnerproto/events.go+95 −0internal/runnerproto/validate.go+3 −3
CI failed — run details
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 16c96a6f..9d5bd752 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,6 +14,6 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| 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 25s Task 6 keeps the mandated connections tests in this package; its focused authority, isolation, atomic-write and real-session checks took 15.5s on the shared machine, above the prior 15s allowance. |
| -size internal/equipo 6500 - Task 8 keeps the mandated runner API, assignment, credential rotation and provenance adapters in the app package alongside the shared transaction and roster checks. |
| -size internal/equipotest - 8300 Task 8 keeps the mandated runner_api_test.go route, ticket, containment, provenance and failure tests beside the existing activation database fixtures; they add coverage across all runner endpoints and cross-job concurrency. |
| +size internal/equipo 7000 - Task 12 adds the mandated transactional event inbox, timeline projections and artifact request deduplication beside the Task 8 runner API and authority checks. |
| +size internal/equipotest - 9100 Task 12 keeps runner_events_test.go beside the existing activation fixtures to verify crash replay, atomic settlement, epoch replacement, authority, HTTP ingestion and migration reopen. |
| time internal/runner/checks 15s Task 11 runs real Go fixtures and Codex sandbox sentinels, including timeout and child-process cleanup; the targeted suite took 10.710s on the shared machine. |
diff --git a/internal/equipo/migrations/0015_runner_events.sql b/internal/equipo/migrations/0015_runner_events.sql| new file mode 100644 |
| index 00000000..04c3f192 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0015_runner_events.sql |
| @@ -0,0 +1,7 @@ |
| +CREATE TABLE runner_events (key text, assignment_id text, stream_key text, epoch text, sequence integer, kind text, content_hash text, body text, isolation text, PRIMARY KEY(key)); |
| +CREATE INDEX runner_event_assignment ON runner_events(assignment_id); |
| +CREATE INDEX runner_event_timeline ON runner_events(stream_key, epoch, sequence); |
| +CREATE TABLE runner_event_ids (runner_id text, event_id text, event_key text, PRIMARY KEY(runner_id, event_id)); |
| +CREATE TABLE runner_timelines (stream_key text, assignment_id text, epoch text, high_water integer, blocked numeric, isolation text, PRIMARY KEY(stream_key)); |
| +CREATE INDEX runner_timeline_assignment ON runner_timelines(assignment_id); |
| +CREATE TABLE runner_artifact_requests (assignment_id text, request_id text, payload_hash text, artifact_id integer, PRIMARY KEY(assignment_id, request_id)); |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 5913eeb2..12888530 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -332,3 +332,11 @@ CREATE TABLE runner_observations (assignment_id text, request_id text, operation |
| CREATE TABLE runner_rotations (runner_id text, assignment_id text, request_id text, state text, credential_id text, PRIMARY KEY(runner_id)); |
| CREATE TABLE artifact_blobs (team_id text, job_id integer, digest text, bytes blob, PRIMARY KEY(team_id, job_id, digest)); |
| CREATE TABLE artifact_blob_uploads (attempt_id integer, digest text, size integer, PRIMARY KEY(attempt_id, digest)); |
| + |
| +CREATE TABLE runner_events (key text, assignment_id text, stream_key text, epoch text, sequence integer, kind text, content_hash text, body text, isolation text, PRIMARY KEY(key)); |
| +CREATE INDEX runner_event_assignment ON runner_events(assignment_id); |
| +CREATE INDEX runner_event_timeline ON runner_events(stream_key, epoch, sequence); |
| +CREATE TABLE runner_event_ids (runner_id text, event_id text, event_key text, PRIMARY KEY(runner_id, event_id)); |
| +CREATE TABLE runner_timelines (stream_key text, assignment_id text, epoch text, high_water integer, blocked numeric, isolation text, PRIMARY KEY(stream_key)); |
| +CREATE INDEX runner_timeline_assignment ON runner_timelines(assignment_id); |
| +CREATE TABLE runner_artifact_requests (assignment_id text, request_id text, payload_hash text, artifact_id integer, PRIMARY KEY(assignment_id, request_id)); |
diff --git a/internal/equipo/models.go b/internal/equipo/models.go| index 4c25d2af..6c852d25 100644 |
| --- a/internal/equipo/models.go |
| +++ b/internal/equipo/models.go |
| @@ -2,7 +2,7 @@ package equipo |
| import "time" |
| -var Models = append([]any{&artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...) |
| +var Models = append([]any{&runnerEvent{}, &runnerEventID{}, &runnerTimeline{}, &runnerArtifactRequest{}, &artifactBlob{}, &artifactBlobUpload{}, &runnerAssignment{}, &runnerCleanup{}, &runnerObservation{}, &runnerRotation{}, &executionAdmissionTicket{}, &Task{}, &taskOutbox{}, &Team{}, &Member{}, &AuditEvent{}, &Account{}, &Project{}, &DecisionOwner{}, &projectRequest{}, &budgetRecord{}, &Specialist{}, &runnerRecord{}, &runnerEnrolment{}, &runnerCredentialRecord{}, &runnerRate{}, &connectionRecord{}, &connectionChoiceRecord{}, &isolationAcknowledgementRecord{}, &ConnectionInvalidation{}}, executionModels...) |
| type Role string |
diff --git a/internal/equipo/runner_events.go b/internal/equipo/runner_events.go| new file mode 100644 |
| index 00000000..39ab31d1 |
| --- /dev/null |
| +++ b/internal/equipo/runner_events.go |
| @@ -0,0 +1,292 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "gorm.io/gorm" |
| +) |
| + |
| +type runnerEvent struct { |
| + Key string `gorm:"primaryKey"` |
| + AssignmentID string `gorm:"index:runner_event_assignment"` |
| + StreamKey string `gorm:"index:runner_event_timeline,priority:1"` |
| + Epoch string `gorm:"index:runner_event_timeline,priority:2"` |
| + Sequence *int64 `gorm:"index:runner_event_timeline,priority:3"` |
| + Kind, ContentHash, Body, Isolation string |
| +} |
| + |
| +func (runnerEvent) TableName() string { return "runner_events" } |
| + |
| +type runnerEventID struct { |
| + RunnerID string `gorm:"primaryKey"` |
| + EventID string `gorm:"primaryKey"` |
| + EventKey string |
| +} |
| + |
| +func (runnerEventID) TableName() string { return "runner_event_ids" } |
| + |
| +type runnerTimeline struct { |
| + StreamKey string `gorm:"primaryKey"` |
| + AssignmentID string `gorm:"index:runner_timeline_assignment"` |
| + Epoch string |
| + HighWater int64 |
| + Blocked bool |
| + Isolation string |
| +} |
| + |
| +func (runnerTimeline) TableName() string { return "runner_timelines" } |
| + |
| +type runnerArtifactRequest struct { |
| + AssignmentID string `gorm:"primaryKey"` |
| + RequestID string `gorm:"primaryKey"` |
| + PayloadHash string |
| + ArtifactID int64 |
| +} |
| + |
| +func (runnerArtifactRequest) TableName() string { return "runner_artifact_requests" } |
| +func (s *Store) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event runnerproto.Event) error { |
| + if s.execution == nil { |
| + return ErrUnavailable |
| + } |
| + return s.execution.IngestRunnerEvent(ctx, p, event) |
| +} |
| +func (e *Execution) IngestRunnerEvent(ctx context.Context, p RunnerPrincipal, event runnerproto.Event) error { |
| + if event.Validate() != nil { |
| + return ErrInvalid |
| + } |
| + return e.atomic(ctx, func(ctx context.Context, tx *gorm.DB) error { |
| + if err := e.syncExposure(ctx, tx); err != nil { |
| + return err |
| + } |
| + if _, err := runnerPrincipalAt(tx, p, e.store.runnerClock.Now().UTC()); err != nil { |
| + return err |
| + } |
| + var a runnerAssignment |
| + if err := tx.First(&a, "id=?", event.AssignmentID).Error; err != nil { |
| + return storeError(err) |
| + } |
| + q := RunnerRequest{Version: 1, AssignmentID: event.AssignmentID, Scope: event.Scope, Handle: event.Handle, RequestID: event.ID, ActionID: event.ActionID} |
| + if !binding(a, q) || a.TaskID != event.TaskID || a.RunnerID != p.RunnerID || a.Person != p.Person { |
| + return ErrForbidden |
| + } |
| + value, err := assignmentValue(a) |
| + if err != nil { |
| + return err |
| + } |
| + // Historical observations need current roster and runner authority, but a |
| + // cancelled task must still accept corroborated completion accounting. |
| + return e.ingestEventAt(ctx, tx, a, value, event) |
| + }) |
| +} |
| +func (e *Execution) ingestEventAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, event runnerproto.Event) error { |
| + key, hash := event.DedupKey(), event.ContentHash() |
| + var alias runnerEventID |
| + err := tx.First(&alias, "runner_id=? AND event_id=?", a.RunnerID, event.ID).Error |
| + if err == nil && alias.EventKey != key { |
| + return ErrConflict |
| + } |
| + if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return storeError(err) |
| + } |
| + var old runnerEvent |
| + err = tx.First(&old, "key=?", key).Error |
| + if err == nil { |
| + if old.ContentHash != hash { |
| + return ErrConflict |
| + } |
| + if alias.EventID == "" { |
| + return storeError(tx.Create(&runnerEventID{RunnerID: a.RunnerID, EventID: event.ID, EventKey: key}).Error) |
| + } |
| + return nil |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return storeError(err) |
| + } |
| + if e.validators.Events == nil { |
| + return ErrUnavailable |
| + } |
| + raw, err := runnerproto.Marshal(event) |
| + if err != nil { |
| + return ErrInvalid |
| + } |
| + q := RunnerRequest{Version: 1, AssignmentID: a.ID, Scope: event.Scope, Handle: event.Handle, RequestID: event.ID, ActionID: event.ActionID, Event: raw} |
| + if err = e.validators.Events(ctx, value, q); err != nil { |
| + return err |
| + } |
| + if event.Kind == "turn_completed" || event.Kind == "turn_failed" { |
| + if e.validators.Receipt == nil { |
| + return ErrUnavailable |
| + } |
| + action, err := e.Core.GetAction(ctx, event.Scope, event.ActionID) |
| + if err != nil { |
| + return err |
| + } |
| + if action.Attempt != event.Handle.Attempt || action.Fence != event.Handle.Fence || action.Operation != team.OpProviderCall { |
| + return ErrForbidden |
| + } |
| + receipt, err := e.validators.Receipt(ctx, value, q) |
| + if err != nil { |
| + return err |
| + } |
| + if err = e.Core.Record(ctx, event.Scope, event.ActionID, receipt); err != nil { |
| + return err |
| + } |
| + } |
| + event.Isolation = value.Selection.Isolation |
| + event.Payload = runner.RedactJSON(event.Payload, nil) |
| + iso, _ := json.Marshal(event.Isolation) |
| + raw, err = json.Marshal(event) |
| + if err != nil { |
| + return ErrInvalid |
| + } |
| + row := runnerEvent{Key: key, AssignmentID: a.ID, StreamKey: event.StreamKey(), Epoch: event.Epoch, Sequence: event.Sequence, Kind: event.Kind, ContentHash: hash, Body: string(raw), Isolation: string(iso)} |
| + if err = tx.Create(&row).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err = tx.Create(&runnerEventID{RunnerID: a.RunnerID, EventID: event.ID, EventKey: key}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err = projectRunnerEvent(tx, event, string(iso)); err != nil { |
| + return err |
| + } |
| + return appendAudit(tx, Actor{Address: a.Person}, "runner.event", key) |
| +} |
| +func projectRunnerEvent(tx *gorm.DB, event runnerproto.Event, iso string) error { |
| + var row runnerTimeline |
| + err := tx.First(&row, "stream_key=?", event.StreamKey()).Error |
| + fresh := errors.Is(err, gorm.ErrRecordNotFound) |
| + if err != nil && !fresh { |
| + return storeError(err) |
| + } |
| + if fresh { |
| + row = runnerTimeline{StreamKey: event.StreamKey(), AssignmentID: event.AssignmentID, Epoch: event.Epoch} |
| + } |
| + var historical team.IsolationSnapshot |
| + if !fresh && json.Unmarshal([]byte(row.Isolation), &historical) != nil { |
| + return ErrInvalid |
| + } |
| + var current team.IsolationSnapshot |
| + if json.Unmarshal([]byte(iso), ¤t) != nil { |
| + return ErrInvalid |
| + } |
| + merged, _ := json.Marshal(mergeIsolation(historical, current)) |
| + row.Isolation = string(merged) |
| + switch event.Kind { |
| + case "timeline_gap": |
| + row.Blocked = true |
| + case "timeline_replacement": |
| + row.Epoch = event.Epoch |
| + row.HighWater = 0 |
| + row.Blocked = true |
| + case "timeline_ready": |
| + if event.Epoch != row.Epoch { |
| + return ErrConflict |
| + } |
| + row.Blocked = false |
| + default: |
| + if event.Sequence != nil { |
| + if row.Epoch == "" { |
| + row.Epoch = event.Epoch |
| + } |
| + if event.Epoch != row.Epoch { |
| + row.Blocked = true |
| + } else { |
| + // Timeline pages may span sequences. Gaps are explicitly validated by the |
| + // adapter; a monotonic high-water alone never establishes readiness. |
| + if *event.Sequence > row.HighWater { |
| + row.HighWater = *event.Sequence |
| + } |
| + } |
| + } |
| + } |
| + if fresh { |
| + return storeError(tx.Create(&row).Error) |
| + } |
| + return storeError(tx.Model(&runnerTimeline{}).Where("stream_key=?", row.StreamKey).Select("Epoch", "HighWater", "Blocked", "Isolation").Updates(&row).Error) |
| +} |
| +func runnerTimelineAvailable(tx *gorm.DB, assignment string) error { |
| + var count int64 |
| + if err := tx.Model(&runnerTimeline{}).Where("assignment_id=? AND blocked=?", assignment, true).Count(&count).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if count != 0 { |
| + return ErrUnavailable |
| + } |
| + return nil |
| +} |
| +func (e *Execution) registerArtifactOnce(ctx context.Context, tx *gorm.DB, a runnerAssignment, q RunnerRequest) (team.Artifact, error) { |
| + hash := runnerproto.EventHash(q.Artifact) |
| + var old runnerArtifactRequest |
| + err := tx.First(&old, "assignment_id=? AND request_id=?", a.ID, q.RequestID).Error |
| + if err == nil { |
| + if old.PayloadHash != hash { |
| + return team.Artifact{}, ErrConflict |
| + } |
| + return e.Core.Artifact(ctx, q.Scope, team.ArtifactID(old.ArtifactID)) |
| + } |
| + if !errors.Is(err, gorm.ErrRecordNotFound) { |
| + return team.Artifact{}, storeError(err) |
| + } |
| + if e.validators.Artifact == nil { |
| + return team.Artifact{}, ErrUnavailable |
| + } |
| + value, err := assignmentValue(a) |
| + if err != nil { |
| + return team.Artifact{}, err |
| + } |
| + if err = e.validators.Artifact(ctx, value, q); err != nil { |
| + return team.Artifact{}, err |
| + } |
| + artifact, err := e.Core.Register(ctx, q.Scope, q.Handle, *q.Artifact) |
| + if err != nil { |
| + return team.Artifact{}, err |
| + } |
| + err = tx.Create(&runnerArtifactRequest{AssignmentID: a.ID, RequestID: q.RequestID, PayloadHash: hash, ArtifactID: int64(artifact.ID)}).Error |
| + return artifact, storeError(err) |
| +} |
| + |
| +func syncRunnerEventExposure(tx *gorm.DB, assignment string, iso team.IsolationSnapshot) error { |
| + expected, _ := json.Marshal(iso) |
| + var events []runnerEvent |
| + if err := tx.Where("assignment_id=? AND isolation!=?", assignment, string(expected)).Find(&events).Error; err != nil { |
| + return storeError(err) |
| + } |
| + for _, row := range events { |
| + var event runnerproto.Event |
| + if err := json.Unmarshal([]byte(row.Body), &event); err != nil { |
| + return err |
| + } |
| + event.Isolation = mergeIsolation(event.Isolation, iso) |
| + raw, _ := json.Marshal(event.Isolation) |
| + body, _ := json.Marshal(event) |
| + if row.Isolation == string(raw) && row.Body == string(body) { |
| + continue |
| + } |
| + if err := tx.Model(&runnerEvent{}).Where("key=?", row.Key).Select("Isolation", "Body").Updates(&runnerEvent{Isolation: string(raw), Body: string(body)}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + } |
| + var timelines []runnerTimeline |
| + if err := tx.Where("assignment_id=? AND isolation!=?", assignment, string(expected)).Find(&timelines).Error; err != nil { |
| + return storeError(err) |
| + } |
| + for _, row := range timelines { |
| + var old team.IsolationSnapshot |
| + if err := json.Unmarshal([]byte(row.Isolation), &old); err != nil { |
| + return err |
| + } |
| + raw, _ := json.Marshal(mergeIsolation(old, iso)) |
| + if row.Isolation == string(raw) { |
| + continue |
| + } |
| + if err := tx.Model(&runnerTimeline{}).Where("stream_key=?", row.StreamKey).Select("Isolation").Updates(&runnerTimeline{Isolation: string(raw)}).Error; err != nil { |
| + return storeError(err) |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/runner_mutations.go b/internal/equipo/runner_mutations.go| index 4a1ef392..aba4437f 100644 |
| --- a/internal/equipo/runner_mutations.go |
| +++ b/internal/equipo/runner_mutations.go |
| @@ -6,6 +6,7 @@ import ( |
| "encoding/hex" |
| "encoding/json" |
| "errors" |
| + "strings" |
| "time" |
| "amadan.net/oficina/equipo/internal/equipo/team" |
| @@ -23,6 +24,13 @@ func (e *Execution) Mutate(ctx context.Context, p RunnerPrincipal, op string, q |
| if !requestValid(q) { |
| return nil, ErrInvalid |
| } |
| + if op == "events" { |
| + var event runnerproto.Event |
| + if runnerproto.DecodeLimit(strings.NewReader(string(q.Event)), &event, runnerproto.MaxEventBytes+4096) != nil || event.AssignmentID != q.AssignmentID || event.Scope != q.Scope || event.Handle != q.Handle || event.ID != q.RequestID || event.ActionID != q.ActionID { |
| + return nil, ErrInvalid |
| + } |
| + return nil, e.IngestRunnerEvent(ctx, p, event) |
| + } |
| if op == "contained" { |
| if err := e.containmentBarrier(ctx, p, "", q); err != nil { |
| return nil, err |
| @@ -152,6 +160,11 @@ func observeRunner(tx *gorm.DB, a runnerAssignment, op string, q RunnerRequest, |
| } |
| func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignment, value Assignment, op string, q RunnerRequest, cleanup bool) (any, error) { |
| now := e.store.runnerClock.Now().UTC() |
| + if op == "intend" || op == "admit" { |
| + if err := runnerTimelineAvailable(tx, a.ID); err != nil { |
| + return nil, err |
| + } |
| + } |
| switch op { |
| case "renew": |
| deadline := now.Add(30 * time.Second) |
| @@ -265,29 +278,11 @@ func (e *Execution) mutateAt(ctx context.Context, tx *gorm.DB, a runnerAssignmen |
| return nil, err |
| } |
| return task, storeError(tx.Model(&runnerAssignment{}).Where("id=?", a.ID).Select("State").Updates(&runnerAssignment{State: "prepared"}).Error) |
| - case "events": |
| - if len(q.Event) == 0 || len(q.Event) > runnerproto.MaxEventBytes { |
| - return nil, ErrInvalid |
| - } |
| - if e.validators.Events == nil { |
| - return nil, ErrUnavailable |
| - } |
| - if err := e.validators.Events(ctx, value, q); err != nil { |
| - return nil, err |
| - } |
| - _, err := observeRunner(tx, a, op, q, now) |
| - return nil, err |
| case "artifacts": |
| if a.Kind != "step" || q.Artifact == nil || len(q.Artifact.Payload) > runnerproto.MaxArtifactBytes { |
| return nil, ErrInvalid |
| } |
| - if e.validators.Artifact == nil { |
| - return nil, ErrUnavailable |
| - } |
| - if err := e.validators.Artifact(ctx, value, q); err != nil { |
| - return nil, err |
| - } |
| - return e.Core.Register(ctx, q.Scope, q.Handle, *q.Artifact) |
| + return e.registerArtifactOnce(ctx, tx, a, q) |
| } |
| return nil, ErrInvalid |
| } |
diff --git a/internal/equipo/runner_provenance.go b/internal/equipo/runner_provenance.go| index 34c1bfac..a3892ade 100644 |
| --- a/internal/equipo/runner_provenance.go |
| +++ b/internal/equipo/runner_provenance.go |
| @@ -100,6 +100,9 @@ func (e *Execution) syncExposure(ctx context.Context, tx *gorm.DB) error { |
| return storeError(err) |
| } |
| if iso.RunnerTainted || iso.Status == "unconfined" { |
| + if err := syncRunnerEventExposure(tx, a.ID, iso); err != nil { |
| + return err |
| + } |
| var artifacts []executionArtifacts |
| if err := tx.Where("attempt_id=? AND job_id=?", a.AttemptID, a.JobID).Find(&artifacts).Error; err != nil { |
| return storeError(err) |
diff --git a/internal/equipotest/runner_api_test.go b/internal/equipotest/runner_api_test.go| index 1a03c36f..f0778efc 100644 |
| --- a/internal/equipotest/runner_api_test.go |
| +++ b/internal/equipotest/runner_api_test.go |
| @@ -227,7 +227,7 @@ func TestRunnerFenceHTTPBindings(t *testing.T) { |
| for _, field := range []string{"scope", "job", "attempt", "runner", "fence", "assignment", "version"} { |
| t.Run(op+"/"+field, func(t *testing.T) { |
| q := f.request() |
| - q.Event = json.RawMessage(`{"kind":"progress"}`) |
| + q.Event = fixtureEventRequest(t, f, q) |
| switch field { |
| case "scope": |
| q.Scope.Account = "other" |
| @@ -244,6 +244,7 @@ func TestRunnerFenceHTTPBindings(t *testing.T) { |
| case "version": |
| q.Version = 2 |
| } |
| + q.Event = fixtureEventRequest(t, f, q) |
| if status := runnerHTTP(t, f, op, token, q); status < 400 { |
| t.Fatal("HTTP binding accepted", status) |
| } |
| @@ -251,7 +252,7 @@ func TestRunnerFenceHTTPBindings(t *testing.T) { |
| } |
| } |
| q := f.request() |
| - q.Event = json.RawMessage(`{"kind":"progress"}`) |
| + q.Event = fixtureEventRequest(t, f, q) |
| if status := runnerHTTP(t, f, "events", token, q); status != 200 { |
| t.Fatal("valid event denied", status) |
| } |
| @@ -715,7 +716,9 @@ func TestRunnerEndpointForeignPrincipal(t *testing.T) { |
| f.x.SetRunnerValidators(equipo.RunnerValidators{Containment: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| for _, op := range []string{"renew", "prepare", "events", "artifacts", "intend", "admit", "receipts", "lost", "complete", "release", "stop", "contained"} { |
| t.Run(op, func(t *testing.T) { |
| - if status := runnerHTTP(t, f, op, credential.Token, f.request()); status != 403 { |
| + q := f.request() |
| + q.Event = fixtureEventRequest(t, f, q) |
| + if status := runnerHTTP(t, f, op, credential.Token, q); status != 403 { |
| t.Fatal("foreign principal did not fail the binding guard", status) |
| } |
| }) |
| @@ -917,7 +920,7 @@ func TestRunnerCannotUseAnotherMachine(t *testing.T) { |
| approveDevice(t, f.s, code, ownerAddress) |
| credential := claimDevice(t, f.s, code, key) |
| q := f.request() |
| - q.Event = json.RawMessage(`{"kind":"progress"}`) |
| + q.Event = fixtureEventRequest(t, f, q) |
| f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| if status := runnerHTTP(t, f, "events", credential.Token, q); status != 403 { |
| t.Fatal("same person used another machine's assignment", status) |
diff --git a/internal/equipotest/runner_events_test.go b/internal/equipotest/runner_events_test.go| new file mode 100644 |
| index 00000000..a3a85340 |
| --- /dev/null |
| +++ b/internal/equipotest/runner_events_test.go |
| @@ -0,0 +1,478 @@ |
| +package equipotest |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "gorm.io/gorm" |
| + "io" |
| + "log/slog" |
| + "math" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| +) |
| + |
| +func fixtureEvent(f runnerFixture, id string, seq int64) runnerproto.Event { |
| + return runnerproto.Event{Version: 1, ID: id, TaskID: f.a.TaskID, AssignmentID: f.a.ID, Scope: f.claim.Scope, Handle: f.claim.Handle, ServerID: "server", AgentID: "agent", SessionID: "session", Epoch: "epoch", Sequence: &seq, Kind: "timeline", Payload: json.RawMessage(`{"text":"hello"}`), SourceTime: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)} |
| +} |
| +func eventValidators(f runnerFixture) { |
| + f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| +} |
| +func TestRunnerEventReplay(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "one", 1) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e.ID = "alias" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + if n := scalar(t, f.d, "SELECT count(*) FROM runner_events"); n != 1 { |
| + t.Fatal("replay duplicated effect", n) |
| + } |
| + if n := scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'"); n != 1 { |
| + t.Fatal("replay duplicated audit", n) |
| + } |
| + e.Payload = json.RawMessage(`{"text":"changed"}`) |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("changed duplicate accepted") |
| + } |
| + e = fixtureEvent(f, "other", 2) |
| + e.Handle.Fence++ |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("wrong fence accepted") |
| + } |
| + e = fixtureEvent(f, "other", 2) |
| + p := f.principal |
| + p.Person = "other@example.com" |
| + if f.s.IngestRunnerEvent(connectionContext, p, e) == nil { |
| + t.Fatal("wrong principal accepted") |
| + } |
| +} |
| +func TestTimelineEpochReplacement(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "old", 1) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e = fixtureEvent(f, "replace", 0) |
| + e.Kind = "timeline_replacement" |
| + e.Sequence = nil |
| + e.Epoch = "new" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + q := f.request() |
| + q.Intent = &team.IntentSpec{Key: "blocked", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`)} |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err == nil { |
| + t.Fatal("gap admitted work") |
| + } |
| + e = fixtureEvent(f, "new", 1) |
| + e.Epoch = "new" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + if n := scalar(t, f.d, "SELECT count(*) FROM runner_events"); n != 3 { |
| + t.Fatal("replacement deleted evidence", n) |
| + } |
| + var epoch, iso string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT epoch,isolation FROM runner_timelines").Scan(&epoch, &iso)) |
| + if epoch != "new" { |
| + t.Fatal("projection retained old epoch", epoch) |
| + } |
| + var isolation team.IsolationSnapshot |
| + executionMust(t, json.Unmarshal([]byte(iso), &isolation)) |
| + if !isolation.RunnerTainted { |
| + t.Fatal("replacement stripped exposure") |
| + } |
| +} |
| + |
| +func eventTurn(t *testing.T, f runnerFixture) team.ActionID { |
| + t.Helper() |
| + q := f.request() |
| + q.Intent = &team.IntentSpec{Key: "turn", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 100, OutputTokens: 100}} |
| + result, err := f.x.Mutate(connectionContext, f.principal, "intend", q) |
| + executionMust(t, err) |
| + q.Intent = nil |
| + q.ActionID = result.(team.ActionID) |
| + q.RequestID = "admit" |
| + _, err = f.x.Mutate(connectionContext, f.principal, "admit", q) |
| + executionMust(t, err) |
| + return q.ActionID |
| +} |
| +func completionEvent(f runnerFixture, id team.ActionID) runnerproto.Event { |
| + e := fixtureEvent(f, "completed", 1) |
| + e.Kind = "turn_completed" |
| + e.Sequence = nil |
| + e.TurnID = "turn" |
| + e.ActionID = id |
| + e.Payload = json.RawMessage(`{"event":{"type":"turn_completed","provider":"claude","turnId":"turn","usage":{"inputTokens":10,"cachedInputTokens":3,"outputTokens":2,"totalCostUsd":0.0673131}}}`) |
| + return e |
| +} |
| +func completionValidators(f runnerFixture, usage *team.Usage) { |
| + f.x.SetRunnerValidators(equipo.RunnerValidators{Events: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }, Receipt: func(context.Context, equipo.Assignment, equipo.RunnerRequest) (team.Receipt, error) { |
| + return team.Receipt{ID: "turn-receipt", Outcome: team.OutcomeSuccess, Usage: usage}, nil |
| + }}) |
| +} |
| +func TestRunnerEventReplayAtomicSettlement(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + e := completionEvent(f, id) |
| + u := &team.Usage{Calls: 1, InputTokens: 13, CachedInputTokens: 3, OutputTokens: 2, CostUnavailable: true} |
| + completionValidators(f, u) |
| + executionMust(t, f.d.G.Callback().Create().Before("gorm:create").Register("task12_crash", func(tx *gorm.DB) { |
| + if tx.Statement.Table == "audit_events" { |
| + if ev, ok := tx.Statement.Dest.(*equipo.AuditEvent); ok && ev.Kind == "runner.event" { |
| + tx.AddError(errors.New("injected task12 failure")) |
| + } |
| + } |
| + })) |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("audit failure accepted") |
| + } |
| + executionMust(t, f.d.G.Callback().Create().Remove("task12_crash")) |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 0 || scalar(t, f.d, "SELECT count(*) FROM runner_timelines") != 0 || scalar(t, f.d, "SELECT count(*) FROM reservations WHERE state='settled'") != 0 { |
| + t.Fatal("partial event transaction committed") |
| + } |
| + action, err := f.x.Core.GetAction(connectionContext, e.Scope, id) |
| + executionMust(t, err) |
| + if action.State != team.ActionDispatching { |
| + t.Fatal("core receipt escaped rollback") |
| + } |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + for i := 0; i < 3; i++ { |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + } |
| + rows, err := f.x.Core.Reservations(connectionContext, e.Scope) |
| + executionMust(t, err) |
| + if len(rows) != 1 || rows[0].Settled != *u { |
| + t.Fatal("replayed charge", rows) |
| + } |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 { |
| + t.Fatal("duplicate acceptance") |
| + } |
| +} |
| +func TestRunnerEventReplayMissingAndLateAfterCancel(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + e := completionEvent(f, id) |
| + completionValidators(f, nil) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + rows, err := f.x.Core.Reservations(connectionContext, e.Scope) |
| + executionMust(t, err) |
| + if rows[0].State != team.ReservationOpen { |
| + t.Fatal("missing usage refunded") |
| + } |
| + q := f.request() |
| + q.RequestID = "next" |
| + q.Intent = &team.IntentSpec{Key: "next", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}} |
| + if _, err = f.x.Mutate(connectionContext, f.principal, "intend", q); err != nil { |
| + t.Fatal("completed unknown usage blocked remaining headroom", err) |
| + } |
| + _, err = f.x.Core.Cancel(connectionContext, e.Scope, ownerAddress, "cancel") |
| + executionMust(t, err) |
| + completionValidators(f, &team.Usage{Calls: 1, InputTokens: 13, CachedInputTokens: 3, OutputTokens: 2, CostUnavailable: true}) |
| + e.ID = "late" |
| + e.RequestID = "late-observation" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + job, err := f.x.Core.GetJob(connectionContext, e.Scope) |
| + executionMust(t, err) |
| + if job.State != team.JobCancelled { |
| + t.Fatal("late usage changed cancellation", job.State) |
| + } |
| + rows, err = f.x.Core.Reservations(connectionContext, e.Scope) |
| + executionMust(t, err) |
| + if rows[0].State != team.ReservationSettled || rows[0].Settled.InputTokens != 13 { |
| + t.Fatal("late usage did not settle", rows) |
| + } |
| +} |
| +func TestRunnerEventReplayArtifactRequest(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + f.x.SetRunnerValidators(equipo.RunnerValidators{Artifact: func(context.Context, equipo.Assignment, equipo.RunnerRequest) error { return nil }}) |
| + q := f.request() |
| + q.Artifact = &team.ArtifactSpec{Role: team.RoleReproduction, MediaType: "text/plain", Payload: []byte("repro")} |
| + first, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q) |
| + executionMust(t, err) |
| + second, err := f.x.Mutate(connectionContext, f.principal, "artifacts", q) |
| + executionMust(t, err) |
| + if first.(team.Artifact).ID != second.(team.Artifact).ID || scalar(t, f.d, "SELECT count(*) FROM artifacts") != 1 { |
| + t.Fatal("artifact replay created semantic duplicate") |
| + } |
| + q.Artifact.Payload = []byte("changed") |
| + if _, err = f.x.Mutate(connectionContext, f.principal, "artifacts", q); err == nil { |
| + t.Fatal("artifact key reused for changed payload") |
| + } |
| +} |
| +func TestRunnerEventReplayHTTP(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "wire", 1) |
| + q := f.request() |
| + q.RequestID = e.ID |
| + raw, err := runnerproto.Marshal(e) |
| + executionMust(t, err) |
| + q.Event = raw |
| + body, err := runnerproto.Marshal(q) |
| + executionMust(t, err) |
| + req := httptest.NewRequest("POST", "/events", bytes.NewReader(body)) |
| + req.Header.Set("Content-Type", "application/json") |
| + req.Header.Set("Authorization", "Bearer "+runnerBearerFor(t, f)) |
| + w := httptest.NewRecorder() |
| + f.s.RunnerHandler().ServeHTTP(w, req) |
| + if w.Code != 200 { |
| + t.Fatal("event endpoint", w.Code, w.Body.String()) |
| + } |
| +} |
| + |
| +func reopenEventFixture(t *testing.T, f *runnerFixture) { |
| + t.Helper() |
| + var path string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path)) |
| + executionMust(t, f.x.Core.Close()) |
| + executionMust(t, f.d.Close()) |
| + d, err := db.Open(path, slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + executionMust(t, err) |
| + t.Cleanup(func() { d.Close() }) |
| + f.d = d |
| + _, err = migrate.Apply(connectionContext, d, equipo.BootSchema) |
| + executionMust(t, err) |
| + f.s = equipo.NewStore(d, equipo.WithRunnerClock(f.clock), equipo.WithVerifiedIsolationTuples([]team.IsolationTuple{connectionTuple(f.reports[0])})) |
| + f.x, err = f.s.AttachExecution(connectionContext, path, team.Options{Clock: f.clock, Authority: equipo.NewAuthority(f.s, f.clock)}) |
| + executionMust(t, err) |
| + x := f.x |
| + t.Cleanup(func() { x.Core.Close() }) |
| +} |
| +func TestRunnerJournalServerCommitBeforeACK(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + e := completionEvent(f, id) |
| + path := filepath.Join(t.TempDir(), "private", "journal.db") |
| + j, err := runner.OpenJournal(connectionContext, path) |
| + executionMust(t, err) |
| + profile := runner.UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "exclusive", CostSemantics: "cumulative", Subscription: true} |
| + agent := paseo.Agent{ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID} |
| + executionMust(t, j.Append(connectionContext, e)) |
| + acc, err := j.Usage(connectionContext, agent, profile) |
| + executionMust(t, err) |
| + u := acc.Observe(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Payload: e.Payload}) |
| + if u == nil { |
| + t.Fatal("journal did not restore usage") |
| + } |
| + completionValidators(f, u) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + executionMust(t, j.Close()) |
| + for i := 0; i < 2; i++ { |
| + reopenEventFixture(t, &f) |
| + j, err = runner.OpenJournal(connectionContext, path) |
| + executionMust(t, err) |
| + acc, err = j.Usage(connectionContext, agent, profile) |
| + executionMust(t, err) |
| + if math.Abs(acc.EstimatedCostUSD()-0.0673131) > 1e-10 { |
| + t.Fatal("reopen lost usage baseline") |
| + } |
| + completionValidators(f, u) |
| + rows, err := j.Pending(connectionContext, 10) |
| + executionMust(t, err) |
| + if len(rows) != 1 { |
| + t.Fatal("commit before ACK lost retry") |
| + } |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, rows[0])) |
| + executionMust(t, j.Close()) |
| + } |
| + j, err = runner.OpenJournal(connectionContext, path) |
| + executionMust(t, err) |
| + defer j.Close() |
| + pump := runner.EventPump{Journal: j, Contain: func(context.Context) error { return nil }, Upload: func(ctx context.Context, e runner.Event) error { return f.s.IngestRunnerEvent(ctx, f.principal, e) }} |
| + executionMust(t, pump.Flush(connectionContext, 10)) |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 || scalar(t, f.d, "SELECT count(*) FROM audit_events WHERE kind='runner.event'") != 1 || scalar(t, f.d, "SELECT count(*) FROM reservations WHERE state='settled'") != 1 { |
| + t.Fatal("reopen duplicated effects") |
| + } |
| + pending, err := j.Pending(connectionContext, 10) |
| + executionMust(t, err) |
| + if len(pending) != 0 { |
| + t.Fatal("accepted event not ACKed") |
| + } |
| +} |
| +func TestRunnerEventReplayValidationAndRollback(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + e := fixtureEvent(f, "one", 1) |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("missing event validator accepted") |
| + } |
| + eventValidators(f) |
| + for _, field := range []string{"scope", "task", "assignment", "runner", "session", "sequence", "payload", "time"} { |
| + t.Run(field, func(t *testing.T) { |
| + bad := e |
| + switch field { |
| + case "scope": |
| + bad.Scope.Account = "other" |
| + case "task": |
| + bad.TaskID = "other" |
| + case "assignment": |
| + bad.AssignmentID = "other" |
| + case "runner": |
| + bad.Handle.Runner = "other" |
| + case "session": |
| + bad.SessionID = "" |
| + case "sequence": |
| + n := int64(-1) |
| + bad.Sequence = &n |
| + case "payload": |
| + bad.Payload = []byte(`invalid`) |
| + case "time": |
| + bad.SourceTime = time.Time{} |
| + } |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, bad) == nil { |
| + t.Fatal("invalid event accepted", field) |
| + } |
| + }) |
| + } |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e.ID = "alias" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + n := int64(2) |
| + e.Sequence = &n |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("event alias reused for new sequence") |
| + } |
| + executionMust(t, f.s.RevokeRunner(connectionContext, ownerActor, f.principal.RunnerID, 1)) |
| + e = fixtureEvent(f, "one", 1) |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("revoked principal replay accepted") |
| + } |
| +} |
| + |
| +func TestRunnerEventReplayProviderWire(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + e := completionEvent(f, id) |
| + completionValidators(f, nil) |
| + q := f.request() |
| + q.RequestID = e.ID |
| + q.ActionID = id |
| + raw, err := runnerproto.Marshal(e) |
| + executionMust(t, err) |
| + q.Event = raw |
| + if status := runnerHTTP(t, f, "events", runnerBearerFor(t, f), q); status != 200 { |
| + t.Fatal("provider payload rejected by wire codec", status) |
| + } |
| +} |
| +func TestRunnerEventReplayControlEpoch(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + e := completionEvent(f, id) |
| + completionValidators(f, nil) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e.Epoch = "replacement" |
| + e.ID = "history-control" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 1 { |
| + t.Fatal("control duplicated across epochs") |
| + } |
| +} |
| + |
| +func TestTimelineEpochHistoricalExposure(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "exposure", 1) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + mustSQL(t, f.d, `UPDATE runner_events SET isolation='{"status":"confined"}',body=json_set(body,'$.isolation',json('{"status":"confined"}'))`) |
| + mustSQL(t, f.d, `UPDATE runner_timelines SET isolation='{"status":"confined"}'`) |
| + executionMust(t, f.x.Sync(connectionContext)) |
| + var raw, body, projection string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT isolation,body FROM runner_events").Scan(&raw, &body)) |
| + executionMust(t, f.d.Writer().QueryRow("SELECT isolation FROM runner_timelines").Scan(&projection)) |
| + for _, value := range []string{raw, projection} { |
| + var iso team.IsolationSnapshot |
| + executionMust(t, json.Unmarshal([]byte(value), &iso)) |
| + if !iso.RunnerTainted { |
| + t.Fatal("running event lost newly observed exposure") |
| + } |
| + } |
| + var restored runnerproto.Event |
| + executionMust(t, json.Unmarshal([]byte(body), &restored)) |
| + if !restored.Isolation.RunnerTainted { |
| + t.Fatal("event body lost exposure") |
| + } |
| +} |
| + |
| +func TestTimelineEpochUnknownOutcome(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "gap", 0) |
| + e.Sequence = nil |
| + e.Kind = "timeline_gap" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e.ID = "ready" |
| + e.Kind = "timeline_ready" |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + q := f.request() |
| + q.RequestID = "next" |
| + q.Intent = &team.IntentSpec{Key: "next", Operation: team.OpProviderCall, Payload: json.RawMessage(`{}`), Reserve: team.Usage{InputTokens: 1, OutputTokens: 1}} |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err == nil { |
| + t.Fatal("refetch invented completion for unknown action") |
| + } |
| + e = completionEvent(f, id) |
| + completionValidators(f, nil) |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + if _, err := f.x.Mutate(connectionContext, f.principal, "intend", q); err != nil { |
| + t.Fatal("known completion cannot use remaining headroom", err) |
| + } |
| +} |
| +func TestRunnerEventReplayCompletionNeedsReceipt(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + id := eventTurn(t, f) |
| + eventValidators(f) |
| + e := completionEvent(f, id) |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("uncorroborated completion accepted") |
| + } |
| + if scalar(t, f.d, "SELECT count(*) FROM runner_events") != 0 { |
| + t.Fatal("uncorroborated event committed") |
| + } |
| +} |
| + |
| +func TestRunnerEventReplayAssignedIsolation(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "assigned", 1) |
| + e.Isolation = team.IsolationSnapshot{Status: "confined"} |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + var raw string |
| + executionMust(t, f.d.Writer().QueryRow("SELECT body FROM runner_events").Scan(&raw)) |
| + var saved runnerproto.Event |
| + executionMust(t, json.Unmarshal([]byte(raw), &saved)) |
| + if !saved.Isolation.RunnerTainted || len(saved.Isolation.AcknowledgementIDs) == 0 { |
| + t.Fatal("event did not retain assigned isolation at commit") |
| + } |
| +} |
| + |
| +func fixtureEventRequest(t *testing.T, f runnerFixture, q equipo.RunnerRequest) json.RawMessage { |
| + t.Helper() |
| + event := fixtureEvent(f, q.RequestID, 1) |
| + event.Scope = q.Scope |
| + event.Handle = q.Handle |
| + event.AssignmentID = q.AssignmentID |
| + event.ActionID = q.ActionID |
| + raw, err := runnerproto.Marshal(event) |
| + executionMust(t, err) |
| + return raw |
| +} |
| + |
| +func TestTimelineEpochChangedReset(t *testing.T) { |
| + f := runnerFixtureNew(t, true) |
| + eventValidators(f) |
| + e := fixtureEvent(f, "reset", 0) |
| + e.Kind = "timeline_replacement" |
| + e.Sequence = nil |
| + executionMust(t, f.s.IngestRunnerEvent(connectionContext, f.principal, e)) |
| + e.Epoch = "different" |
| + if f.s.IngestRunnerEvent(connectionContext, f.principal, e) == nil { |
| + t.Fatal("replacement ID accepted a different target epoch") |
| + } |
| +} |
diff --git a/internal/runner/events.go b/internal/runner/events.go| new file mode 100644 |
| index 00000000..006f0b5b |
| --- /dev/null |
| +++ b/internal/runner/events.go |
| @@ -0,0 +1,247 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "html" |
| + "math/rand/v2" |
| + "net/http" |
| + "regexp" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type EventPump struct { |
| + Journal *Journal |
| + Upload func(context.Context, Event) error |
| + Contain func(context.Context) error |
| + Secrets []string |
| +} |
| + |
| +func (p *EventPump) Append(ctx context.Context, e Event, ack func() error) error { |
| + if p.Journal == nil || p.Contain == nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + if err := p.Journal.appendRedacted(ctx, e, p.Secrets); err != nil { |
| + return p.storageFailure(ctx, err) |
| + } |
| + if ack != nil { |
| + return ack() |
| + } |
| + return nil |
| +} |
| +func (p *EventPump) Flush(ctx context.Context, limit int) error { |
| + if p.Journal == nil || p.Upload == nil || p.Contain == nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + pending, err := p.Journal.Pending(ctx, limit) |
| + if err != nil { |
| + return p.storageFailure(ctx, err) |
| + } |
| + for _, e := range pending { |
| + if err = p.Upload(ctx, e); err != nil { |
| + return err |
| + } |
| + if err = p.Journal.Ack(ctx, e.ID); err != nil { |
| + return p.storageFailure(ctx, err) |
| + } |
| + } |
| + return nil |
| +} |
| +func streamKey(a paseo.Agent) string { |
| + return runnerproto.EventHash([]string{a.ServerID, a.AgentID, a.ProviderSessionID}) |
| +} |
| +func (j *Journal) BeginReplay(ctx context.Context, a paseo.Agent) error { |
| + if a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { |
| + return runnerproto.ErrInvalid |
| + } |
| + _, err := j.db.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,'',0,-1) ON CONFLICT(stream) DO UPDATE SET ready=-1`, streamKey(a)) |
| + if err != nil { |
| + return j.fail() |
| + } |
| + return nil |
| +} |
| +func (j *Journal) Cursor(ctx context.Context, a paseo.Agent) (paseo.Cursor, error) { |
| + var c paseo.Cursor |
| + err := j.db.QueryRowContext(ctx, "SELECT epoch,sequence FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&c.Epoch, &c.Sequence) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + return c, nil |
| + } |
| + return c, err |
| +} |
| +func (j *Journal) Ready(ctx context.Context, a paseo.Agent) error { |
| + if err := j.AdmissionAllowed(ctx); err != nil { |
| + return err |
| + } |
| + var ready int |
| + if err := j.db.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&ready); err != nil || ready != 1 { |
| + return paseo.ErrNotReady |
| + } |
| + return nil |
| +} |
| +func (j *Journal) Recovered(ctx context.Context, a paseo.Agent, c paseo.Cursor) error { |
| + if c.Epoch == "" || c.Sequence < 0 || a.ServerID == "" || a.AgentID == "" || a.ProviderSessionID == "" { |
| + return runnerproto.ErrInvalid |
| + } |
| + if err := j.AdmissionAllowed(ctx); err != nil { |
| + return err |
| + } |
| + // Called only after Subscribe.Ready and durable draining of its refetch. |
| + tx, err := j.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return j.fail() |
| + } |
| + defer tx.Rollback() |
| + var phase int |
| + if err = tx.QueryRowContext(ctx, "SELECT ready FROM journal_streams WHERE stream=?", streamKey(a)).Scan(&phase); err != nil || phase != -1 { |
| + return paseo.ErrNotReady |
| + } |
| + var maximum sql.NullInt64 |
| + if err = tx.QueryRowContext(ctx, `SELECT MAX(json_extract(body,'$.sequence')) FROM journal_events WHERE json_extract(body,'$.server_id')=? AND json_extract(body,'$.agent_id')=? AND json_extract(body,'$.session_id')=? AND json_extract(body,'$.epoch')=?`, a.ServerID, a.AgentID, a.ProviderSessionID, c.Epoch).Scan(&maximum); err != nil { |
| + return ErrJournal |
| + } |
| + if c.Sequence > 0 && (!maximum.Valid || c.Sequence > maximum.Int64) { |
| + return runnerproto.ErrInvalid |
| + } |
| + if _, err = tx.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,?,?,1) ON CONFLICT(stream) DO UPDATE SET epoch=excluded.epoch,sequence=excluded.sequence,ready=1`, streamKey(a), c.Epoch, c.Sequence); err != nil { |
| + return ErrJournal |
| + } |
| + return tx.Commit() |
| +} |
| +func ReconnectDelay(attempt int) time.Duration { |
| + if attempt < 0 { |
| + attempt = 0 |
| + } |
| + if attempt > 5 { |
| + attempt = 5 |
| + } |
| + base := time.Second * time.Duration(1<<attempt) |
| + if base > 30*time.Second { |
| + base = 30 * time.Second |
| + } |
| + return base + time.Duration(rand.Int64N(int64(250*time.Millisecond))) |
| +} |
| +func WaitReconnect(ctx context.Context, attempt int, leaseDeadline time.Time) error { |
| + remaining := time.Until(leaseDeadline) |
| + if remaining <= 0 { |
| + return paseo.ErrUncertain |
| + } |
| + delay := ReconnectDelay(attempt) |
| + if delay >= remaining { |
| + return paseo.ErrUncertain |
| + } |
| + timer := time.NewTimer(delay) |
| + defer timer.Stop() |
| + select { |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + case <-timer.C: |
| + if !time.Now().Before(leaseDeadline) { |
| + return paseo.ErrUncertain |
| + } |
| + return nil |
| + } |
| +} |
| + |
| +var secretPattern = regexp.MustCompile(`(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+|((?:api[_-]?key|password|secret|token)\s*[=:]\s*)[^\s,"'<>]+|(?:sk-|ghp_|github_pat_)[A-Za-z0-9_-]{8,}`) |
| + |
| +func redactText(s string, secrets []string) string { |
| + for _, secret := range secrets { |
| + if secret != "" { |
| + s = strings.ReplaceAll(s, secret, "***") |
| + } |
| + } |
| + return secretPattern.ReplaceAllString(s, "***") |
| +} |
| +func RedactJSON(raw json.RawMessage, secrets []string) json.RawMessage { |
| + var v any |
| + d := json.NewDecoder(strings.NewReader(string(raw))) |
| + d.UseNumber() |
| + if d.Decode(&v) != nil { |
| + return json.RawMessage(`null`) |
| + } |
| + var walk func(any) any |
| + walk = func(v any) any { |
| + switch x := v.(type) { |
| + case map[string]any: |
| + for k, item := range x { |
| + key := strings.ToLower(strings.NewReplacer("_", "", "-", "").Replace(k)) |
| + if strings.HasSuffix(key, "token") || strings.HasSuffix(key, "password") || strings.HasSuffix(key, "secret") || strings.HasSuffix(key, "apikey") || strings.HasSuffix(key, "privatekey") { |
| + x[k] = "***" |
| + continue |
| + } |
| + switch key { |
| + case "authorization", "password", "secret", "token", "accesstoken", "refreshtoken", "apikey", "credential", "credentials", "cleanuptoken", "bearer": |
| + x[k] = "***" |
| + default: |
| + x[k] = walk(item) |
| + } |
| + } |
| + case []any: |
| + for i := range x { |
| + x[i] = walk(x[i]) |
| + } |
| + case string: |
| + return redactText(x, secrets) |
| + } |
| + return v |
| + } |
| + out, err := json.Marshal(walk(v)) |
| + if err != nil { |
| + return json.RawMessage(`null`) |
| + } |
| + return out |
| +} |
| +func DownloadLog(w http.ResponseWriter, data []byte, secrets []string) { |
| + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| + w.Header().Set("Content-Disposition", `attachment; filename="runner.log"`) |
| + w.Header().Set("X-Content-Type-Options", "nosniff") |
| + w.Header().Set("Cache-Control", "no-store") |
| + _, _ = w.Write([]byte(html.EscapeString(redactText(string(data), secrets)))) |
| +} |
| + |
| +func journalStreamEvent(ctx context.Context, tx *sql.Tx, e Event) error { |
| + key := streamKey(paseo.Agent{ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID}) |
| + var epoch string |
| + var sequence int64 |
| + var ready int |
| + err := tx.QueryRowContext(ctx, "SELECT epoch,sequence,ready FROM journal_streams WHERE stream=?", key).Scan(&epoch, &sequence, &ready) |
| + if errors.Is(err, sql.ErrNoRows) { |
| + epoch = e.Epoch |
| + } else if err != nil { |
| + return err |
| + } |
| + switch e.Kind { |
| + case "timeline_replacement": |
| + epoch = e.Epoch |
| + sequence = 0 |
| + ready = 0 |
| + case "timeline_gap": |
| + ready = 0 |
| + default: |
| + if e.Sequence != nil { |
| + if epoch == "" { |
| + epoch = e.Epoch |
| + } |
| + if epoch != e.Epoch { |
| + ready = 0 |
| + } else if *e.Sequence > sequence { |
| + sequence = *e.Sequence |
| + } |
| + } |
| + } |
| + _, err = tx.ExecContext(ctx, `INSERT INTO journal_streams VALUES(?,?,?,?) ON CONFLICT(stream) DO UPDATE SET epoch=excluded.epoch,sequence=excluded.sequence,ready=excluded.ready`, key, epoch, sequence, ready) |
| + return err |
| +} |
| + |
| +func (p *EventPump) storageFailure(ctx context.Context, err error) error { |
| + _ = p.Journal.fail() |
| + cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) |
| + defer cancel() |
| + return errors.Join(err, p.Contain(cleanup)) |
| +} |
diff --git a/internal/runner/journal.go b/internal/runner/journal.go| new file mode 100644 |
| index 00000000..5448af51 |
| --- /dev/null |
| +++ b/internal/runner/journal.go |
| @@ -0,0 +1,273 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "encoding/json" |
| + "errors" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + _ "modernc.org/sqlite" |
| +) |
| + |
| +type Event = runnerproto.Event |
| + |
| +const MaxJournalBytes int64 = 128 << 20 |
| + |
| +var ErrJournal = paseo.ErrUncertain |
| + |
| +type Journal struct { |
| + db *sql.DB |
| + path string |
| + maxBytes int64 |
| + mu sync.Mutex |
| + blocked bool |
| +} |
| + |
| +func OpenJournal(ctx context.Context, path string) (*Journal, error) { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| + return nil, runnerproto.ErrInvalid |
| + } |
| + dir := filepath.Dir(path) |
| + if err := os.MkdirAll(dir, 0700); err != nil { |
| + return nil, ErrJournal |
| + } |
| + resolved, err := filepath.EvalSymlinks(dir) |
| + if err != nil || resolved != dir { |
| + return nil, ErrJournal |
| + } |
| + info, err := os.Stat(dir) |
| + if err != nil || info.Mode().Perm()&0077 != 0 { |
| + return nil, ErrJournal |
| + } |
| + f, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) |
| + if os.IsExist(err) { |
| + info, err = os.Lstat(path) |
| + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0600 { |
| + return nil, ErrJournal |
| + } |
| + } else if err != nil { |
| + return nil, ErrJournal |
| + } else { |
| + err = f.Sync() |
| + closeErr := f.Close() |
| + if err != nil || closeErr != nil { |
| + return nil, ErrJournal |
| + } |
| + } |
| + for p := dir; ; p = filepath.Dir(p) { |
| + f, err := os.Open(p) |
| + if err != nil { |
| + return nil, ErrJournal |
| + } |
| + err = f.Sync() |
| + _ = f.Close() |
| + if err != nil { |
| + return nil, ErrJournal |
| + } |
| + if p == filepath.Dir(p) { |
| + break |
| + } |
| + } |
| + dsn := (&url.URL{Scheme: "file", Path: path}).String() + "?_pragma=busy_timeout(5000)&_pragma=synchronous(FULL)&_pragma=journal_mode(DELETE)&_txlock=immediate" |
| + db, err := sql.Open("sqlite", dsn) |
| + if err != nil { |
| + return nil, ErrJournal |
| + } |
| + db.SetMaxOpenConns(1) |
| + j := &Journal{db: db, path: path, maxBytes: MaxJournalBytes} |
| + var version int |
| + if err = db.QueryRowContext(ctx, "PRAGMA user_version").Scan(&version); err != nil || version > 1 { |
| + db.Close() |
| + return nil, ErrJournal |
| + } |
| + _, err = db.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS journal_events (ordinal INTEGER PRIMARY KEY AUTOINCREMENT, id TEXT UNIQUE NOT NULL, event_key TEXT UNIQUE NOT NULL, content_hash TEXT NOT NULL, body BLOB NOT NULL, size INTEGER NOT NULL, acked INTEGER NOT NULL DEFAULT 0); |
| + CREATE INDEX IF NOT EXISTS journal_pending ON journal_events(acked,ordinal); |
| + CREATE TABLE IF NOT EXISTS journal_aliases (id TEXT PRIMARY KEY, event_key TEXT NOT NULL); |
| + CREATE TABLE IF NOT EXISTS journal_intents (intent_key TEXT PRIMARY KEY, body BLOB NOT NULL); |
| + CREATE TABLE IF NOT EXISTS journal_streams (stream TEXT PRIMARY KEY, epoch TEXT NOT NULL, sequence INTEGER NOT NULL, ready INTEGER NOT NULL); |
| + CREATE TABLE IF NOT EXISTS journal_state (id INTEGER PRIMARY KEY, blocked INTEGER NOT NULL); |
| + INSERT OR IGNORE INTO journal_state VALUES(1,0); |
| + UPDATE journal_streams SET ready=0; |
| + PRAGMA user_version=1;`) |
| + if err != nil { |
| + db.Close() |
| + return nil, ErrJournal |
| + } |
| + return j, nil |
| +} |
| +func (j *Journal) Close() error { return j.db.Close() } |
| +func (j *Journal) fail() error { |
| + j.mu.Lock() |
| + j.blocked = true |
| + j.mu.Unlock() |
| + // A failed disk write still fences this process. Startup requires refetch. |
| + _, _ = j.db.Exec("UPDATE journal_state SET blocked=1 WHERE id=1") |
| + return ErrJournal |
| +} |
| +func (j *Journal) AdmissionAllowed(ctx context.Context) error { |
| + j.mu.Lock() |
| + blocked := j.blocked |
| + j.mu.Unlock() |
| + if blocked { |
| + return ErrJournal |
| + } |
| + var saved int |
| + var size int64 |
| + if err := j.db.QueryRowContext(ctx, "SELECT blocked,(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0) FROM journal_state WHERE id=1").Scan(&saved, &size); err != nil || saved != 0 || size >= j.maxBytes { |
| + return ErrJournal |
| + } |
| + return nil |
| +} |
| +func (j *Journal) Append(ctx context.Context, e Event) error { return j.appendRedacted(ctx, e, nil) } |
| +func (j *Journal) appendRedacted(ctx context.Context, e Event, secrets []string) error { |
| + if err := e.Validate(); err != nil { |
| + return err |
| + } |
| + hash := e.ContentHash() |
| + e.Payload = RedactJSON(e.Payload, secrets) |
| + if err := e.Validate(); err != nil { |
| + return err |
| + } |
| + body, err := json.Marshal(e) |
| + if err != nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + err = j.append(ctx, e, hash, body) |
| + if err != nil && !errors.Is(err, runnerproto.ErrInvalid) { |
| + return j.fail() |
| + } |
| + return err |
| +} |
| +func (j *Journal) append(ctx context.Context, e Event, hash string, body []byte) error { |
| + tx, err := j.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return err |
| + } |
| + defer tx.Rollback() |
| + key := e.DedupKey() |
| + var oldKey string |
| + err = tx.QueryRowContext(ctx, "SELECT event_key FROM journal_aliases WHERE id=?", e.ID).Scan(&oldKey) |
| + if err == nil && oldKey != key { |
| + return runnerproto.ErrInvalid |
| + } |
| + if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + var oldHash string |
| + err = tx.QueryRowContext(ctx, "SELECT content_hash FROM journal_events WHERE event_key=?", key).Scan(&oldHash) |
| + if err == nil { |
| + if oldHash != hash { |
| + return runnerproto.ErrInvalid |
| + } |
| + } else { |
| + if !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + var size int64 |
| + var blocked int |
| + if err = tx.QueryRowContext(ctx, "SELECT blocked,(SELECT COALESCE(SUM(size),0) FROM journal_events WHERE acked=0) FROM journal_state WHERE id=1").Scan(&blocked, &size); err != nil { |
| + return err |
| + } |
| + if blocked != 0 || size < 0 || int64(len(body)) > j.maxBytes-size { |
| + return ErrJournal |
| + } |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO journal_events(id,event_key,content_hash,body,size) VALUES(?,?,?,?,?)", e.ID, key, hash, body, len(body)); err != nil { |
| + return err |
| + } |
| + if err = journalStreamEvent(ctx, tx, e); err != nil { |
| + return err |
| + } |
| + } |
| + if _, err = tx.ExecContext(ctx, "INSERT OR IGNORE INTO journal_aliases(id,event_key) VALUES(?,?)", e.ID, key); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| +} |
| +func (j *Journal) Pending(ctx context.Context, limit int) ([]Event, error) { |
| + if limit < 1 || limit > 1024 { |
| + return nil, runnerproto.ErrInvalid |
| + } |
| + rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events WHERE acked=0 ORDER BY ordinal LIMIT ?", limit) |
| + if err != nil { |
| + return nil, j.fail() |
| + } |
| + defer rows.Close() |
| + result := []Event{} |
| + for rows.Next() { |
| + var b []byte |
| + var e Event |
| + if rows.Scan(&b) != nil || json.Unmarshal(b, &e) != nil { |
| + return nil, ErrJournal |
| + } |
| + result = append(result, e) |
| + } |
| + return result, rows.Err() |
| +} |
| +func (j *Journal) Ack(ctx context.Context, id string) error { |
| + result, err := j.db.ExecContext(ctx, "UPDATE journal_events SET acked=1 WHERE event_key=(SELECT event_key FROM journal_aliases WHERE id=?)", id) |
| + if err != nil { |
| + return j.fail() |
| + } |
| + n, err := result.RowsAffected() |
| + if err != nil || n != 1 { |
| + return ErrJournal |
| + } |
| + return nil |
| +} |
| +func (j *Journal) RecordIntent(ctx context.Context, i paseo.Intent) error { |
| + if i.Key == "" || i.Kind == "" || i.RequestHash == "" || !json.Valid(i.Request) { |
| + return runnerproto.ErrInvalid |
| + } |
| + if err := j.AdmissionAllowed(ctx); err != nil { |
| + return err |
| + } |
| + if i.Kind == "turn" { |
| + var request struct { |
| + Agent paseo.Agent `json:"agent"` |
| + } |
| + if json.Unmarshal(i.Request, &request) != nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + if err := j.Ready(ctx, request.Agent); err != nil { |
| + return err |
| + } |
| + } |
| + i.Request = RedactJSON(i.Request, nil) |
| + b, err := json.Marshal(i) |
| + if err != nil { |
| + return runnerproto.ErrInvalid |
| + } |
| + tx, err := j.db.BeginTx(ctx, nil) |
| + if err != nil { |
| + return j.fail() |
| + } |
| + err = func() error { |
| + defer tx.Rollback() |
| + key := runnerproto.EventHash([]string{i.Kind, i.Key}) |
| + var old []byte |
| + err := tx.QueryRowContext(ctx, "SELECT body FROM journal_intents WHERE intent_key=?", key).Scan(&old) |
| + if err == nil { |
| + if string(old) != string(b) { |
| + return runnerproto.ErrInvalid |
| + } |
| + return tx.Commit() |
| + } |
| + if !errors.Is(err, sql.ErrNoRows) { |
| + return err |
| + } |
| + if _, err = tx.ExecContext(ctx, "INSERT INTO journal_intents VALUES(?,?)", key, b); err != nil { |
| + return err |
| + } |
| + return tx.Commit() |
| + }() |
| + if err != nil && !errors.Is(err, runnerproto.ErrInvalid) { |
| + return j.fail() |
| + } |
| + return err |
| +} |
diff --git a/internal/runner/journal_test.go b/internal/runner/journal_test.go| new file mode 100644 |
| index 00000000..9c7abf54 |
| --- /dev/null |
| +++ b/internal/runner/journal_test.go |
| @@ -0,0 +1,392 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| +) |
| + |
| +var journalCtx = context.Background() |
| + |
| +func journalEvent(id string, seq int64) Event { |
| + return Event{Version: 1, ID: id, TaskID: "task", AssignmentID: "assignment", ServerID: "server", AgentID: "agent", SessionID: "session", Epoch: "epoch", Kind: "timeline", Sequence: &seq, Scope: team.Scope{Account: "team", Job: 1}, Handle: team.Handle{Attempt: 1, Fence: 1, Runner: "runner"}, Payload: json.RawMessage(`{"text":"hello"}`), SourceTime: time.Date(2026, 11, 2, 0, 0, 0, 0, time.UTC)} |
| +} |
| +func mustJournal(t *testing.T, err error) { |
| + t.Helper() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| +func TestRunnerJournalCrashBoundaries(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "private", "journal.db") |
| + j, err := OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + pending, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(pending) != 0 { |
| + t.Fatal("effect before append") |
| + } |
| + e := journalEvent("event", 1) |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + mustJournal(t, j.Close()) |
| + for i := 0; i < 2; i++ { |
| + j, err = OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + pending, err = j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(pending) != 1 { |
| + t.Fatal("lost durable event", len(pending)) |
| + } |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + mustJournal(t, j.Close()) |
| + } |
| + j, err = OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + e.Payload = json.RawMessage(`{"text":"changed"}`) |
| + if j.Append(journalCtx, e) == nil { |
| + t.Fatal("changed duplicate accepted") |
| + } |
| + mustJournal(t, j.Ack(journalCtx, "event")) |
| + mustJournal(t, j.Close()) |
| + j, err = OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + pending, err = j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(pending) != 0 { |
| + t.Fatal("ACK did not survive reopen") |
| + } |
| + info, err := os.Stat(path) |
| + mustJournal(t, err) |
| + if info.Mode().Perm() != 0600 { |
| + t.Fatal("journal is not private") |
| + } |
| + intent := paseo.Intent{Kind: "agent", Key: "creation", RequestHash: "hash", Request: json.RawMessage(`{"idempotency_key":"creation"}`)} |
| + mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| + mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| + intent.RequestHash = "changed" |
| + if j.RecordIntent(journalCtx, intent) == nil { |
| + t.Fatal("creation key changed") |
| + } |
| +} |
| +func TestBufferFullStopsWork(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + j.maxBytes = 1 |
| + stopped := 0 |
| + p := EventPump{Journal: j, Contain: func(context.Context) error { stopped++; return nil }} |
| + acked := false |
| + if p.Append(journalCtx, journalEvent("full", 1), func() error { acked = true; return nil }) == nil { |
| + t.Fatal("full journal accepted") |
| + } |
| + if stopped != 1 || acked || j.AdmissionAllowed(journalCtx) == nil { |
| + t.Fatal("buffer full did not stop admission and contain", stopped, acked) |
| + } |
| + j.maxBytes = MaxJournalBytes |
| + if j.AdmissionAllowed(journalCtx) == nil { |
| + t.Fatal("buffer failure automatically reopened admission") |
| + } |
| + mustJournal(t, j.Close()) |
| + if p.Append(journalCtx, journalEvent("closed", 2), nil) == nil || stopped != 2 { |
| + t.Fatal("disk failure did not contain") |
| + } |
| +} |
| +func TestRunnerEventReplay(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + p := EventPump{Journal: j, Contain: func(context.Context) error { return nil }} |
| + mustJournal(t, p.Append(journalCtx, journalEvent("event", 1), func() error { |
| + rows, err := j.Pending(journalCtx, 10) |
| + if err != nil || len(rows) != 1 { |
| + t.Fatal("ACK before append") |
| + } |
| + return nil |
| + })) |
| + calls := 0 |
| + p.Upload = func(context.Context, Event) error { |
| + calls++ |
| + if calls == 1 { |
| + return paseo.ErrUncertain |
| + } |
| + return nil |
| + } |
| + if p.Flush(journalCtx, 10) == nil { |
| + t.Fatal("lost upload was ACKed") |
| + } |
| + mustJournal(t, p.Flush(journalCtx, 10)) |
| + rows, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(rows) != 0 || calls != 2 { |
| + t.Fatal("replay failed") |
| + } |
| +} |
| +func TestTimelineEpochReplacement(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| + if _, err = j.Cursor(journalCtx, a); err != nil { |
| + t.Fatal(err) |
| + } |
| + if j.Ready(journalCtx, a) == nil { |
| + t.Fatal("live before refetch") |
| + } |
| + mustJournal(t, j.Append(journalCtx, journalEvent("old", 1))) |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + mustJournal(t, j.Recovered(journalCtx, a, paseo.Cursor{Epoch: "epoch", Sequence: 1})) |
| + mustJournal(t, j.Ready(journalCtx, a)) |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + if j.Ready(journalCtx, a) == nil { |
| + t.Fatal("reconnect retained readiness") |
| + } |
| + e := journalEvent("replacement", 1) |
| + e.Epoch = "new" |
| + reset := e |
| + reset.ID = "reset" |
| + reset.Kind = "timeline_replacement" |
| + reset.Sequence = nil |
| + mustJournal(t, j.Append(journalCtx, reset)) |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + mustJournal(t, j.Recovered(journalCtx, a, paseo.Cursor{Epoch: "new", Sequence: 1})) |
| + c, err := j.Cursor(journalCtx, a) |
| + mustJournal(t, err) |
| + if c.Epoch != "new" { |
| + t.Fatal("epoch did not replace projection") |
| + } |
| + rows, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(rows) != 3 { |
| + t.Fatal("epoch deleted accounting evidence") |
| + } |
| + mustJournal(t, j.Close()) |
| + j, err = OpenJournal(journalCtx, j.path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + if j.Ready(journalCtx, a) == nil { |
| + t.Fatal("restart trusted old live readiness") |
| + } |
| +} |
| + |
| +func TestRunnerJournalCursorCannotSkip(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + if j.Recovered(journalCtx, a, paseo.Cursor{Epoch: "epoch", Sequence: 9}) == nil { |
| + t.Fatal("cursor skipped unjournaled events") |
| + } |
| + mustJournal(t, j.Append(journalCtx, journalEvent("saved", 1))) |
| + if j.Recovered(journalCtx, a, paseo.Cursor{Epoch: "epoch", Sequence: 2}) == nil { |
| + t.Fatal("cursor advanced beyond durable event") |
| + } |
| +} |
| + |
| +func TestRunnerJournalSecretsAndLog(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "private", "journal.db") |
| + j, err := OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + e := journalEvent("secret", 1) |
| + e.Payload = json.RawMessage(`{"authorization":"Bearer credential-value","text":"Bearer credential-value <script>alert(1)</script>","inputTokens":2}`) |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + rows, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if strings.Contains(string(rows[0].Payload), "credential-value") || !strings.Contains(string(rows[0].Payload), "inputTokens") { |
| + t.Fatal("redaction lost accounting or leaked secret", string(rows[0].Payload)) |
| + } |
| + intent := paseo.Intent{Kind: "agent", Key: "secret-intent", RequestHash: "hash", Request: json.RawMessage(`{"env":{"EQUIPO_TOOL_TOKEN":"private-key-value"}}`)} |
| + mustJournal(t, j.RecordIntent(journalCtx, intent)) |
| + var raw []byte |
| + mustJournal(t, j.db.QueryRow("SELECT body FROM journal_intents").Scan(&raw)) |
| + if strings.Contains(string(raw), "private-key-value") { |
| + t.Fatal("intent persisted credential") |
| + } |
| + w := httptest.NewRecorder() |
| + DownloadLog(w, []byte(`<script>secret</script> Bearer credential-value`), []string{"secret"}) |
| + if strings.Contains(w.Body.String(), "<script>") || strings.Contains(w.Body.String(), "credential-value") || strings.Contains(w.Body.String(), "secret") || w.Header().Get("Content-Type") != "text/plain; charset=utf-8" { |
| + t.Fatal("unsafe log download", w.Body.String()) |
| + } |
| +} |
| +func TestBufferFullStopsWorkSQLite(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + var pages int |
| + mustJournal(t, j.db.QueryRow("PRAGMA page_count").Scan(&pages)) |
| + _, err = j.db.Exec(fmt.Sprintf("PRAGMA max_page_count=%d", pages)) |
| + mustJournal(t, err) |
| + e := journalEvent("disk-full", 1) |
| + e.Payload = json.RawMessage(`{"text":"` + strings.Repeat("x", 15000) + `"}`) |
| + contained := false |
| + p := EventPump{Journal: j, Contain: func(ctx context.Context) error { |
| + if ctx.Err() != nil { |
| + t.Fatal("containment inherited cancelled context") |
| + } |
| + contained = true |
| + return nil |
| + }} |
| + if p.Append(journalCtx, e, nil) == nil || !contained || j.AdmissionAllowed(journalCtx) == nil { |
| + t.Fatal("SQLite full did not stop and contain") |
| + } |
| + rows, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + if len(rows) != 0 { |
| + t.Fatal("partial disk-full append") |
| + } |
| +} |
| +func TestRunnerJournalCrashProcess(t *testing.T) { |
| + if path := os.Getenv("EQUIPO_TASK12_CRASH_PATH"); path != "" { |
| + j, err := OpenJournal(journalCtx, path) |
| + if err != nil { |
| + os.Exit(11) |
| + } |
| + if os.Getenv("EQUIPO_TASK12_CRASH_STAGE") != "before" { |
| + if j.Append(journalCtx, journalEvent("crash", 1)) != nil { |
| + os.Exit(12) |
| + } |
| + } |
| + os.Exit(0) |
| + } |
| + for _, stage := range []string{"before", "after"} { |
| + t.Run(stage, func(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "private", "journal.db") |
| + cmd := exec.Command(os.Args[0], "-test.run=^TestRunnerJournalCrashProcess$") |
| + cmd.Env = append(os.Environ(), "EQUIPO_TASK12_CRASH_PATH="+path, "EQUIPO_TASK12_CRASH_STAGE="+stage) |
| + if b, err := cmd.CombinedOutput(); err != nil { |
| + t.Fatal(err, string(b)) |
| + } |
| + j, err := OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + rows, err := j.Pending(journalCtx, 10) |
| + mustJournal(t, err) |
| + want := 0 |
| + if stage == "after" { |
| + want = 1 |
| + } |
| + if len(rows) != want { |
| + t.Fatal("crash boundary lost event", stage, len(rows)) |
| + } |
| + }) |
| + } |
| +} |
| +func TestRunnerJournalBackoffLease(t *testing.T) { |
| + for _, attempt := range []int{-1, 0, 1, 4, 5, 100} { |
| + delay := ReconnectDelay(attempt) |
| + if delay < time.Second || delay > 30250*time.Millisecond { |
| + t.Fatal("unbounded backoff", delay) |
| + } |
| + } |
| + if WaitReconnect(journalCtx, 10, time.Now().Add(10*time.Millisecond)) == nil { |
| + t.Fatal("backoff extended lease") |
| + } |
| + ctx, cancel := context.WithCancel(journalCtx) |
| + cancel() |
| + if WaitReconnect(ctx, 0, time.Now().Add(time.Minute)) == nil { |
| + t.Fatal("reconnect ignored cancellation") |
| + } |
| +} |
| + |
| +func TestTimelineEpochGapStopsLocalDispatch(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| + e := journalEvent("first", 1) |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + mustJournal(t, j.Recovered(journalCtx, a, paseo.Cursor{Epoch: "epoch", Sequence: 1})) |
| + mustJournal(t, j.Ready(journalCtx, a)) |
| + e.ID = "gap" |
| + e.Kind = "timeline_gap" |
| + e.Sequence = nil |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + if j.Ready(journalCtx, a) == nil { |
| + t.Fatal("timeline gap retained live readiness") |
| + } |
| + request, _ := json.Marshal(struct { |
| + Agent paseo.Agent `json:"agent"` |
| + }{a}) |
| + if j.RecordIntent(journalCtx, paseo.Intent{Kind: "turn", Key: "dispatch", RequestHash: "hash", Request: request}) == nil { |
| + t.Fatal("gap allowed dispatch ID") |
| + } |
| +} |
| + |
| +func TestRunnerJournalDurabilityConfiguration(t *testing.T) { |
| + path := filepath.Join(t.TempDir(), "private", "journal.db") |
| + j, err := OpenJournal(journalCtx, path) |
| + mustJournal(t, err) |
| + var syncLevel int |
| + var mode string |
| + mustJournal(t, j.db.QueryRow("PRAGMA synchronous").Scan(&syncLevel)) |
| + mustJournal(t, j.db.QueryRow("PRAGMA journal_mode").Scan(&mode)) |
| + if syncLevel != 2 || mode != "delete" { |
| + t.Fatal("journal writes are not durably synced", syncLevel, mode) |
| + } |
| + _, err = j.db.Exec("PRAGMA user_version=2") |
| + mustJournal(t, err) |
| + mustJournal(t, j.Close()) |
| + if other, err := OpenJournal(journalCtx, path); err == nil { |
| + other.Close() |
| + t.Fatal("newer journal accepted") |
| + } |
| + public := filepath.Join(t.TempDir(), "public") |
| + mustJournal(t, os.Mkdir(public, 0755)) |
| + if other, err := OpenJournal(journalCtx, filepath.Join(public, "journal.db")); err == nil { |
| + other.Close() |
| + t.Fatal("public journal directory accepted") |
| + } |
| +} |
| + |
| +func TestTimelineEpochRefetchReadiness(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + a := paseo.Agent{ServerID: "server", AgentID: "agent", ProviderSessionID: "session"} |
| + e := journalEvent("saved", 1) |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + c := paseo.Cursor{Epoch: "epoch", Sequence: 1} |
| + if j.Recovered(journalCtx, a, c) == nil { |
| + t.Fatal("recovered without starting refetch") |
| + } |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + e.ID = "gap-during-refetch" |
| + e.Kind = "timeline_gap" |
| + e.Sequence = nil |
| + mustJournal(t, j.Append(journalCtx, e)) |
| + if j.Recovered(journalCtx, a, c) == nil { |
| + t.Fatal("gap during refetch regained readiness") |
| + } |
| + mustJournal(t, j.BeginReplay(journalCtx, a)) |
| + mustJournal(t, j.Recovered(journalCtx, a, c)) |
| + mustJournal(t, j.Ready(journalCtx, a)) |
| +} |
| + |
| +func TestRunnerEventReplayRejectsMalformedBeforeRedaction(t *testing.T) { |
| + j, err := OpenJournal(journalCtx, filepath.Join(t.TempDir(), "private", "journal.db")) |
| + mustJournal(t, err) |
| + defer j.Close() |
| + contained := false |
| + acked := false |
| + p := EventPump{Journal: j, Contain: func(context.Context) error { contained = true; return nil }} |
| + e := journalEvent("invalid", 1) |
| + e.Payload = json.RawMessage(`invalid`) |
| + if p.Append(journalCtx, e, func() error { acked = true; return nil }) == nil || acked || !contained { |
| + t.Fatal("redaction hid malformed event") |
| + } |
| +} |
diff --git a/internal/runner/paseo/client.go b/internal/runner/paseo/client.go| index 20bb1f55..02bdaf7e 100644 |
| --- a/internal/runner/paseo/client.go |
| +++ b/internal/runner/paseo/client.go |
| @@ -570,11 +570,15 @@ func (c *Client) Send(ctx context.Context, a Agent, message, messageID string) e |
| if !c.isReady(a) { |
| return ErrNotReady |
| } |
| - return c.call(ctx, "send", struct { |
| + request := struct { |
| Agent Agent `json:"agent"` |
| Message string `json:"message"` |
| MessageID string `json:"message_id"` |
| - }{a, message, messageID}, nil) |
| + }{a, message, messageID} |
| + if err := c.intent(ctx, "turn", messageID, request); err != nil { |
| + return err |
| + } |
| + return c.call(ctx, "send", request, nil) |
| } |
| func (c *Client) Respond(ctx context.Context, a Agent, r PermissionResponse) error { |
| if !c.isReady(a) { |
diff --git a/internal/runner/paseo/client_test.go b/internal/runner/paseo/client_test.go| index 046f69a6..57f1ae8e 100644 |
| --- a/internal/runner/paseo/client_test.go |
| +++ b/internal/runner/paseo/client_test.go |
| @@ -397,3 +397,30 @@ func TestPaseoRegisterProject(t *testing.T) { |
| t.Fatal("protected project registered") |
| } |
| } |
| + |
| +func TestPaseoSendDurableIntent(t *testing.T) { |
| + recorded := 0 |
| + c := testClient(t, "normal", func(cfg *Config) { |
| + cfg.RecordIntent = func(_ context.Context, i Intent) error { |
| + if i.Kind == "turn" { |
| + recorded++ |
| + if i.Key != "message" { |
| + t.Fatal("dispatch ID lost") |
| + } |
| + return ErrUncertain |
| + } |
| + return nil |
| + } |
| + }) |
| + a := createFixture(t, c) |
| + sub, err := c.Subscribe(context.Background(), a, Cursor{}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = <-sub.Ready; err != nil { |
| + t.Fatal(err) |
| + } |
| + if err = c.Send(context.Background(), a, "hello", "message"); !errors.Is(err, ErrUncertain) || recorded != 1 { |
| + t.Fatal("send bypassed durable intent", err, recorded) |
| + } |
| +} |
diff --git a/internal/runner/usage.go b/internal/runner/usage.go| new file mode 100644 |
| index 00000000..74d3c8b1 |
| --- /dev/null |
| +++ b/internal/runner/usage.go |
| @@ -0,0 +1,176 @@ |
| +package runner |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "math" |
| + "sync" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type TokenUsage struct { |
| + UncachedInput, CachedInput, Output int64 |
| + UncachedKnown, CachedKnown, OutputKnown bool |
| +} |
| +type ProviderTokens struct { |
| + Input, Cached, CacheWrite, Output int64 |
| + InputKnown, CachedKnown, CacheWriteKnown, OutputKnown bool |
| +} |
| + |
| +func NormalizeTokens(v ProviderTokens, inputSemantics string, writeIncluded bool) (TokenUsage, error) { |
| + u := TokenUsage{UncachedInput: v.Input, CachedInput: v.Cached, Output: v.Output, UncachedKnown: v.InputKnown, CachedKnown: v.CachedKnown, OutputKnown: v.OutputKnown} |
| + if v.Input < 0 || v.Cached < 0 || v.CacheWrite < 0 || v.Output < 0 { |
| + return TokenUsage{}, runnerproto.ErrInvalid |
| + } |
| + switch inputSemantics { |
| + case "inclusive": |
| + if !v.CachedKnown { |
| + u.UncachedKnown = false |
| + } else if v.InputKnown { |
| + if v.Cached > v.Input { |
| + return TokenUsage{}, runnerproto.ErrInvalid |
| + } |
| + u.UncachedInput -= v.Cached |
| + } |
| + case "exclusive": |
| + default: |
| + return TokenUsage{}, runnerproto.ErrInvalid |
| + } |
| + if !writeIncluded { |
| + if !v.CacheWriteKnown { |
| + u.UncachedKnown = false |
| + } else if v.CacheWrite > math.MaxInt64-u.UncachedInput { |
| + return TokenUsage{}, runnerproto.ErrInvalid |
| + } else { |
| + u.UncachedInput += v.CacheWrite |
| + } |
| + } |
| + if u.UncachedKnown && u.CachedKnown && u.UncachedInput > math.MaxInt64-u.CachedInput { |
| + return TokenUsage{}, runnerproto.ErrInvalid |
| + } |
| + return u, nil |
| +} |
| + |
| +type UsageProfile struct { |
| + Version int |
| + Provider, PaseoVersion, TokenSemantics, InputSemantics, CostSemantics string |
| + Subscription bool |
| + // Paseo exposes cache writes only when its adapter includes them in input. |
| + CacheWriteSeparate bool |
| +} |
| +type UsageAccumulator struct { |
| + mu sync.Mutex |
| + profile UsageProfile |
| + settled map[string]team.Usage |
| + cost map[string]float64 |
| + estimated float64 |
| +} |
| + |
| +func NewUsageAccumulator(profile UsageProfile) *UsageAccumulator { |
| + return &UsageAccumulator{profile: profile, settled: map[string]team.Usage{}, cost: map[string]float64{}} |
| +} |
| + |
| +type observedUsage struct { |
| + Input *int64 `json:"inputTokens"` |
| + Cached *int64 `json:"cachedInputTokens"` |
| + CacheWrite *int64 `json:"cacheWriteInputTokens"` |
| + Output *int64 `json:"outputTokens"` |
| + Cost *float64 `json:"totalCostUsd"` |
| +} |
| + |
| +func (a *UsageAccumulator) Observe(e paseo.Event) *team.Usage { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + p := a.profile |
| + if p.Version != 1 || p.PaseoVersion != paseo.PinnedVersion || p.TokenSemantics != "turn" || e.Kind != "turn_completed" || e.TurnID == "" || e.ServerID == "" || e.AgentID == "" || e.ProviderSessionID == "" { |
| + return nil |
| + } |
| + var envelope struct { |
| + Event struct { |
| + Type string `json:"type"` |
| + Provider string `json:"provider"` |
| + TurnID string `json:"turnId"` |
| + Usage *observedUsage `json:"usage"` |
| + } `json:"event"` |
| + } |
| + if json.Unmarshal(e.Payload, &envelope) != nil || envelope.Event.Type != "turn_completed" || envelope.Event.Provider != p.Provider || envelope.Event.TurnID != e.TurnID { |
| + return nil |
| + } |
| + key := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID, e.TurnID}) |
| + if old, ok := a.settled[key]; ok { |
| + return &old |
| + } |
| + v := envelope.Event.Usage |
| + if v == nil { |
| + return nil |
| + } |
| + tokens := ProviderTokens{InputKnown: v.Input != nil, CachedKnown: v.Cached != nil, OutputKnown: v.Output != nil, CacheWriteKnown: v.CacheWrite != nil} |
| + if v.Input != nil { |
| + tokens.Input = *v.Input |
| + } |
| + if v.Cached != nil { |
| + tokens.Cached = *v.Cached |
| + } |
| + if v.Output != nil { |
| + tokens.Output = *v.Output |
| + } |
| + if v.CacheWrite != nil { |
| + tokens.CacheWrite = *v.CacheWrite |
| + } |
| + t, err := NormalizeTokens(tokens, p.InputSemantics, !p.CacheWriteSeparate) |
| + if err != nil || !t.UncachedKnown || !t.CachedKnown || !t.OutputKnown { |
| + return nil |
| + } |
| + u := team.Usage{Calls: 1, InputTokens: t.UncachedInput + t.CachedInput, CachedInputTokens: t.CachedInput, OutputTokens: t.Output, CostUnavailable: p.Subscription} |
| + if v.Cost != nil && (*v.Cost < 0 || math.IsNaN(*v.Cost) || math.IsInf(*v.Cost, 0)) { |
| + return nil |
| + } |
| + if !p.Subscription { |
| + // Cumulative currency is not a per-turn receipt without a verified baseline. |
| + if p.CostSemantics != "turn" || v.Cost == nil || *v.Cost >= float64(math.MaxInt64)/1e6 { |
| + return nil |
| + } |
| + u.CostMicros = int64(math.Ceil(*v.Cost * 1e6)) |
| + } |
| + if v.Cost != nil { |
| + stream := runnerproto.EventHash([]string{e.ServerID, e.AgentID, e.ProviderSessionID}) |
| + switch p.CostSemantics { |
| + case "cumulative": |
| + if *v.Cost > a.cost[stream] { |
| + a.estimated += *v.Cost - a.cost[stream] |
| + a.cost[stream] = *v.Cost |
| + } |
| + case "turn": |
| + a.estimated += *v.Cost |
| + } |
| + } |
| + a.settled[key] = u |
| + return &u |
| +} |
| +func (a *UsageAccumulator) EstimatedCostUSD() float64 { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + return a.estimated |
| +} |
| +func (j *Journal) Usage(ctx context.Context, a paseo.Agent, profile UsageProfile) (*UsageAccumulator, error) { |
| + accumulator := NewUsageAccumulator(profile) |
| + rows, err := j.db.QueryContext(ctx, "SELECT body FROM journal_events ORDER BY ordinal") |
| + if err != nil { |
| + return nil, err |
| + } |
| + defer rows.Close() |
| + for rows.Next() { |
| + var b []byte |
| + var e Event |
| + if rows.Scan(&b) != nil || json.Unmarshal(b, &e) != nil { |
| + return nil, ErrJournal |
| + } |
| + if e.ServerID == a.ServerID && e.AgentID == a.AgentID && e.SessionID == a.ProviderSessionID { |
| + accumulator.Observe(paseo.Event{Kind: e.Kind, ServerID: e.ServerID, AgentID: e.AgentID, ProviderSessionID: e.SessionID, TurnID: e.TurnID, Epoch: e.Epoch, Sequence: e.Sequence, Payload: e.Payload}) |
| + } |
| + } |
| + return accumulator, rows.Err() |
| +} |
diff --git a/internal/runner/usage_test.go b/internal/runner/usage_test.go| new file mode 100644 |
| index 00000000..790b0c81 |
| --- /dev/null |
| +++ b/internal/runner/usage_test.go |
| @@ -0,0 +1,125 @@ |
| +package runner |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runner/paseo" |
| + "encoding/json" |
| + "math" |
| + "testing" |
| +) |
| + |
| +func usageEvent(turn, usage string) paseo.Event { |
| + return paseo.Event{Kind: "turn_completed", ServerID: "server", AgentID: "agent", ProviderSessionID: "session", TurnID: turn, Payload: json.RawMessage(`{"event":{"type":"turn_completed","provider":"claude","turnId":"` + turn + `","usage":` + usage + `}}`)} |
| +} |
| +func TestUsageCumulativeAndMissing(t *testing.T) { |
| + a := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "exclusive", CostSemantics: "cumulative", Subscription: true}) |
| + first := usageEvent("one", `{"inputTokens":18,"cachedInputTokens":29591,"outputTokens":404,"totalCostUsd":0.0673131}`) |
| + u := a.Observe(first) |
| + if u == nil || u.InputTokens != 29609 || u.CachedInputTokens != 29591 || u.CostMicros != 0 || !u.CostUnavailable { |
| + t.Fatal("normalization", u) |
| + } |
| + next := usageEvent("two", `{"inputTokens":2,"cachedInputTokens":3,"outputTokens":4,"totalCostUsd":0.0758928}`) |
| + if a.Observe(next) == nil { |
| + t.Fatal("second completion unknown") |
| + } |
| + if math.Abs(a.EstimatedCostUSD()-0.0758928) > 1e-10 { |
| + t.Fatal("cumulative cost summed", a.EstimatedCostUSD()) |
| + } |
| + if a.Observe(usageEvent("missing", `null`)) != nil { |
| + t.Fatal("missing usage became zero") |
| + } |
| + for _, kind := range []string{"agent_update", "queued", "idle", "timeline"} { |
| + e := first |
| + e.Kind = kind |
| + e.Payload = json.RawMessage(`{"agent":{"lastUsage":{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}}}`) |
| + if a.Observe(e) != nil { |
| + t.Fatal("status proved completion", kind) |
| + } |
| + } |
| + if got := a.Observe(first); got == nil || *got != *u { |
| + t.Fatal("lastUsage erased completion", got) |
| + } |
| + unknown := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "unverified", InputSemantics: "exclusive", Subscription: true}) |
| + if unknown.Observe(first) != nil { |
| + t.Fatal("unverified cumulative semantics settled") |
| + } |
| + if got := a.Observe(usageEvent("zero", `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}`)); got == nil || got.InputTokens != 0 { |
| + t.Fatal("known zero lost") |
| + } |
| + for _, raw := range []string{`{"inputTokens":1,"outputTokens":2}`, `{"inputTokens":9223372036854775807,"cachedInputTokens":1,"outputTokens":1}`, `{"inputTokens":-1,"cachedInputTokens":0,"outputTokens":1}`} { |
| + if a.Observe(usageEvent("invalid", raw)) != nil { |
| + t.Fatal("partial or invalid usage settled") |
| + } |
| + } |
| + inclusive := NewUsageAccumulator(UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "inclusive", Subscription: true}) |
| + if v := inclusive.Observe(first); v != nil { |
| + t.Fatal("cache exceeds inclusive input") |
| + } |
| + got := inclusive.Observe(usageEvent("inclusive", `{"inputTokens":20,"cachedInputTokens":5,"outputTokens":2}`)) |
| + if got == nil || got.InputTokens != 20 || got.CachedInputTokens != 5 { |
| + t.Fatal("inclusive cache counted twice", got) |
| + } |
| + tokens, err := NormalizeTokens(ProviderTokens{Input: 10, Cached: 3, CacheWrite: 4, Output: 2, InputKnown: true, CachedKnown: true, CacheWriteKnown: true, OutputKnown: true}, "exclusive", false) |
| + mustJournal(t, err) |
| + if tokens.UncachedInput != 14 || tokens.CachedInput != 3 { |
| + t.Fatal("cache write normalization", tokens) |
| + } |
| +} |
| + |
| +func TestUsageCumulativeCompletionGuards(t *testing.T) { |
| + p := UsageProfile{Version: 1, Provider: "claude", PaseoVersion: "0.14.0", TokenSemantics: "turn", InputSemantics: "exclusive", CostSemantics: "cumulative", Subscription: true} |
| + e := usageEvent("turn", `{"inputTokens":5,"cachedInputTokens":3,"outputTokens":2,"totalCostUsd":0.0673131}`) |
| + for _, kind := range []string{"idle", "queued", "timeline", "agent_update"} { |
| + bad := e |
| + bad.Kind = kind |
| + if NewUsageAccumulator(p).Observe(bad) != nil { |
| + t.Fatal("noncompletion kind settled", kind) |
| + } |
| + } |
| + for _, field := range []string{"version", "paseo", "provider", "turn", "session", "input_mode"} { |
| + bad := e |
| + profile := p |
| + switch field { |
| + case "version": |
| + profile.Version = 2 |
| + case "paseo": |
| + profile.PaseoVersion = "unknown" |
| + case "provider": |
| + profile.Provider = "codex" |
| + case "turn": |
| + bad.TurnID = "other" |
| + case "session": |
| + bad.ProviderSessionID = "" |
| + case "input_mode": |
| + profile.InputSemantics = "unknown" |
| + } |
| + if NewUsageAccumulator(profile).Observe(bad) != nil { |
| + t.Fatal("unverified usage settled", field) |
| + } |
| + } |
| + a := NewUsageAccumulator(p) |
| + u := a.Observe(e) |
| + if u == nil { |
| + t.Fatal("completion missing") |
| + } |
| + zero := usageEvent("turn", `{"inputTokens":0,"cachedInputTokens":0,"outputTokens":0}`) |
| + if got := a.Observe(zero); got == nil || *got != *u { |
| + t.Fatal("zero erased completed evidence") |
| + } |
| + p.Subscription = false |
| + if NewUsageAccumulator(p).Observe(e) != nil { |
| + t.Fatal("unverified cumulative currency settled") |
| + } |
| + p.CostSemantics = "turn" |
| + if got := NewUsageAccumulator(p).Observe(e); got == nil || got.CostMicros != 67314 || got.CostUnavailable { |
| + t.Fatal("metered per-turn normalization", got) |
| + } |
| + partial, err := NormalizeTokens(ProviderTokens{Input: 5, InputKnown: true, OutputKnown: true}, "inclusive", true) |
| + mustJournal(t, err) |
| + if partial.UncachedKnown || partial.CachedKnown || !partial.OutputKnown { |
| + t.Fatal("missing cache treated as zero", partial) |
| + } |
| + _, err = NormalizeTokens(ProviderTokens{Input: math.MaxInt64, InputKnown: true, CacheWrite: 1, CacheWriteKnown: true}, "exclusive", false) |
| + if err == nil { |
| + t.Fatal("cache-write overflow accepted") |
| + } |
| +} |
diff --git a/internal/runnerproto/events.go b/internal/runnerproto/events.go| new file mode 100644 |
| index 00000000..e5be5fcc |
| --- /dev/null |
| +++ b/internal/runnerproto/events.go |
| @@ -0,0 +1,95 @@ |
| +package runnerproto |
| + |
| +import ( |
| + "bytes" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| +) |
| + |
| +type Event struct { |
| + Version int `json:"version"` |
| + ID string `json:"id"` |
| + TaskID string `json:"task_id"` |
| + AssignmentID string `json:"assignment_id"` |
| + ServerID string `json:"server_id"` |
| + AgentID string `json:"agent_id"` |
| + SessionID string `json:"session_id"` |
| + Epoch string `json:"epoch"` |
| + Kind string `json:"kind"` |
| + TurnID string `json:"turn_id"` |
| + RequestID string `json:"request_id"` |
| + Sequence *int64 `json:"sequence"` |
| + Scope team.Scope `json:"scope"` |
| + Handle team.Handle `json:"handle"` |
| + ActionID team.ActionID `json:"action_id,omitempty"` |
| + Payload json.RawMessage `json:"payload"` |
| + SourceTime time.Time `json:"source_time"` |
| + Isolation team.IsolationSnapshot `json:"isolation"` |
| +} |
| + |
| +func (e Event) Validate() error { |
| + if e.Version != Version || e.Scope.Account == "" || e.Scope.Job <= 0 || e.Handle.Attempt <= 0 || e.Handle.Fence <= 0 || e.Handle.Runner == "" || e.SourceTime.IsZero() || e.SourceTime.Location() != time.UTC || !json.Valid(e.Payload) || len(e.Payload) > MaxEventBytes || e.ActionID < 0 { |
| + return ErrInvalid |
| + } |
| + for _, s := range []string{e.ID, e.TaskID, e.AssignmentID, e.ServerID, e.AgentID, e.SessionID, e.Kind} { |
| + if s == "" || len(s) > 256 || strings.ContainsRune(s, 0) { |
| + return ErrInvalid |
| + } |
| + } |
| + for _, s := range []string{e.Epoch, e.TurnID, e.RequestID} { |
| + if len(s) > 256 || strings.ContainsRune(s, 0) { |
| + return ErrInvalid |
| + } |
| + } |
| + if e.Sequence != nil && (*e.Sequence < 0 || e.Epoch == "") { |
| + return ErrInvalid |
| + } |
| + if (e.Kind == "turn_completed" || e.Kind == "turn_failed") && (e.TurnID == "" || e.ActionID <= 0) { |
| + return ErrInvalid |
| + } |
| + if (e.Kind == "timeline_replacement" || e.Kind == "timeline_ready") && e.Epoch == "" { |
| + return ErrInvalid |
| + } |
| + return nil |
| +} |
| +func EventHash(v any) string { |
| + b, _ := json.Marshal(v) |
| + sum := sha256.Sum256(b) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| +func (e Event) StreamKey() string { |
| + return EventHash([]string{e.AssignmentID, e.ServerID, e.AgentID, e.SessionID}) |
| +} |
| +func (e Event) DedupKey() string { |
| + if e.Sequence != nil { |
| + return EventHash([]any{e.StreamKey(), e.Epoch, *e.Sequence}) |
| + } |
| + stable := e.RequestID |
| + if stable == "" { |
| + stable = e.TurnID |
| + } |
| + if stable == "" { |
| + stable = e.ID |
| + } |
| + return EventHash([]string{e.StreamKey(), e.Kind, stable}) |
| +} |
| +func (e Event) ContentHash() string { |
| + // Delivery IDs may change across history/live overlap; content may not. |
| + e.ID = "" |
| + e.Isolation = team.IsolationSnapshot{} |
| + if e.Sequence == nil && e.Kind != "timeline_replacement" && e.Kind != "timeline_ready" && e.Kind != "timeline_gap" { |
| + e.Epoch = "" |
| + } |
| + var payload any |
| + decoder := json.NewDecoder(bytes.NewReader(e.Payload)) |
| + decoder.UseNumber() |
| + if decoder.Decode(&payload) == nil { |
| + e.Payload, _ = json.Marshal(payload) |
| + } |
| + return EventHash(e) |
| +} |
diff --git a/internal/runnerproto/validate.go b/internal/runnerproto/validate.go| index ad9a5c1a..c4ce05ae 100644 |
| --- a/internal/runnerproto/validate.go |
| +++ b/internal/runnerproto/validate.go |
| @@ -52,9 +52,9 @@ func uniqueJSON(d *json.Decoder) error { |
| return err |
| } |
| s, ok := key.(string) |
| - if !ok || s == "" || strings.ContainsFunc(s, func(r rune) bool { |
| - return r != '_' && (r < 'a' || r > 'z') && (r < '0' || r > '9') |
| - }) || keys[s] { |
| + // Typed envelope names are checked by incoming. Opaque provider |
| + // payloads retain their native field names, with no duplicate keys. |
| + if !ok || s == "" || keys[s] { |
| return ErrInvalid |
| } |
| keys[s] = true |