package runner import ( "context" "encoding/json" "errors" "path/filepath" "sync" "time" "amadan.net/oficina/equipo/internal/equipo/team" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) const leaseRenewInterval = 15 * time.Second type InstanceAPI interface { Call(context.Context, string, runnerproto.RunnerRequest, any) error } type RunClaim struct { Assignment runnerproto.Assignment runnerproto.ClaimResponse } type attemptState struct { Direct bool Session provider.Session WorkspacePath string InFlightAction team.ActionID Claim RunClaim Owner ProcessOwner Agent provider.Agent Phase string FailurePhase string FailureDetail string FailureReason string ServiceInterrupted bool StopError string SocketPath, CapabilityPath string Proof *ContainmentProof Rotation *runnerproto.CredentialRotation // Authority is deliberately not restored from this record. } type SupervisorConfig struct { Namespaces *containment.Manager Journal *Journal API InstanceAPI Workflow *BugWorkflow CredentialsPath string InstallCredentials func(context.Context, runnerproto.CredentialRotation, string) error } type Supervisor struct { leaseDone <-chan struct{} leaseStop context.CancelFunc activeRelease func() error namespaces *containment.Manager activeProxy *ToolProxy journal *Journal api InstanceAPI workflow *BugWorkflow clock ElapsedClock credentialsPath string installCredentials func(context.Context, runnerproto.CredentialRotation, string) error mu sync.Mutex runMu sync.Mutex activeKey string activeCancel context.CancelCauseFunc activeCurrent func(context.Context) error activeStop runnerproto.RunnerRequest states map[string]*attemptState ready bool } func NewSupervisor(c SupervisorConfig) (*Supervisor, error) { if c.Journal == nil || c.Namespaces == nil || c.API == nil || c.Workflow == nil || !filepath.IsAbs(c.CredentialsPath) || filepath.Clean(c.CredentialsPath) != c.CredentialsPath || c.InstallCredentials == nil { return nil, provider.ErrContract } if c.Workflow.cfg.Witness == nil || c.Workflow.cfg.Workspaces == nil || (c.Workflow.cfg.Namespaces != c.Namespaces || len(c.Workflow.cfg.Launchers) != 2 || c.Workflow.cfg.Launch == nil) || c.Workflow.cfg.Witness.journal != c.Journal { return nil, provider.ErrContract } return &Supervisor{namespaces: c.Namespaces, journal: c.Journal, api: c.API, workflow: c.Workflow, clock: hostClock{}, credentialsPath: c.CredentialsPath, installCredentials: c.InstallCredentials, states: map[string]*attemptState{}}, nil } func attemptKey(scope team.Scope, h team.Handle) string { return runnerproto.EventHash([]any{scope, h.Attempt, h.Fence, h.Runner}) } func (s *Supervisor) save(ctx context.Context, r *attemptState) error { return s.journal.saveState(ctx, "attempt", attemptKey(r.Claim.Scope, r.Claim.Handle), r) } func (r *attemptState) request(op string) runnerproto.RunnerRequest { return runnerproto.RunnerRequest{Version: 2, AssignmentID: r.Claim.Assignment.ID, Scope: r.Claim.Scope, Handle: r.Claim.Handle, RequestID: attemptKey(r.Claim.Scope, r.Claim.Handle) + "/" + op} } func (s *Supervisor) Run(ctx context.Context, claim RunClaim) error { // One active attempt also serializes runner-wide credential rotation. s.runMu.Lock() defer s.runMu.Unlock() if !s.ready || s.namespaces == nil { return provider.ErrUncertain } key := attemptKey(claim.Scope, claim.Handle) if _, exists := s.states[key]; exists { return provider.ErrUncertain } if err := s.journal.AdmissionAllowed(ctx); err != nil { return err } for _, old := range s.states { if old.Phase != "contained" { return provider.ErrUncertain } } now, err := s.clock.Read() if err != nil { return err } lease, err := newLease(now, claim.LeaseDeadline, claim.AttemptDeadline) if err != nil { return err } r := &attemptState{Direct: s.namespaces != nil, Claim: claim, Phase: "claimed"} raw, err := json.Marshal(r) if err != nil { return err } if _, err = s.journal.db.ExecContext(ctx, "INSERT INTO journal_supervisor(kind,state_key,body) VALUES('attempt',?,?)", key, raw); err != nil { return provider.ErrUncertain } s.states[key] = r active, cancel := context.WithCancelCause(ctx) defer cancel(nil) s.mu.Lock() s.activeKey = key s.activeCancel = cancel s.activeStop = r.request("stop") s.mu.Unlock() defer func() { s.mu.Lock() s.activeKey = "" s.activeCancel = nil s.activeProxy = nil s.activeCurrent = nil s.mu.Unlock() }() done := make(chan struct{}) watchCtx, stopWatch := context.WithCancel(active) s.leaseStop = stopWatch s.leaseDone = done defer stopWatch() go s.watchLease(watchCtx, cancel, r, lease, done) err = s.workflow.run(active, s, r, lease) if err != nil { err = errors.Join(err, context.Cause(active)) r.FailurePhase = r.Phase r.FailureDetail = err.Error() } r.ServiceInterrupted = ctx.Err() != nil cancel(nil) <-done cleanupCtx, cleanupCancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer cleanupCancel() return s.finishAttempt(cleanupCtx, r, err) } func (s *Supervisor) finishAttempt(cleanupCtx context.Context, r *attemptState, err error) error { if err != nil { r.FailureReason = attemptFailureReason(err) } outcome := "unprocessed" if err != nil { outcome = "rejected" } bookkeepingErr := s.journal.finishTools(cleanupCtx, r.Claim, outcome) if err != nil { if r.Direct && r.InFlightAction != 0 { q := r.request("lost") q.ActionID = r.InFlightAction err = errors.Join(err, s.api.Call(cleanupCtx, "lost", q, nil)) } else if infrastructureOnly(err, r) { q := r.request("release") q.Reason = team.WaitRunnerUnavailable err = errors.Join(err, s.api.Call(cleanupCtx, "release", q, nil)) } else { q := r.request("failed") q.Result = &team.AttemptResult{Outcome: team.OutcomeFailure, Detail: r.FailureReason} err = errors.Join(err, s.api.Call(cleanupCtx, "complete", q, nil)) } } _, cleanupErr := s.cleanup(cleanupCtx, r) if err == nil && cleanupErr == nil && (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) { cleanupErr = s.api.Call(cleanupCtx, "conclude", r.request("conclude"), nil) } return errors.Join(err, bookkeepingErr, cleanupErr) } func (s *Supervisor) watchLease(ctx context.Context, cancel context.CancelCauseFunc, r *attemptState, l *leaseGuard, done chan struct{}) { defer close(done) tick := time.NewTicker(100 * time.Millisecond) defer tick.Stop() last, err := s.clock.Read() if err != nil { cancel(attemptCancellation{"watchLease.Read", err}) return } renewAt := last.Elapsed + leaseRenewInterval for { select { case <-ctx.Done(): return case <-tick.C: now, err := l.checkClock(s.clock) if err != nil { cancel(attemptCancellation{"watchLease.check", err}) return } if now.Elapsed < renewAt { continue } // A blocked renewal never pauses the local lease watchdog. reply := make(chan error, 1) go func() { err := retryAuthority(ctx, func() error { sent, e := s.clock.Read() if e != nil { return e } var deadline time.Time if e = s.api.Call(ctx, "renew", r.request("renew"), &deadline); e != nil { return e } return l.renewClock(s.clock, sent, deadline) }) if err == nil { s.mu.Lock() current := s.activeCurrent s.mu.Unlock() if current != nil { err = current(ctx) } } reply <- err }() for { select { case <-ctx.Done(): return case err := <-reply: if err != nil { if ctx.Err() != nil { return } cancel(attemptCancellation{"watchLease.renew", err}) return } s.mu.Lock() proxy := s.activeProxy s.mu.Unlock() if proxy != nil { if err = proxy.RenewLease(ctx, l.bound()); err != nil { cancel(err) return } } renewAt = now.Elapsed + leaseRenewInterval goto renewed case <-tick.C: _, e := l.checkClock(s.clock) if e != nil { cancel(attemptCancellation{"watchLease.checkRenewal", e}) return } } } renewed: } } } func (s *Supervisor) Cancel(ctx context.Context, scope team.Scope, h team.Handle) (ContainmentProof, error) { key := attemptKey(scope, h) s.mu.Lock() active := s.activeKey == key && s.activeCancel != nil cancel := s.activeCancel stop := s.activeStop s.mu.Unlock() var stopErr error if active { stopErr = s.api.Call(ctx, "stop", stop, nil) cancel(attemptCancellation{"Supervisor.Cancel", context.Canceled}) } s.runMu.Lock() defer s.runMu.Unlock() r := s.states[key] if r == nil { return ContainmentProof{}, provider.ErrIdentity } // Instance fences first; failure never prevents local stopping. if !active { stopErr = s.api.Call(ctx, "stop", r.request("stop"), nil) } proof, err := s.cleanup(ctx, r) return proof, errors.Join(stopErr, err) } func (s *Supervisor) cleanup(ctx context.Context, r *attemptState) (ContainmentProof, error) { if !r.Direct { return ContainmentProof{}, provider.ErrContainment } return s.cleanupDirect(ctx, r) } func (s *Supervisor) reportContainment(ctx context.Context, r *attemptState) (ContainmentProof, error) { if r.Proof == nil || r.Proof.Version != 2 { return ContainmentProof{}, provider.ErrUncertain } q := r.request("contained") raw, err := json.Marshal(r.Proof) if err != nil { return *r.Proof, err } q.Proof = raw if s.workflow != nil && s.workflow.cfg.Witness != nil { if err = s.workflow.cfg.Witness.Containment(ctx, r.Claim.Assignment, q); err != nil { return *r.Proof, err } } var rotation runnerproto.CredentialRotation if err = s.api.Call(ctx, "contained", q, &rotation); err != nil { return *r.Proof, err } r.Rotation = &rotation if err = s.save(ctx, r); err != nil { return *r.Proof, err } return s.finishRotation(ctx, r) } func (s *Supervisor) finishRotation(ctx context.Context, r *attemptState) (ContainmentProof, error) { if r.Proof == nil || r.Rotation == nil { return ContainmentProof{}, provider.ErrUncertain } if r.Rotation.Bearer.Token != "" { if s.credentialsPath == "" || s.installCredentials == nil { return *r.Proof, provider.ErrContract } if err := runnerproto.JournalCredentials(s.credentialsPath, r.Rotation); err != nil { return *r.Proof, err } if err := s.installCredentials(ctx, *r.Rotation, r.request("contained").RequestID); err != nil { return *r.Proof, err } } r.Phase = "contained" return *r.Proof, s.save(ctx, r) } func (s *Supervisor) Recover(ctx context.Context) error { s.runMu.Lock() defer s.runMu.Unlock() s.ready = false if s.namespaces != nil { if _, err := s.journal.ReconcileDirect(ctx, s.namespaces); err != nil { return err } } var states []attemptState if err := s.journal.readStates(ctx, "attempt", &states); err != nil { return err } var failures error for i := range states { r := &states[i] if !r.Direct && r.Phase != "contained" { failures = errors.Join(failures, s.api.Call(ctx, "stop", r.request("stop"), nil), provider.ErrContainment) continue } failures = errors.Join(failures, s.journal.finishTools(ctx, r.Claim, "interrupted")) s.states[attemptKey(r.Claim.Scope, r.Claim.Handle)] = r if restore, ok := s.api.(interface{ RestoreClaim(RunClaim) error }); ok { failures = errors.Join(failures, restore.RestoreClaim(r.Claim)) } if r.Claim.Brief.Target.Kind == team.TargetProjectRead && r.Phase == "delivering-answer" { if err := s.recoverReadAnswer(ctx, r); err != nil { failures = errors.Join(failures, err) continue } } if r.Phase != "contained" { if r.Direct { if r.InFlightAction != 0 { q := r.request("lost") q.ActionID = r.InFlightAction failures = errors.Join(failures, s.api.Call(ctx, "lost", q, nil)) } } if r.Phase != "completed" && r.Phase != "prepared" && r.Phase != "verified" { stopErr := s.api.Call(ctx, "stop", r.request("stop"), nil) if stopErr != nil { r.StopError = stopErr.Error() failures = errors.Join(failures, s.save(ctx, r)) } } if _, err := s.cleanup(ctx, r); err != nil { failures = errors.Join(failures, err) continue } } if (r.Claim.Assignment.StepKey == "publish" || r.Claim.Brief.Target.Kind == team.TargetProjectRead) && r.FailurePhase == "" { failures = errors.Join(failures, s.api.Call(ctx, "conclude", r.request("conclude"), nil)) } } for { pending, err := s.journal.Pending(ctx, 128) if err != nil { failures = errors.Join(failures, err) break } if len(pending) == 0 { break } var batchErr error for _, e := range pending { raw, err := runnerproto.Marshal(e) if err != nil { batchErr = errors.Join(batchErr, err) continue } q := runnerproto.RunnerRequest{Version: 2, AssignmentID: e.AssignmentID, Scope: e.Scope, Handle: e.Handle, RequestID: e.ID, ActionID: e.ActionID, Event: raw} if err := s.api.Call(ctx, "events", q, nil); err != nil { batchErr = errors.Join(batchErr, err) continue } batchErr = errors.Join(batchErr, s.journal.Ack(ctx, e.ID)) } if batchErr != nil { failures = errors.Join(failures, batchErr) break } } s.ready = failures == nil return failures } func (s *Supervisor) stopLeaseWatch() { if s.leaseStop != nil { s.leaseStop() <-s.leaseDone } }