| 1 | package runner |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/equipo/internal/runner/containment" |
| 11 | "amadan.net/oficina/equipo/internal/runner/provider" |
| 12 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 13 | ) |
| 14 | |
| 15 | func (s *CoordinatorService) Recover(ctx context.Context) error { |
| 16 | if err := s.reopenUncodedRefusals(ctx); err != nil { |
| 17 | return err |
| 18 | } |
| 19 | var pending []runnerproto.CoordinatorRequest |
| 20 | if err := s.Journal.readStates(ctx, "coordinator-claim", &pending); err != nil { |
| 21 | return err |
| 22 | } |
| 23 | for _, q := range pending { |
| 24 | if !s.retryDue(q.TurnID) { |
| 25 | continue |
| 26 | } |
| 27 | var n int |
| 28 | if err := s.Journal.db.QueryRowContext(ctx, "SELECT count(*) FROM journal_supervisor WHERE kind='coordinator' AND state_key=?", q.TurnID).Scan(&n); err != nil { |
| 29 | return err |
| 30 | } |
| 31 | if n != 0 { |
| 32 | continue |
| 33 | } |
| 34 | var c runnerproto.CoordinatorClaim |
| 35 | if err := s.call(ctx, "recover", q, &c); err != nil { |
| 36 | r := coordinatorState{Claim: runnerproto.CoordinatorClaim{Turn: runnerproto.CoordinatorTurn{ID: q.TurnID, Revision: q.Revision}}} |
| 37 | if err = s.refusedCall(ctx, &r, "recover", err); err != nil { |
| 38 | return err |
| 39 | } |
| 40 | continue |
| 41 | } |
| 42 | if c.Turn.ID == "" { |
| 43 | if _, err := s.Journal.db.ExecContext(ctx, "DELETE FROM journal_supervisor WHERE kind='coordinator-claim' AND state_key=?", q.TurnID); err != nil { |
| 44 | return err |
| 45 | } |
| 46 | continue |
| 47 | } |
| 48 | if err := s.Journal.saveState(ctx, "coordinator", c.Turn.ID, coordinatorState{Claim: c}); err != nil { |
| 49 | return err |
| 50 | } |
| 51 | } |
| 52 | var states []coordinatorState |
| 53 | if err := s.Journal.readStates(ctx, "coordinator", &states); err != nil { |
| 54 | return err |
| 55 | } |
| 56 | for _, r := range states { |
| 57 | if !s.retryDue(r.Claim.Turn.ID) { |
| 58 | continue |
| 59 | } |
| 60 | if r.Finished { |
| 61 | continue |
| 62 | } |
| 63 | if r.Refused { |
| 64 | if err := s.retireCoordinator(ctx, &r); err != nil { |
| 65 | return err |
| 66 | } |
| 67 | continue |
| 68 | } |
| 69 | proof, err := s.Contain(ctx, r.Claim) |
| 70 | if err != nil { |
| 71 | return err |
| 72 | } |
| 73 | if s.release != nil { |
| 74 | if err = s.release(); err != nil { |
| 75 | return err |
| 76 | } |
| 77 | s.release = nil |
| 78 | } else if s.RecoverFiles != nil { |
| 79 | if err = s.RecoverFiles(ctx, r.Claim); err != nil { |
| 80 | return err |
| 81 | } |
| 82 | } |
| 83 | if err = s.Journal.interruptDirect(ctx, r.Session.AttemptKey, true); err != nil { |
| 84 | return err |
| 85 | } |
| 86 | var status string |
| 87 | 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) |
| 88 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 89 | return err |
| 90 | } |
| 91 | var deliveryErr error |
| 92 | if r.DeliveryRefusal != nil { |
| 93 | deliveryErr = r.DeliveryRefusal |
| 94 | } else if status == "completed" { |
| 95 | deliveryErr = s.reconcileTools(ctx, r) |
| 96 | if deliveryErr == nil { |
| 97 | deliveryErr = s.finishDelivery(ctx, r) |
| 98 | } |
| 99 | } |
| 100 | if err = s.finishContained(ctx, &r, proof, deliveryErr); err != nil { |
| 101 | if errors.Is(err, ErrTransient) { |
| 102 | s.deferRetry(r.Claim.Turn.ID) |
| 103 | continue |
| 104 | } |
| 105 | return err |
| 106 | } |
| 107 | } |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | // Keep delivery authority until its report is accepted or explicitly fenced. |
| 112 | func (s *CoordinatorService) finishContained(ctx context.Context, r *coordinatorState, proof runnerproto.ContainmentProof, deliveryErr error) error { |
| 113 | r.Containment = &proof |
| 114 | var refusal *RefusalError |
| 115 | if errors.As(deliveryErr, &refusal) && refusal.CoordinatorDefinitive() { |
| 116 | r.DeliveryRefusal = refusal |
| 117 | } |
| 118 | if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| 119 | return err |
| 120 | } |
| 121 | if deliveryErr != nil && !errors.Is(deliveryErr, ErrTransient) && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil { |
| 122 | return deliveryErr |
| 123 | } |
| 124 | pendingDelivery := deliveryErr != nil && !errors.Is(deliveryErr, provider.ErrUncertain) && r.DeliveryRefusal == nil |
| 125 | // Once admission expires, containment must still reach the instance. Its |
| 126 | // next delivery response can then confirm the durable fence explicitly. |
| 127 | if pendingDelivery && s.clock().Before(r.Claim.LeaseDeadline) && s.clock().Before(r.Claim.AttemptDeadline) { |
| 128 | return ErrTransient |
| 129 | } |
| 130 | q := runnerproto.NewCoordinatorRequest(r.Claim) |
| 131 | q.Proof = &proof |
| 132 | if err := s.call(ctx, "containment", q, nil); err != nil { |
| 133 | if errors.As(err, &refusal) && refusal.CoordinatorDefinitive() { |
| 134 | return s.recordRefusal(ctx, r, "containment", refusal) |
| 135 | } |
| 136 | return ErrTransient |
| 137 | } |
| 138 | if pendingDelivery { |
| 139 | return ErrTransient |
| 140 | } |
| 141 | if r.DeliveryRefusal != nil { |
| 142 | return s.recordRefusal(ctx, r, "delivery", r.DeliveryRefusal) |
| 143 | } |
| 144 | return s.retireCoordinator(ctx, r) |
| 145 | } |
| 146 | |
| 147 | func (s *CoordinatorService) recordRefusal(ctx context.Context, r *coordinatorState, operation string, refusal *RefusalError) error { |
| 148 | if !refusal.CoordinatorDefinitive() { |
| 149 | return ErrTransient |
| 150 | } |
| 151 | r.Refused, r.RefusalOperation, r.RefusalStatus, r.RefusalCode = true, operation, refusal.Status, refusal.Reason |
| 152 | // Save the refusal before acknowledging events, so interrupted retirement |
| 153 | // resumes locally without repeating a refused call or sending a prompt. |
| 154 | if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| 155 | return err |
| 156 | } |
| 157 | return s.retireCoordinator(ctx, r) |
| 158 | } |
| 159 | |
| 160 | func (s *CoordinatorService) retireCoordinator(ctx context.Context, r *coordinatorState) error { |
| 161 | if err := s.retirePending(ctx, r.Claim.Turn.ID); err != nil { |
| 162 | return err |
| 163 | } |
| 164 | r.Finished = true |
| 165 | if err := s.Journal.saveState(ctx, "coordinator", r.Claim.Turn.ID, *r); err != nil { |
| 166 | return err |
| 167 | } |
| 168 | delete(s.retry, r.Claim.Turn.ID) |
| 169 | return nil |
| 170 | } |
| 171 | |
| 172 | // Contained uncertain observations stay in the local audit journal but cannot |
| 173 | // leak into the ordinary task uploader or regain delivery authority. |
| 174 | func (s *CoordinatorService) retirePending(ctx context.Context, turn string) error { |
| 175 | rows, err := s.Journal.db.QueryContext(ctx, "SELECT id FROM journal_events WHERE acked=0 AND json_extract(body,'$.assignment_id')=?", turn) |
| 176 | if err != nil { |
| 177 | return err |
| 178 | } |
| 179 | var ids []string |
| 180 | for rows.Next() { |
| 181 | var id string |
| 182 | if err = rows.Scan(&id); err != nil { |
| 183 | rows.Close() |
| 184 | return err |
| 185 | } |
| 186 | ids = append(ids, id) |
| 187 | } |
| 188 | err = rows.Err() |
| 189 | rows.Close() |
| 190 | if err != nil { |
| 191 | return err |
| 192 | } |
| 193 | for _, id := range ids { |
| 194 | if err = s.Journal.Ack(ctx, id); err != nil { |
| 195 | return err |
| 196 | } |
| 197 | } |
| 198 | return nil |
| 199 | } |
| 200 | func (s *CoordinatorService) reconcileTools(ctx context.Context, r coordinatorState) error { |
| 201 | calls, err := s.Journal.CoordinatorToolSubmissions(ctx, 128) |
| 202 | if err != nil { |
| 203 | return err |
| 204 | } |
| 205 | for _, call := range calls { |
| 206 | if call.Claim.Turn.ID != r.Claim.Turn.ID || call.Session != r.Session { |
| 207 | continue |
| 208 | } |
| 209 | q := runnerproto.NewCoordinatorRequest(r.Claim) |
| 210 | q.ToolCall = &call.Call |
| 211 | var out runnerproto.CoordinatorToolResult |
| 212 | if err = s.call(ctx, "tool_result", q, &out); err != nil { |
| 213 | return err |
| 214 | } |
| 215 | // An empty response means the tool never committed. Do not execute it now. |
| 216 | if out.ResourceID == "" { |
| 217 | continue |
| 218 | } |
| 219 | if err = s.Journal.ackCoordinatorTool(ctx, r.Claim, r.Session, call.Call, out); err != nil { |
| 220 | return err |
| 221 | } |
| 222 | } |
| 223 | return nil |
| 224 | } |
| 225 | |
| 226 | func (c *HTTPInstance) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| 227 | token, err := c.token("", false) |
| 228 | if err != nil { |
| 229 | return err |
| 230 | } |
| 231 | q.Version = 2 |
| 232 | q.Capabilities = []string{runnerproto.CoordinatorCapability} |
| 233 | return c.post(ctx, "coordinator/"+op, q, token, out) |
| 234 | } |
| 235 | func (r *Runtime) CoordinatorCall(ctx context.Context, op string, q runnerproto.CoordinatorRequest, out any) error { |
| 236 | if op == "renew" { |
| 237 | r.mu.Lock() |
| 238 | reports := append([]runnerproto.ConnectionReport(nil), r.lastReports...) |
| 239 | r.mu.Unlock() |
| 240 | if len(reports) == 0 { |
| 241 | return provider.ErrPreflightRequired |
| 242 | } |
| 243 | if err := r.api.Heartbeat(ctx, reports); err != nil { |
| 244 | return err |
| 245 | } |
| 246 | } |
| 247 | return r.api.CoordinatorCall(ctx, op, q, out) |
| 248 | } |
| 249 | func (r *Runtime) coordinatorService() *CoordinatorService { |
| 250 | s := &CoordinatorService{Journal: r.journal, API: r, Launchers: r.launchers} |
| 251 | s.OpenLaunch = r.coordinatorLaunch |
| 252 | s.RecoverFiles = r.cleanupCoordinatorFiles |
| 253 | s.NamespaceContext = func(ctx context.Context, c runnerproto.CoordinatorClaim) context.Context { |
| 254 | return context.WithValue(ctx, namespaceAdmissionKey{}, func(ctx context.Context, record containment.Record) error { |
| 255 | owner := attemptKey(c.Scope, c.Handle) |
| 256 | if err := r.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record}); err != nil { |
| 257 | return err |
| 258 | } |
| 259 | if record.HostPID == 0 { |
| 260 | return nil |
| 261 | } |
| 262 | 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} |
| 263 | if err := s.namespaceEvent(ctx, c, "namespace.launch", record.AttemptKey, record.ID, n); err != nil { |
| 264 | return err |
| 265 | } |
| 266 | return r.journal.saveState(ctx, "namespace", record.ID, namespaceState{Owner: owner, Record: record, LaunchAcknowledged: true}) |
| 267 | }) |
| 268 | } |
| 269 | s.Contain = func(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| 270 | return r.containCoordinator(ctx, c) |
| 271 | } |
| 272 | return s |
| 273 | } |
| 274 | |
| 275 | // Containment reporting uses the coordinator endpoint, not task credentials. |
| 276 | func (r *Runtime) containCoordinator(ctx context.Context, c runnerproto.CoordinatorClaim) (runnerproto.ContainmentProof, error) { |
| 277 | proof := runnerproto.ContainmentProof{Version: 2, Scope: c.Scope, Handle: c.Handle, CheckedAt: time.Now().UTC()} |
| 278 | var states []namespaceState |
| 279 | if err := r.journal.readStates(ctx, "namespace", &states); err != nil { |
| 280 | return proof, err |
| 281 | } |
| 282 | var failures error |
| 283 | for _, n := range states { |
| 284 | if n.Owner != attemptKey(c.Scope, c.Handle) { |
| 285 | continue |
| 286 | } |
| 287 | p, err := r.namespaces.Stop(ctx, n.Record.ID) |
| 288 | if err != nil { |
| 289 | p, err = r.namespaces.Recover(ctx, n.Record) |
| 290 | } |
| 291 | if err != nil || !p.Verified { |
| 292 | failures = errors.Join(failures, provider.ErrContainment, err) |
| 293 | continue |
| 294 | } |
| 295 | if err = r.journal.validateDirectRecord(ctx, p.Record); err != nil { |
| 296 | failures = errors.Join(failures, err) |
| 297 | continue |
| 298 | } |
| 299 | n.Proof = &p |
| 300 | if err = r.journal.saveState(ctx, "namespace", n.Record.ID, n); err != nil { |
| 301 | failures = errors.Join(failures, err) |
| 302 | continue |
| 303 | } |
| 304 | if _, err = r.journal.db.ExecContext(ctx, "UPDATE direct_attempts SET contained=1 WHERE attempt=?", n.Record.AttemptKey); err != nil { |
| 305 | failures = errors.Join(failures, err) |
| 306 | continue |
| 307 | } |
| 308 | if p.Record.HostPID == 0 { |
| 309 | continue |
| 310 | } |
| 311 | 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} |
| 312 | if n.LaunchAcknowledged { |
| 313 | proof.Namespaces = append(proof.Namespaces, exit) |
| 314 | } else { |
| 315 | proof.Unstarted = append(proof.Unstarted, exit) |
| 316 | } |
| 317 | } |
| 318 | return proof, failures |
| 319 | } |
| 320 | |
| 321 | func (s *CoordinatorService) namespaceEvent(ctx context.Context, c runnerproto.CoordinatorClaim, kind, agent, session string, payload any) error { |
| 322 | r := coordinatorState{Claim: c, Session: provider.Session{AttemptKey: agent, ID: session}} |
| 323 | return s.emit(ctx, r, kind, json.RawMessage(marshal(payload))) |
| 324 | } |
| 325 | |