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}
98
99#[derive(Clone, Copy)]
100enum Source<'a> {
101    Borrowed(&'a RepoConfig),
102    Shared(&'a Arc<RepoConfig>),
103}
104
105impl<'a> Source<'a> {
106    fn config(self) -> &'a RepoConfig {
107        match self {
108            Self::Borrowed(config) => config,
109            Self::Shared(config) => config,
110        }
111    }
112}
113
114impl Inputs {
115    pub(crate) fn new(config: &RepoConfig, evals: &[&Eval]) -> Result<Self, String> {
116        let targets: BTreeSet<_> = evals
117            .iter()
118            .flat_map(|eval| dependencies(config, eval))
119            .collect();
120        let mut needed = targets.clone();
121        for id in &targets {
122            match &config.artifacts[*id].fingerprint {
123                Some(Fingerprint::Artifactsum { .. }) => needed.extend(config.descendants(id)),
124                Some(Fingerprint::Script { args, .. }) => {
125                    let argv =
126                        scope::argv_scope(config, id, args).map_err(|error| error.to_string())?;
127                    needed.extend(argv.artifacts.into_values().map(|artifact| &artifact.name));
128                }
129                _ => {}
130            }
131        }
132        let artifacts = needed
133            .into_iter()
134            .map(|id| {
135                let artifact = &config.artifacts[id];
136                (
137                    id.clone(),
138                    crate::config::Artifact {
139                        definition: artifact.definition.clone(),
140                        authored_path: None,
141                        target_error: None,
142                        path: artifact.path.clone(),
143                        nested: artifact.nested.clone(),
144                        covering_part: artifact.covering_part.clone(),
145                        parts: artifact.parts.clone(),
146                        name: artifact.name.clone(),
147                        tags: Vec::new(),
148                        views: Default::default(),
149                        tools: None,
150                        toolsets: Vec::new(),
151                        binding: None,
152                        basis: artifact.basis,
153                        fingerprint: artifact.fingerprint.clone(),
154                    },
155                )
156            })
157            .collect();
158        Ok(Self {
159            files: Arc::new(RepoConfig {
160                root: config.root.clone(),
161                artifacts,
162                evals: Vec::new(),
163                relations: Vec::new(),
164                profiles: BTreeMap::new(),
165                program: None,
166                plugins: BTreeMap::new(),
167            }),
168            targets: targets.into_iter().cloned().collect(),
169        })
170    }
171
172    pub(crate) async fn prepare(
173        self,
174        output_root: &Path,
175        parallelism: &Parallelism,
176        cancellation: CancellationToken,
177    ) -> Result<BTreeMap<ArtifactName, PreparedFingerprint>, String> {
178        // Missing targets are per-eval errors. The Broker revalidates and reports the
179        // affected requests; other evals still prepare their keys.
180        let mut fingerprints = BTreeMap::new();
181        acquire_each(
182            Source::Shared(&self.files),
183            self.targets.iter().filter(|id| {
184                scope::validate_file_target(&self.files.root, &self.files.artifacts[*id]).is_ok()
185            }),
186            output_root,
187            parallelism,
188            cancellation,
189            |id, fingerprint| {
190                fingerprints.insert(id.clone(), fingerprint);
191            },
192        )
193        .await?;
194        Ok(fingerprints)
195    }
196}
197
198/// Prepare only the selected dependency closure, once per Artifact, computing up to the
199/// parallelism's limit of fingerprints at a time. The result does not depend on completion
200/// order: a failure reports the first failing Artifact in input order, and fingerprints after
201/// it are cancelled because they cannot change which failure that is.
202pub async fn prepare<'a>(
203    config: &RepoConfig,
204    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
205    output_root: &Path,
206    parallelism: &Parallelism,
207    cancellation: CancellationToken,
208) -> Result<BTreeMap<&'a ArtifactName, PreparedFingerprint>, String> {
209    let artifacts = artifacts.into_iter().collect::<Vec<_>>();
210    for id in &artifacts {
211        let artifact = config
212            .artifacts
213            .get(*id)
214            .ok_or_else(|| format!("Unknown Artifact: {id}"))?;
215        scope::validate_file_target(&config.root, artifact).map_err(|error| error.to_string())?;
216    }
217    let mut prepared = BTreeMap::new();
218    prepare_each(
219        config,
220        artifacts,
221        output_root,
222        parallelism,
223        cancellation,
224        |id, fingerprint| {
225            prepared.insert(id, fingerprint);
226        },
227    )
228    .await?;
229    Ok(prepared)
230}
231
232/// [`prepare`], handing each fingerprint to `ready` as soon as it is computed.
233pub(crate) async fn prepare_each<'a>(
234    config: &RepoConfig,
235    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
236    output_root: &Path,
237    parallelism: &Parallelism,
238    cancellation: CancellationToken,
239    ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
240) -> Result<(), String> {
241    acquire_each(
242        Source::Borrowed(config),
243        artifacts,
244        output_root,
245        parallelism,
246        cancellation,
247        ready,
248    )
249    .await
250}
251
252async fn acquire_each<'a>(
253    source: Source<'_>,
254    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
255    output_root: &Path,
256    parallelism: &Parallelism,
257    cancellation: CancellationToken,
258    mut ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
259) -> Result<(), String> {
260    let config = source.config();
261    let mut seen = BTreeSet::new();
262    let ids: Vec<&'a ArtifactName> = artifacts
263        .into_iter()
264        .filter(|id| config.artifacts[*id].fingerprint.is_some() && seen.insert(*id))
265        .collect();
266    let tokens: Vec<_> = ids.iter().map(|_| cancellation.child_token()).collect();
267    // Keep at most a window of full futures, including their process state, resident. The
268    // shared semaphore also includes overlapping end-of-review rechecks.
269    let fingerprint = |index: usize| {
270        let id = ids[index];
271        let token = &tokens[index];
272        async move {
273            let result = match parallelism.slots.acquire().await {
274                Ok(_slot) if !token.is_cancelled() => {
275                    compute(source, id, output_root, token.clone()).await
276                }
277                _ => Err(process::Error::Cancelled.to_string()),
278            };
279            (index, result)
280        }
281    };
282    let mut pending = 0..ids.len();
283    let mut running: FuturesUnordered<_> = pending
284        .by_ref()
285        .take(parallelism.limit())
286        .map(&fingerprint)
287        .collect();
288    let mut failure: Option<(usize, String)> = None;
289    while let Some((index, result)) = running.next().await {
290        match result {
291            Ok(fingerprint) => ready(ids[index], fingerprint),
292            Err(error) if failure.as_ref().is_none_or(|(first, _)| index < *first) => {
293                for token in &tokens[index + 1..] {
294                    token.cancel();
295                }
296                failure = Some((index, error));
297            }
298            Err(_) => {}
299        }
300        if failure.is_none()
301            && let Some(index) = pending.next()
302        {
303            running.push(fingerprint(index));
304        }
305    }
306    match failure {
307        Some((_, error)) => Err(error),
308        None => Ok(()),
309    }
310}
311
312/// Recompute the eval's key after a review: every Artifact it depends on is fingerprinted
313/// again, so a change to any of them during the review is detected.
314pub async fn recheck(
315    config: &RepoConfig,
316    eval: &Eval,
317    output_root: &Path,
318    parallelism: &Parallelism,
319    cancellation: CancellationToken,
320) -> Result<Option<crate::types::ReuseKey>, String> {
321    validate_file_inputs(config, eval)?;
322    let fingerprints = prepare(
323        config,
324        dependencies(config, eval),
325        output_root,
326        parallelism,
327        cancellation,
328    )
329    .await?;
330    validate_file_inputs(config, eval)?;
331    Ok(eval_key(config, eval, &fingerprints)
332        .ok()
333        .map(|key| key.value))
334}
335
336/// Keyless Live reviews retain and compare every available admitted snapshot too.
337pub(crate) async fn recheck_observations(
338    config: &RepoConfig,
339    expected: &BTreeMap<ArtifactName, crate::types::Fingerprint>,
340    output: &Path,
341    parallelism: &Parallelism,
342    cancellation: CancellationToken,
343) -> Result<bool, String> {
344    let current = prepare(config, expected.keys(), output, parallelism, cancellation).await?;
345    Ok(expected.iter().all(|(name, value)| {
346        current
347            .get(name)
348            .is_some_and(|current| current.value == *value)
349    }))
350}
351
352async fn compute(
353    source: Source<'_>,
354    id: &ArtifactName,
355    output_root: &Path,
356    cancellation: CancellationToken,
357) -> Result<PreparedFingerprint, String> {
358    let config = source.config();
359    scope::validate_file_target(&config.root, &config.artifacts[id])
360        .map_err(|error| error.to_string())?;
361    let result = match &config.artifacts[id].fingerprint {
362        // What the definitions bound under its target declare once expanded, not their bytes.
363        Some(Fingerprint::Graph) => Ok(PreparedFingerprint {
364            value: crate::graph_structure::read_scoped(&config.root, &config.artifacts[id])?
365                .fingerprint(),
366            manifest: None,
367        }),
368        Some(Fingerprint::Artifactsum { files, ignore }) => {
369            content(config, id, files, ignore, &cancellation)
370                .await
371                .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
372        }
373        Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
374            value: script(source, id, output_root, cancellation)
375                .await
376                .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
377            manifest: None,
378        }),
379        None => Err(format!("Artifact {id} declares fingerprint: false.")),
380    }?;
381    scope::validate_file_target(&config.root, &config.artifacts[id])
382        .map_err(|error| error.to_string())?;
383    Ok(result)
384}
385
386/// The built-in hash of the Artifact's own input files, nothing else.
387async fn content(
388    config: &RepoConfig,
389    id: &ArtifactName,
390    inputs: &[crate::config::LogicalPath],
391    ignore: &IgnorePatterns,
392    cancellation: &CancellationToken,
393) -> Result<PreparedFingerprint, String> {
394    let files = content::files(config, id, inputs, ignore, cancellation).await?;
395    Ok(artifactsum(files))
396}
397
398fn artifactsum(files: content::Files) -> PreparedFingerprint {
399    let mut manifest = Manifest {
400        inputs: files.digest.clone(),
401        files: Some(
402            files
403                .files
404                .iter()
405                .map(|(path, file)| {
406                    (
407                        path.clone(),
408                        content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
409                            .parse()
410                            .expect("eight-byte SHA-256 prefix"),
411                    )
412                })
413                .collect(),
414        ),
415    };
416    if serde_json::to_vec(&manifest)
417        .expect("manifest is JSON")
418        .len()
419        > MANIFEST_BYTES
420    {
421        manifest.files = None;
422    }
423    PreparedFingerprint {
424        value: format!("artifactsum:{}", files.digest)
425            .parse()
426            .expect("artifactsum digest is a fingerprint"),
427        manifest: Some(manifest),
428    }
429}
430
431async fn script(
432    source: Source<'_>,
433    artifact_id: &ArtifactName,
434    output_root: &Path,
435    cancellation: CancellationToken,
436) -> Result<crate::types::Fingerprint, String> {
437    if cancellation.is_cancelled() {
438        return Err(process::Error::Cancelled.to_string());
439    }
440    let (command, disposable) = match source {
441        Source::Borrowed(config) => prepare_script(config, artifact_id, output_root)?,
442        Source::Shared(config) => {
443            let config = config.clone();
444            let id = artifact_id.clone();
445            let output_root = output_root.to_path_buf();
446            crate::task::blocking(move || prepare_script(&config, &id, &output_root)).await??
447        }
448    };
449    let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id});
450    let result = command
451        .fingerprint(input.to_string().into_bytes(), cancellation.clone())
452        .await;
453    let cleaned = match source {
454        Source::Borrowed(_) => disposable.close(),
455        Source::Shared(_) => crate::task::blocking(move || disposable.close()).await?,
456    };
457    if cancellation.is_cancelled() {
458        return Err(process::Error::Cancelled.to_string());
459    }
460    let output = result.map_err(|error| error.to_string())?;
461    if !output.status.success() {
462        return Err(format!(
463            "Fingerprint command exited with {}.",
464            output.status
465        ));
466    }
467    if output.truncated {
468        return Err("Fingerprint command output exceeded its limit.".into());
469    }
470    let value = validate_output(&output.stdout)?;
471    cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
472    Ok(value)
473}
474
475fn prepare_script(
476    config: &RepoConfig,
477    artifact_id: &ArtifactName,
478    output_root: &Path,
479) -> Result<(runtime::Command, scratch::Scratch), String> {
480    let artifact = &config.artifacts[artifact_id];
481    let Some(Fingerprint::Script {
482        command,
483        args,
484        files,
485        timeout_ms,
486    }) = &artifact.fingerprint
487    else {
488        unreachable!("fingerprint script")
489    };
490    let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
491    for input in files {
492        scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
493    }
494    let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
495    let program = scope::executable(&config.root, &scope, artifact_id, command)
496        .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
497    let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
498    let output_root =
499        workspace::prepare_directory(output_root, &config.root).map_err(|e| e.to_string())?;
500    let disposable = scratch::Scratch::create(&output_root).map_err(|e| e.to_string())?;
501    let mut command = runtime::Command::prepare(
502        program,
503        args.into_iter().map(Into::into).collect(),
504        &config.root,
505        disposable.path(),
506        *timeout_ms,
507    )
508    .map_err(|e| e.to_string())?;
509    command.cwd = cwd;
510    Ok((command, disposable))
511}
512
513fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
514    let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
515    if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
516        || !value
517            .iter()
518            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
519    {
520        return Err(format!(
521            "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
522        ));
523    }
524    String::from_utf8(value.to_vec())
525        .map_err(|error| error.to_string())?
526        .parse()
527}