artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Acquire and recheck fingerprints from Artifact inputs and author-defined scripts.

use super::{IgnorePatterns, content, dependencies, eval_key, scratch};
use crate::{
    config::{ArtifactName, Eval, Fingerprint, RepoConfig},
    process, runtime, scope, workspace,
};
use futures_util::{StreamExt, stream::FuturesUnordered};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::{
    collections::{BTreeMap, BTreeSet},
    path::Path,
    sync::Arc,
};
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;

/// Keep retained per-file provenance small; the content digest remains complete
/// even when the optional explain-changes manifest is too large to store.
const MANIFEST_BYTES: usize = 64 * 1024;

/// Fingerprint scripts receive version 1's Artifact identity stdin envelope. Its
/// explicit format version lets owner scripts distinguish future envelopes, not DB schemas.
const FINGERPRINT_INPUT_VERSION: u32 = 1;
/// Keep per-file change explanations compact with 8 digest bytes (16 hex characters).
/// This diagnostic prefix is not identity: artifactsum/reuse keys retain full SHA-256.
const MANIFEST_DIGEST_PREFIX_BYTES: usize = 8;

/// A prepared fingerprint; artifactsum also carries its manifest.
#[derive(Debug, Clone)]
pub struct PreparedFingerprint {
    pub value: crate::types::Fingerprint,
    pub manifest: Option<Manifest>,
}

/// What artifactsum covered, saved with executions to explain later changes.
/// A file map that would exceed 64 KiB is omitted; the fingerprint still covers it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Manifest {
    /// SHA-256 over every input path and file digest: the fingerprint without its prefix.
    pub inputs: crate::types::Sha256Digest,
    /// Owner-relative path to the first 16 hex digits of its SHA-256.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub files: Option<BTreeMap<scope::LogicalTarget, crate::types::DigestPrefix>>,
}

/// How many fingerprints a process computes at once: one bound shared by a Run's
/// preparation and its end-of-review rechecks, or by `status`.
#[derive(Debug, Clone)]
pub struct Parallelism {
    slots: Arc<Semaphore>,
    limit: usize,
}

impl Parallelism {
    /// At most `limit` fingerprints at a time; at least one.
    pub fn new(limit: usize) -> Result<Self, String> {
        let limit = limit.max(1);
        if limit > Semaphore::MAX_PERMITS {
            return Err(format!(
                "fingerprint jobs must be at most {}.",
                Semaphore::MAX_PERMITS
            ));
        }
        Ok(Self {
            slots: Arc::new(Semaphore::new(limit)),
            limit,
        })
    }

    /// The default bound: the CPUs available to this process.
    pub fn available() -> usize {
        std::thread::available_parallelism().map_or(1, usize::from)
    }

    pub fn limit(&self) -> usize {
        self.limit
    }
}

/// Every file visible to a review must still be its declared regular target.
pub(crate) fn validate_file_inputs(config: &RepoConfig, eval: &Eval) -> Result<(), String> {
    for id in dependencies(config, eval) {
        scope::validate_file_target(&config.root, &config.artifacts[id])
            .map_err(|error| error.to_string())?;
    }
    Ok(())
}

/// The file inputs needed during planning, independent of instructions, tooling and the
/// saved Run graph. Keeping only these inputs during native launch avoids making every
/// fingerprint process inherit the memory of the expanded project.
pub(crate) struct Inputs {
    files: Arc<RepoConfig>,
    targets: BTreeSet<ArtifactName>,
}

#[derive(Clone, Copy)]
enum Source<'a> {
    Borrowed(&'a RepoConfig),
    Shared(&'a Arc<RepoConfig>),
}

impl<'a> Source<'a> {
    fn config(self) -> &'a RepoConfig {
        match self {
            Self::Borrowed(config) => config,
            Self::Shared(config) => config,
        }
    }
}

impl Inputs {
    pub(crate) fn new(config: &RepoConfig, evals: &[&Eval]) -> Result<Self, String> {
        let targets: BTreeSet<_> = evals
            .iter()
            .flat_map(|eval| dependencies(config, eval))
            .collect();
        let mut needed = targets.clone();
        for id in &targets {
            match &config.artifacts[*id].fingerprint {
                Some(Fingerprint::Artifactsum { .. }) => needed.extend(config.descendants(id)),
                Some(Fingerprint::Script { args, .. }) => {
                    let argv =
                        scope::argv_scope(config, id, args).map_err(|error| error.to_string())?;
                    needed.extend(argv.artifacts.into_values().map(|artifact| &artifact.name));
                }
                _ => {}
            }
        }
        let artifacts = needed
            .into_iter()
            .map(|id| {
                let artifact = &config.artifacts[id];
                (
                    id.clone(),
                    crate::config::Artifact {
                        definition: artifact.definition.clone(),
                        authored_path: None,
                        target_error: None,
                        path: artifact.path.clone(),
                        nested: artifact.nested.clone(),
                        covering_part: artifact.covering_part.clone(),
                        parts: artifact.parts.clone(),
                        name: artifact.name.clone(),
                        tags: Vec::new(),
                        views: Default::default(),
                        tools: None,
                        toolsets: Vec::new(),
                        binding: None,
                        basis: artifact.basis,
                        fingerprint: artifact.fingerprint.clone(),
                    },
                )
            })
            .collect();
        Ok(Self {
            files: Arc::new(RepoConfig {
                root: config.root.clone(),
                artifacts,
                evals: Vec::new(),
                relations: Vec::new(),
                profiles: BTreeMap::new(),
                program: None,
                plugins: BTreeMap::new(),
            }),
            targets: targets.into_iter().cloned().collect(),
        })
    }

    pub(crate) async fn prepare(
        self,
        output_root: &Path,
        parallelism: &Parallelism,
        cancellation: CancellationToken,
    ) -> Result<BTreeMap<ArtifactName, PreparedFingerprint>, String> {
        // Missing targets are per-eval errors. The Broker revalidates and reports the
        // affected requests; other evals still prepare their keys.
        let mut fingerprints = BTreeMap::new();
        acquire_each(
            Source::Shared(&self.files),
            self.targets.iter().filter(|id| {
                scope::validate_file_target(&self.files.root, &self.files.artifacts[*id]).is_ok()
            }),
            output_root,
            parallelism,
            cancellation,
            |id, fingerprint| {
                fingerprints.insert(id.clone(), fingerprint);
            },
        )
        .await?;
        Ok(fingerprints)
    }
}

/// Prepare only the selected dependency closure, once per Artifact, computing up to the
/// parallelism's limit of fingerprints at a time. The result does not depend on completion
/// order: a failure reports the first failing Artifact in input order, and fingerprints after
/// it are cancelled because they cannot change which failure that is.
pub async fn prepare<'a>(
    config: &RepoConfig,
    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
    output_root: &Path,
    parallelism: &Parallelism,
    cancellation: CancellationToken,
) -> Result<BTreeMap<&'a ArtifactName, PreparedFingerprint>, String> {
    let artifacts = artifacts.into_iter().collect::<Vec<_>>();
    for id in &artifacts {
        let artifact = config
            .artifacts
            .get(*id)
            .ok_or_else(|| format!("Unknown Artifact: {id}"))?;
        scope::validate_file_target(&config.root, artifact).map_err(|error| error.to_string())?;
    }
    let mut prepared = BTreeMap::new();
    prepare_each(
        config,
        artifacts,
        output_root,
        parallelism,
        cancellation,
        |id, fingerprint| {
            prepared.insert(id, fingerprint);
        },
    )
    .await?;
    Ok(prepared)
}

/// [`prepare`], handing each fingerprint to `ready` as soon as it is computed.
pub(crate) async fn prepare_each<'a>(
    config: &RepoConfig,
    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
    output_root: &Path,
    parallelism: &Parallelism,
    cancellation: CancellationToken,
    ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
) -> Result<(), String> {
    acquire_each(
        Source::Borrowed(config),
        artifacts,
        output_root,
        parallelism,
        cancellation,
        ready,
    )
    .await
}

async fn acquire_each<'a>(
    source: Source<'_>,
    artifacts: impl IntoIterator<Item = &'a ArtifactName>,
    output_root: &Path,
    parallelism: &Parallelism,
    cancellation: CancellationToken,
    mut ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
) -> Result<(), String> {
    let config = source.config();
    let mut seen = BTreeSet::new();
    let ids: Vec<&'a ArtifactName> = artifacts
        .into_iter()
        .filter(|id| config.artifacts[*id].fingerprint.is_some() && seen.insert(*id))
        .collect();
    let tokens: Vec<_> = ids.iter().map(|_| cancellation.child_token()).collect();
    // Keep at most a window of full futures, including their process state, resident. The
    // shared semaphore also includes overlapping end-of-review rechecks.
    let fingerprint = |index: usize| {
        let id = ids[index];
        let token = &tokens[index];
        async move {
            let result = match parallelism.slots.acquire().await {
                Ok(_slot) if !token.is_cancelled() => {
                    compute(source, id, output_root, token.clone()).await
                }
                _ => Err(process::Error::Cancelled.to_string()),
            };
            (index, result)
        }
    };
    let mut pending = 0..ids.len();
    let mut running: FuturesUnordered<_> = pending
        .by_ref()
        .take(parallelism.limit())
        .map(&fingerprint)
        .collect();
    let mut failure: Option<(usize, String)> = None;
    while let Some((index, result)) = running.next().await {
        match result {
            Ok(fingerprint) => ready(ids[index], fingerprint),
            Err(error) if failure.as_ref().is_none_or(|(first, _)| index < *first) => {
                for token in &tokens[index + 1..] {
                    token.cancel();
                }
                failure = Some((index, error));
            }
            Err(_) => {}
        }
        if failure.is_none()
            && let Some(index) = pending.next()
        {
            running.push(fingerprint(index));
        }
    }
    match failure {
        Some((_, error)) => Err(error),
        None => Ok(()),
    }
}

/// Recompute the eval's key after a review: every Artifact it depends on is fingerprinted
/// again, so a change to any of them during the review is detected.
pub async fn recheck(
    config: &RepoConfig,
    eval: &Eval,
    output_root: &Path,
    parallelism: &Parallelism,
    cancellation: CancellationToken,
) -> Result<Option<crate::types::ReuseKey>, String> {
    validate_file_inputs(config, eval)?;
    let fingerprints = prepare(
        config,
        dependencies(config, eval),
        output_root,
        parallelism,
        cancellation,
    )
    .await?;
    validate_file_inputs(config, eval)?;
    Ok(eval_key(config, eval, &fingerprints)
        .ok()
        .map(|key| key.value))
}

/// Keyless Live reviews retain and compare every available admitted snapshot too.
pub(crate) async fn recheck_observations(
    config: &RepoConfig,
    expected: &BTreeMap<ArtifactName, crate::types::Fingerprint>,
    output: &Path,
    parallelism: &Parallelism,
    cancellation: CancellationToken,
) -> Result<bool, String> {
    let current = prepare(config, expected.keys(), output, parallelism, cancellation).await?;
    Ok(expected.iter().all(|(name, value)| {
        current
            .get(name)
            .is_some_and(|current| current.value == *value)
    }))
}

async fn compute(
    source: Source<'_>,
    id: &ArtifactName,
    output_root: &Path,
    cancellation: CancellationToken,
) -> Result<PreparedFingerprint, String> {
    let config = source.config();
    scope::validate_file_target(&config.root, &config.artifacts[id])
        .map_err(|error| error.to_string())?;
    let result = match &config.artifacts[id].fingerprint {
        // What the definitions bound under its target declare once expanded, not their bytes.
        Some(Fingerprint::Graph) => Ok(PreparedFingerprint {
            value: crate::graph_structure::read_scoped(&config.root, &config.artifacts[id])?
                .fingerprint(),
            manifest: None,
        }),
        Some(Fingerprint::Artifactsum { files, ignore }) => {
            content(config, id, files, ignore, &cancellation)
                .await
                .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
        }
        Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
            value: script(source, id, output_root, cancellation)
                .await
                .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
            manifest: None,
        }),
        None => Err(format!("Artifact {id} declares fingerprint: false.")),
    }?;
    scope::validate_file_target(&config.root, &config.artifacts[id])
        .map_err(|error| error.to_string())?;
    Ok(result)
}

/// The built-in hash of the Artifact's own input files, nothing else.
async fn content(
    config: &RepoConfig,
    id: &ArtifactName,
    inputs: &[crate::config::LogicalPath],
    ignore: &IgnorePatterns,
    cancellation: &CancellationToken,
) -> Result<PreparedFingerprint, String> {
    let files = content::files(config, id, inputs, ignore, cancellation).await?;
    Ok(artifactsum(files))
}

fn artifactsum(files: content::Files) -> PreparedFingerprint {
    let mut manifest = Manifest {
        inputs: files.digest.clone(),
        files: Some(
            files
                .files
                .iter()
                .map(|(path, file)| {
                    (
                        path.clone(),
                        content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
                            .parse()
                            .expect("eight-byte SHA-256 prefix"),
                    )
                })
                .collect(),
        ),
    };
    if serde_json::to_vec(&manifest)
        .expect("manifest is JSON")
        .len()
        > MANIFEST_BYTES
    {
        manifest.files = None;
    }
    PreparedFingerprint {
        value: format!("artifactsum:{}", files.digest)
            .parse()
            .expect("artifactsum digest is a fingerprint"),
        manifest: Some(manifest),
    }
}

async fn script(
    source: Source<'_>,
    artifact_id: &ArtifactName,
    output_root: &Path,
    cancellation: CancellationToken,
) -> Result<crate::types::Fingerprint, String> {
    if cancellation.is_cancelled() {
        return Err(process::Error::Cancelled.to_string());
    }
    let (command, disposable) = match source {
        Source::Borrowed(config) => prepare_script(config, artifact_id, output_root)?,
        Source::Shared(config) => {
            let config = config.clone();
            let id = artifact_id.clone();
            let output_root = output_root.to_path_buf();
            crate::task::blocking(move || prepare_script(&config, &id, &output_root)).await??
        }
    };
    let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id});
    let result = command
        .fingerprint(input.to_string().into_bytes(), cancellation.clone())
        .await;
    let cleaned = match source {
        Source::Borrowed(_) => disposable.close(),
        Source::Shared(_) => crate::task::blocking(move || disposable.close()).await?,
    };
    if cancellation.is_cancelled() {
        return Err(process::Error::Cancelled.to_string());
    }
    let output = result.map_err(|error| error.to_string())?;
    if !output.status.success() {
        return Err(format!(
            "Fingerprint command exited with {}.",
            output.status
        ));
    }
    if output.truncated {
        return Err("Fingerprint command output exceeded its limit.".into());
    }
    let value = validate_output(&output.stdout)?;
    cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
    Ok(value)
}

fn prepare_script(
    config: &RepoConfig,
    artifact_id: &ArtifactName,
    output_root: &Path,
) -> Result<(runtime::Command, scratch::Scratch), String> {
    let artifact = &config.artifacts[artifact_id];
    let Some(Fingerprint::Script {
        command,
        args,
        files,
        timeout_ms,
    }) = &artifact.fingerprint
    else {
        unreachable!("fingerprint script")
    };
    let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
    for input in files {
        scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
    }
    let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
    let program = scope::executable(&config.root, &scope, artifact_id, command)
        .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
    let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
    let output_root =
        workspace::prepare_directory(output_root, &config.root).map_err(|e| e.to_string())?;
    let disposable = scratch::Scratch::create(&output_root).map_err(|e| e.to_string())?;
    let mut command = runtime::Command::prepare(
        program,
        args.into_iter().map(Into::into).collect(),
        &config.root,
        disposable.path(),
        *timeout_ms,
    )
    .map_err(|e| e.to_string())?;
    command.cwd = cwd;
    Ok((command, disposable))
}

fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
    let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
    if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
        || !value
            .iter()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
    {
        return Err(format!(
            "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
        ));
    }
    String::from_utf8(value.to_vec())
        .map_err(|error| error.to_string())?
        .parse()
}