package runner import ( "context" "database/sql" "encoding/json" "errors" "time" "amadan.net/oficina/equipo/internal/runner/containment" "amadan.net/oficina/equipo/internal/runner/provider" "amadan.net/oficina/equipo/internal/runnerproto" ) func (s *CoordinatorService) Recover(ctx context.Context) error { if err := s.reopenUncodedRefusals(ctx); err != nil { return err } var pending []runnerproto.CoordinatorRequest if err := s.Journal.readStates(ctx, "coordinator-claim", &pending); err != nil { return err } for _, q := range pending { if !s.retryDue(q.TurnID) { continue } var n int if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", q.TurnID).Scan(&n); err != nil { return err } if n != 0 { continue } var c runnerproto.CoordinatorClaim if err := s.call(ctx, "recover", q, &c); err != nil { r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: runnerproto.CoordinatorTurn{ID: q.TurnID, Revision: q.Revision}}} if err = s.refusedCall(ctx, &r, "recover", err); err != nil { return err } continue } if c.Turn.ID == "" { if _, err := s.Journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='coordinator-claim' AND state_key=?", q.TurnID); err != nil { return err } continue } if err := s.Journal.saveState(ctx, "coordinator", c.Turn.ID, coordinatorState{Claim: c}); err != nil { return err } } var states []coordinatorState if err := s.Journal.readStates(ctx, "coordinator", &states); err != nil { return err } for _, r := range states { if !s.retryDue(r.Claim.Turn.ID) { continue } if r.Finished { continue } if r.Refused { if err := s.retireCoordinator(ctx, &r); err != nil { return err } continue } proof, err := s.Contain(ctx, r.Claim) if err != nil { return err } if s.release != nil { if err = s.release(); err != nil { return err } s.release = nil } else if s.RecoverFiles != nil { if err = s.RecoverFiles(ctx, r.Claim); err != nil { return err } } if err = s.Journal.interruptDirect(ctx, r.Session.AttemptKey, true); err != nil { return err } var status string err = s.Journal.db.QueryRowContext(ctx, "SELECT state FROM direct_turns WHERE attempt=? AND session=? AND turn=?", r.Session.AttemptKey, r.Session.ID, r.Claim.Turn.ID).Scan(&status) if err != nil && !errors.Is(err, sql.ErrNoRows) { return err } var deliveryErr error if r.DeliveryRefusal != nil { deliveryErr = r.DeliveryRefusal } else if status == "completed" { deliveryErr = s.reconcileTools(ctx, r) if deliveryErr == nil { deliveryErr = s.finishDelivery(ctx, r) } } if err = s.finishContained(ctx, &r, proof, deliveryErr); err != nil { if errors.Is(err, ErrTransient) { s.deferRetry(r.Claim.Turn.ID) continue } return err } } return nil } // Keep delivery authority until its report is accepted or explicitly fenced. func (s *CoordinatorService) finishContained(ctx context.Context, r *coordinatorState, proof runnerproto.ContainmentProof, deliveryErr error) error { r.Containment = &proof var refusal *RefusalError if errors.As(deliveryErr, &refusal) && refusal.CoordinatorDefinitive() { r.DeliveryRefusal = refusal } if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { return err } if deliveryErr != nil && !errors.Is(deliveryErr, ErrTransient) && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil { return deliveryErr } pendingDelivery := deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil // Once admission expires, containment must still reach the instance. Its // next delivery response can then confirm the durable fence explicitly. if pendingDelivery && s.clock().Before(r.Claim.LeaseDeadline) && s.clock().Before(r.Claim.AttemptDeadline) { return ErrTransient } q := runnerproto.NewCoordinatorRequest(r.Claim) q.Proof = &proof if err := s.call(ctx, "containment", q, nil); err != nil { if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { return s.recordRefusal(ctx, r, "containment", refusal) } return ErrTransient } if pendingDelivery { return ErrTransient } if r.DeliveryRefusal != nil { return s.recordRefusal(ctx, r, "delivery", r.DeliveryRefusal) } return s.retireCoordinator(ctx, r) } func (s *CoordinatorService) recordRefusal(ctx context.Context, r *coordinatorState, operation string, refusal *RefusalError) error { if !refusal.CoordinatorDefinitive() { return ErrTransient } r.Refused, r.RefusalOperation, r.RefusalStatus, r.RefusalCode = true, operation, refusal.Status, refusal.Reason // Save the refusal before acknowledging events, so interrupted retirement // resumes locally without repeating a refused call or sending a prompt. if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { return err } return s.retireCoordinator(ctx, r) } func (s *CoordinatorService) retireCoordinator(ctx context.Context, r *coordinatorState) error { if err := s.retirePending(ctx, r.Claim.Turn.ID); err != nil { return err } r.Finished = true if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { return err } delete(s.retry, r.Claim.Turn.ID) return nil } // Contained uncertain observations stay in the local audit journal but cannot // leak into the ordinary task uploader or regain delivery authority. func (s *CoordinatorService) retirePending(ctx context.Context, turn string) error { rows, err := s.Journal.db.QueryContext(ctx, "SELECT id FROM journal_events WHERE acked=0 AND json_extract(body,'$.assignment_id')=?", turn) if err != nil { return err } var ids []string for rows.Next() { var id string if err = rows.Scan(&id); err != nil { rows.Close() return err } ids = append(ids, id) } err = rows.Err() rows.Close() if err != nil { return err } for _, id := range ids { if err = s.Journal.Ack(ctx, id); err != nil { return err } } return nil } func (s *CoordinatorService) reconcileTools(ctx context.Context, r coordinatorState) error { calls, err := s.Journal.CoordinatorToolSubmissions(ctx, 128) if err != nil { return err } for _, call := range calls { if call.Claim.Turn.ID != r.Claim.Turn.ID || call.Session != r.Session { continue } q := runnerproto.NewCoordinatorRequest(r.Claim) q.ToolCall = &call.Call var out runnerproto.CoordinatorToolResult if err = s.call(ctx, "tool_result", q, &out); err != nil { return err } // An empty response means the tool never committed. Do not execute it now. if out.ResourceID == "" { continue } if err = s.Journal.ackCoordinatorTool(ctx, r.Claim, r.Session, call.Call, out); err != nil { return err } } return nil } func (c *HTTPInstance) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { token, err := c.token("", false) if err != nil { return err } q.Version = 2 q.Capabilities = []string{runnerproto.CoordinatorCapability} return c.post(ctx, "coordinator/"+op, q, token, out) } func (r *Runtime) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { if op == "renew" { r.mu.Lock() reports := append([]runnerproto.ConnectionReport(nil), r.lastReports...) r.mu.Unlock() if len(reports) == 0 { return provider.ErrPreflightRequired } if err := r.api.Heartbeat(ctx, reports); err != nil { return err } } return r.api.CoordinatorCall(ctx, op, q, out) } func (r *Runtime) coordinatorService() *CoordinatorService { s := &CoordinatorService{Journal: r.journal, API: r, Launchers: r.launchers} s.OpenLaunch = r.coordinatorLaunch s.RecoverFiles = r.cleanupCoordinatorFiles s.NamespaceContext = func(ctx context.Context, c runnerproto.CoordinatorClaim) context.Context { return context.WithValue(ctx, namespaceAdmissionKey{}, func(ctx context.Context, record containment.Record) error { owner := attemptKey(c.Scope, c.Handle) if err := r.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record}); err != nil { return err } if record.HostPID == 0 { return nil } n := runnerproto.NamespaceLaunch{ID: record.ID, AttemptKey: record.AttemptKey, OwnerKey: owner, BootID: record.BootID, NamespaceID: record.NamespaceID, ManifestHash: record.ManifestHash, PolicyHash: record.PolicyHash, HostPID: record.HostPID, StartTicks: record.StartTicks} if err := s.namespaceEvent(ctx, c, "namespace.launch", record.AttemptKey, record.ID, n); err != nil { return err } return r.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record, LaunchAcknowledged: true}) }) } s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { return r.containCoordinator(ctx, c) } return s } // Containment reporting uses the coordinator endpoint, not task credentials. func (r *Runtime) containCoordinator(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { proof := runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now().UTC()} var states []namespaceState if err := r.journal.readStates(ctx, "namespace", &states); err != nil { return proof, err } var failures error for _, n := range states { if n.Owner != attemptKey(c.Scope, c.Handle) { continue } p, err := r.namespaces.Stop(ctx, n.Record.ID) if err != nil { p, err = r.namespaces.Recover(ctx, n.Record) } if err != nil || !p.Verified { failures = errors.Join(failures, provider.ErrContainment, err) continue } if err = r.journal.validateDirectRecord(ctx, p.Record); err != nil { failures = errors.Join(failures, err) continue } n.Proof = &p if err = r.journal.saveState(ctx, "namespace", n.Record.ID, n); err != nil { failures = errors.Join(failures, err) continue } if _, err = r.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", n.Record.AttemptKey); err != nil { failures = errors.Join(failures, err) continue } if p.Record.HostPID == 0 { continue } exit := runnerproto.NamespaceExit{ID: p.Record.ID, AttemptKey: p.Record.AttemptKey, BootID: p.Record.BootID, NamespaceID: p.Record.NamespaceID, ManifestHash: p.Record.ManifestHash, HostPID: p.Record.HostPID, StartTicks: p.Record.StartTicks, ExitCode: p.Exit.Code, Signal: p.Exit.Signal, ObservedAt: p.Exit.ObservedAt} if n.LaunchAcknowledged { proof.Namespaces = append(proof.Namespaces, exit) } else { proof.Unstarted = append(proof.Unstarted, exit) } } return proof, failures } func (s *CoordinatorService) namespaceEvent(ctx context.Context, c runnerproto.CoordinatorClaim, kind, agent, session string, payload any) error { r := coordinatorState{Claim: c, Session: provider.Session{AttemptKey: agent, ID: session}} return s.emit(ctx, r, kind, json.RawMessage(marshal(payload))) }