Skip to main content

sail_api/runtime/transport/
client.rs

1//! Synchronous client with capability negotiation and responsive cancellation.
2use super::{
3    Deadline, IO_TIMEOUT, MAX_REQUEST_BYTES, MAX_RESPONSE_BYTES, Request, Response, read_frame,
4    validate_socket, write_frame,
5};
6use crate::runtime::{
7    Capabilities, Input, Request as RuntimeRequest, Response as RuntimeResponse, VERSION,
8};
9use socket2::{Domain, SockAddr, Socket, Type};
10use std::{
11    fmt::Write as _,
12    io::{self, Read as _},
13    net::Shutdown,
14    os::unix::net::UnixStream,
15    path::PathBuf,
16    sync::mpsc,
17    time::Duration,
18};
19
20/// Owner-private runtime client; no solver process or fallback is ever started here.
21#[derive(Clone, Debug)]
22pub struct Client {
23    socket: PathBuf,
24}
25
26fn unavailable(error: impl std::fmt::Display) -> io::Error {
27    io::Error::other(format!(
28        "SAIL6201: runtime endpoint unavailable or incompatible; restart sail serve: {error}"
29    ))
30}
31
32impl Client {
33    /// Construct a side-effect-free client for the independently versioned endpoint.
34    #[must_use]
35    pub fn new(socket: impl Into<PathBuf>) -> Self {
36        Self {
37            socket: socket.into(),
38        }
39    }
40
41    fn connect(&self) -> io::Result<UnixStream> {
42        validate_socket(&self.socket).map_err(unavailable)?;
43        let socket = Socket::new(Domain::UNIX, Type::STREAM, None)?;
44        socket
45            .connect_timeout(&SockAddr::unix(&self.socket)?, IO_TIMEOUT)
46            .map_err(unavailable)?;
47        let fd: std::os::fd::OwnedFd = socket.into();
48        Ok(UnixStream::from(fd))
49    }
50
51    fn call(&self, request: &Request) -> io::Result<Response> {
52        let stream = self.connect()?;
53        let mut deadline = Deadline::new(&stream, IO_TIMEOUT);
54        write_frame(&mut deadline, request, MAX_REQUEST_BYTES)?;
55        read_frame(&mut deadline, MAX_RESPONSE_BYTES)
56    }
57
58    /// Negotiate implementation and actual installation readiness without checking a theorem.
59    ///
60    /// # Errors
61    /// Reports absent, incompatible, malformed or failed services explicitly.
62    pub fn capabilities(&self) -> io::Result<Capabilities> {
63        match self.call(&Request::Capabilities)? {
64            Response::Capabilities { capabilities } if capabilities.version == VERSION => {
65                Ok(capabilities)
66            }
67            Response::Error { error } => Err(io::Error::other(error)),
68            _ => Err(unavailable("unexpected capability response")),
69        }
70    }
71
72    /// Cancel an exact active transport identity on a separate control connection.
73    ///
74    /// # Errors
75    /// Returns connection or protocol failures instead of claiming cancellation.
76    pub fn cancel(&self, id: &str) -> io::Result<bool> {
77        match self.call(&Request::Cancel { id: id.into() })? {
78            Response::Cancelled { id: actual, found } if actual == id => Ok(found),
79            Response::Error { error } => Err(io::Error::other(error)),
80            _ => Err(unavailable("unexpected cancellation response")),
81        }
82    }
83
84    /// Execute through the service with no local solver fallback.
85    ///
86    /// # Errors
87    /// Returns admission, connection and protocol failures explicitly.
88    pub fn execute(&self, request: &RuntimeRequest) -> io::Result<RuntimeResponse> {
89        self.execute_cancellable(request, || false)
90    }
91
92    /// Execute while polling caller cancellation; all started I/O workers are joined.
93    ///
94    /// # Errors
95    /// Returns admission, cancellation transport or service failures explicitly.
96    pub fn execute_cancellable(
97        &self,
98        request: &RuntimeRequest,
99        cancelled: impl Fn() -> bool,
100    ) -> io::Result<RuntimeResponse> {
101        if cancelled() {
102            return Err(io::Error::new(
103                io::ErrorKind::Interrupted,
104                "SAIL6201: runtime request cancelled before dispatch",
105            ));
106        }
107        let capabilities = self.capabilities()?;
108        if matches!(request.input, Input::Temporal { .. })
109            && !capabilities
110                .temporal
111                .as_ref()
112                .is_some_and(|c| c.implemented)
113        {
114            return Err(unavailable(
115                "running service has no native temporal endpoint",
116            ));
117        }
118        let mut random = [0_u8; 16];
119        std::fs::File::open("/dev/urandom")?.read_exact(&mut random)?;
120        let id = random.iter().fold(String::new(), |mut id, byte| {
121            let _ = write!(id, "{byte:02x}");
122            id
123        });
124        let stream = self.connect()?;
125        write_frame(
126            &mut Deadline::new(&stream, IO_TIMEOUT),
127            &Request::Execute {
128                id: id.clone(),
129                temporal_replay: matches!(request.input, Input::Temporal { .. })
130                    && capabilities
131                        .temporal
132                        .as_ref()
133                        .is_some_and(|c| c.replay_context.is_some()),
134                request: request.clone(),
135            },
136            MAX_REQUEST_BYTES,
137        )?;
138        let wait = match &request.input {
139            Input::Smt { queries } => queries.iter().try_fold(10_000_u64, |sum, query| {
140                sum.checked_add(query.limits.wall_time_ms)
141            }),
142            Input::Temporal { job } => job.wall_time_ms.checked_add(10_000),
143        }
144        .filter(|millis| *millis <= 20_000_000)
145        .ok_or_else(|| io::Error::other("SAIL6201: request execution deadline is excessive"))?;
146        let response = std::thread::scope(|scope| {
147            let (transmit, receive) = mpsc::channel();
148            let read_stream = &stream;
149            let worker = std::thread::Builder::new()
150                .name("sail-runtime-client".into())
151                .spawn_scoped(scope, move || {
152                    let result = read_frame(
153                        &mut Deadline::new(read_stream, Duration::from_millis(wait)),
154                        MAX_RESPONSE_BYTES,
155                    );
156                    let _ = transmit.send(result);
157                })?;
158            let mut cancel_sent = false;
159            let result = loop {
160                if cancelled() && !cancel_sent {
161                    match self.cancel(&id) {
162                        Ok(found) => cancel_sent = found,
163                        Err(error) => {
164                            let _ = stream.shutdown(Shutdown::Both);
165                            break Err(error);
166                        }
167                    }
168                }
169                match receive.recv_timeout(Duration::from_millis(20)) {
170                    Ok(response) => break response,
171                    Err(mpsc::RecvTimeoutError::Timeout) => {}
172                    Err(mpsc::RecvTimeoutError::Disconnected) => {
173                        break Err(unavailable("response worker stopped"));
174                    }
175                }
176            };
177            worker
178                .join()
179                .map_err(|_| unavailable("response worker panicked"))?;
180            result
181        })?;
182        match response {
183            Response::Completed {
184                id: actual,
185                response,
186            } if actual == id && response.version == VERSION => {
187                validate_payload(request, &response, &capabilities)?;
188                Ok(response)
189            }
190            Response::Error { error } => Err(io::Error::other(error)),
191            _ => Err(unavailable(
192                "unexpected execution response identity or version",
193            )),
194        }
195    }
196}
197
198pub(super) fn validate_payload(
199    request: &RuntimeRequest,
200    response: &RuntimeResponse,
201    capabilities: &Capabilities,
202) -> io::Result<()> {
203    use crate::runtime::{Answer, Outcome, Output};
204    let (queries, results) = match (&request.input, &response.output) {
205        (Input::Temporal { job }, Output::Temporal { result }) => {
206            return validate_temporal(job, result, capabilities);
207        }
208        (Input::Smt { queries }, Output::Smt { results }) => (queries, results),
209        _ => return Err(unavailable("runtime response family differs")),
210    };
211    if results.len() != queries.len() {
212        return Err(unavailable("runtime query result count changed"));
213    }
214    for (query, result) in queries.iter().zip(results) {
215        let digest = sail_key::sha256(query.script.as_bytes()).iter().fold(
216            String::new(),
217            |mut text, byte| {
218                let _ = write!(text, "{byte:02x}");
219                text
220            },
221        );
222        if result.obligation_id != query.obligation_id
223            || result.requirement_ids != query.requirement_ids
224            || result.backend != query.backend
225            || result.script_sha256 != digest
226            || result.limits != query.limits
227            || result.stdout.len() > query.limits.output_bytes
228            || result.stderr.len() > query.limits.output_bytes
229        {
230            return Err(unavailable(
231                "runtime result changed request attribution, content or limits",
232            ));
233        }
234        if result.outcome == Outcome::Completed {
235            let identity = capabilities
236                .backends
237                .iter()
238                .find(|backend| backend.backend == query.backend)
239                .and_then(|backend| backend.solver.as_ref());
240            if result.checks.is_empty()
241                || result.stdout.is_empty()
242                || !result.stderr.is_empty()
243                || result.error.is_some()
244                || identity.is_none()
245                || result.solver.as_ref() != identity
246                || result
247                    .checks
248                    .windows(2)
249                    .any(|pair| pair[0].command_index >= pair[1].command_index)
250                || (result.cache_hit
251                    && result
252                        .checks
253                        .iter()
254                        .any(|check| check.answer == Answer::Unknown))
255            {
256                return Err(unavailable(
257                    "completed runtime result lacks valid checks or negotiated solver identity",
258                ));
259            }
260            for (index, check) in result.checks.iter().enumerate() {
261                let next = result
262                    .checks
263                    .get(index + 1)
264                    .map_or(usize::MAX, |check| check.command_index);
265                if check.products.iter().any(|product| {
266                    product.command_index <= check.command_index || product.command_index >= next
267                }) || check
268                    .products
269                    .windows(2)
270                    .any(|pair| pair[0].command_index >= pair[1].command_index)
271                {
272                    return Err(unavailable("runtime products changed check ordering"));
273                }
274            }
275        } else if !result.checks.is_empty() || result.cache_hit || result.error.is_none() {
276            return Err(unavailable(
277                "failed runtime execution carries successful check evidence",
278            ));
279        }
280    }
281    Ok(())
282}
283
284fn validate_temporal(
285    job: &crate::temporal::Job,
286    result: &crate::temporal::Result,
287    capabilities: &Capabilities,
288) -> io::Result<()> {
289    use crate::runtime::Outcome;
290    let capability = capabilities
291        .temporal
292        .as_ref()
293        .ok_or_else(|| unavailable("temporal capability missing"))?;
294    if result.obligation_id != job.obligation_id
295        || result.requirement_ids != job.requirement_ids
296        || result.request_sha256
297            != crate::temporal::request_sha256(&job.request).map_err(unavailable)?
298        || result.backend_revision != capability.backend_revision
299        || result.wall_time_ms != job.wall_time_ms
300        || result.cache_hit != result.cache_key.is_some()
301    {
302        return Err(unavailable(
303            "temporal result attribution, content or limits differ",
304        ));
305    }
306    if result.outcome == Outcome::Completed {
307        let response = result
308            .response
309            .as_ref()
310            .ok_or_else(|| unavailable("completed temporal execution lacks native evidence"))?;
311        if !capability.installed
312            || result.worker_sha256.is_none()
313            || result.worker_sha256 != capability.worker_sha256
314            || result.error.is_some()
315        {
316            return Err(unavailable(
317                "temporal result lacks negotiated worker identity",
318            ));
319        }
320        if let Some(key) = &result.cache_key {
321            let context = capability
322                .replay_context
323                .as_deref()
324                .ok_or_else(|| unavailable("temporal replay was not negotiated"))?;
325            if !matches!(
326                job.request.operation,
327                crate::temporal::Operation::Check { .. }
328            ) || !matches!(
329                response.outcome,
330                crate::temporal::Outcome::Holds | crate::temporal::Outcome::Refuted
331            ) || key
332                != &crate::temporal::check_receipt_key(
333                    context,
334                    &result.request_sha256,
335                    job.wall_time_ms,
336                )
337                .to_string()
338            {
339                return Err(unavailable(
340                    "temporal replay evidence or receipt key differs",
341                ));
342            }
343        }
344        crate::temporal::validate_response(&job.request, response).map_err(unavailable)?;
345    } else if result.cache_hit || result.response.is_some() || result.error.is_none() {
346        return Err(unavailable(
347            "failed temporal execution supplied logical evidence",
348        ));
349    }
350    Ok(())
351}