Skip to main content

artifactize_core/cache/
acquire.rs

1//! Acquire and recheck fingerprints from Artifact inputs and author-defined scripts.
2
3use super::{IgnorePatterns, content, dependencies, eval_key, scratch};
4use crate::{
5    config::{ArtifactName, Eval, Fingerprint, RepoConfig},
6    process, runtime, scope, workspace,
7};
8use futures_util::{StreamExt, stream::FuturesUnordered};
9use serde::{Deserialize, Serialize};
10use serde_json::json;
11use std::{
12    collections::{BTreeMap, BTreeSet},
13    path::Path,
14    sync::Arc,
15};
16use tokio::sync::Semaphore;
17use tokio_util::sync::CancellationToken;
18
19/// Keep retained per-file provenance small; the content digest remains complete
20/// even when the optional explain-changes manifest is too large to store.
21const MANIFEST_BYTES: usize = 64 * 1024;
22
23/// Fingerprint scripts receive version 1's Artifact identity stdin envelope. Its
24/// explicit format version lets owner scripts distinguish future envelopes, not DB schemas.
25const FINGERPRINT_INPUT_VERSION: u32 = 1;
26/// Keep per-file change explanations compact with 8 digest bytes (16 hex characters).
27/// This diagnostic prefix is not identity: artifactsum/reuse keys retain full SHA-256.
28const MANIFEST_DIGEST_PREFIX_BYTES: usize = 8;
29
30/// A prepared fingerprint; artifactsum also carries its manifest.
31#[derive(Debug, Clone)]
32pub struct PreparedFingerprint {
33    pub value: crate::types::Fingerprint,
34    pub manifest: Option<Manifest>,
35}
36
37/// What artifactsum covered, saved with executions to explain later changes.
38/// A file map that would exceed 64 KiB is omitted; the fingerprint still covers it.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct Manifest {
41    /// SHA-256 over every input path and file digest: the fingerprint without its prefix.
42    pub inputs: crate::types::Sha256Digest,
43    /// Owner-relative path to the first 16 hex digits of its SHA-256.
44    #[serde(default, skip_serializing_if = "Option::is_none")]
45    pub files: Option<BTreeMap<scope::LogicalTarget, crate::types::DigestPrefix>>,
46}
47
48/// How many fingerprints a process computes at once: one bound shared by a Run's
49/// preparation and its end-of-review rechecks, or by `status`.
50#[derive(Debug, Clone)]
51pub struct Parallelism {
52    slots: Arc<Semaphore>,
53    limit: usize,
54}
55
56impl Parallelism {
57    /// At most `limit` fingerprints at a time; at least one.
58    pub fn new(limit: usize) -> Result<Self, String> {
59        let limit = limit.max(1);
60        if limit > Semaphore::MAX_PERMITS {
61            return Err(format!(
62                "fingerprint jobs must be at most {}.",
63                Semaphore::MAX_PERMITS
64            ));
65        }
66        Ok(Self {
67            slots: Arc::new(Semaphore::new(limit)),
68            limit,
69        })
70    }
71
72    /// The default bound: the CPUs available to this process.
73    pub fn available() -> usize {
74        std::thread::available_parallelism().map_or(1, usize::from)
75    }
76
77    pub fn limit(&self) -> usize {
78        self.limit
79    }
80}
81
82/// Every file visible to a review must still be its declared regular target.
83pub(crate) fn validate_file_inputs(config: &RepoConfig, eval: &Eval) -> Result<(), String> {
84    for id in dependencies(config, eval) {
85        scope::validate_file_target(&config.root, &config.artifacts[id])
86            .map_err(|error| error.to_string())?;
87    }
88    Ok(())
89}
90
91/// The file inputs needed during planning, independent of instructions, tooling and the
92/// saved Run graph. Keeping only these inputs during native launch avoids making every
93/// fingerprint process inherit the memory of the expanded project.
94pub(crate) struct Inputs {
95    files: Arc<RepoConfig>,
96    targets: BTreeSet<ArtifactName>,
97    graphs: BTreeMap<ArtifactName, crate::types::Fingerprint>,
98}
99
100#[derive(Clone, Copy)]
101enum Source<'a> {
102    Borrowed(&'a RepoConfig),
103    Snapshot(&'a RepoConfig),
104    Shared(
105        &'a Arc<RepoConfig>,
106        &'a BTreeMap<ArtifactName, crate::types::Fingerprint>,
107    ),
108}
109
110impl<'a> Source<'a> {
111    fn config(self) -> &'a RepoConfig {
112        match self {
113            Self::Borrowed(config) | Self::Snapshot(config) => config,
114            Self::Shared(config, _) => config,
115        }
116    }
117
118    fn graph(self, id: &ArtifactName) -> Result<crate::types::Fingerprint, String> {
119        let config = self.config();
120        let owner = &config.artifacts[id];
121        Ok(match self {
122            Self::Borrowed(_) => {
123                crate::graph_structure::read_scoped(&config.root, owner)?.fingerprint()
124            }
125            Self::Snapshot(_) => crate::graph_structure::scoped(config, owner)?.fingerprint(),
126            Self::Shared(_, graphs) => graphs[id].clone(),
127        })
128    }
129}
130
131impl Inputs {
132    pub(crate) fn new(config: &RepoConfig, evals: &[&Eval]) -> Result<Self, String> {
133        let targets: BTreeSet<_> = evals
134            .iter()
135            .flat_map(|eval| dependencies(config, eval))
136            .collect();
137        let graphs = targets
138            .iter()
139            .filter(|id| matches!(config.artifacts[**id].fingerprint, Some(Fingerprint::Graph)))
140            .map(|id| {
141                Source::Snapshot(config)
142                    .graph(id)
143                    .map(|fingerprint| ((*id).clone(), fingerprint))
144            })
145            .collect::<Result<_, _>>()?;
146        let mut needed = targets.clone();
147        for id in &targets {
148            match &config.artifacts[*id].fingerprint {
149                Some(Fingerprint::Artifactsum { .. }) => needed.extend(config.descendants(id)),
150                Some(Fingerprint::Script { args, .. }) => {
151                    let argv =
152                        scope::argv_scope(config, id, args).map_err(|error| error.to_string())?;
153                    needed.extend(argv.artifacts.into_values().map(|artifact| &artifact.name));
154                }
155                _ => {}
156            }
157        }
158        let artifacts = needed
159            .into_iter()
160            .map(|id| {
161                let artifact = &config.artifacts[id];
162                (
163                    id.clone(),
164                    crate::config::Artifact {
165                        definition: artifact.definition.clone(),
166                        authored_path: None,
167                        target_error: None,
168                        path: artifact.path.clone(),
169                        nested: artifact.nested.clone(),
170                        covering_part: artifact.covering_part.clone(),
171                        parts: artifact.parts.clone(),
172                        name: artifact.name.clone(),
173                        tags: Vec::new(),
174                        views: Default::default(),
175                        tools: None,
176                        toolsets: Vec::new(),
177                        binding: None,
178                        basis: artifact.basis,
179                        fingerprint: artifact.fingerprint.clone(),
180                    },
181                )
182            })
183            .collect();
184        Ok(Self {
185            files: Arc::new(RepoConfig {
186                root: config.root.clone(),
187                artifacts,
188                evals: Vec::new(),
189                relations: Vec::new(),
190                profiles: BTreeMap::new(),
191                program: None,
192                plugins: BTreeMap::new(),
193            }),
194            targets: targets.into_iter().cloned().collect(),
195            graphs,
196        })
197    }
198
199    pub(crate) async fn prepare(
200        self,
201        output_root: &Path,
202        parallelism: &Parallelism,
203        cancellation: CancellationToken,
204    ) -> Result<BTreeMap<ArtifactName, PreparedFingerprint>, String> {
205        // Missing targets are per-eval errors. The Broker revalidates and reports the
206        // affected requests; other evals still prepare their keys.
207        let mut fingerprints = BTreeMap::new();
208        acquire_each(
209            Source::Shared(&self.files, &self.graphs),
210            self.targets.iter().filter(|id| {
211                scope::validate_file_target(&self.files.root, &self.files.artifacts[*id]).is_ok()
212            }),
213            output_root,
214            parallelism,
215            cancellation,
216            |id, fingerprint| {
217                fingerprints.insert(id.clone(), fingerprint);
218            },
219        )
220        .await?;
221        Ok(fingerprints)
222    }
223
224    /// Forecast a validated scope, with the same bounded blocking workers as Run preparation.
225    pub(crate) async fn prepare_each<'a>(
226        &self,
227        targets: impl IntoIterator<Item = &'a ArtifactName>,
228        output_root: &Path,
229        parallelism: &Parallelism,
230        cancellation: CancellationToken,
231        ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
232    ) -> Result<(), String> {
233        acquire_each(
234            Source::Shared(&self.files, &self.graphs),
235            targets,
236            output_root,
237            parallelism,
238            cancellation,
239            ready,
240        )
241        .await
242    }
243}
244
245/// Prepare only the selected dependency closure, once per Artifact, computing up to the
246/// parallelism's limit of fingerprints at a time. The result does not depend on completion
247/// order: a failure reports the first failing Artifact in input order, and fingerprints after
248/// it are cancelled because they cannot change which failure that is.
249pub async fn prepare<'a>(
250    config: &RepoConfig,
251    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
252    output_root: &Path,
253    parallelism: &Parallelism,
254    cancellation: CancellationToken,
255) -> Result<BTreeMap<&'a ArtifactName, PreparedFingerprint>, String> {
256    let artifacts = artifacts.into_iter().collect::<Vec<_>>();
257    for id in &artifacts {
258        let artifact = config
259            .artifacts
260            .get(*id)
261            .ok_or_else(|| format!("Unknown Artifact: {id}"))?;
262        scope::validate_file_target(&config.root, artifact).map_err(|error| error.to_string())?;
263    }
264    let mut prepared = BTreeMap::new();
265    acquire_each(
266        Source::Borrowed(config),
267        artifacts,
268        output_root,
269        parallelism,
270        cancellation,
271        |id, fingerprint| {
272            prepared.insert(id, fingerprint);
273        },
274    )
275    .await?;
276    Ok(prepared)
277}
278
279async fn acquire_each<'a>(
280    source: Source<'_>,
281    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
282    output_root: &Path,
283    parallelism: &Parallelism,
284    cancellation: CancellationToken,
285    mut ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
286) -> Result<(), String> {
287    let config = source.config();
288    let mut seen = BTreeSet::new();
289    let ids: Vec<&'a ArtifactName> = artifacts
290        .into_iter()
291        .filter(|id| config.artifacts[*id].fingerprint.is_some() && seen.insert(*id))
292        .collect();
293    let tokens: Vec<_> = ids.iter().map(|_| cancellation.child_token()).collect();
294    // Keep at most a window of full futures, including their process state, resident. The
295    // shared semaphore also includes overlapping end-of-review rechecks.
296    let batch = Batch::default();
297    let fingerprint = |index: usize| {
298        let id = ids[index];
299        let token = &tokens[index];
300        let batch = &batch;
301        async move {
302            let result = match parallelism.slots.acquire().await {
303                Ok(_slot) if !token.is_cancelled() => {
304                    compute(source, id, output_root, batch, token.clone()).await
305                }
306                _ => Err(process::Error::Cancelled.to_string()),
307            };
308            (index, result)
309        }
310    };
311    let mut pending = 0..ids.len();
312    let mut running: FuturesUnordered<_> = pending
313        .by_ref()
314        .take(parallelism.limit())
315        .map(&fingerprint)
316        .collect();
317    let mut failure: Option<(usize, String)> = None;
318    while let Some((index, result)) = running.next().await {
319        match result {
320            Ok(fingerprint) => ready(ids[index], fingerprint),
321            Err(error) if failure.as_ref().is_none_or(|(first, _)| index < *first) => {
322                for token in &tokens[index + 1..] {
323                    token.cancel();
324                }
325                failure = Some((index, error));
326            }
327            Err(_) => {}
328        }
329        if failure.is_none()
330            && let Some(index) = pending.next()
331        {
332            running.push(fingerprint(index));
333        }
334    }
335    drop(running);
336    let cleaned = match batch.scratch.into_inner() {
337        Some(scratch) => crate::task::blocking(move || scratch.close())
338            .await?
339            .map_err(|error| error.to_string()),
340        None => Ok(()),
341    };
342    match failure {
343        Some((_, error)) => Err(error),
344        None => cleaned,
345    }
346}
347
348/// Recompute the eval's key after a review: every Artifact it depends on is fingerprinted
349/// again, so a change to any of them during the review is detected.
350pub async fn recheck(
351    config: &RepoConfig,
352    eval: &Eval,
353    output_root: &Path,
354    parallelism: &Parallelism,
355    cancellation: CancellationToken,
356) -> Result<Option<crate::types::ReuseKey>, String> {
357    validate_file_inputs(config, eval)?;
358    let fingerprints = prepare(
359        config,
360        dependencies(config, eval),
361        output_root,
362        parallelism,
363        cancellation,
364    )
365    .await?;
366    validate_file_inputs(config, eval)?;
367    Ok(eval_key(config, eval, &fingerprints)
368        .ok()
369        .map(|key| key.value))
370}
371
372/// Keyless Live reviews retain and compare every available admitted snapshot too.
373pub(crate) async fn recheck_observations(
374    config: &RepoConfig,
375    expected: &BTreeMap<ArtifactName, crate::types::Fingerprint>,
376    output: &Path,
377    parallelism: &Parallelism,
378    cancellation: CancellationToken,
379) -> Result<bool, String> {
380    let current = prepare(config, expected.keys(), output, parallelism, cancellation).await?;
381    Ok(expected.iter().all(|(name, value)| {
382        current
383            .get(name)
384            .is_some_and(|current| current.value == *value)
385    }))
386}
387
388/// A scan owns its hash memo and one leased scratch root. Each script gets private
389/// runtime directories inside that root and cleans them up after it finishes.
390#[derive(Default)]
391struct Batch {
392    memo: Arc<content::Memo>,
393    scratch: tokio::sync::OnceCell<scratch::Scratch>,
394}
395
396async fn compute(
397    source: Source<'_>,
398    id: &ArtifactName,
399    output_root: &Path,
400    batch: &Batch,
401    cancellation: CancellationToken,
402) -> Result<PreparedFingerprint, String> {
403    let config = source.config();
404    scope::validate_file_target(&config.root, &config.artifacts[id])
405        .map_err(|error| error.to_string())?;
406    let result = match &config.artifacts[id].fingerprint {
407        // What the definitions bound under its target declare once expanded, not their bytes.
408        Some(Fingerprint::Graph) => Ok(PreparedFingerprint {
409            value: source.graph(id)?,
410            manifest: None,
411        }),
412        Some(Fingerprint::Artifactsum { files, ignore }) => {
413            content(config, id, files, ignore, batch.memo.clone(), &cancellation)
414                .await
415                .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
416        }
417        Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
418            value: script(source, id, output_root, batch, cancellation)
419                .await
420                .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
421            manifest: None,
422        }),
423        None => Err(format!("Artifact {id} declares fingerprint: false.")),
424    }?;
425    scope::validate_file_target(&config.root, &config.artifacts[id])
426        .map_err(|error| error.to_string())?;
427    Ok(result)
428}
429
430/// The built-in hash of the Artifact's own input files, nothing else.
431async fn content(
432    config: &RepoConfig,
433    id: &ArtifactName,
434    inputs: &[crate::config::LogicalPath],
435    ignore: &IgnorePatterns,
436    memo: Arc<content::Memo>,
437    cancellation: &CancellationToken,
438) -> Result<PreparedFingerprint, String> {
439    let files = content::files(config, id, inputs, ignore, memo, cancellation).await?;
440    Ok(artifactsum(files))
441}
442
443fn artifactsum(files: content::Files) -> PreparedFingerprint {
444    let mut manifest = Manifest {
445        inputs: files.digest.clone(),
446        files: Some(
447            files
448                .files
449                .iter()
450                .map(|(path, file)| {
451                    (
452                        path.clone(),
453                        content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
454                            .parse()
455                            .expect("eight-byte SHA-256 prefix"),
456                    )
457                })
458                .collect(),
459        ),
460    };
461    if serde_json::to_vec(&manifest)
462        .expect("manifest is JSON")
463        .len()
464        > MANIFEST_BYTES
465    {
466        manifest.files = None;
467    }
468    PreparedFingerprint {
469        value: format!("artifactsum:{}", files.digest)
470            .parse()
471            .expect("artifactsum digest is a fingerprint"),
472        manifest: Some(manifest),
473    }
474}
475
476async fn script(
477    source: Source<'_>,
478    artifact_id: &ArtifactName,
479    output_root: &Path,
480    batch: &Batch,
481    cancellation: CancellationToken,
482) -> Result<crate::types::Fingerprint, String> {
483    if cancellation.is_cancelled() {
484        return Err(process::Error::Cancelled.to_string());
485    }
486    let scratch = batch
487        .scratch
488        .get_or_try_init(|| async {
489            let output_root = output_root.to_owned();
490            let workspace = source.config().root.clone();
491            crate::task::blocking(move || {
492                let output_root = workspace::prepare_directory(&output_root, &workspace)?;
493                scratch::Scratch::create(&output_root)
494            })
495            .await?
496            .map_err(|error| error.to_string())
497        })
498        .await?;
499    let command = match source {
500        Source::Borrowed(config) | Source::Snapshot(config) => {
501            prepare_script(config, artifact_id, scratch.path())?
502        }
503        Source::Shared(config, _) => {
504            let config = config.clone();
505            let id = artifact_id.clone();
506            let root = scratch.path().to_owned();
507            crate::task::blocking(move || prepare_script(&config, &id, &root)).await??
508        }
509    };
510    let directory = command.directory().to_owned();
511    let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id})
512        .to_string()
513        .into_bytes();
514    let result = run_fingerprint(command.into_process(), input, cancellation.clone()).await;
515    let cleaned = match source {
516        Source::Borrowed(_) | Source::Snapshot(_) => crate::platform::remove_tree(&directory),
517        Source::Shared(_, _) => {
518            crate::task::blocking(move || crate::platform::remove_tree(&directory)).await?
519        }
520    };
521    if cancellation.is_cancelled() {
522        return Err(process::Error::Cancelled.to_string());
523    }
524    let value = result?;
525    cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
526    Ok(value)
527}
528
529async fn run_fingerprint(
530    command: process::Command,
531    input: Vec<u8>,
532    cancellation: CancellationToken,
533) -> Result<crate::types::Fingerprint, String> {
534    let output = process::run_fingerprint(command, input, cancellation)
535        .await
536        .map_err(|error| error.to_string())?;
537    if !output.status.success() {
538        return Err(format!(
539            "Fingerprint command exited with {}.",
540            output.status
541        ));
542    }
543    if output.truncated {
544        return Err("Fingerprint command output exceeded its limit.".into());
545    }
546    validate_output(&output.stdout)
547}
548
549fn prepare_script(
550    config: &RepoConfig,
551    artifact_id: &ArtifactName,
552    output_root: &Path,
553) -> Result<runtime::Command, String> {
554    let artifact = &config.artifacts[artifact_id];
555    let Some(Fingerprint::Script {
556        command,
557        args,
558        files,
559        timeout_ms,
560    }) = &artifact.fingerprint
561    else {
562        unreachable!("fingerprint script")
563    };
564    let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
565    for input in files {
566        scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
567    }
568    let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
569    let program = scope::executable(&config.root, &scope, artifact_id, command)
570        .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
571    let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
572    let mut command = runtime::Command::prepare(
573        program,
574        args.into_iter().map(Into::into).collect(),
575        &config.root,
576        output_root,
577        *timeout_ms,
578    )
579    .map_err(|e| e.to_string())?;
580    command.cwd = cwd;
581    Ok(command)
582}
583
584fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
585    let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
586    if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
587        || !value
588            .iter()
589            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
590    {
591        return Err(format!(
592            "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
593        ));
594    }
595    String::from_utf8(value.to_vec())
596        .map_err(|error| error.to_string())?
597        .parse()
598}