Skip to main content

dive_api/
core_worker.rs

1//! Public independently initialized pure Core worker preparation.
2
3use std::net::TcpListener;
4use std::path::Path;
5use std::sync::Arc;
6use std::time::Duration;
7
8use crate::{ApiError, CheckRequest, DistributedUsage};
9
10fn rejected(message: impl Into<String>) -> ApiError {
11    ApiError::Rejected {
12        message: message.into(),
13    }
14}
15
16// The executable hash pins this representation. Include the full evaluator
17// policy here without changing the existing checkpoint identity or its
18// compatibility rules; search admission/transport limits remain coordinator
19// policy and never alter the worker's source semantics.
20pub(crate) fn identity(
21    ir: &dive_ir::Ir,
22    model: &dive_config::ModelConfig,
23    options: &dive_runtime::CheckOptions,
24    config_hash: &str,
25    opts: dive_core::Opts,
26) -> Result<Vec<u8>, dive_runtime::Verdict> {
27    let request = dive_runtime::checkpoint::Request {
28        path: std::path::PathBuf::new(),
29        action: dive_runtime::checkpoint::Action::PauseAfterLevels(0),
30        counters: dive_runtime::checkpoint::Counters::Retain,
31        config_source_sha256: Some(config_hash.into()),
32    };
33    let mut identity =
34        dive_runtime::checkpoint::owned_identity(ir, model, options, &request, &opts.describe())?;
35    identity.extend_from_slice(
36        format!(
37            "\ndistributed-policy-0151-v1/{:?}/{:?}",
38            options.eval, options.symmetry_liveness
39        )
40        .as_bytes(),
41    );
42    Ok(identity)
43}
44
45/// An independently loaded, bound and compiled worker with no received-code or
46/// host-I/O grants. Assigned source expansion requires an authenticated session;
47/// local constant/ASSUME binding and compilation happen during preparation.
48pub struct CoreWorker {
49    inner: dive_explore::distributed::Worker,
50}
51impl CoreWorker {
52    /// Serves authenticated work from the supplied listener until the caller
53    /// stops it or `max_units` complete. This never creates a model verdict.
54    ///
55    /// # Errors
56    /// Listener/setup failures. Invalid sessions are rejected in worker facts.
57    pub fn serve(
58        &self,
59        listener: &TcpListener,
60        max_units: Option<u64>,
61        stop: &(dyn Fn() -> bool + Sync),
62    ) -> Result<DistributedUsage, ApiError> {
63        std::thread::scope(|scope| {
64            std::thread::Builder::new()
65                .stack_size(dive_eval::RECOMMENDED_STACK)
66                .spawn_scoped(scope, || self.inner.serve(listener, max_units, stop))
67                .map_err(|e| rejected(format!("worker execution thread: {e}")))?
68                .join()
69                .map_err(|_| rejected("worker execution thread panicked"))?
70                .map_err(|e| rejected(e.message()))
71        })
72    }
73}
74
75/// Independently prepares the same pure Core model as a distributed coordinator.
76///
77/// The source/config, executable, seed/fingerprint, value policy, Core switches
78/// and compiled startup are pinned before receiving any work. The local key file
79/// must hold exactly 32 secret bytes; work messages cannot choose paths or code.
80/// Both worker and coordinator require explicit seed and fingerprint options.
81///
82/// ```no_run
83/// use dive_api::{CheckRequest, prepare_core_worker};
84/// use std::{net::TcpListener, path::Path, time::Duration};
85/// let request = CheckRequest {
86///     file: "Counter.tla".into(), seed: Some(0), fp: Some(0),
87///     ..CheckRequest::default()
88/// };
89/// let worker = prepare_core_worker(&request, Path::new("worker.key"), Duration::from_secs(5))?;
90/// let listener = TcpListener::bind("127.0.0.1:7801")?;
91/// let facts = worker.serve(&listener, Some(5), &|| false)?;
92/// assert!(facts.completed_units <= 5); // Work facts never prove the model.
93/// # Ok::<(), Box<dyn std::error::Error>>(())
94/// ```
95///
96/// # Errors
97/// Source/configuration errors, effects, unimplemented combinations, compilation,
98/// private protocol admission, key-file or identity failures.
99pub fn prepare_core_worker(
100    request: &CheckRequest,
101    key_file: &Path,
102    timeout: Duration,
103) -> Result<CoreWorker, ApiError> {
104    std::thread::scope(|scope| {
105        std::thread::Builder::new()
106            .stack_size(dive_eval::RECOMMENDED_STACK)
107            .spawn_scoped(scope, || prepare_inner(request, key_file, timeout))
108            .map_err(|e| rejected(format!("worker preparation thread: {e}")))?
109            .join()
110            .map_err(|_| rejected("worker preparation thread panicked"))?
111    })
112}
113
114fn admit_request(request: &CheckRequest) -> Result<(), ApiError> {
115    if request.debugger.is_some() {
116        return Err(ApiError::Unsupported {
117            feature: "worker preparation with compiled debugger is not implemented".into(),
118        });
119    }
120    if request.store_compact_bytes.is_some() {
121        return Err(ApiError::Unsupported {
122            feature: "worker preparation with Store reclamation is not implemented".into(),
123        });
124    }
125    if request.tlc_coverage {
126        return Err(ApiError::Unsupported {
127            feature: "worker preparation with TLC logical coverage is not implemented".into(),
128        });
129    }
130    if request.seed.is_none()
131        || request.fp.is_none()
132        || !request.host_access.is_empty()
133        || request.distributed.is_some()
134        || request.source_coverage
135        || request.core_sample.is_some()
136        || request.temporal_refusal.is_some()
137        || request.seen_disk.is_some()
138        || request.candidate_memory_bytes.is_some()
139        || request.candidate_directory.is_some()
140        || request.frontier_memory_bytes.is_some()
141        || request.frontier_directory.is_some()
142        || request.predecessor_memory_bytes.is_some()
143        || request.predecessor_directory.is_some()
144        || request.sequential
145        || request.chaos.is_some()
146        || request.max_states.is_some()
147        || request.max_depth.is_some()
148        || request.time_limit != crate::BudgetSetting::Default
149        || request.max_memory != crate::BudgetSetting::Default
150        || request.workers.is_some_and(|workers| workers != 1)
151    {
152        return Err(ApiError::Unsupported{feature:"worker preparation requires explicit seed/fp and pure ordinary Core roles; coordinator search/storage/coverage options are unsupported".into()});
153    }
154    Ok(())
155}
156
157fn preparation_refusal(verdict: dive_runtime::Verdict) -> ApiError {
158    match verdict {
159        dive_runtime::Verdict::Unsupported { feature }
160            if feature.starts_with("temporal properties") =>
161        {
162            ApiError::Unsupported {
163                feature: format!(
164                    "worker preparation with temporal properties is not implemented ({feature})"
165                ),
166            }
167        }
168        dive_runtime::Verdict::Unsupported { feature } => ApiError::Unsupported {
169            feature: format!("worker preparation: {feature}"),
170        },
171        verdict => stopped_before_serving("worker preparation", &verdict),
172    }
173}
174
175/// A worker whose own start-up (assumptions, constants, admission) ended in
176/// something other than a refusal cannot serve units: name the verdict and its
177/// message the way `dive check` would, rather than labelling it unsupported.
178fn stopped_before_serving(stage: &str, verdict: &dive_runtime::Verdict) -> ApiError {
179    use dive_runtime::Verdict as V;
180    let detail = match verdict {
181        V::AssumptionFalse { message, .. }
182        | V::PostconditionFalse { message, .. }
183        | V::ModelError { message, .. }
184        | V::NotCompletelySpecified { message, .. }
185        | V::EvaluationError { message, .. }
186        | V::ResourceLimit { message }
187        | V::InternalError { message } => Some(message.clone()),
188        V::Unsupported { feature } => Some(feature.clone()),
189        V::Stopped(stopped) => Some(stopped.to_string()),
190        V::BudgetMeasurement { error } => Some(error.to_string()),
191        V::InvariantViolated { property, .. }
192        | V::PropertyViolatedInitially { property }
193        | V::ActionPropertyViolated { property } => Some(property.clone()),
194        _ => None,
195    };
196    let kind = verdict.kind();
197    rejected(match detail {
198        Some(detail) => format!(
199            "{stage} stopped with {kind} before serving units (run `dive check` on the model \
200             to see the full report): {}",
201            detail.trim_end()
202        ),
203        None => format!("{stage} stopped with {kind} before serving units"),
204    })
205}
206
207fn prepare_inner(
208    request: &CheckRequest,
209    key_file: &Path,
210    timeout: Duration,
211) -> Result<CoreWorker, ApiError> {
212    admit_request(request)?;
213    let analysis = crate::analyze_file(
214        &request.file,
215        &crate::AnalyzeOptions {
216            library_paths: request.library_paths.clone(),
217            after_standard: request.module_paths.clone(),
218        },
219    )?;
220    if !analysis.accepted() {
221        return Err(rejected(analysis.render_human()));
222    }
223    let ir = Arc::new(
224        dive_ir::lower(analysis.analysis())
225            .map_err(|e| rejected(format!("worker lowering: {e}")))?,
226    );
227    let config_path = request
228        .config
229        .clone()
230        .unwrap_or_else(|| request.file.with_extension("cfg"));
231    let config = crate::parse_config_file(&config_path)?;
232    let model = config
233        .config()
234        .ok_or_else(|| rejected(config.render_human()))?;
235    let seed = request.seed.ok_or_else(|| rejected("worker seed"))?;
236    let fp = request.fp.ok_or_else(|| rejected("worker fingerprint"))?;
237    let mut options = if request.compat_tlc {
238        dive_runtime::CheckOptions::tlc(fp, seed)
239    } else {
240        let mut options = dive_runtime::CheckOptions::dive(seed);
241        options.fp_index = fp;
242        options
243    };
244    options.no_deadlock = request.no_deadlock;
245    options.store = match request.store {
246        crate::Store::Fingerprint => dive_store::StoreMode::Fingerprint,
247        crate::Store::Exact => dive_store::StoreMode::Exact,
248    };
249    if let Some(composition) = request.action_composition {
250        options.eval.action_composition = composition;
251    }
252    if let Some(policy) = request.symmetry_liveness {
253        options.symmetry_liveness = policy;
254    }
255    let opts = std::env::var("DIVE_CORE_OPT")
256        .ok()
257        .map_or_else(
258            || Ok(dive_core::Opts::default()),
259            |s| dive_core::Opts::parse(&s),
260        )
261        .map_err(|e| ApiError::Unsupported {
262            feature: format!("worker Core switches: {e}"),
263        })?;
264    if let Some(feature) = crate::core_engine::option_refusal(&options, request.compat_tlc) {
265        return Err(ApiError::Unsupported { feature });
266    }
267    let prepared =
268        crate::core_engine::prepare(&ir, model, &options, request.compat_tlc, opts, false)
269            .map_err(|r| preparation_refusal(r.verdict))?;
270
271    if let Some(feature) =
272        crate::core_engine::distributed_model_refusal(&prepared.plan, &prepared.model)
273    {
274        return Err(ApiError::Unsupported {
275            feature: feature.replacen("distributed safety", "worker preparation", 1),
276        });
277    }
278    let identity = identity(
279        &ir,
280        model,
281        &options,
282        &dive_runtime::checkpoint::config_source_hash(config.source_bytes()),
283        opts,
284    )
285    .map_err(|v| match v {
286        dive_runtime::Verdict::Unsupported { feature } => ApiError::Unsupported {
287            feature: format!("worker identity admission: {feature}"),
288        },
289        verdict => stopped_before_serving("worker identity admission", &verdict),
290    })?;
291    let inner = dive_explore::distributed::Worker::new(
292        prepared.plan,
293        prepared.store,
294        opts,
295        &identity,
296        key_file,
297        timeout,
298    )
299    .map_err(|e| rejected(e.message()))?;
300    Ok(CoreWorker { inner })
301}