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
//! `apr cp SRC DST` copy-by-manifest classifier (CRUX-A-11).
//!
//! Contract: `contracts/crux-A-11-v1.yaml`.
//!
//! Pure classifier — models what `apr cp` does at the manifest layer
//! without touching the filesystem. Given a source manifest (list of
//! blob shas) and a destination tag, returns the destination manifest
//! and a plan of what filesystem ops are expected (0 blob bytes
//! copied; one new manifest file; N hard-link-or-noop operations).
//!
//! Formula (from contract):
//! `manifest(DST).blobs == manifest(SRC).blobs (identical sha256 list)`
//! `stat(blob_path).st_ino == stat(blob_path_after_cp).st_ino`
//! `disk_usage_delta ≈ sizeof(manifest_json)`
//!
//! The integration-level claims
//! * `du -b` delta ≤ 4 KiB,
//! * `stat -c %i` equality across SRC/DST blob paths,
//! are discharged by a separate filesystem-gated harness. This module
//! proves the algorithm-level precondition: the destination manifest
//! references the same blob-sha set, and the planned op stream contains
//! zero "copy bytes" ops.
/// Reason the classifier rejects a copy.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CopyError {
/// Source tag not found in the local registry.
SourceNotFound(String),
/// Destination tag already exists — `apr cp` refuses to overwrite.
DestinationExists(String),
/// Tag string is syntactically invalid (empty or contains a NUL /
/// path separator that would escape the registry directory).
InvalidTag(String),
/// Source manifest has zero blobs — nothing to copy.
EmptyManifest(String),
}
impl std::fmt::Display for CopyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CopyError::SourceNotFound(t) => write!(f, "source tag not found: {t:?}"),
CopyError::DestinationExists(t) => {
write!(f, "destination tag already exists: {t:?}")
}
CopyError::InvalidTag(t) => write!(f, "invalid tag: {t:?}"),
CopyError::EmptyManifest(t) => {
write!(f, "source manifest has no blobs: {t:?}")
}
}
}
}
impl std::error::Error for CopyError {}
/// Minimal view of a manifest the classifier needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManifestView {
pub tag: String,
/// Sha256 digests (lowercase hex) of each blob referenced by the
/// manifest, in manifest order.
pub blob_shas: Vec<String>,
}
/// One step in the planned op stream for `apr cp`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CopyOp {
/// Attempt to hard-link the blob identified by `sha` from the
/// registry's blob dir to itself at the same path. Real hard-link
/// in the filesystem harness; in the classifier this is a no-op
/// that records the sha so the caller can assert "no byte-copy".
HardLink { sha: String },
/// Write a new manifest JSON file for the destination tag. The
/// `bytes` field is the serialized manifest length in the harness;
/// the classifier only records that exactly one such op exists.
WriteManifest { tag: String },
}
/// Plan returned by `plan_copy`. `dst` is the destination manifest;
/// `ops` is the ordered op stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CopyPlan {
pub dst: ManifestView,
pub ops: Vec<CopyOp>,
}
/// Tags are `name:tag` or `name` forms. Reject empty strings, strings
/// containing path separators, and NUL. This is the algorithm-level
/// analogue of the filesystem-level "tag path must stay inside
/// ~/.apr/models" invariant.
fn tag_is_valid(tag: &str) -> bool {
!tag.is_empty() && !tag.contains('/') && !tag.contains('\\') && !tag.contains('\0')
}
/// Look up a manifest by tag in a registry slice.
fn find_manifest<'a>(registry: &'a [ManifestView], tag: &str) -> Option<&'a ManifestView> {
registry.iter().find(|m| m.tag == tag)
}
/// Build the destination manifest + op stream for `apr cp SRC DST`.
///
/// Algorithm-level precondition for FALSIFY-CRUX-A-11-001/002:
/// * the destination manifest has the EXACT same blob-sha list as SRC,
/// so no new bytes need to land on disk (disk-usage delta is the
/// manifest file only);
/// * every blob op is a `HardLink`, not a byte-copy;
/// * exactly one `WriteManifest { tag: dst }` op is emitted.
pub fn plan_copy(registry: &[ManifestView], src: &str, dst: &str) -> Result<CopyPlan, CopyError> {
if !tag_is_valid(src) {
return Err(CopyError::InvalidTag(src.to_string()));
}
if !tag_is_valid(dst) {
return Err(CopyError::InvalidTag(dst.to_string()));
}
let src_manifest =
find_manifest(registry, src).ok_or_else(|| CopyError::SourceNotFound(src.to_string()))?;
if find_manifest(registry, dst).is_some() {
return Err(CopyError::DestinationExists(dst.to_string()));
}
if src_manifest.blob_shas.is_empty() {
return Err(CopyError::EmptyManifest(src.to_string()));
}
let dst_manifest = ManifestView {
tag: dst.to_string(),
blob_shas: src_manifest.blob_shas.clone(),
};
let mut ops: Vec<CopyOp> = src_manifest
.blob_shas
.iter()
.map(|sha| CopyOp::HardLink { sha: sha.clone() })
.collect();
ops.push(CopyOp::WriteManifest {
tag: dst.to_string(),
});
Ok(CopyPlan {
dst: dst_manifest,
ops,
})
}
/// Return true iff `plan` contains zero byte-copy operations. Used by
/// the FALSIFY-001 algorithm-level proof that `apr cp` never allocates
/// new blob bytes.
pub fn plan_has_no_byte_copy(plan: &CopyPlan) -> bool {
plan.ops
.iter()
.all(|op| matches!(op, CopyOp::HardLink { .. } | CopyOp::WriteManifest { .. }))
}
/// Return the number of blob ops in the plan. All of them must be
/// `HardLink`; asserted by `plan_has_no_byte_copy`.
pub fn plan_blob_op_count(plan: &CopyPlan) -> usize {
plan.ops
.iter()
.filter(|op| matches!(op, CopyOp::HardLink { .. }))
.count()
}
/// Count the number of manifest-write ops. Must be exactly 1 for a
/// well-formed copy.
pub fn plan_manifest_write_count(plan: &CopyPlan) -> usize {
plan.ops
.iter()
.filter(|op| matches!(op, CopyOp::WriteManifest { .. }))
.count()
}
/// Return true iff src and dst manifests reference the SAME blob shas
/// in the SAME order — the algorithm-level precondition for the
/// hard-link-inode-equality FALSIFY-002 check.
pub fn dst_blob_shas_match_src(src: &ManifestView, dst: &ManifestView) -> bool {
src.blob_shas == dst.blob_shas
}
#[cfg(test)]
mod tests {
use super::*;
fn sample_registry() -> Vec<ManifestView> {
vec![
ManifestView {
tag: "qwen2.5-0.5b:latest".to_string(),
blob_shas: vec!["a".repeat(64), "b".repeat(64), "c".repeat(64)],
},
ManifestView {
tag: "llama3:latest".to_string(),
blob_shas: vec!["d".repeat(64)],
},
]
}
#[test]
fn copy_produces_identical_blob_sha_list() {
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:mycopy").unwrap();
assert_eq!(plan.dst.tag, "qwen2.5-0.5b:mycopy");
assert_eq!(plan.dst.blob_shas, reg[0].blob_shas);
assert!(dst_blob_shas_match_src(®[0], &plan.dst));
}
#[test]
fn falsify_001_sub_claim_zero_byte_copy_ops() {
// CRUX-A-11 ALGO-001 sub-claim of FALSIFY-001: the planned op
// stream contains zero byte-copy operations — every blob op
// is a HardLink. Algorithm-level analogue of the `du -b`
// delta ≤ 4 KiB check (if no byte-copy, then delta == sizeof
// manifest file, which is well under 4 KiB).
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:mycopy").unwrap();
assert!(plan_has_no_byte_copy(&plan));
assert_eq!(plan_blob_op_count(&plan), reg[0].blob_shas.len());
assert_eq!(plan_manifest_write_count(&plan), 1);
}
#[test]
fn falsify_002_sub_claim_blob_shas_equal() {
// CRUX-A-11 ALGO-002 sub-claim of FALSIFY-002: if SRC and DST
// manifests reference the same sha256, then (assuming a
// content-addressed blob store) `stat -c %i` on the resolved
// blob path is equal — there is only one path per sha.
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:mycopy").unwrap();
for (src_sha, dst_sha) in reg[0].blob_shas.iter().zip(plan.dst.blob_shas.iter()) {
assert_eq!(
src_sha, dst_sha,
"blob-sha divergence breaks hard-link claim"
);
}
}
#[test]
fn source_not_found_is_error() {
let reg = sample_registry();
let err = plan_copy(®, "does-not-exist:latest", "x:y").unwrap_err();
assert_eq!(
err,
CopyError::SourceNotFound("does-not-exist:latest".to_string())
);
}
#[test]
fn destination_exists_is_error() {
let reg = sample_registry();
let err = plan_copy(®, "qwen2.5-0.5b:latest", "llama3:latest").unwrap_err();
assert_eq!(
err,
CopyError::DestinationExists("llama3:latest".to_string())
);
}
#[test]
fn empty_source_tag_is_invalid() {
let reg = sample_registry();
let err = plan_copy(®, "", "x:y").unwrap_err();
assert!(matches!(err, CopyError::InvalidTag(_)));
}
#[test]
fn empty_destination_tag_is_invalid() {
let reg = sample_registry();
let err = plan_copy(®, "qwen2.5-0.5b:latest", "").unwrap_err();
assert!(matches!(err, CopyError::InvalidTag(_)));
}
#[test]
fn tag_with_path_separator_is_invalid() {
let reg = sample_registry();
// Forward slash would escape ~/.apr/models via path traversal.
let err = plan_copy(®, "qwen2.5-0.5b:latest", "../evil").unwrap_err();
assert!(matches!(err, CopyError::InvalidTag(_)));
// Backslash, same reason on Windows hosts.
let err = plan_copy(®, "qwen2.5-0.5b:latest", r"a\b").unwrap_err();
assert!(matches!(err, CopyError::InvalidTag(_)));
}
#[test]
fn tag_with_nul_is_invalid() {
let reg = sample_registry();
let err = plan_copy(®, "qwen2.5-0.5b:latest", "bad\0tag").unwrap_err();
assert!(matches!(err, CopyError::InvalidTag(_)));
}
#[test]
fn empty_manifest_source_is_error() {
let reg = vec![ManifestView {
tag: "empty:latest".to_string(),
blob_shas: vec![],
}];
let err = plan_copy(®, "empty:latest", "empty:copy").unwrap_err();
assert_eq!(err, CopyError::EmptyManifest("empty:latest".to_string()));
}
#[test]
fn single_blob_source_works() {
let reg = sample_registry();
let plan = plan_copy(®, "llama3:latest", "llama3:pinned").unwrap();
assert_eq!(plan.dst.blob_shas.len(), 1);
assert_eq!(plan_blob_op_count(&plan), 1);
assert_eq!(plan_manifest_write_count(&plan), 1);
}
#[test]
fn plan_is_deterministic() {
// Same inputs → byte-identical plan across invocations.
let reg = sample_registry();
let a = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:a").unwrap();
let b = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:a").unwrap();
assert_eq!(a, b);
}
#[test]
fn ops_preserve_source_manifest_order() {
// Blob order must match SRC manifest so content-addressed
// lookup is stable downstream.
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:a").unwrap();
let mut seen = vec![];
for op in &plan.ops {
if let CopyOp::HardLink { sha } = op {
seen.push(sha.clone());
}
}
assert_eq!(seen, reg[0].blob_shas);
}
#[test]
fn write_manifest_op_is_last() {
// The manifest file must be written AFTER all hard-links are
// in place; crash-safety invariant (a partial state with a
// manifest pointing at a missing blob is forbidden).
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:a").unwrap();
match plan.ops.last() {
Some(CopyOp::WriteManifest { tag }) => {
assert_eq!(tag, "qwen2.5-0.5b:a");
}
other => panic!("expected WriteManifest last, got {other:?}"),
}
}
#[test]
fn no_byte_copy_holds_for_all_plans() {
// Stronger: FALSIFY-001 sub-claim holds for every manifest in
// the sample registry.
let reg = sample_registry();
for src in ® {
let plan = plan_copy(®, &src.tag, &format!("{}-copy", src.tag)).unwrap();
assert!(plan_has_no_byte_copy(&plan));
}
}
#[test]
fn copying_to_self_is_destination_exists() {
// SRC == DST ⇒ DestinationExists (SRC already occupies that
// tag). Prevents accidental self-clobber.
let reg = sample_registry();
let err = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:latest").unwrap_err();
assert_eq!(
err,
CopyError::DestinationExists("qwen2.5-0.5b:latest".to_string())
);
}
#[test]
fn blob_count_matches_src_exactly() {
// FALSIFY-001 invariant: blob count unchanged across registry.
// The DST manifest references the SAME number of shas as SRC
// (and, since shas are content-addressed, refers to the same
// physical blobs).
let reg = sample_registry();
let plan = plan_copy(®, "qwen2.5-0.5b:latest", "qwen2.5-0.5b:a").unwrap();
assert_eq!(plan.dst.blob_shas.len(), reg[0].blob_shas.len());
}
}