1mod content;
4mod scratch;
5
6use std::{
7 collections::{BTreeMap, BTreeSet},
8 path::Path,
9 sync::Arc,
10};
11
12use futures_util::{StreamExt, stream::FuturesUnordered};
13use serde::{Deserialize, Serialize};
14use serde_json::json;
15use sha2::{Digest, Sha256};
16use tokio::sync::Semaphore;
17use tokio_util::sync::CancellationToken;
18
19pub use crate::store::history::{Entry, list, remove, show};
20pub(crate) use content::HASH_BUFFER_BYTES;
21pub use content::IgnorePatterns;
22
23use crate::{
24 config::{ArtifactName, Eval, EvalDeclaration, Fingerprint, Profile, RepoConfig},
25 process, runtime, scope,
26 store::{Execution, Request},
27 workspace,
28};
29
30const MANIFEST_BYTES: usize = 64 * 1024;
33const MAX_SUMMARY_PATHS: usize = 10;
35const FINGERPRINT_INPUT_VERSION: u32 = 1;
38const MANIFEST_DIGEST_PREFIX_BYTES: usize = 8;
41const KIND_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-kind-key-v1\n";
43const PARTS_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-parts-key-v1\n";
46const REUSE_KEY_FORMAT_PREFIX: &str = "artifactize-key-v2\n";
49
50pub fn eval_definition_hash(eval: &EvalDeclaration) -> crate::types::DefinitionHash {
54 let kind = match &eval.profile() {
55 Profile::Agent { .. } => "agent",
56 Profile::Human {} => "human",
57 Profile::Runtime { .. } => "runtime",
58 };
59 let mut criteria = json!({
60 "kind": kind,
61 "payload": eval.payload(),
62 "passSchema": eval.pass_schema(),
63 "failSchema": eval.fail_schema(),
64 });
65 if let Profile::Runtime { command, args, .. } = &eval.profile() {
66 criteria["command"] = json!(command);
67 criteria["args"] = json!(args);
68 }
69 criteria.sort_all_objects();
70 content::hex(&Sha256::digest(
71 serde_json::to_vec(&criteria).expect("evaluation criteria is JSON"),
72 ))
73 .parse()
74 .expect("a SHA-256 digest in hex is a definition hash")
75}
76
77#[derive(Debug, Clone)]
79pub struct PreparedFingerprint {
80 pub value: crate::types::Fingerprint,
81 pub manifest: Option<Manifest>,
82}
83
84#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87pub struct Manifest {
88 pub inputs: crate::types::Sha256Digest,
90 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub files: Option<BTreeMap<String, crate::types::DigestPrefix>>,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct Key {
99 pub value: crate::types::ReuseKey,
100 pub eval_def_hash: crate::types::DefinitionHash,
101 pub fingerprints: BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
103 pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub enum Unkeyed {
109 Target,
111 Dependency(ArtifactName),
113}
114
115#[derive(Debug, Serialize)]
118#[serde(rename_all = "camelCase")]
119pub struct Changes {
120 pub since_run_id: crate::types::RunId,
121 #[serde(skip_serializing_if = "Option::is_none")]
124 pub files: Option<Vec<String>>,
125 #[serde(skip_serializing_if = "Option::is_none")]
128 pub dependencies: Option<Vec<String>>,
129 pub summary: String,
130}
131
132pub fn dependencies<'a>(config: &'a RepoConfig, eval: &'a Eval) -> BTreeSet<&'a ArtifactName> {
135 std::iter::once(&eval.target)
136 .chain(config.descendants(&eval.target))
137 .chain(&eval.deps)
138 .collect()
139}
140
141pub(crate) fn fingerprint_targets<'a>(
143 config: &'a RepoConfig,
144 required: &BTreeSet<&'a ArtifactName>,
145) -> BTreeSet<&'a ArtifactName> {
146 config
147 .evals
148 .iter()
149 .filter(|eval| required.contains(&eval.target))
150 .flat_map(|eval| dependencies(config, eval))
151 .collect()
152}
153
154pub fn key(
156 eval_def_hash: &crate::types::DefinitionHash,
157 fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
158) -> crate::types::ReuseKey {
159 let mut digest = Sha256::new();
160 digest.update(format!("{REUSE_KEY_FORMAT_PREFIX}eval {eval_def_hash}\n"));
161 for (name, fingerprint) in fingerprints {
163 digest.update(format!("artifact {name} {fingerprint}\n"));
164 }
165 content::hex(&digest.finalize())
166 .parse()
167 .expect("SHA-256 is a reuse key")
168}
169
170pub fn key_with_kinds(
172 eval_def_hash: &crate::types::DefinitionHash,
173 fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
174 kinds: &BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
175) -> crate::types::ReuseKey {
176 if kinds.is_empty() {
177 return key(eval_def_hash, fingerprints);
178 }
179 let mut digest = Sha256::new();
180 digest.update(KIND_KEY_FORMAT_PREFIX);
181 digest.update(key(eval_def_hash, fingerprints).as_bytes());
182 digest.update(serde_json::to_vec(kinds).expect("Artifact kinds are JSON"));
183 content::hex(&digest.finalize())
184 .parse()
185 .expect("SHA-256 is a reuse key")
186}
187
188pub(crate) fn parts_key(value: &crate::types::ReuseKey) -> crate::types::ReuseKey {
191 let mut digest = Sha256::new();
192 digest.update(PARTS_KEY_FORMAT_PREFIX);
193 digest.update(value.as_bytes());
194 content::hex(&digest.finalize())
195 .parse()
196 .expect("SHA-256 is a reuse key")
197}
198
199pub fn eval_key(
202 config: &RepoConfig,
203 eval: &Eval,
204 fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
205) -> Result<Key, Unkeyed> {
206 if !fingerprints.contains_key(&eval.target) {
207 return Err(Unkeyed::Target);
208 }
209 let mut values: BTreeMap<ArtifactName, crate::types::Fingerprint> = BTreeMap::new();
210 for id in dependencies(config, eval) {
211 let fingerprint = fingerprints
212 .get(id)
213 .ok_or_else(|| Unkeyed::Dependency(id.clone()))?;
214 values.insert(id.clone(), fingerprint.value.clone());
215 }
216 let eval_def_hash = eval_definition_hash(&eval.declaration);
217 let artifact_kinds = values
218 .keys()
219 .map(|id| (id.clone(), config.artifacts[id].kind))
220 .collect();
221 let value = key_with_kinds(&eval_def_hash, &values, &artifact_kinds);
222 let value = if config.artifacts[&eval.target].parts.is_empty() {
223 value
224 } else {
225 parts_key(&value)
226 };
227 Ok(Key {
228 value,
229 eval_def_hash,
230 fingerprints: values,
231 artifact_kinds,
232 })
233}
234
235pub fn eval_keys<'a>(
237 config: &'a RepoConfig,
238 fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
239) -> BTreeMap<&'a crate::types::EvalId, Key> {
240 config
241 .evals
242 .iter()
243 .filter_map(|eval| Some((&eval.id, eval_key(config, eval, fingerprints).ok()?)))
244 .collect()
245}
246
247#[derive(Debug, Clone)]
250pub struct Parallelism {
251 slots: Arc<Semaphore>,
252 limit: usize,
253}
254
255impl Parallelism {
256 pub fn new(limit: usize) -> Self {
258 let limit = limit.max(1);
259 Self {
260 slots: Arc::new(Semaphore::new(limit)),
261 limit,
262 }
263 }
264
265 pub fn available() -> usize {
267 std::thread::available_parallelism().map_or(1, usize::from)
268 }
269
270 pub fn limit(&self) -> usize {
271 self.limit
272 }
273}
274
275pub(crate) fn validate_file_inputs(config: &RepoConfig, eval: &Eval) -> Result<(), String> {
277 let scope = scope::eval_scope(config, eval).map_err(|error| error.to_string())?;
278 for artifact in scope.artifacts.values() {
279 scope::validate_file_target(&config.root, artifact).map_err(|error| error.to_string())?;
280 }
281 Ok(())
282}
283
284pub async fn prepare<'a>(
289 config: &RepoConfig,
290 artifacts: impl IntoIterator<Item = &'a ArtifactName>,
291 output_root: &Path,
292 parallelism: &Parallelism,
293 cancellation: CancellationToken,
294) -> Result<BTreeMap<&'a ArtifactName, PreparedFingerprint>, String> {
295 let mut prepared = BTreeMap::new();
296 prepare_each(
297 config,
298 artifacts,
299 output_root,
300 parallelism,
301 cancellation,
302 |id, fingerprint| {
303 prepared.insert(id, fingerprint);
304 },
305 )
306 .await?;
307 Ok(prepared)
308}
309
310pub(crate) async fn prepare_each<'a>(
312 config: &RepoConfig,
313 artifacts: impl IntoIterator<Item = &'a ArtifactName>,
314 output_root: &Path,
315 parallelism: &Parallelism,
316 cancellation: CancellationToken,
317 mut ready: impl FnMut(&'a ArtifactName, PreparedFingerprint),
318) -> Result<(), String> {
319 let artifacts: Vec<_> = artifacts.into_iter().collect();
320 for id in &artifacts {
321 scope::validate_file_target(&config.root, &config.artifacts[*id])
322 .map_err(|error| error.to_string())?;
323 }
324 let mut seen = BTreeSet::new();
325 let ids: Vec<&'a ArtifactName> = artifacts
326 .into_iter()
327 .filter(|id| config.artifacts[*id].fingerprint.is_some() && seen.insert(*id))
328 .collect();
329 let tokens: Vec<_> = ids.iter().map(|_| cancellation.child_token()).collect();
330 let mut running: FuturesUnordered<_> = ids
331 .iter()
332 .zip(&tokens)
333 .enumerate()
334 .map(|(index, (id, token))| async move {
335 let result = match parallelism.slots.acquire().await {
336 Ok(_slot) if !token.is_cancelled() => {
338 compute(config, id, output_root, token.clone()).await
339 }
340 _ => Err(process::Error::Cancelled.to_string()),
341 };
342 (index, result)
343 })
344 .collect();
345 let mut failure: Option<(usize, String)> = None;
346 while let Some((index, result)) = running.next().await {
347 match result {
348 Ok(fingerprint) => ready(ids[index], fingerprint),
349 Err(error) if failure.as_ref().is_none_or(|(first, _)| index < *first) => {
350 for token in &tokens[index + 1..] {
351 token.cancel();
352 }
353 failure = Some((index, error));
354 }
355 Err(_) => {}
356 }
357 }
358 match failure {
359 Some((_, error)) => Err(error),
360 None => Ok(()),
361 }
362}
363
364pub fn reuse(request: &mut Request, execution: &Execution, completed_at: crate::types::Timestamp) {
368 request.joined = request.execution_id.as_ref() == Some(&execution.id);
369 request.state = match execution.state.clone() {
370 crate::store::ExecutionState::Completed { result, .. } => {
371 crate::store::RequestState::completed(result, completed_at)
372 }
373 crate::store::ExecutionState::Failed { error, code, .. } => {
374 crate::store::RequestState::failed(error, code, completed_at)
375 }
376 state => state.into(),
377 };
378 request.execution_id = Some(execution.id.clone());
379 request.profile = execution.profile.clone();
380 request.options = execution.options.clone();
381 request.provenance = Some(execution.provenance.clone());
382 request.usage = None;
383 request.reused_usage = execution.usage.clone();
384 request.producer = execution.producer.clone();
385 request.session = execution
386 .producer
387 .as_ref()
388 .and_then(|producer| producer.session.clone());
389 request.reviewer = execution.reviewer.clone();
390 request.origin = execution.origin.clone();
391 request.queue = None;
392 request.blocked_reason = None;
393}
394
395pub async fn recheck(
398 config: &RepoConfig,
399 eval: &Eval,
400 output_root: &Path,
401 parallelism: &Parallelism,
402 cancellation: CancellationToken,
403) -> Result<Option<crate::types::ReuseKey>, String> {
404 validate_file_inputs(config, eval)?;
405 let fingerprints = prepare(
406 config,
407 dependencies(config, eval),
408 output_root,
409 parallelism,
410 cancellation,
411 )
412 .await?;
413 validate_file_inputs(config, eval)?;
414 Ok(eval_key(config, eval, &fingerprints)
415 .ok()
416 .map(|key| key.value))
417}
418
419async fn compute(
420 config: &RepoConfig,
421 id: &ArtifactName,
422 output_root: &Path,
423 cancellation: CancellationToken,
424) -> Result<PreparedFingerprint, String> {
425 scope::validate_file_target(&config.root, &config.artifacts[id])
426 .map_err(|error| error.to_string())?;
427 let result = match &config.artifacts[id].fingerprint {
428 Some(Fingerprint::Graph) => Ok(PreparedFingerprint {
429 value: crate::graph_structure::read(&config.root)?.fingerprint(),
430 manifest: None,
431 }),
432 Some(Fingerprint::Artifactsum { files, ignore }) => {
433 content(config, id, files, ignore, &cancellation)
434 .await
435 .map_err(|error| format!("Artifactsum for Artifact {id} failed: {error}"))
436 }
437 Some(Fingerprint::Script { .. }) => Ok(PreparedFingerprint {
438 value: script(config, id, output_root, cancellation)
439 .await
440 .map_err(|error| format!("Fingerprint script for Artifact {id} failed: {error}"))?,
441 manifest: None,
442 }),
443 None => Err(format!("Artifact {id} declares fingerprint: false.")),
444 }?;
445 scope::validate_file_target(&config.root, &config.artifacts[id])
446 .map_err(|error| error.to_string())?;
447 Ok(result)
448}
449
450async fn content(
452 config: &RepoConfig,
453 id: &ArtifactName,
454 inputs: &[crate::config::LogicalPath],
455 ignore: &IgnorePatterns,
456 cancellation: &CancellationToken,
457) -> Result<PreparedFingerprint, String> {
458 let files = content::files(config, id, inputs, ignore, cancellation).await?;
459 let mut manifest = Manifest {
460 inputs: files.digest.clone(),
461 files: Some(
462 files
463 .files
464 .iter()
465 .map(|(path, file)| {
466 (
467 path.to_string(),
468 content::hex(&file.as_bytes()[..MANIFEST_DIGEST_PREFIX_BYTES])
469 .parse()
470 .expect("eight-byte SHA-256 prefix"),
471 )
472 })
473 .collect(),
474 ),
475 };
476 if serde_json::to_vec(&manifest)
477 .expect("manifest is JSON")
478 .len()
479 > MANIFEST_BYTES
480 {
481 manifest.files = None;
482 }
483 Ok(PreparedFingerprint {
484 value: format!("artifactsum:{}", files.digest)
485 .parse()
486 .expect("artifactsum digest is a fingerprint"),
487 manifest: Some(manifest),
488 })
489}
490
491pub fn changes(
494 previous: &Execution,
495 target: &ArtifactName,
496 current: &Key,
497 manifest: Option<&Manifest>,
498) -> Changes {
499 let mut parts = Vec::new();
500 let mut files = None;
501 if previous.fingerprints.get(target) != current.fingerprints.get(target) {
502 match previous.manifest.as_ref().zip(manifest) {
503 Some((old, new)) if old.inputs == new.inputs => files = Some(Vec::new()),
504 Some((old, new)) => {
505 files = old
506 .files
507 .as_ref()
508 .zip(new.files.as_ref())
509 .map(|(old, new)| diff(old, new));
510 match &files {
511 Some(files) if !files.is_empty() => {
512 let shown = files
513 .iter()
514 .take(MAX_SUMMARY_PATHS)
515 .cloned()
516 .collect::<Vec<_>>()
517 .join(", ");
518 parts.push(match files.len() {
519 0..=MAX_SUMMARY_PATHS => format!("changed: {shown}"),
520 total => {
521 format!("changed: {shown} and {} more", total - MAX_SUMMARY_PATHS)
522 }
523 });
524 }
525 _ => parts.push("inputs changed".to_owned()),
526 }
527 }
528 None => parts.push("fingerprint changed".to_owned()),
529 }
530 }
531 let dependencies = (!previous.fingerprints.is_empty())
532 .then(|| {
533 let others = |map: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>| {
534 map.iter()
535 .filter(|(name, _)| *name != target)
536 .map(|(name, value)| (name.clone(), value.clone()))
537 .collect::<BTreeMap<_, _>>()
538 };
539 diff(
540 &others(&previous.fingerprints),
541 &others(¤t.fingerprints),
542 )
543 })
544 .filter(|dependencies| !dependencies.is_empty());
545 for dependency in dependencies.iter().flatten() {
546 parts.push(if let Some(id) = dependency.strip_prefix('+') {
547 format!("dependency {id} added")
548 } else if let Some(id) = dependency.strip_prefix('-') {
549 format!("dependency {id} removed")
550 } else {
551 format!("dependency {dependency} changed")
552 });
553 }
554 if parts.is_empty() {
555 parts.push("fingerprint changed".to_owned());
556 }
557 Changes {
558 since_run_id: previous.provenance.run_id.clone(),
559 files,
560 dependencies,
561 summary: parts.join("; "),
562 }
563}
564
565fn diff<K: Ord + std::fmt::Display, T: PartialEq>(
566 old: &BTreeMap<K, T>,
567 new: &BTreeMap<K, T>,
568) -> Vec<String> {
569 old.keys()
570 .chain(new.keys())
571 .collect::<BTreeSet<_>>()
572 .into_iter()
573 .filter_map(|key| match (old.get(key), new.get(key)) {
574 (Some(old), Some(new)) if old != new => Some(key.to_string()),
575 (None, Some(_)) => Some(format!("+{key}")),
576 (Some(_), None) => Some(format!("-{key}")),
577 _ => None,
578 })
579 .collect()
580}
581
582async fn script(
583 config: &RepoConfig,
584 artifact_id: &ArtifactName,
585 output_root: &Path,
586 cancellation: CancellationToken,
587) -> Result<crate::types::Fingerprint, String> {
588 if cancellation.is_cancelled() {
589 return Err(process::Error::Cancelled.to_string());
590 }
591 let artifact = &config.artifacts[artifact_id];
592 let Some(Fingerprint::Script {
593 command,
594 args,
595 files,
596 timeout_ms,
597 }) = &artifact.fingerprint
598 else {
599 unreachable!("fingerprint script")
600 };
601 let cwd = scope::scoped_path(&config.root, artifact.folder()).map_err(|e| e.to_string())?;
602 for input in files {
603 scope::scoped_path(&cwd, Path::new(input)).map_err(|e| e.to_string())?;
604 }
605 let scope = scope::argv_scope(config, artifact_id, args).map_err(|e| e.to_string())?;
606 let program = scope::executable(&config.root, &scope, artifact_id, command)
607 .map_err(|error| format!("Fingerprint executable could not be spawned: {error}"))?;
608 let args = scope::resolve_argv(config, &scope, artifact_id, args).map_err(|e| e.to_string())?;
609 let input = json!({"version":FINGERPRINT_INPUT_VERSION,"artifactId":artifact_id});
610 let output_root =
611 workspace::prepare_directory(output_root, &config.root).map_err(|e| e.to_string())?;
612 let disposable = scratch::Scratch::create(&output_root).map_err(|e| e.to_string())?;
613 let result = async {
614 let mut command = runtime::Command::prepare(
615 program,
616 args.iter().map(Into::into).collect(),
617 &config.root,
618 disposable.path(),
619 *timeout_ms,
620 )
621 .map_err(|e| e.to_string())?;
622 command.cwd = cwd;
623 let output = command
624 .output(input.to_string().into_bytes(), cancellation.clone())
625 .await
626 .map_err(|e| e.to_string())?;
627 if !output.status.success() {
628 return Err(format!(
629 "Fingerprint command exited with {}.",
630 crate::platform::exit_description(&output.status)
631 ));
632 }
633 if output.truncated {
634 return Err("Fingerprint command output exceeded its limit.".into());
635 }
636 validate_output(&output.stdout)
637 }
638 .await;
639 let cleaned = disposable.close();
640 if cancellation.is_cancelled() {
641 return Err(process::Error::Cancelled.to_string());
642 }
643 let value = result?;
644 cleaned.map_err(|_| "Fingerprint validation failed.".to_owned())?;
645 Ok(value)
646}
647
648fn validate_output(stdout: &[u8]) -> Result<crate::types::Fingerprint, String> {
649 let (value, endings) = crate::platform::fingerprint_line_ending(stdout);
650 if !(1..=crate::types::MAX_FINGERPRINT_BYTES).contains(&value.len())
651 || !value
652 .iter()
653 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b':' | b'-'))
654 {
655 return Err(format!(
656 "stdout must contain 1–128 characters from [A-Za-z0-9._:-], with at most one trailing {endings}."
657 ));
658 }
659 String::from_utf8(value.to_vec())
660 .map_err(|error| error.to_string())?
661 .parse()
662}
663
664#[cfg(test)]
665mod tests;