Skip to main content

lean_ctx/core/hive/compute/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Optional Task Compute, engine side (Release C, BAUPLAN v1.1 §9; C0 2.x
3//! `schemas/compute.schema.json`, E47–E52).
4//!
5//! An agent of this machine hands one clearly defined job (tests, static
6//! analysis, an index build) of the checkout it works in to an isolated
7//! sandbox of its Hive workspace and gets a bounded result back. No model
8//! runs there (no Agent Compute).
9//!
10//! The rules the engine keeps:
11//! - Only a C0 2.x Hive is asked: an engine enrolled with a 1.x Hive
12//!   (prod before the cutover) answers "not available" without a request.
13//!   A 2.x Hive with Task Compute switched off answers every route `404
14//!   feature_disabled`, shown as "Task Compute is not enabled for this
15//!   workspace"; one without the routes as "not available".
16//! - The job goes out under this engine's lease (right `tasks.work`) for the
17//!   vault this checkout is linked to; the server enforces the plan, the
18//!   workspace's hard caps and its prepaid credit. `credit_exhausted` and
19//!   `cap_reached` are shown with their numbers; nothing is retried.
20//! - Before anything leaves, the request is checked against the contract
21//!   (bounds, network allowlist, the budget covers the reserve).
22//! - Inputs are one deterministic, screened bundle of the checkout
23//!   ([`bundle`]); a bundle Hive already holds is not sent again.
24//! - Results are written only below a PathJail-checked directory of the
25//!   checkout, every artifact checked against its digest; text from the job
26//!   (summary, log tail) reaches an agent fenced as foreign data.
27//! - No telemetry; output is a function of the job and its result.
28
29pub mod bundle;
30mod client;
31pub mod render;
32
33use std::collections::BTreeMap;
34use std::path::{Path, PathBuf};
35use std::time::{Duration, Instant};
36
37use chrono::Utc;
38use serde::{Deserialize, Serialize};
39
40use crate::core::hive::HiveError;
41use crate::core::hive::tasks::{Connected, connected};
42use lean_ctx_protocol::hive::compute::{
43    COMPUTE_JOB_SCHEMA, ComputeBudgetV1, ComputeCommandV1, ComputeInputsV1, ComputeJobV1,
44    ComputeResourcesV1, ComputeResultResponseV1, ComputeSubmitRequestV1, INPUTS_VERSION, JobType,
45    MAX_LOG_BYTES, ResultFormat, content_digest, reserve_for,
46};
47use lean_ctx_protocol::hive::lease::HiveRight;
48
49pub use bundle::{Bundle, BundleReport, BundleRules};
50
51/// Time one JSON call may take in all.
52pub const CALL_BUDGET: Duration = Duration::from_secs(15);
53/// Time a bundle upload may take (up to 64 MiB).
54pub const UPLOAD_BUDGET: Duration = Duration::from_secs(180);
55/// Time one artifact download may take.
56pub const DOWNLOAD_BUDGET: Duration = Duration::from_secs(120);
57/// A bundle Hive holds is sent again this long before it expires there.
58const REUPLOAD_MARGIN_MS: u64 = 60 * 60 * 1000;
59/// Uploaded bundles remembered on this machine.
60const MAX_REMEMBERED: usize = 256;
61const BUNDLES_FILE: &str = "bundles.json";
62
63/// Defaults of a job the caller does not size.
64pub const DEFAULT_CPU: u32 = 2;
65pub const DEFAULT_MEMORY_MB: u32 = 4096;
66pub const DEFAULT_DISK_MB: u32 = 8192;
67pub const DEFAULT_RUNTIME_S: u32 = 600;
68
69/// What a caller asks for.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct JobSpec {
72    pub job_type: JobType,
73    /// A runner image of the server's allowlist (e.g. `rust-1.99`).
74    pub image: String,
75    pub argv: Vec<String>,
76    pub workdir: String,
77    pub cpu: u32,
78    pub memory_mb: u32,
79    pub disk_mb: u32,
80    pub max_runtime_s: u32,
81    /// Hosts the job may reach (TCP 443); empty = no network.
82    pub network: Vec<String>,
83    /// `None` = exactly the reserve.
84    pub budget: Option<u64>,
85    /// `None` = the job type's default.
86    pub result_format: Option<ResultFormat>,
87    /// Paths of the checkout to bundle; empty = the whole checkout.
88    pub paths: Vec<String>,
89    pub client_ref: Option<String>,
90}
91
92impl JobSpec {
93    /// A spec with the defaults for `job_type`.
94    pub fn new(job_type: JobType, image: &str, argv: Vec<String>) -> Self {
95        Self {
96            job_type,
97            image: image.to_owned(),
98            argv,
99            workdir: String::new(),
100            cpu: DEFAULT_CPU,
101            memory_mb: DEFAULT_MEMORY_MB,
102            disk_mb: DEFAULT_DISK_MB,
103            max_runtime_s: DEFAULT_RUNTIME_S,
104            network: Vec::new(),
105            budget: None,
106            result_format: None,
107            paths: Vec::new(),
108            client_ref: None,
109        }
110    }
111
112    /// The E47 request for `vault_id` with `inputs`.
113    pub fn request(&self, vault_id: &str, inputs: ComputeInputsV1) -> ComputeSubmitRequestV1 {
114        let mut network = self.network.clone();
115        network.sort();
116        network.dedup();
117        ComputeSubmitRequestV1 {
118            schema: COMPUTE_JOB_SCHEMA.into(),
119            vault_id: vault_id.to_owned(),
120            job_type: self.job_type,
121            inputs,
122            image: self.image.clone(),
123            command: ComputeCommandV1 {
124                argv: self.argv.clone(),
125                workdir: self.workdir.clone(),
126            },
127            resources: ComputeResourcesV1 {
128                cpu: self.cpu,
129                memory_mb: self.memory_mb,
130                disk_mb: self.disk_mb,
131            },
132            max_runtime_s: self.max_runtime_s,
133            network_allowlist: network,
134            budget: ComputeBudgetV1 {
135                credits: self
136                    .budget
137                    .unwrap_or_else(|| reserve_for(self.cpu, self.max_runtime_s)),
138            },
139            result_format: self
140                .result_format
141                .unwrap_or_else(|| self.job_type.default_format()),
142            client_ref: self.client_ref.clone(),
143        }
144    }
145
146    /// Every contract rule that does not need the bundle, before it is built.
147    pub fn check(&self) -> Result<(), HiveError> {
148        let placeholder = ComputeInputsV1 {
149            version: INPUTS_VERSION,
150            bundles: vec![lean_ctx_protocol::hive::compute::BundleRefV1 {
151                name: bundle::BUNDLE_NAME.into(),
152                digest: content_digest(b""),
153                size_bytes: 1,
154            }],
155        };
156        self.request(&"0".repeat(32), placeholder)
157            .validate()
158            .map_err(|e| HiveError::Config(format!("invalid compute job: {e}")))
159    }
160}
161
162/// A submitted job and how its bundle was made.
163#[derive(Debug, Clone)]
164pub struct Submitted {
165    pub job: ComputeJobV1,
166    pub bundle: SentBundle,
167}
168
169/// The bundle reference, whether it was uploaded now, and what was left out.
170#[derive(Debug, Clone)]
171pub struct SentBundle {
172    pub reference: lean_ctx_protocol::hive::compute::BundleRefV1,
173    pub uploaded: bool,
174    pub report: BundleReport,
175}
176
177/// One result file written to disk.
178#[derive(Debug, Clone, PartialEq, Eq)]
179pub struct Written {
180    pub name: String,
181    pub path: PathBuf,
182    pub size_bytes: u64,
183}
184
185/// A fetched result: the answer, the log tail and the files written.
186#[derive(Debug, Clone)]
187pub struct Fetched {
188    pub response: ComputeResultResponseV1,
189    pub log_tail: Option<String>,
190    pub written: Vec<Written>,
191    pub out_dir: Option<PathBuf>,
192}
193
194/// Connected for compute: lease with `tasks.work`, a linked vault, and a
195/// C0 2.x Hive. `Err` says why not; no request is made.
196pub fn session(project_root: &Path) -> Result<Connected, HiveError> {
197    // The protocol first: an engine of a 1.x Hive hears "not available"
198    // wherever it runs, linked checkout or not.
199    let store = crate::core::hive::HiveStore::open()?;
200    if store.instance()?.is_some() && !crate::core::hive::bus::relay_v2::speaks_v2(&store) {
201        return Err(not_available_1x());
202    }
203    let c = connected(project_root, HiveRight::TasksWork)?;
204    if !crate::core::hive::bus::relay_v2::speaks_v2(&c.store) {
205        return Err(not_available_1x());
206    }
207    Ok(c)
208}
209
210fn not_available_1x() -> HiveError {
211    HiveError::Refused(
212        "not_available: Task Compute is not available on this Hive (it speaks the 1.x protocol)."
213            .into(),
214    )
215}
216
217fn call<T>(
218    c: &Connected,
219    budget: Duration,
220    f: impl FnOnce(&crate::core::hive::transport::HiveClient) -> Result<T, HiveError>,
221) -> Result<T, HiveError> {
222    let client = c.session.bounded_client(Instant::now() + budget)?;
223    f(&client).map_err(|e| c.session.noted(e))
224}
225
226fn now_ms(c: &Connected) -> u64 {
227    u64::try_from(c.session.lease.service_time(Utc::now()).timestamp_millis()).unwrap_or_default()
228}
229
230/// `security.excluded_paths` of the effective policy for this vault; a
231/// policy in force that is missing or damaged refuses (fail closed).
232fn excluded_paths(c: &Connected) -> Result<Vec<String>, HiveError> {
233    use crate::core::hive::effective_floor;
234    let dir = effective_floor::floor_dir_in(c.store.data_dir());
235    let (floor, required) = effective_floor::read(&dir).map_err(HiveError::Refused)?;
236    let floor = effective_floor::check(floor.as_deref(), required.as_deref())
237        .map_err(|e| HiveError::Refused(format!("policy_unavailable: {e}")))?;
238    Ok(floor
239        .and_then(|f| {
240            f.policy
241                .for_vault(Some(&c.project.vault_id))
242                .security
243                .excluded_paths
244                .clone()
245        })
246        .unwrap_or_default())
247}
248
249/// `<data>/hive/compute/bundles.json`: digests Hive holds, until when.
250#[derive(Debug, Default, Serialize, Deserialize)]
251struct Remembered {
252    bundles: BTreeMap<String, u64>,
253}
254
255fn compute_dir(c: &Connected) -> PathBuf {
256    c.store.data_dir().join("compute")
257}
258
259fn remembered(c: &Connected) -> Remembered {
260    std::fs::read(compute_dir(c).join(BUNDLES_FILE))
261        .ok()
262        .and_then(|bytes| serde_json::from_slice(&bytes).ok())
263        .unwrap_or_default()
264}
265
266fn remember(c: &Connected, digest: &str, expires_ms: u64, now: u64) -> Result<(), HiveError> {
267    let mut known = remembered(c);
268    known.bundles.retain(|_, until| *until > now);
269    known.bundles.insert(digest.to_owned(), expires_ms);
270    while known.bundles.len() > MAX_REMEMBERED {
271        let Some(oldest) = known
272            .bundles
273            .iter()
274            .min_by_key(|(digest, until)| (**until, *digest))
275            .map(|(digest, _)| digest.clone())
276        else {
277            break;
278        };
279        known.bundles.remove(&oldest);
280    }
281    let bytes = serde_json::to_vec(&known).map_err(|e| HiveError::Local(e.to_string()))?;
282    crate::core::hive::state::write_private(&compute_dir(c), BUNDLES_FILE, &bytes)
283}
284
285/// Build, screen and (unless Hive holds it) upload the bundle, then submit.
286pub fn submit(project_root: &Path, spec: &JobSpec) -> Result<Submitted, HiveError> {
287    spec.check()?;
288    let c = session(project_root)?;
289    let rules = BundleRules::for_installation(excluded_paths(&c)?);
290    let built = bundle::build(&c.root, &spec.paths, &rules)?;
291    let now = now_ms(&c);
292    let digest = built.reference.digest.clone();
293    let held = remembered(&c)
294        .bundles
295        .get(&digest)
296        .is_some_and(|until| *until > now.saturating_add(REUPLOAD_MARGIN_MS));
297    if !held {
298        let answer = call(&c, UPLOAD_BUDGET, |client| {
299            client::put_bundle(client, &digest, &built.bytes)
300        })?;
301        remember(&c, &digest, answer.expires_ms, now)?;
302    }
303    let inputs = ComputeInputsV1 {
304        version: INPUTS_VERSION,
305        bundles: vec![built.reference.clone()],
306    };
307    let request = spec.request(&c.project.vault_id, inputs);
308    let job = call(&c, CALL_BUDGET, |client| client::submit(client, &request))?;
309    Ok(Submitted {
310        job,
311        bundle: SentBundle {
312            reference: built.reference,
313            uploaded: !held,
314            report: built.report,
315        },
316    })
317}
318
319/// E48: the job as it is now.
320pub fn status(project_root: &Path, job_id: &str) -> Result<ComputeJobV1, HiveError> {
321    let c = session(project_root)?;
322    call(&c, CALL_BUDGET, |client| client::get(client, job_id))
323}
324
325/// E49: ask Hive to cancel the job; a finished job stays as it is.
326pub fn cancel(project_root: &Path, job_id: &str) -> Result<ComputeJobV1, HiveError> {
327    let c = session(project_root)?;
328    call(&c, CALL_BUDGET, |client| client::cancel(client, job_id))
329}
330
331/// Lines and bytes of the log tail shown.
332const LOG_TAIL_LINES: usize = 40;
333const LOG_TAIL_BYTES: usize = 4096;
334
335/// The last lines of `logs`, bounded.
336pub fn log_tail(logs: &[u8]) -> String {
337    let text = String::from_utf8_lossy(logs);
338    let lines: Vec<&str> = text.lines().collect();
339    let mut tail = lines[lines.len().saturating_sub(LOG_TAIL_LINES)..].join("\n");
340    if tail.len() > LOG_TAIL_BYTES {
341        let mut cut = tail.len() - LOG_TAIL_BYTES;
342        while !tail.is_char_boundary(cut) {
343            cut += 1;
344        }
345        tail = format!("…{}", &tail[cut..]);
346    }
347    tail
348}
349
350/// The directory results of `job_id` go to: `<out>/<job_id>`, jailed to
351/// the checkout and writable; never inside `.git` or `.lean-ctx`.
352pub fn out_dir(project_root: &Path, out: &Path, job_id: &str) -> Result<PathBuf, HiveError> {
353    let root = crate::core::pathutil::canonicalize_secure(project_root)
354        .map_err(|e| HiveError::Local(format!("{}: {e}", project_root.display())))?;
355    let candidate = if out.is_absolute() {
356        out.to_path_buf()
357    } else {
358        root.join(out)
359    };
360    let jailed = crate::core::pathjail::jail_path_enforced(&candidate, &root)
361        .map_err(|e| HiveError::Refused(format!("path_refused: {}: {e}", out.display())))?;
362    // The jail's allow-list may admit more; results stay in the checkout.
363    let Ok(inside) = jailed.strip_prefix(&root) else {
364        return Err(HiveError::Refused(format!(
365            "path_refused: {} is outside this checkout",
366            out.display()
367        )));
368    };
369    if inside.components().any(|part| {
370        matches!(part, std::path::Component::Normal(name) if name == ".git" || name == ".lean-ctx")
371    }) {
372        return Err(HiveError::Refused(format!(
373            "path_refused: results are never written into .git or .lean-ctx: {}",
374            out.display()
375        )));
376    }
377    let dir = jailed.join(job_id);
378    crate::core::pathjail::enforce_writable(&dir).map_err(HiveError::Refused)?;
379    Ok(dir)
380}
381
382fn write_checked(
383    dir: &Path,
384    name: &str,
385    bytes: &[u8],
386    digest: &str,
387    size: u64,
388) -> Result<Written, HiveError> {
389    if content_digest(bytes) != digest || bytes.len() as u64 != size {
390        return Err(HiveError::Protocol(format!(
391            "compute result: {name} does not match its digest"
392        )));
393    }
394    // Only plain names below `dir` (the contract already refuses `..` and
395    // absolute names; `.`, empty parts and a trailing `/` are refused here).
396    if name.ends_with('/')
397        || name.split('/').any(|part| part.is_empty() || part == ".")
398        || !Path::new(name)
399            .components()
400            .all(|part| matches!(part, std::path::Component::Normal(_)))
401    {
402        return Err(HiveError::Protocol(format!(
403            "compute result: {name} is not a plain file name"
404        )));
405    }
406    let path = dir.join(name);
407    let parent = path
408        .parent()
409        .ok_or_else(|| HiveError::Local(format!("{name}: no parent directory")))?;
410    let file = path
411        .file_name()
412        .and_then(|f| f.to_str())
413        .ok_or_else(|| HiveError::Local(format!("{name}: no file name")))?;
414    crate::core::hive::state::write_private(parent, file, bytes)?;
415    Ok(Written {
416        name: name.to_owned(),
417        path,
418        size_bytes: size,
419    })
420}
421
422/// E50 (+ E52): the result of a terminal job, its log tail, and with `out`
423/// its artifacts and logs written to `<out>/<job_id>/`.
424pub fn result(project_root: &Path, job_id: &str, out: Option<&Path>) -> Result<Fetched, HiveError> {
425    let c = session(project_root)?;
426    let response = call(&c, CALL_BUDGET, |client| client::result(client, job_id))?;
427    let dir = out.map(|out| out_dir(&c.root, out, job_id)).transpose()?;
428    let mut written = Vec::new();
429    let mut log_tail_text = None;
430    if let Some(result) = &response.result {
431        if let Some(logs) = &result.logs {
432            let bytes = call(&c, DOWNLOAD_BUDGET, |client| {
433                client::blob(client, job_id, &logs.digest, MAX_LOG_BYTES)
434            })?;
435            if content_digest(&bytes) != logs.digest {
436                return Err(HiveError::Protocol(
437                    "compute result: the logs do not match their digest".into(),
438                ));
439            }
440            log_tail_text = Some(log_tail(&bytes));
441            if let Some(dir) = &dir {
442                written.push(write_checked(
443                    dir,
444                    "logs.txt",
445                    &bytes,
446                    &logs.digest,
447                    logs.size_bytes,
448                )?);
449            }
450        }
451        if let Some(dir) = &dir {
452            let artifacts_dir = dir.join("artifacts");
453            for artifact in &result.artifacts {
454                let bytes = call(&c, DOWNLOAD_BUDGET, |client| {
455                    client::blob(client, job_id, &artifact.digest, artifact.size_bytes)
456                })?;
457                written.push(write_checked(
458                    &artifacts_dir,
459                    &artifact.name,
460                    &bytes,
461                    &artifact.digest,
462                    artifact.size_bytes,
463                )?);
464            }
465        }
466    }
467    Ok(Fetched {
468        response,
469        log_tail: log_tail_text,
470        written,
471        out_dir: dir,
472    })
473}
474
475#[cfg(test)]
476mod tests;