Skip to main content

sail_api/
jobs.rs

1//! Versioned, bounded local project-job protocol, independent of the SMT cache.
2
3use std::collections::BTreeMap;
4use std::fmt::Write as _;
5use std::io::{self, Read, Write};
6use std::path::{Path, PathBuf};
7
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11/// Project job protocol version.
12pub const VERSION: u32 = 1;
13/// Capability-set version a service advertises in [`Response::Capabilities`].
14///
15/// Absent (read as 1) on 0.2 services, whose set included the neutral source
16/// jobs, mutation, literal witness and assurance operations. Version 2 is the
17/// Sail 0.3 set without them (ADR 0109). The frame [`VERSION`] is unchanged, so
18/// 0.2 clients and retained records keep working for ordinary jobs.
19pub const CAPABILITIES_VERSION: u32 = 2;
20/// Maximum request or response frame (32 MiB).
21pub const MAX_FRAME: usize = 32 * 1024 * 1024;
22
23/// A verification request. The environment belongs to its submitting client.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Submission {
26    /// Explicit backend/repair mode; old endpoints are never used for these requests.
27    #[serde(default)]
28    pub mode: Mode,
29    /// Absolute Cargo project directory.
30    pub project_dir: PathBuf,
31    /// Verification arguments, without the `verify` subcommand or output flags.
32    pub args: Vec<String>,
33    /// Force fresh verification even when a proof receipt exists.
34    pub force: bool,
35    /// UTF-8 process environment, captured by the submitting client.
36    pub environment: BTreeMap<String, String>,
37    /// Content revision observed by the submitting client.
38    pub input_revision: Option<String>,
39}
40
41/// Verification execution mode, negotiated through the version-two job endpoint.
42#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
43#[serde(tag = "kind", content = "selection", rename_all = "snake_case")]
44pub enum Mode {
45    /// Existing stock pinned Verus verification.
46    #[default]
47    Stock,
48    /// Direct standalone Verus file; requires explicit endpoint support.
49    Standalone,
50    /// Exact standalone repair focus plus independent full-file validation.
51    StandaloneRepair {
52        /// Exact crate-qualified function reported by Verus.
53        function: String,
54    },
55    /// Optional explicitly selected Sail-managed interactive engine.
56    Interactive,
57    /// One engine batch containing focus and independent full validation.
58    Repair(crate::repair::Selection),
59}
60
61/// Durable lifecycle, independent of the proof outcome.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(rename_all = "snake_case")]
64pub enum Lifecycle {
65    /// Waiting for the single verification worker.
66    Queued,
67    /// The verification process is running.
68    Running,
69    /// A complete verification result is available (including failed proofs).
70    Completed,
71    /// Explicitly cancelled by a client.
72    Cancelled,
73    /// Cancelled because a newer input revision was requested.
74    Superseded,
75    /// Startup, persistence, process, or restart failure.
76    InfrastructureError,
77}
78impl Lifecycle {
79    /// Whether no more worker events are expected.
80    #[must_use]
81    pub const fn terminal(self) -> bool {
82        !matches!(self, Self::Queued | Self::Running)
83    }
84}
85
86/// How the result's input revision relates to current inputs.
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
88#[serde(rename_all = "snake_case")]
89pub enum Currentness {
90    /// The runner established a coherent current revision.
91    Current,
92    /// Inputs changed during or since verification.
93    Historical,
94    /// Input coverage or result attribution could not be established.
95    Unknown,
96}
97
98/// Persistent status, safe to inspect while verification runs.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct Status {
101    /// Protocol/store format version.
102    pub version: u32,
103    /// Durable job id.
104    pub id: String,
105    /// Absolute project directory.
106    pub project_dir: PathBuf,
107    /// Requested arguments; never broadened silently.
108    pub args: Vec<String>,
109    /// Lifecycle, distinct from proof verdict.
110    pub state: Lifecycle,
111    /// Submission time, milliseconds since the Unix epoch.
112    pub submitted_at_ms: u64,
113    /// Start time, if started.
114    pub started_at_ms: Option<u64>,
115    /// Completion time, if terminal.
116    pub finished_at_ms: Option<u64>,
117    /// Process exit status, if available.
118    pub exit_code: Option<i32>,
119    /// Input revision before the run.
120    pub input_revision: Option<String>,
121    /// Result currentness.
122    pub currentness: Currentness,
123    /// Stable infrastructure error code and explanatory text, when present.
124    pub error: Option<String>,
125}
126
127/// Stable refusal for a record written by the neutral source jobs that Sail
128/// 0.2 offered and 0.3.0 removed. Such a record is never read as an ordinary
129/// job result.
130pub const RETIRED_NEUTRAL_RECORD: &str = "SAIL3161: this record was written by a neutral source job, which Sail 0.3.0 removed; it cannot be read as verification evidence";
131
132/// The wire form of [`ResultDocument`]. It also recognises the retired
133/// `contracts` member, so a neutral record is refused instead of having that
134/// member silently ignored.
135#[derive(Deserialize)]
136struct ResultDocumentWire {
137    #[serde(default)]
138    contracts: Option<serde::de::IgnoredAny>,
139    #[serde(default)]
140    repair: Option<Box<crate::repair::ResultDocument>>,
141    job: Status,
142    result: Option<Value>,
143}
144impl TryFrom<ResultDocumentWire> for ResultDocument {
145    type Error = &'static str;
146    fn try_from(wire: ResultDocumentWire) -> Result<Self, Self::Error> {
147        if wire.contracts.is_some() {
148            return Err(RETIRED_NEUTRAL_RECORD);
149        }
150        Ok(Self {
151            repair: wire.repair,
152            job: wire.job,
153            result: wire.result,
154        })
155    }
156}
157
158/// A job result preserving the managed runner's versioned document.
159#[derive(Debug, Clone, Serialize, Deserialize)]
160#[serde(try_from = "ResultDocumentWire")]
161pub struct ResultDocument {
162    /// Independent focus/full repair evidence, when this was an engine batch.
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub repair: Option<Box<crate::repair::ResultDocument>>,
165    /// Job status and provenance.
166    pub job: Status,
167    /// Managed project result, only after a complete worker output.
168    pub result: Option<Value>,
169}
170
171/// A bounded slice of a job's diagnostics or target events.
172#[derive(Debug, Clone, Serialize, Deserialize)]
173pub struct Chunk {
174    /// Byte offset of the next slice.
175    pub next: u64,
176    /// UTF-8 text (lossy only for diagnostics from non-UTF-8 subprocesses).
177    pub text: String,
178    /// Whether this job has reached a terminal state.
179    pub complete: bool,
180}
181
182/// One local RPC.
183#[derive(Debug, Clone, Serialize, Deserialize)]
184#[serde(tag = "operation", rename_all = "snake_case")]
185pub enum Request {
186    /// Negotiate and inspect optional daemon-owned preparation.
187    PreparationStatus,
188    /// Enqueue optional work; never changes the original verification result.
189    Prepare(crate::preparation::Submission),
190    /// Hold foreground priority until this connection closes.
191    Foreground {
192        /// Preparation protocol version.
193        version: u32,
194        /// Originating working directory.
195        project_dir: PathBuf,
196        /// Arguments used to resolve the workspace scheduling key.
197        args: Vec<String>,
198    },
199    /// Fail-closed negotiation before any non-stock submission.
200    Capabilities,
201    /// Legacy attributed submission; services since 0.3 refuse this operation.
202    SubmitAttributed {
203        /// Requested stock or standalone verification.
204        submission: Submission,
205        /// Canonical, non-empty submitter attributions.
206        requirements: Vec<crate::attribution::RequirementAttribution>,
207    },
208    /// Legacy assurance read; services since 0.3 refuse this operation.
209    AttributedAssurance {
210        /// Exact durable job identity.
211        id: String,
212    },
213    /// Read bounded version-one proof observations using a resumable cursor.
214    ProofEvents {
215        /// Durable job identity.
216        id: String,
217        /// Last consumed event; stream identity must match on reconnect.
218        cursor: crate::proof::Cursor,
219        /// Maximum event count, clamped by the service.
220        limit: usize,
221    },
222    /// Explain an exact reported target/function, preserving raw evidence.
223    Explain {
224        /// Durable completed job identity.
225        id: String,
226        /// Complete Cargo target identity.
227        target: crate::proof::Target,
228        /// Exact crate-qualified function.
229        function: String,
230        /// Optional exact obligation id.
231        obligation: Option<String>,
232    },
233    /// Save independent immutable proof evidence outside job retention.
234    SaveBaseline {
235        /// Completed evidence source.
236        id: String,
237        /// Immutable owner-selected name.
238        name: String,
239    },
240    /// List retained immutable named baselines.
241    Baselines,
242    /// Read immutable evidence for its recorded revision, never current inputs.
243    GetBaseline {
244        /// Exact retained baseline name.
245        name: String,
246    },
247    /// Compare explicit completed evidence with an earlier job or baseline.
248    Compare {
249        /// Earlier named baseline or durable job.
250        before: crate::evidence::Reference,
251        /// Later completed job identity.
252        after: String,
253    },
254    /// Submit or coalesce an identical in-flight request.
255    Submit {
256        /// Requested verification.
257        submission: Submission,
258    },
259    /// List retained jobs, optionally for one canonical project directory.
260    List {
261        /// Project filter.
262        project_dir: Option<PathBuf>,
263    },
264    /// Inspect one job without waiting for verification.
265    Status {
266        /// Job id.
267        id: String,
268    },
269    /// Read one completed or in-progress result.
270    Result {
271        /// Job id.
272        id: String,
273    },
274    /// Cancel one job and its entire process group.
275    Cancel {
276        /// Job id.
277        id: String,
278        /// New edits supersede this run.
279        superseded: bool,
280    },
281    /// Read bounded stderr diagnostics from a byte offset.
282    Logs {
283        /// Job id.
284        id: String,
285        /// Byte offset.
286        offset: u64,
287    },
288    /// Read bounded JSON-lines target events from a byte offset.
289    Events {
290        /// Job id.
291        id: String,
292        /// Byte offset.
293        offset: u64,
294    },
295}
296
297/// A response or a stable user-facing error.
298#[derive(Debug, Clone, Serialize, Deserialize)]
299#[serde(tag = "response", content = "value", rename_all = "snake_case")]
300pub enum Response {
301    /// Optional preparation negotiation, status, or handoff acknowledgement.
302    Preparation(crate::preparation::Status),
303    /// Supported product contracts; does not claim an optional engine is installed.
304    Capabilities {
305        /// [`CAPABILITIES_VERSION`]; absent from 0.2 services, which decode as 1.
306        #[serde(default = "legacy_capabilities")]
307        capabilities_version: u32,
308        /// Independent proof stream version.
309        proof_version: u32,
310        /// Ordinary-job requirement attribution view version; absent on older services.
311        #[serde(default, skip_serializing_if = "Option::is_none")]
312        attribution_version: Option<u32>,
313        /// Non-stock submission modes are understood and never ignored.
314        /// Absent from services without the engine, which decode as false.
315        #[serde(default)]
316        repair: bool,
317        /// Direct-file jobs are understood; false on older endpoints.
318        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
319        standalone: bool,
320        /// Standalone repair is explicitly understood; absent on older endpoints.
321        #[serde(default, skip_serializing_if = "std::ops::Not::not")]
322        standalone_repair: bool,
323    },
324    /// Ordered, resumable proof observations.
325    ProofEvents(crate::proof::Page),
326    /// Exact establishing evidence for a failure or proof.
327    Explanation(Box<crate::evidence::Explanation>),
328    /// Submitter-attributed ordinary Verus evidence.
329    AttributedAssurance(Box<crate::attribution::View>),
330    /// Independently retained immutable evidence.
331    Baseline(Box<crate::evidence::Baseline>),
332    /// Immutable baseline names.
333    Baselines(Vec<String>),
334    /// Scoped, configuration-aware proof comparison.
335    Comparison(crate::evidence::Comparison),
336    /// One status.
337    Status(Status),
338    /// Retained jobs, oldest first.
339    List(Vec<Status>),
340    /// A result with its lifecycle and provenance.
341    Result(ResultDocument),
342    /// Diagnostics or target events.
343    Chunk(Chunk),
344    /// Stable error text, prefixed with a `SAIL` code.
345    Error(String),
346}
347
348#[derive(Serialize, Deserialize)]
349struct Envelope<T> {
350    version: u32,
351    body: T,
352}
353
354const fn legacy_capabilities() -> u32 {
355    1
356}
357
358/// Writes a bounded versioned frame.
359///
360/// # Errors
361/// Returns invalid data for oversized frames or serialization errors, or an I/O error.
362pub fn write_frame<T: Serialize>(writer: &mut impl Write, body: &T) -> io::Result<()> {
363    let bytes = serde_json::to_vec(&Envelope {
364        version: VERSION,
365        body,
366    })
367    .map_err(io::Error::other)?;
368    if bytes.len() > MAX_FRAME {
369        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
370    }
371    let size = u32::try_from(bytes.len()).map_err(io::Error::other)?;
372    writer.write_all(&size.to_be_bytes())?;
373    writer.write_all(&bytes)?;
374    writer.flush()
375}
376
377/// Reads a bounded frame, refusing unsupported versions before dispatch.
378///
379/// # Errors
380/// Returns invalid data for malformed, oversized, or unsupported frames, or an I/O error.
381pub fn read_frame<T: serde::de::DeserializeOwned>(reader: &mut impl Read) -> io::Result<T> {
382    let mut length = [0; 4];
383    reader.read_exact(&mut length)?;
384    let size = usize::try_from(u32::from_be_bytes(length)).map_err(io::Error::other)?;
385    if size > MAX_FRAME {
386        return Err(io::Error::other("SAIL0802: job frame exceeds limit"));
387    }
388    let mut bytes = vec![0; size];
389    reader.read_exact(&mut bytes)?;
390    let envelope: Envelope<T> = serde_json::from_slice(&bytes).map_err(io::Error::other)?;
391    if envelope.version != VERSION {
392        return Err(io::Error::other("SAIL0802: incompatible job protocol"));
393    }
394    Ok(envelope.body)
395}
396
397/// Resolve the configured cache root without accessing the filesystem.
398///
399/// # Errors
400/// Returns `SAIL3001` when no cache or home environment setting is available.
401pub fn cache_directory() -> io::Result<PathBuf> {
402    let var = |name: &str| std::env::var_os(name).filter(|value| !value.is_empty());
403    var("SAIL_CACHE_DIR")
404        .map(PathBuf::from)
405        .or_else(|| var("XDG_CACHE_HOME").map(|root| PathBuf::from(root).join("sail")))
406        .or_else(|| var("HOME").map(|root| PathBuf::from(root).join(".cache/sail")))
407        .ok_or_else(|| {
408            io::Error::other(
409                "error[SAIL3001]: none of SAIL_CACHE_DIR, XDG_CACHE_HOME or HOME is set",
410            )
411        })
412}
413
414/// The longest Unix socket path, in bytes, this platform accepts
415/// (`sun_path` less its terminating NUL: 108 bytes on Linux, 104 on macOS
416/// and the BSDs).
417pub const MAX_SOCKET_PATH: usize = if cfg!(target_os = "linux") { 107 } else { 103 };
418
419/// Default cache-service endpoint for the current protocol:
420/// `<cache>/daemon-v<N>-workspace-v2-proof-v1.sock`.
421///
422/// When that path, or the job endpoint beside it, would exceed
423/// [`MAX_SOCKET_PATH`] (a deep `HOME` or a long `SAIL_CACHE_DIR`), the
424/// endpoint moves to a private per-cache directory `/tmp/sail-<hash>/`,
425/// where `<hash>` names the cache. That directory is created mode 0700 and
426/// used only when it is a real directory that no other user can access and
427/// this user can write; otherwise the long path is returned unchanged, and
428/// starting the daemon reports that it is too long.
429#[must_use]
430pub fn default_cache_socket(cache: &Path) -> PathBuf {
431    let socket = cache.join(format!(
432        "daemon-v{}-workspace-v2-proof-v1.sock",
433        crate::protocol::PROTOCOL_VERSION
434    ));
435    if socket_fits(&socket) {
436        return socket;
437    }
438    short_socket(&socket).unwrap_or(socket)
439}
440
441/// Whether both the cache endpoint and its job endpoint fit in `sun_path`.
442#[must_use]
443pub fn socket_fits(cache_socket: &Path) -> bool {
444    let absolute = std::path::absolute(cache_socket).unwrap_or_else(|_| cache_socket.to_owned());
445    absolute.as_os_str().len() <= MAX_SOCKET_PATH
446        && socket_path(cache_socket).as_os_str().len() <= MAX_SOCKET_PATH
447}
448
449#[cfg(unix)]
450fn short_socket(socket: &Path) -> Option<PathBuf> {
451    use std::os::unix::fs::{DirBuilderExt as _, MetadataExt as _};
452    let name = socket.file_name()?;
453    let digest = sail_key::sha256(endpoint_path(socket).as_os_str().as_encoded_bytes());
454    let hash = digest
455        .iter()
456        .take(8)
457        .fold(String::new(), |mut value, byte| {
458            let _ = write!(value, "{byte:02x}");
459            value
460        });
461    let directory = Path::new("/tmp").join(format!("sail-{hash}"));
462    // An existing directory is accepted only when it is private.
463    let _ = std::fs::DirBuilder::new().mode(0o700).create(&directory);
464    let metadata = std::fs::symlink_metadata(&directory).ok()?;
465    if !metadata.is_dir() || metadata.mode() & 0o077 != 0 {
466        return None;
467    }
468    // Only its owner can create a file in a 0700 directory, so this proves
469    // the directory is this user's and no other user's daemon can be there.
470    let probe = directory.join(format!(".probe-{}", std::process::id()));
471    std::fs::File::create(&probe).ok()?;
472    std::fs::remove_file(&probe).ok()?;
473    let short = directory.join(name);
474    socket_fits(&short).then_some(short)
475}
476
477#[cfg(not(unix))]
478fn short_socket(_socket: &Path) -> Option<PathBuf> {
479    None
480}
481
482/// Resolve a cache endpoint using the caller's working directory.
483/// Relative cache roots and explicit overrides belong to that caller.
484#[must_use]
485pub fn cache_socket(cache: &Path, explicit: Option<&Path>, cwd: &Path) -> PathBuf {
486    // Anchor a relative cache first, so the length check sees the caller's path.
487    let socket = explicit.map_or_else(|| default_cache_socket(&cwd.join(cache)), Path::to_path_buf);
488    if socket.is_absolute() {
489        socket
490    } else {
491        cwd.join(socket)
492    }
493}
494
495/// Resolve the job endpoint with the same environment semantics as the CLI.
496///
497/// # Errors
498/// Returns the cache configuration error without starting a service.
499pub fn configured_socket(cwd: &Path) -> io::Result<PathBuf> {
500    let explicit = std::env::var_os("SAIL_DAEMON_SOCKET")
501        .filter(|value| !value.is_empty())
502        .map(PathBuf::from);
503    Ok(socket_path(&cache_socket(
504        &cache_directory()?,
505        explicit.as_deref(),
506        cwd,
507    )))
508}
509
510/// The job endpoint alongside a cache endpoint, without changing cache protocol.
511/// Relative paths and existing filesystem aliases identify the same endpoint.
512#[must_use]
513pub fn socket_path(cache_socket: &Path) -> PathBuf {
514    let cache_socket = endpoint_path(cache_socket);
515    let digest = sail_key::sha256(cache_socket.as_os_str().as_encoded_bytes());
516    let suffix = digest
517        .iter()
518        .take(4)
519        .fold(String::new(), |mut value, byte| {
520            let _ = write!(value, "{byte:02x}");
521            value
522        });
523    cache_socket.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
524}
525
526fn endpoint_path(path: &Path) -> PathBuf {
527    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
528    // Resolve the socket itself when it exists, including a symlink to a live
529    // endpoint. Before startup, resolve its nearest existing ancestor instead.
530    // This also covers aliases whose socket parent has not been created yet.
531    for ancestor in absolute.ancestors() {
532        if let Ok(resolved) = ancestor.canonicalize()
533            && let Ok(suffix) = absolute.strip_prefix(ancestor)
534        {
535            return if suffix.as_os_str().is_empty() {
536                resolved
537            } else {
538                resolved.join(suffix)
539            };
540        }
541    }
542    absolute
543}
544
545/// A timeout-bounded local client. Every call receives a complete fresh frame.
546#[cfg(unix)]
547#[derive(Debug, Clone)]
548pub struct Client {
549    socket: PathBuf,
550}
551#[cfg(unix)]
552impl Client {
553    /// Legacy attributed submission, retained for wire compatibility.
554    /// Services since 0.3 do not advertise this capability and refuse the call.
555    ///
556    /// # Errors
557    /// Refuses older services, unsupported modes and invalid attributions
558    /// without falling back to an unattributed submission.
559    pub fn submit_attributed(
560        &self,
561        submission: Submission,
562        requirements: Vec<crate::attribution::RequirementAttribution>,
563    ) -> io::Result<Status> {
564        let requirements = crate::attribution::canonical(requirements).map_err(io::Error::other)?;
565        if !crate::attribution::mode_supported(&submission.mode) {
566            return Err(io::Error::other(
567                "SAIL3160: requirement attribution applies only to stock and standalone jobs",
568            ));
569        }
570        self.require_attribution()?;
571        match self.call(&Request::SubmitAttributed {
572            submission,
573            requirements,
574        })? {
575            Response::Status(status) => Ok(status),
576            Response::Error(message) => Err(io::Error::other(message)),
577            _ => Err(io::Error::other(
578                "SAIL3160: unexpected attributed submission response",
579            )),
580        }
581    }
582
583    /// Legacy assurance read, retained for wire compatibility.
584    /// Services since 0.3 do not advertise this capability and refuse the call.
585    ///
586    /// # Errors
587    /// Refuses unsupported services, unknown or unattributed jobs and invalid evidence.
588    pub fn attributed_assurance(&self, id: &str) -> io::Result<crate::attribution::View> {
589        if id.is_empty() || id.len() > 256 || id.contains('\0') {
590            return Err(io::Error::other("SAIL3160: invalid assurance job identity"));
591        }
592        self.require_attribution()?;
593        match self.call(&Request::AttributedAssurance { id: id.into() })? {
594            Response::AttributedAssurance(view)
595                if view.version == crate::attribution::VERSION && view.job_id == id =>
596            {
597                Ok(*view)
598            }
599            Response::Error(message) => Err(io::Error::other(message)),
600            _ => Err(io::Error::other(
601                "SAIL3160: invalid attributed assurance response",
602            )),
603        }
604    }
605
606    fn require_attribution(&self) -> io::Result<()> {
607        if matches!(
608            self.call(&Request::Capabilities)?,
609            Response::Capabilities {
610                attribution_version: Some(crate::attribution::VERSION),
611                ..
612            }
613        ) {
614            Ok(())
615        } else {
616            Err(io::Error::other(
617                "SAIL3160: endpoint does not support requirement attribution; restart Sail's daemon",
618            ))
619        }
620    }
621
622    /// A client for `socket`; no connection or side effect until a call.
623    #[must_use]
624    pub fn new(socket: impl Into<PathBuf>) -> Self {
625        Self {
626            socket: socket.into(),
627        }
628    }
629    /// Sends one RPC with five-second I/O deadlines.
630    ///
631    /// # Errors
632    /// Returns connection, framing, timeout, or server errors.
633    pub fn call(&self, request: &Request) -> io::Result<Response> {
634        self.call_with(request, |_| {})
635    }
636    /// Like [`Client::call`], first handing `connected` a clone of the
637    /// connected stream. Another thread can shut that clone down to abandon
638    /// the call; `connected` is not called when the connection fails.
639    ///
640    /// # Errors
641    /// Returns connection, framing, timeout, or server errors.
642    pub fn call_with(
643        &self,
644        request: &Request,
645        connected: impl FnOnce(std::os::unix::net::UnixStream),
646    ) -> io::Result<Response> {
647        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::Interactive | Mode::Repair(_)))
648            && !matches!(
649                self.call(&Request::Capabilities)?,
650                Response::Capabilities {
651                    proof_version: crate::proof::VERSION,
652                    repair: true,
653                    ..
654                }
655            )
656        {
657            return Err(io::Error::other(
658                "SAIL0903: endpoint does not support proof/repair contracts",
659            ));
660        }
661        if matches!(request, Request::Submit { submission } if submission.mode == Mode::Standalone)
662            && !matches!(
663                self.call(&Request::Capabilities)?,
664                Response::Capabilities {
665                    standalone: true,
666                    ..
667                }
668            )
669        {
670            return Err(io::Error::other(
671                "SAIL3150: endpoint does not support standalone file jobs; restart Sail's daemon",
672            ));
673        }
674        if matches!(request, Request::Submit { submission } if matches!(submission.mode, Mode::StandaloneRepair { .. }))
675            && !matches!(
676                self.call(&Request::Capabilities)?,
677                Response::Capabilities {
678                    proof_version: crate::proof::VERSION,
679                    repair: true,
680                    standalone_repair: true,
681                    ..
682                }
683            )
684        {
685            return Err(io::Error::other(
686                "SAIL3150: endpoint does not support standalone repair; restart Sail's daemon",
687            ));
688        }
689        let mut stream =
690            crate::client::connect_stream(&self.socket, std::time::Duration::from_secs(5))?;
691        connected(stream.try_clone()?);
692        write_frame(&mut stream, request)?;
693        match read_frame(&mut stream)? {
694            Response::Error(message) => Err(io::Error::other(message)),
695            response => Ok(response),
696        }
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703    #[test]
704    fn baseline_read_has_exact_additive_wire_identity() {
705        let request = Request::GetBaseline {
706            name: "--json".into(),
707        };
708        assert_eq!(
709            serde_json::to_value(&request).unwrap_or_else(|error| unreachable!("{error}")),
710            serde_json::json!({"operation":"get_baseline","name":"--json"})
711        );
712        let mut bytes = Vec::new();
713        assert!(write_frame(&mut bytes, &request).is_ok());
714        assert!(matches!(read_frame::<Request>(&mut bytes.as_slice()),
715            Ok(Request::GetBaseline { name }) if name == "--json"));
716        assert!(
717            serde_json::from_value::<Request>(
718                serde_json::json!({"operation":"unknown_baseline","name":"--json"})
719            )
720            .is_err()
721        );
722    }
723
724    #[test]
725    fn endpoint_resolution_anchors_only_relative_settings_to_each_caller() {
726        let a = Path::new("/workspace/a");
727        let b = Path::new("/workspace/b");
728        assert_ne!(
729            cache_socket(Path::new("cache"), None, a),
730            cache_socket(Path::new("cache"), None, b)
731        );
732        assert_eq!(
733            cache_socket(Path::new("/shared/cache"), None, a),
734            cache_socket(Path::new("/shared/cache"), None, b)
735        );
736        assert_eq!(
737            cache_socket(
738                Path::new("ignored"),
739                Some(Path::new("sockets/service.sock")),
740                a
741            ),
742            a.join("sockets/service.sock")
743        );
744        assert_eq!(
745            cache_socket(
746                Path::new("ignored"),
747                Some(Path::new("/explicit/service.sock")),
748                b
749            ),
750            Path::new("/explicit/service.sock")
751        );
752        assert_eq!(
753            cache_socket(Path::new("cache"), None, a),
754            default_cache_socket(&a.join("cache"))
755        );
756    }
757
758    #[cfg(unix)]
759    #[test]
760    fn endpoint_aliases_share_the_same_namespace_before_and_after_startup() {
761        use std::os::unix::fs::symlink;
762        let root = std::env::temp_dir().join(format!("sail-job-socket-{}", std::process::id()));
763        let canonical = root.join("actual");
764        assert!(std::fs::create_dir_all(&canonical).is_ok());
765        let canonical = canonical
766            .canonicalize()
767            .unwrap_or_else(|e| unreachable!("{e}"));
768        let alias = root.join("alias");
769        assert!(symlink(&canonical, &alias).is_ok());
770        let endpoint = canonical.join("nested/cache.sock");
771        assert_eq!(
772            socket_path(&endpoint),
773            socket_path(&alias.join("nested/cache.sock"))
774        );
775        assert!(std::fs::create_dir_all(endpoint.parent().unwrap_or(&canonical)).is_ok());
776        let current = std::env::current_dir().unwrap_or_else(|e| unreachable!("{e}"));
777        let relative = PathBuf::from("../".repeat(current.components().count().saturating_sub(1)))
778            .join(endpoint.strip_prefix("/").unwrap_or(&endpoint));
779        assert_eq!(socket_path(&endpoint), socket_path(&relative));
780        let listener = std::os::unix::net::UnixListener::bind(&endpoint)
781            .unwrap_or_else(|e| unreachable!("{e}"));
782        let socket_alias = root.join("cache-alias.sock");
783        assert!(symlink(&endpoint, &socket_alias).is_ok());
784        assert_eq!(socket_path(&endpoint), socket_path(&socket_alias));
785        let hash = sail_key::sha256(endpoint.as_os_str().as_encoded_bytes());
786        let suffix = hash.iter().take(4).fold(String::new(), |mut s, b| {
787            let _ = write!(s, "{b:02x}");
788            s
789        });
790        assert_eq!(
791            socket_path(&endpoint),
792            endpoint.with_file_name(format!("jobs-v1-proof-v1-{suffix}.sock"))
793        );
794        drop(listener);
795        let _ = std::fs::remove_dir_all(root);
796    }
797    /// A deep cache directory (as under a long `HOME` or `SAIL_CACHE_DIR`)
798    /// gets a short, private, per-cache endpoint; a short one is unchanged.
799    #[cfg(unix)]
800    #[test]
801    fn long_cache_paths_get_a_short_private_socket() {
802        use std::os::unix::fs::MetadataExt as _;
803        let short = Path::new("/tmp/c");
804        assert_eq!(
805            default_cache_socket(short),
806            short.join(format!(
807                "daemon-v{}-workspace-v2-proof-v1.sock",
808                crate::protocol::PROTOCOL_VERSION
809            ))
810        );
811        let deep = Path::new("/nonexistent").join("d".repeat(120));
812        let socket = default_cache_socket(&deep);
813        assert!(socket.starts_with("/tmp"), "{}", socket.display());
814        assert!(socket_fits(&socket));
815        assert_eq!(socket, default_cache_socket(&deep), "deterministic");
816        let directory = socket.parent().unwrap_or(Path::new("/"));
817        let mode = std::fs::metadata(directory).map(|m| m.mode() & 0o777);
818        assert!(matches!(mode, Ok(0o700)), "{mode:?}");
819        assert_ne!(
820            socket,
821            default_cache_socket(&Path::new("/nonexistent").join("e".repeat(120))),
822            "one directory per cache"
823        );
824        // Another user's (here: a non-private) directory is never used.
825        assert!(
826            std::fs::set_permissions(
827                directory,
828                std::os::unix::fs::PermissionsExt::from_mode(0o755)
829            )
830            .is_ok()
831        );
832        assert!(!default_cache_socket(&deep).starts_with("/tmp"));
833        let _ = std::fs::remove_dir_all(directory);
834    }
835
836    #[test]
837    fn versions_and_size_are_checked() {
838        let mut bytes = Vec::new();
839        assert!(write_frame(&mut bytes, &Request::List { project_dir: None }).is_ok());
840        assert!(matches!(
841            read_frame::<Request>(&mut bytes.as_slice()),
842            Ok(Request::List { .. })
843        ));
844        let huge = u32::MAX.to_be_bytes();
845        assert!(read_frame::<Request>(&mut huge.as_slice()).is_err());
846        let body = br#"{"version":2,"body":{"operation":"list","project_dir":null}}"#;
847        let mut wrong = u32::try_from(body.len())
848            .unwrap_or(0)
849            .to_be_bytes()
850            .to_vec();
851        wrong.extend_from_slice(body);
852        assert!(read_frame::<Request>(&mut wrong.as_slice()).is_err());
853    }
854}