interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / supervisor / canary_exec.rs

740 lines · 29602 bytes Raw Blame History
1//! The canary executor: the supervisor drives every request itself.
2//!
3//! The one rule above everything: no candidate-controlled statement can independently establish
4//! that a canary passed. This module issues each request, measures elapsed time on the
5//! supervisor's own clock, compares the answer with the pinned workload, and durably records the
6//! verified observation through `crate::canary::log`. Worker self-reports (`CanaryReport`,
7//! `worker_latency_us`) are diagnostics and never become observations.
8//!
9//! The executor never decides `Durable` and never touches `active.sock`. It returns the sealed
10//! log; the quota validator (`crate::canary::admit_sealed_quota`) is the only authority on
11//! whether the evidence suffices. Sequence, from docs/CANARY-CONTRACT.md: verify the executable,
12//! bind the generation socket, spawn the worker with `--socket`, wait for versioned
13//! authenticated readiness, then for each request in workload order send `ExecuteRequest`, wait
14//! up to its deadline for the `ExecuteResult` of that request, and append one observation. Any
15//! non-success observation is an early safety revert: stop issuing, kill the worker, mark the
16//! generation `Reverting`, seal.
17
18use crate::canary::observation::ObservationInput;
19use crate::canary::{
20 result_digest, CanaryObservationV2, CanaryRequestSpec, CandidateIdentity, LogHeader, LogRecord,
21 ObservationLogWriter, PinnedWorkload, Provenance, SealedObservationLog, VerifiedStatus,
22 CANARY_PROTOCOL_VERSION,
23};
24use crate::supervisor::daemon::{authenticate_worker_connection, SupervisorConfig};
25use crate::supervisor::ipc::{IpcConnection, IpcServer, SupervisorMessage, WorkerMessage};
26use crate::supervisor::{GenerationInfo, GenerationState, HostSupervisor};
27use std::collections::BTreeSet;
28use std::path::{Path, PathBuf};
29use std::sync::{Arc, Mutex as StdMutex};
30use std::time::{Duration, Instant};
31
32/// How the executor behaves on top of the workload. The workload owns the requests, expected
33/// outcomes and deadlines; nothing here can loosen them.
34#[derive(Debug, Clone)]
35pub struct ExecutorConfig {
36 /// Time from spawn to a completed authenticated versioned handshake.
37 pub readiness_deadline: Duration,
38 /// How long to keep listening for stray connections after the last request.
39 pub settle_window: Duration,
40 /// Shortens, never lengthens, each request's deadline.
41 pub deadline_cap_ms: Option<u64>,
42 /// Runs only the first N requests of the workload. The quota target still decides whether
43 /// N is enough.
44 pub request_limit: Option<usize>,
45 /// Fault injection for restart tests: after this many observations recorded in this run,
46 /// kill the worker and return `Halted` without sealing, as a supervisor crash would.
47 pub halt_after_requests: Option<usize>,
48 /// Extra environment for the worker, after `SUPERVISOR_SECRET`.
49 pub worker_env: Vec<(String, String)>,
50}
51
52impl Default for ExecutorConfig {
53 fn default() -> Self {
54 Self {
55 readiness_deadline: Duration::from_secs(10),
56 settle_window: Duration::from_millis(150),
57 deadline_cap_ms: None,
58 request_limit: None,
59 halt_after_requests: None,
60 worker_env: Vec::new(),
61 }
62 }
63}
64
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct ExecutionSummary {
67 /// Requests in scope for this run (workload size after `request_limit`).
68 pub requests_planned: usize,
69 /// Observations already stored by an earlier run of the same log, kept as they are.
70 pub recovered: usize,
71 /// Requests this run sent.
72 pub issued: usize,
73 pub verified_success: usize,
74 pub wrong_result: usize,
75 pub timeout: usize,
76 pub invalid_response: usize,
77 pub connection_closed: usize,
78 /// Rejection records this run appended.
79 pub rejections: usize,
80 /// Whether the worker completed authenticated versioned readiness.
81 pub ready: bool,
82 /// The first failure that stopped the run, if any.
83 pub first_failure: Option<String>,
84 /// The generation was marked `Reverting`.
85 pub reverted: bool,
86}
87
88#[derive(Debug)]
89pub enum ExecutionOutcome {
90 /// The log is sealed and verified. Hand it to `admit_sealed_quota`.
91 Sealed {
92 sealed: SealedObservationLog,
93 summary: ExecutionSummary,
94 },
95 /// The run stopped on purpose without sealing (`halt_after_requests`). The log on disk is
96 /// unsealed and can be reopened.
97 Halted { summary: ExecutionSummary },
98}
99
100impl ExecutionOutcome {
101 pub fn summary(&self) -> &ExecutionSummary {
102 match self {
103 ExecutionOutcome::Sealed { summary, .. } | ExecutionOutcome::Halted { summary } => {
104 summary
105 }
106 }
107 }
108
109 pub fn sealed(&self) -> Option<&SealedObservationLog> {
110 match self {
111 ExecutionOutcome::Sealed { sealed, .. } => Some(sealed),
112 ExecutionOutcome::Halted { .. } => None,
113 }
114 }
115}
116
117pub struct CanaryExecutor<'a> {
118 supervisor: &'a HostSupervisor,
119 config: SupervisorConfig,
120 workload: PinnedWorkload,
121 identity: CandidateIdentity,
122 executable: PathBuf,
123 args: Vec<String>,
124 exec: ExecutorConfig,
125}
126
127/// Kills and reaps the worker when dropped, so no path leaks it.
128struct WorkerProcess(Option<std::process::Child>);
129
130impl WorkerProcess {
131 fn has_exited(&mut self) -> bool {
132 match self.0.as_mut() {
133 Some(child) => !matches!(child.try_wait(), Ok(None)),
134 None => true,
135 }
136 }
137
138 fn stop(&mut self) {
139 if let Some(mut child) = self.0.take() {
140 let _ = child.kill();
141 let _ = child.wait();
142 }
143 }
144}
145
146impl Drop for WorkerProcess {
147 fn drop(&mut self) {
148 self.stop();
149 }
150}
151
152/// A dropped executor future or a failed log append must not leave the socket guard alive.
153struct AbortOnDrop(tokio::task::AbortHandle);
154
155impl Drop for AbortOnDrop {
156 fn drop(&mut self) {
157 self.0.abort();
158 }
159}
160
161fn now_ms() -> u64 {
162 std::time::SystemTime::now()
163 .duration_since(std::time::UNIX_EPOCH)
164 .map(|d| d.as_millis() as u64)
165 .unwrap_or(0)
166}
167
168/// The observation log path for a generation: `<rsi_root>/canary/observations/<id>.jsonl`.
169pub fn observation_log_path(rsi_root: &Path, generation_id: &str) -> PathBuf {
170 rsi_root
171 .join("canary")
172 .join("observations")
173 .join(format!("{}.jsonl", generation_id))
174}
175
176/// The generation socket: `<rsi_root>/workers/<id>.sock`.
177pub fn generation_socket_path(rsi_root: &Path, generation_id: &str) -> PathBuf {
178 rsi_root
179 .join("workers")
180 .join(format!("{}.sock", generation_id))
181}
182
183/// Every complete record of an unsealed log. A partial trailing record has no newline and is
184/// ignored, exactly as `ObservationLogWriter::reopen` drops it.
185fn stored_records(path: &Path) -> Result<Vec<LogRecord>, String> {
186 let bytes = std::fs::read(path)
187 .map_err(|e| format!("cannot read observation log {:?}: {}", path, e))?;
188 let mut records = Vec::new();
189 let mut rest: &[u8] = &bytes;
190 while let Some(pos) = rest.iter().position(|b| *b == b'\n') {
191 let record: LogRecord = serde_json::from_slice(&rest[..pos])
192 .map_err(|e| format!("observation log {:?} has an unreadable record: {}", path, e))?;
193 records.push(record);
194 rest = &rest[pos + 1..];
195 }
196 Ok(records)
197}
198
199/// Stray connections to the generation socket after the worker authenticated. Each one starts
200/// `Unauthenticated`, so whatever it sends is a rejection and the connection is closed.
201fn spawn_stray_connection_guard(
202 server: IpcServer,
203 rejections: Arc<StdMutex<Vec<String>>>,
204) -> tokio::task::JoinHandle<()> {
205 tokio::spawn(async move {
206 loop {
207 let mut conn = match server.accept().await {
208 Ok(conn) => conn,
209 Err(_) => continue,
210 };
211 let rejections = rejections.clone();
212 tokio::spawn(async move {
213 let what = match tokio::time::timeout(
214 Duration::from_secs(2),
215 conn.recv::<WorkerMessage>(),
216 )
217 .await
218 {
219 Ok(Ok(msg)) => format!("{:?}", msg),
220 Ok(Err(e)) => format!("unreadable frame ({})", e),
221 Err(_) => "no frame".to_string(),
222 };
223 let reason = format!("message on an unauthenticated connection: {}", what);
224 if let Ok(mut list) = rejections.lock() {
225 list.push(reason);
226 }
227 // Dropping the connection closes it.
228 });
229 }
230 })
231}
232
233impl<'a> CanaryExecutor<'a> {
234 pub fn new(
235 supervisor: &'a HostSupervisor,
236 config: SupervisorConfig,
237 workload: PinnedWorkload,
238 identity: CandidateIdentity,
239 executable: PathBuf,
240 args: Vec<String>,
241 exec: ExecutorConfig,
242 ) -> Self {
243 Self {
244 supervisor,
245 config,
246 workload,
247 identity,
248 executable,
249 args,
250 exec,
251 }
252 }
253
254 fn requests(&self) -> &[CanaryRequestSpec] {
255 let all = &self.workload.manifest.requests;
256 match self.exec.request_limit {
257 Some(n) => &all[..n.min(all.len())],
258 None => all,
259 }
260 }
261
262 fn open_log(&self, path: &Path) -> Result<ObservationLogWriter, String> {
263 let wanted = LogHeader::new(
264 &self.identity.generation_id,
265 &self.workload.digest,
266 &self.identity.executable_digest,
267 now_ms(),
268 );
269 if !path.exists() {
270 return ObservationLogWriter::create(path, wanted);
271 }
272 // A restart: the header on disk must bind the same generation, workload and
273 // executable. Its opening time is the only field that differs.
274 let existing = match stored_records(path)?.into_iter().next() {
275 Some(LogRecord::Header(h)) => h,
276 _ => {
277 return Err(format!(
278 "observation log {:?} has no header; refusing",
279 path
280 ))
281 }
282 };
283 if existing.generation_id != wanted.generation_id
284 || existing.workload_digest != wanted.workload_digest
285 || existing.candidate_executable_digest != wanted.candidate_executable_digest
286 {
287 return Err(format!(
288 "observation log {:?} is bound to another generation, workload or executable; refusing",
289 path
290 ));
291 }
292 ObservationLogWriter::reopen(path, &existing)
293 }
294
295 /// Runs the whole canary for `generation` and returns the sealed log with a summary.
296 /// `Err` means the canary could not be run at all (the executable is not the candidate's,
297 /// the workload digest does not match, the log cannot be opened or written).
298 pub async fn run(&self, generation: &mut GenerationInfo) -> Result<ExecutionOutcome, String> {
299 self.identity.validate()?;
300 if generation.generation_id != self.identity.generation_id {
301 return Err(format!(
302 "generation {} is not the candidate identity's generation {}",
303 generation.generation_id, self.identity.generation_id
304 ));
305 }
306 self.workload.manifest.validate()?;
307 if self.workload.manifest.digest() != self.workload.digest {
308 return Err("pinned workload does not match its own digest; refusing".to_string());
309 }
310 // Right before launch: the file about to run is the executable in the chain.
311 self.identity.verify_executable(&self.executable)?;
312
313 let rsi_root = &self.config.rsi_root;
314 let log_path = observation_log_path(rsi_root, &self.identity.generation_id);
315 let mut writer = self.open_log(&log_path)?;
316
317 let mut summary = ExecutionSummary {
318 requests_planned: self.requests().len(),
319 ..Default::default()
320 };
321
322 // Earlier run of the same log: failures stay failures; only stored successes are kept.
323 let mut prior_failure = None;
324 for record in stored_records(&log_path)? {
325 if let LogRecord::Observation(o) = record {
326 summary.recovered += 1;
327 if o.observation.status != VerifiedStatus::VerifiedSuccess
328 && prior_failure.is_none()
329 {
330 prior_failure = Some(format!(
331 "{}: {:?} recorded before a restart",
332 o.observation.request_id, o.observation.status
333 ));
334 }
335 }
336 }
337 if let Some(reason) = prior_failure {
338 summary.first_failure = Some(reason);
339 return self.finish(generation, writer, summary, true);
340 }
341
342 let todo: Vec<&CanaryRequestSpec> = self
343 .requests()
344 .iter()
345 .filter(|spec| {
346 let digest = spec.request_digest(&self.workload.manifest.workload_id);
347 !writer.contains(&crate::canary::observation_id(
348 &self.identity.generation_id,
349 &spec.request_id,
350 &digest,
351 ))
352 })
353 .collect();
354 if todo.is_empty() {
355 summary.ready = true;
356 return self.finish(generation, writer, summary, false);
357 }
358
359 // Bind before spawning, then launch.
360 let socket_path = generation_socket_path(rsi_root, &self.identity.generation_id);
361 let server = IpcServer::bind(&socket_path)?;
362 let args: Vec<&str> = self.args.iter().map(String::as_str).collect();
363 // A fresh secret for this run only. The candidate process has to hold it to answer the
364 // handshake, so it must never be the supervisor's long-lived secret: possession proves
365 // that this process is the one launched for this run, nothing more.
366 let run_secret = format!("canary-run-{}", uuid::Uuid::new_v4().simple());
367 let mut env: Vec<(&str, &str)> = vec![("SUPERVISOR_SECRET", run_secret.as_str())];
368 for (k, v) in &self.exec.worker_env {
369 env.push((k.as_str(), v.as_str()));
370 }
371 let child = self.supervisor.spawn_worker_process(
372 generation,
373 &self.executable,
374 &args,
375 &socket_path,
376 &env,
377 )?;
378 let mut worker = WorkerProcess(Some(child));
379
380 // Readiness: a versioned Ready, the HMAC and Ping on a connection, within the deadline.
381 let ready_by = Instant::now() + self.exec.readiness_deadline;
382 let mut conn: Option<IpcConnection> = None;
383 while conn.is_none() {
384 let now = Instant::now();
385 if now >= ready_by {
386 summary.first_failure = Some(format!(
387 "no authenticated versioned readiness within {:?}",
388 self.exec.readiness_deadline
389 ));
390 break;
391 }
392 let tick = (ready_by - now).min(Duration::from_millis(50));
393 match tokio::time::timeout(tick, server.accept()).await {
394 Ok(Ok(mut candidate)) => {
395 let remaining = ready_by.saturating_duration_since(Instant::now());
396 match authenticate_worker_connection(
397 &mut candidate,
398 &self.identity.generation_id,
399 &run_secret,
400 remaining,
401 )
402 .await
403 {
404 Ok(state) if state.can_execute_for(&self.identity.generation_id) => {
405 conn = Some(candidate);
406 }
407 Ok(_) => {}
408 Err(failure) => {
409 // Rejected and closed. No rollback; the deadline still fails the canary.
410 self.record_rejection(&mut writer, &mut summary, &failure.to_string());
411 }
412 }
413 }
414 Ok(Err(_)) => {}
415 Err(_) => {
416 if worker.has_exited() {
417 summary.first_failure =
418 Some("worker exited before it became ready".to_string());
419 break;
420 }
421 }
422 }
423 }
424 let mut conn = match conn {
425 Some(conn) => conn,
426 None => {
427 drop(server);
428 worker.stop();
429 return self.finish(generation, writer, summary, true);
430 }
431 };
432 summary.ready = true;
433 generation.state = GenerationState::CanaryActive;
434
435 let strays = Arc::new(StdMutex::new(Vec::new()));
436 let guard = spawn_stray_connection_guard(server, strays.clone());
437 let _guard_lifetime = AbortOnDrop(guard.abort_handle());
438
439 let mut answered: BTreeSet<String> = BTreeSet::new();
440 let mut issued: BTreeSet<String> = BTreeSet::new();
441 let mut recorded_this_run = 0usize;
442 let mut revert = false;
443
444 for spec in todo {
445 self.drain_strays(&strays, &mut writer, &mut summary);
446 let request_digest = spec.request_digest(&self.workload.manifest.workload_id);
447 let deadline_ms = match self.exec.deadline_cap_ms {
448 Some(cap) => spec.deadline_ms.min(cap),
449 None => spec.deadline_ms,
450 };
451 let pid = generation.pid;
452
453 issued.insert(spec.request_id.clone());
454 summary.issued += 1;
455 let started = Instant::now();
456 let sent = conn
457 .send(&SupervisorMessage::ExecuteRequest {
458 protocol_version: CANARY_PROTOCOL_VERSION,
459 generation_id: self.identity.generation_id.clone(),
460 request_id: spec.request_id.clone(),
461 request_digest: request_digest.clone(),
462 workload_digest: self.workload.digest.clone(),
463 input: spec.input.clone(),
464 deadline_ms,
465 })
466 .await;
467
468 let (status, output, elapsed) = if sent.is_err() {
469 (VerifiedStatus::ConnectionClosed, None, started.elapsed())
470 } else {
471 self.await_result(
472 &mut conn,
473 spec,
474 &issued,
475 &answered,
476 started,
477 deadline_ms,
478 &mut writer,
479 &mut summary,
480 )
481 .await
482 };
483
484 let mut status = status;
485 let mut digest = output.as_ref().map(|o| result_digest(o.as_bytes()));
486 if status == VerifiedStatus::VerifiedSuccess || status == VerifiedStatus::WrongResult {
487 if !spec.matches_output(output.as_deref().unwrap_or("")) {
488 status = VerifiedStatus::WrongResult;
489 } else {
490 status = VerifiedStatus::VerifiedSuccess;
491 }
492 if elapsed > Duration::from_millis(deadline_ms) {
493 status = VerifiedStatus::Timeout;
494 digest = None;
495 }
496 }
497
498 // A failed resource read is not proof that memory is within budget.
499 if status == VerifiedStatus::VerifiedSuccess {
500 let budget = match pid {
501 Some(pid) => self.supervisor.is_memory_within_budget(pid),
502 None => Err("no worker pid to read".to_string()),
503 };
504 match budget {
505 Ok(true) => {}
506 other => {
507 let reason = match other {
508 Ok(_) => format!(
509 "resource budget exceeded: worker above {} MB",
510 self.supervisor.memory_limit_mb
511 ),
512 Err(e) => format!("resource budget unreadable, reverting: {}", e),
513 };
514 // The success is not recorded: the request counts as incomplete.
515 self.record_rejection(&mut writer, &mut summary, &reason);
516 summary.first_failure = Some(format!("{}: {}", spec.request_id, reason));
517 revert = true;
518 break;
519 }
520 }
521 }
522
523 answered.insert(spec.request_id.clone());
524 let observation = CanaryObservationV2::new(ObservationInput {
525 generation_id: &self.identity.generation_id,
526 request_id: &spec.request_id,
527 request_digest: &request_digest,
528 workload_digest: &self.workload.digest,
529 candidate_executable_digest: &self.identity.executable_digest,
530 result_digest: digest.as_deref(),
531 elapsed_us: elapsed.as_micros() as u64,
532 observed_at_ms: now_ms(),
533 status,
534 provenance: Provenance::Measured,
535 });
536 writer.append_observation(&observation)?;
537 recorded_this_run += 1;
538 match status {
539 VerifiedStatus::VerifiedSuccess => summary.verified_success += 1,
540 VerifiedStatus::WrongResult => summary.wrong_result += 1,
541 VerifiedStatus::Timeout => summary.timeout += 1,
542 VerifiedStatus::InvalidResponse => summary.invalid_response += 1,
543 VerifiedStatus::ConnectionClosed => summary.connection_closed += 1,
544 }
545 if status != VerifiedStatus::VerifiedSuccess {
546 summary.first_failure = Some(format!("{}: {:?}", spec.request_id, status));
547 revert = true;
548 break;
549 }
550 if self.exec.halt_after_requests == Some(recorded_this_run) {
551 guard.abort();
552 let _ = guard.await;
553 worker.stop();
554 return Ok(ExecutionOutcome::Halted { summary });
555 }
556 }
557
558 if !revert {
559 tokio::time::sleep(self.exec.settle_window).await;
560 }
561 self.drain_strays(&strays, &mut writer, &mut summary);
562 guard.abort();
563 let _ = guard.await;
564 worker.stop();
565 self.finish(generation, writer, summary, revert)
566 }
567
568 /// Waits for the result of `spec`. Only an `ExecuteResult` for this issued request on this
569 /// authenticated connection ends the wait with a result; heartbeats and self-reports are
570 /// diagnostics and do not.
571 #[allow(clippy::too_many_arguments)]
572 async fn await_result(
573 &self,
574 conn: &mut IpcConnection,
575 spec: &CanaryRequestSpec,
576 issued: &BTreeSet<String>,
577 answered: &BTreeSet<String>,
578 started: Instant,
579 deadline_ms: u64,
580 writer: &mut ObservationLogWriter,
581 summary: &mut ExecutionSummary,
582 ) -> (VerifiedStatus, Option<String>, Duration) {
583 let generation_id = &self.identity.generation_id;
584 let deadline_at =
585 tokio::time::Instant::from_std(started) + Duration::from_millis(deadline_ms);
586 loop {
587 let msg = match tokio::time::timeout_at(deadline_at, conn.recv::<WorkerMessage>()).await
588 {
589 Err(_) => return (VerifiedStatus::Timeout, None, started.elapsed()),
590 Ok(Err(e)) if e.contains("closed by peer") => {
591 return (VerifiedStatus::ConnectionClosed, None, started.elapsed())
592 }
593 Ok(Err(e)) if e.contains("Failed to read") => {
594 return (VerifiedStatus::ConnectionClosed, None, started.elapsed())
595 }
596 Ok(Err(e)) => {
597 // A frame arrived for the open request but could not be decoded.
598 tracing::warn!(target: "supervisor", "undecodable frame during {}: {}", spec.request_id, e);
599 return (VerifiedStatus::InvalidResponse, None, started.elapsed());
600 }
601 Ok(Ok(msg)) => msg,
602 };
603 match msg {
604 WorkerMessage::ExecuteResult {
605 protocol_version,
606 generation_id: named,
607 request_id,
608 output,
609 worker_latency_us,
610 } => {
611 let elapsed = started.elapsed();
612 if request_id == spec.request_id {
613 tracing::debug!(
614 target: "supervisor",
615 "diagnostic worker_latency_us={:?} for {}",
616 worker_latency_us, request_id
617 );
618 if protocol_version != CANARY_PROTOCOL_VERSION || &named != generation_id {
619 return (VerifiedStatus::InvalidResponse, None, elapsed);
620 }
621 return (VerifiedStatus::VerifiedSuccess, Some(output), elapsed);
622 }
623 let why = if answered.contains(&request_id) {
624 "already answered"
625 } else if issued.contains(&request_id) {
626 "not the open request"
627 } else {
628 "not issued"
629 };
630 self.record_rejection(
631 writer,
632 summary,
633 &format!("ExecuteResult for request {} which was {}", request_id, why),
634 );
635 if &named != generation_id {
636 return (VerifiedStatus::ConnectionClosed, None, started.elapsed());
637 }
638 }
639 WorkerMessage::Heartbeat {
640 generation_id: named,
641 ..
642 }
643 | WorkerMessage::CanaryReport {
644 generation_id: named,
645 ..
646 } if &named == generation_id => {
647 tracing::debug!(target: "supervisor", "diagnostic frame during {}", spec.request_id);
648 }
649 WorkerMessage::Pong => {}
650 WorkerMessage::Heartbeat {
651 generation_id: named,
652 ..
653 }
654 | WorkerMessage::CanaryReport {
655 generation_id: named,
656 ..
657 }
658 | WorkerMessage::DrainComplete {
659 generation_id: named,
660 } if &named != generation_id => {
661 self.record_rejection(
662 writer,
663 summary,
664 &format!("message naming generation {}", named),
665 );
666 return (VerifiedStatus::ConnectionClosed, None, started.elapsed());
667 }
668 other => {
669 // DrainComplete, a repeated Ready, a stray AuthResponse: a worker cannot
670 // promote or re-authenticate itself. Logged, never an observation.
671 self.record_rejection(
672 writer,
673 summary,
674 &format!(
675 "unexpected frame on the authenticated connection: {:?}",
676 other
677 ),
678 );
679 }
680 }
681 }
682 }
683
684 fn record_rejection(
685 &self,
686 writer: &mut ObservationLogWriter,
687 summary: &mut ExecutionSummary,
688 reason: &str,
689 ) {
690 tracing::warn!(target: "supervisor", "rejected worker message: {}", reason);
691 if writer.append_rejection(reason, now_ms()).is_ok() {
692 summary.rejections += 1;
693 }
694 }
695
696 fn drain_strays(
697 &self,
698 strays: &Arc<StdMutex<Vec<String>>>,
699 writer: &mut ObservationLogWriter,
700 summary: &mut ExecutionSummary,
701 ) {
702 let reasons: Vec<String> = match strays.lock() {
703 Ok(mut list) => std::mem::take(&mut *list),
704 Err(_) => Vec::new(),
705 };
706 for reason in reasons {
707 self.record_rejection(writer, summary, &reason);
708 }
709 }
710
711 fn finish(
712 &self,
713 generation: &mut GenerationInfo,
714 writer: ObservationLogWriter,
715 mut summary: ExecutionSummary,
716 revert: bool,
717 ) -> Result<ExecutionOutcome, String> {
718 if revert {
719 // Early safety revert. Rolling back the active generation is the caller's job; the
720 // executor only marks the candidate and never touches active.sock.
721 generation.state = GenerationState::Reverting;
722 summary.reverted = true;
723 }
724 let sealed = writer.seal(now_ms())?;
725 Ok(ExecutionOutcome::Sealed { sealed, summary })
726 }
727}
728
729#[cfg(test)]
730mod tests {
731 use super::AbortOnDrop;
732
733 #[tokio::test]
734 async fn dropping_executor_guard_cancels_its_socket_task() {
735 let task = tokio::spawn(std::future::pending::<()>());
736 let guard = AbortOnDrop(task.abort_handle());
737 drop(guard);
738 assert!(task.await.unwrap_err().is_cancelled());
739 }
740}