team-ljyzipelo

공개

파일 스냅샷 공개 API 회귀를 추가함

작성자
코노모리 카논
작성 시각
커밋
b6521d55061c721c2a9102b39533ad941a910010
부모
b7c3d55
이 시점의 파일 보기

변경된 파일 13개

+1,782-0
추가tests/rust-file-snapshot/Cargo.lock+102-0
@@ -0,0 +1,102 @@
1추가: # This file is automatically @generated by Cargo.
2추가: # It is not intended for manual editing.
3추가: version = 4
4추가:
5추가: [[package]]
6추가: name = "block-buffer"
7추가: version = "0.10.4"
8추가: source = "registry+https://github.com/rust-lang/crates.io-index"
9추가: checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
10추가: dependencies = [
11추가: "generic-array",
12추가: ]
13추가:
14추가: [[package]]
15추가: name = "cfg-if"
16추가: version = "1.0.5"
17추가: source = "registry+https://github.com/rust-lang/crates.io-index"
18추가: checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
19추가:
20추가: [[package]]
21추가: name = "cpufeatures"
22추가: version = "0.2.17"
23추가: source = "registry+https://github.com/rust-lang/crates.io-index"
24추가: checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
25추가: dependencies = [
26추가: "libc",
27추가: ]
28추가:
29추가: [[package]]
30추가: name = "crypto-common"
31추가: version = "0.1.7"
32추가: source = "registry+https://github.com/rust-lang/crates.io-index"
33추가: checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
34추가: dependencies = [
35추가: "generic-array",
36추가: "typenum",
37추가: ]
38추가:
39추가: [[package]]
40추가: name = "digest"
41추가: version = "0.10.7"
42추가: source = "registry+https://github.com/rust-lang/crates.io-index"
43추가: checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
44추가: dependencies = [
45추가: "block-buffer",
46추가: "crypto-common",
47추가: ]
48추가:
49추가: [[package]]
50추가: name = "generic-array"
51추가: version = "0.14.7"
52추가: source = "registry+https://github.com/rust-lang/crates.io-index"
53추가: checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
54추가: dependencies = [
55추가: "typenum",
56추가: "version_check",
57추가: ]
58추가:
59추가: [[package]]
60추가: name = "libc"
61추가: version = "0.2.191"
62추가: source = "registry+https://github.com/rust-lang/crates.io-index"
63추가: checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
64추가:
65추가: [[package]]
66추가: name = "sha2"
67추가: version = "0.10.9"
68추가: source = "registry+https://github.com/rust-lang/crates.io-index"
69추가: checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
70추가: dependencies = [
71추가: "cfg-if",
72추가: "cpufeatures",
73추가: "digest",
74추가: ]
75추가:
76추가: [[package]]
77추가: name = "typenum"
78추가: version = "1.20.1"
79추가: source = "registry+https://github.com/rust-lang/crates.io-index"
80추가: checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
81추가:
82추가: [[package]]
83추가: name = "version_check"
84추가: version = "0.9.5"
85추가: source = "registry+https://github.com/rust-lang/crates.io-index"
86추가: checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
87추가:
88추가: [[package]]
89추가: name = "zipelo-file-snapshot"
90추가: version = "0.1.0"
91추가: dependencies = [
92추가: "libc",
93추가: "sha2",
94추가: ]
95추가:
96추가: [[package]]
97추가: name = "zipelo-file-snapshot-regressions"
98추가: version = "0.1.0"
99추가: dependencies = [
100추가: "libc",
101추가: "zipelo-file-snapshot",
102추가: ]
추가tests/rust-file-snapshot/Cargo.toml+20-0
@@ -0,0 +1,20 @@
1추가: [package]
2추가: name = "zipelo-file-snapshot-regressions"
3추가: version = "0.1.0"
4추가: edition = "2024"
5추가: rust-version = "1.99"
6추가: license = "MIT"
7추가: publish = false
8추가: autotests = false
9추가: autoexamples = false
10추가: autobenches = false
11추가:
12추가: [[test]]
13추가: name = "snapshot_public_api"
14추가: path = "main.rs"
15추가:
16추가: [dependencies]
17추가: snapshot = { package = "zipelo-file-snapshot", path = "../../experiments/rust-file-snapshot" }
18추가: libc = { version = "=0.2.191", default-features = false, features = ["std"] }
19추가:
20추가: [workspace]
추가tests/rust-file-snapshot/SHA256SUMS+12-0
@@ -0,0 +1,12 @@
1추가: 2dd86687bc8613e2c59b22fd59b433e10f9a8b855ebfd04a582007234080e83a Cargo.lock
2추가: 33cb8190edc30437576f2266644d4cad9ff1cf77f590e795d6602fa0377c95e2 Cargo.toml
3추가: 1e79a6a86ad505593089a69675ae425afe3841c990d60afba359d252c8893906 boundaries.rs
4추가: 070de4c064bce0f2accce815e19d93d8acf3a9569c21fa2b6e95e0f323cb2284 contract.json
5추가: fb2d014bdba4e799f9f2d5e52a825bee4ba698e519bcc17524b305b0c7dcbac3 control.rs
6추가: ba7671882fa9ed4cdb1ad66aafa733bcb8f04562cf75862302e205226622b9ce main.rs
7추가: 4f8aa79cd8395952872a379146d87d62e801f76ab7dace1ecb3874b2684e1bcf mutations.rs
8추가: 3311c3b3fb7bfab8b2ed21a321381a7ac788237d5270f93b481ff76ecc80667a paths.rs
9추가: 07c7697ddacd9689cffb094cc9edcbe56d523af669986454944cbf27e8eab8cb source-pins.json
10추가: 424745cf6f6a136410d313b4a8cefe7c190073b134ef1c6dc85e5b40688a8722 static_check.py
11추가: ef38ac3975b593e03130f81293130d9468bebbdbd3d8f128e44db9c74756bd13 static_check_helper_tests.py
12추가: cfaae5d310eeb3e5e1e60d7f7700ae3df3646a39a7bdbaf3e16f6f4725ac400c support.rs
추가tests/rust-file-snapshot/boundaries.rs+289-0
@@ -0,0 +1,289 @@
1추가: use crate::support::*;
2추가: use snapshot::{Error, LimitKind, Limits, MAX_BYTES, MAX_IO_BYTES, MAX_READ_CALLS};
3추가: use std::{fs, os::unix::fs::MetadataExt, path::Path, time::Duration};
4추가:
5추가: fn boundary(length: usize) {
6추가: let sandbox = Sandbox::new();
7추가: let bytes = pattern(length);
8추가: let path = sandbox.file("input", &bytes);
9추가: let before = fs::metadata(&path).unwrap();
10추가: let result = get(&path, Limits::default()).unwrap();
11추가: assert_eq!(result.bytes(), bytes);
12추가: assert_eq!(result.identity().length(), length as u64);
13추가: assert_eq!(result.identity().device(), before.dev());
14추가: assert_eq!(result.identity().inode(), before.ino());
15추가: assert_eq!(result.identity().links(), 1);
16추가: assert_eq!(result.identity().mode(), before.mode());
17추가: assert_eq!(
18추가: result.identity().modified(),
19추가: (before.mtime(), before.mtime_nsec())
20추가: );
21추가: assert_eq!(
22추가: result.identity().changed(),
23추가: (before.ctime(), before.ctime_nsec())
24추가: );
25추가: expect_usage(&result, length);
26추가: assert_eq!(result.into_bytes(), bytes);
27추가: assert_eq!(fs::read(&path).unwrap(), bytes);
28추가: sandbox.finish();
29추가: }
30추가:
31추가: #[test]
32추가: fn empty() {
33추가: boundary(0);
34추가: }
35추가:
36추가: #[test]
37추가: fn one() {
38추가: boundary(1);
39추가: }
40추가:
41추가: #[test]
42추가: fn chunk_minus_one() {
43추가: boundary(65535);
44추가: }
45추가:
46추가: #[test]
47추가: fn chunk() {
48추가: boundary(65536);
49추가: }
50추가:
51추가: #[test]
52추가: fn chunk_plus_one() {
53추가: boundary(65537);
54추가: }
55추가:
56추가: #[test]
57추가: fn maximum_minus_one() {
58추가: boundary(16777215);
59추가: }
60추가:
61추가: #[test]
62추가: fn maximum() {
63추가: boundary(16777216);
64추가: }
65추가:
66추가: #[test]
67추가: fn sha256_known_abc_and_debug_redaction() {
68추가: let sandbox = Sandbox::new();
69추가: let path = sandbox.file("private-input-marker", b"abc");
70추가: let result = get(&path, Limits::default()).unwrap();
71추가: assert_eq!(
72추가: result.sha256(),
73추가: [
74추가: 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae,
75추가: 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61,
76추가: 0xf2, 0x00, 0x15, 0xad,
77추가: ]
78추가: );
79추가: let debug = format!("{result:?}");
80추가: for secret in ["private-input-marker", "abc", "sha256", "identity"] {
81추가: assert!(!debug.contains(secret));
82추가: }
83추가: sandbox.finish();
84추가: }
85추가:
86추가: fn invalid(limits: Limits) {
87추가: let mut called = false;
88추가: let result = snapshot::capture(
89추가: snapshot::Request {
90추가: path: Path::new(""),
91추가: limits,
92추가: },
93추가: |_| {
94추가: called = true;
95추가: Err(snapshot::Stop::<()>::Cancelled)
96추가: },
97추가: )
98추가: .unwrap_err();
99추가: assert!(matches!(result.cause, Error::InvalidLimits));
100추가: assert_eq!(result.usage, snapshot::Usage::default());
101추가: assert!(!called);
102추가: }
103추가:
104추가: #[test]
105추가: fn invalid_bytes_cap() {
106추가: invalid(Limits {
107추가: max_bytes: MAX_BYTES + 1,
108추가: ..Limits::default()
109추가: });
110추가: }
111추가:
112추가: #[test]
113추가: fn invalid_io_cap() {
114추가: invalid(Limits {
115추가: max_io_bytes: MAX_IO_BYTES + 1,
116추가: ..Limits::default()
117추가: });
118추가: }
119추가:
120추가: #[test]
121추가: fn invalid_calls_zero() {
122추가: invalid(Limits {
123추가: max_read_calls: 0,
124추가: ..Limits::default()
125추가: });
126추가: }
127추가:
128추가: #[test]
129추가: fn invalid_calls_cap() {
130추가: invalid(Limits {
131추가: max_read_calls: MAX_READ_CALLS + 1,
132추가: ..Limits::default()
133추가: });
134추가: }
135추가:
136추가: #[test]
137추가: fn invalid_deadline_zero() {
138추가: invalid(Limits {
139추가: max_duration: Duration::ZERO,
140추가: ..Limits::default()
141추가: });
142추가: }
143추가:
144추가: #[test]
145추가: fn invalid_deadline_cap() {
146추가: invalid(Limits {
147추가: max_duration: Duration::from_secs(301),
148추가: ..Limits::default()
149추가: });
150추가: }
151추가:
152추가: #[test]
153추가: fn source_over_maximum_rejected_before_data_open() {
154추가: let sandbox = Sandbox::new();
155추가: let path = sandbox.file("input", &pattern(MAX_BYTES as usize + 1));
156추가: let failure = get(&path, Limits::default()).unwrap_err();
157추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::Bytes)));
158추가: assert_eq!(failure.usage.open_calls, 1);
159추가: assert_eq!(failure.usage.metadata_calls, 1);
160추가: assert_eq!(failure.usage.read_calls, 0);
161추가: sandbox.finish();
162추가: }
163추가:
164추가: #[test]
165추가: fn empty_accepts_zero_byte_limit_with_exact_eof_budget() {
166추가: let sandbox = Sandbox::new();
167추가: let path = sandbox.file("input", b"");
168추가: let result = get(
169추가: &path,
170추가: Limits {
171추가: max_bytes: 0,
172추가: max_io_bytes: 2,
173추가: max_read_calls: 2,
174추가: ..Limits::default()
175추가: },
176추가: )
177추가: .unwrap();
178추가: expect_usage(&result, 0);
179추가: sandbox.finish();
180추가: }
181추가:
182추가: #[test]
183추가: fn nonempty_rejects_zero_byte_limit() {
184추가: let sandbox = Sandbox::new();
185추가: let path = sandbox.file("input", b"x");
186추가: let failure = get(
187추가: &path,
188추가: Limits {
189추가: max_bytes: 0,
190추가: ..Limits::default()
191추가: },
192추가: )
193추가: .unwrap_err();
194추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::Bytes)));
195추가: assert_eq!(failure.usage.read_calls, 0);
196추가: sandbox.finish();
197추가: }
198추가:
199추가: #[test]
200추가: fn zero_io_budget_is_valid_but_cannot_probe_eof() {
201추가: let sandbox = Sandbox::new();
202추가: let path = sandbox.file("input", b"");
203추가: let failure = get(
204추가: &path,
205추가: Limits {
206추가: max_io_bytes: 0,
207추가: ..Limits::default()
208추가: },
209추가: )
210추가: .unwrap_err();
211추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::IoBytes)));
212추가: assert_eq!(failure.usage.read_calls, 0);
213추가: assert_eq!(failure.usage.reserved_read_bytes, 0);
214추가: sandbox.finish();
215추가: }
216추가:
217추가: #[test]
218추가: fn exact_io_and_call_budget_includes_both_eof_probes() {
219추가: let sandbox = Sandbox::new();
220추가: let path = sandbox.file("input", &pattern(65_537));
221추가: let result = get(
222추가: &path,
223추가: Limits {
224추가: max_io_bytes: 131_076,
225추가: max_read_calls: 6,
226추가: ..Limits::default()
227추가: },
228추가: )
229추가: .unwrap();
230추가: expect_usage(&result, 65_537);
231추가: sandbox.finish();
232추가: }
233추가:
234추가: #[test]
235추가: fn one_less_io_budget_fails_last_eof_without_refund() {
236추가: let sandbox = Sandbox::new();
237추가: let path = sandbox.file("input", &pattern(65_537));
238추가: let failure = get(
239추가: &path,
240추가: Limits {
241추가: max_io_bytes: 131_075,
242추가: ..Limits::default()
243추가: },
244추가: )
245추가: .unwrap_err();
246추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::IoBytes)));
247추가: assert_eq!(failure.usage.read_calls, 5);
248추가: assert_eq!(failure.usage.reserved_read_bytes, 131_075);
249추가: assert_eq!(failure.usage.actual_read_bytes, 131_074);
250추가: assert_eq!(failure.usage.compared_bytes, 65_537);
251추가: sandbox.finish();
252추가: }
253추가:
254추가: #[test]
255추가: fn one_less_call_budget_fails_last_eof() {
256추가: let sandbox = Sandbox::new();
257추가: let path = sandbox.file("input", &pattern(65_537));
258추가: let failure = get(
259추가: &path,
260추가: Limits {
261추가: max_read_calls: 5,
262추가: ..Limits::default()
263추가: },
264추가: )
265추가: .unwrap_err();
266추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::ReadCalls)));
267추가: assert_eq!(failure.usage.read_calls, 5);
268추가: assert_eq!(failure.usage.reserved_read_bytes, 131_075);
269추가: sandbox.finish();
270추가: }
271추가:
272추가: #[test]
273추가: fn retry_usage_is_per_attempt_not_hidden_cumulative_state() {
274추가: let sandbox = Sandbox::new();
275추가: let path = sandbox.file("input", b"x");
276추가: let failure = get(
277추가: &path,
278추가: Limits {
279추가: max_read_calls: 1,
280추가: ..Limits::default()
281추가: },
282추가: )
283추가: .unwrap_err();
284추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::ReadCalls)));
285추가: assert_eq!(failure.usage.actual_read_bytes, 1);
286추가: let result = get(&path, Limits::default()).unwrap();
287추가: expect_usage(&result, 1);
288추가: sandbox.finish();
289추가: }
추가tests/rust-file-snapshot/contract.json+226-0
@@ -0,0 +1,226 @@
1추가: {
2추가: "schema": "zipelo.file-snapshot.regressions.v1",
3추가: "source_head": "b7c3d5575943f8caab8bbdcf465c278c3e7059d1",
4추가: "source_manifest_sha256": "668b1c3f140a033a6a0768b84ec52f111ee5fbfaf707632d2fc9a5a380758120",
5추가: "branch": "fix/rust-file-snapshot-regressions",
6추가: "scope": "Source-only public API regressions; Rust compile/discovery/execution not performed. No production changes, copies, include!, private access, worker or publication.",
7추가: "declared_test_count": 72,
8추가: "test_names": [
9추가: "boundaries::chunk",
10추가: "boundaries::chunk_minus_one",
11추가: "boundaries::chunk_plus_one",
12추가: "boundaries::empty",
13추가: "boundaries::empty_accepts_zero_byte_limit_with_exact_eof_budget",
14추가: "boundaries::exact_io_and_call_budget_includes_both_eof_probes",
15추가: "boundaries::invalid_bytes_cap",
16추가: "boundaries::invalid_calls_cap",
17추가: "boundaries::invalid_calls_zero",
18추가: "boundaries::invalid_deadline_cap",
19추가: "boundaries::invalid_deadline_zero",
20추가: "boundaries::invalid_io_cap",
21추가: "boundaries::maximum",
22추가: "boundaries::maximum_minus_one",
23추가: "boundaries::nonempty_rejects_zero_byte_limit",
24추가: "boundaries::one",
25추가: "boundaries::one_less_call_budget_fails_last_eof",
26추가: "boundaries::one_less_io_budget_fails_last_eof_without_refund",
27추가: "boundaries::retry_usage_is_per_attempt_not_hidden_cumulative_state",
28추가: "boundaries::sha256_known_abc_and_debug_redaction",
29추가: "boundaries::source_over_maximum_rejected_before_data_open",
30추가: "boundaries::zero_io_budget_is_valid_but_cannot_probe_eof",
31추가: "control::callback_error_precedes_expired_checkpoint_deadline",
32추가: "control::callback_error_precedes_next_observed_source_change",
33추가: "control::callback_panic_propagates_without_snapshot",
34추가: "control::callback_preserves_non_send_error_identity",
35추가: "control::cancel_after_first_chunk_preserves_accumulated_usage",
36추가: "control::cancel_at_comparing",
37추가: "control::cancel_at_copying",
38추가: "control::cancel_at_finalizing",
39추가: "control::cancel_at_opening",
40추가: "control::cancel_at_pinned",
41추가: "control::cancellation_precedes_expired_checkpoint_deadline",
42추가: "control::cancellation_requested_after_return_does_not_change_owned_result",
43추가: "control::checkpoint_order_offsets_and_usage_are_observable",
44추가: "control::natural_elapsed_deadline_precedes_path_validation",
45추가: "control::selected_public_types_have_send_bounds",
46추가: "mutations::append_after_comparison_detected_by_second_eof_probe",
47추가: "mutations::append_after_copy_detected_by_first_eof_probe",
48추가: "mutations::append_after_pinning_detected_before_data_read",
49추가: "mutations::finalizing_append_detected_by_final_metadata",
50추가: "mutations::hard_link_added_at_finalizing_rejected",
51추가: "mutations::positive_short_read_is_accumulated_before_later_eof",
52추가: "mutations::replaced_leaf_never_captures_replacement_bytes",
53추가: "mutations::replaced_parent_keeps_pinned_inode_not_new_path_contents",
54추가: "mutations::returned_snapshot_owns_bytes_after_source_changes",
55추가: "mutations::same_size_overwrite_before_comparison_returns_content_change",
56추가: "mutations::truncate_after_pinning_detected_before_data_read",
57추가: "mutations::truncate_before_comparison_returns_early_eof",
58추가: "mutations::truncate_before_copy_returns_early_eof",
59추가: "paths::ancestor_symlink_rejected",
60추가: "paths::component_255_bytes_is_supported",
61추가: "paths::component_over_255",
62추가: "paths::dangling_symlink_preserves_eloop",
63추가: "paths::directory_rejected_before_data_open",
64추가: "paths::dot_component",
65추가: "paths::empty_path",
66추가: "paths::fifo_without_writer_rejected_before_data_open",
67추가: "paths::leaf_symlink_rejected_without_reading_target",
68추가: "paths::linux_backslash_and_colon_are_name_bytes",
69추가: "paths::missing_path_preserves_enoent_and_stage",
70추가: "paths::multiple_hard_links_rejected_and_contents_preserved",
71추가: "paths::non_utf8_linux_name_is_supported",
72추가: "paths::nul_byte",
73추가: "paths::parent_component",
74추가: "paths::path_over_4096",
75추가: "paths::regular_parent_component_preserves_enotdir",
76추가: "paths::relative_path",
77추가: "paths::repeated_slash",
78추가: "paths::root_only",
79추가: "paths::trailing_slash",
80추가: "paths::unix_socket_rejected_before_data_open"
81추가: ],
82추가: "evidence_classes": {
83추가: "boundaries::chunk": "real-file-public-api",
84추가: "boundaries::chunk_minus_one": "real-file-public-api",
85추가: "boundaries::chunk_plus_one": "real-file-public-api",
86추가: "boundaries::empty": "real-file-public-api",
87추가: "boundaries::empty_accepts_zero_byte_limit_with_exact_eof_budget": "real-file-public-api",
88추가: "boundaries::exact_io_and_call_budget_includes_both_eof_probes": "real-file-public-api",
89추가: "boundaries::invalid_bytes_cap": "public-validation-no-file",
90추가: "boundaries::invalid_calls_cap": "public-validation-no-file",
91추가: "boundaries::invalid_calls_zero": "public-validation-no-file",
92추가: "boundaries::invalid_deadline_cap": "public-validation-no-file",
93추가: "boundaries::invalid_deadline_zero": "public-validation-no-file",
94추가: "boundaries::invalid_io_cap": "public-validation-no-file",
95추가: "boundaries::maximum": "real-file-public-api",
96추가: "boundaries::maximum_minus_one": "real-file-public-api",
97추가: "boundaries::nonempty_rejects_zero_byte_limit": "real-file-public-api",
98추가: "boundaries::one": "real-file-public-api",
99추가: "boundaries::one_less_call_budget_fails_last_eof": "real-file-public-api",
100추가: "boundaries::one_less_io_budget_fails_last_eof_without_refund": "real-file-public-api",
101추가: "boundaries::retry_usage_is_per_attempt_not_hidden_cumulative_state": "real-file-public-api",
102추가: "boundaries::sha256_known_abc_and_debug_redaction": "real-file-public-api",
103추가: "boundaries::source_over_maximum_rejected_before_data_open": "real-file-public-api",
104추가: "boundaries::zero_io_budget_is_valid_but_cannot_probe_eof": "real-file-public-api",
105추가: "control::callback_error_precedes_expired_checkpoint_deadline": "natural-elapsed-callback-no-file",
106추가: "control::callback_error_precedes_next_observed_source_change": "real-file-callback-injection",
107추가: "control::callback_panic_propagates_without_snapshot": "real-file-callback-injection",
108추가: "control::callback_preserves_non_send_error_identity": "real-file-callback-injection",
109추가: "control::cancel_after_first_chunk_preserves_accumulated_usage": "real-file-callback-injection",
110추가: "control::cancel_at_comparing": "real-file-callback-injection",
111추가: "control::cancel_at_copying": "real-file-callback-injection",
112추가: "control::cancel_at_finalizing": "real-file-callback-injection",
113추가: "control::cancel_at_opening": "real-file-callback-injection",
114추가: "control::cancel_at_pinned": "real-file-callback-injection",
115추가: "control::cancellation_precedes_expired_checkpoint_deadline": "natural-elapsed-callback-no-file",
116추가: "control::cancellation_requested_after_return_does_not_change_owned_result": "real-file-callback-injection",
117추가: "control::checkpoint_order_offsets_and_usage_are_observable": "real-file-callback-injection",
118추가: "control::natural_elapsed_deadline_precedes_path_validation": "natural-elapsed-callback-no-file",
119추가: "control::selected_public_types_have_send_bounds": "compile-bound-assertions",
120추가: "mutations::append_after_comparison_detected_by_second_eof_probe": "real-file-checkpoint-mutation",
121추가: "mutations::append_after_copy_detected_by_first_eof_probe": "real-file-checkpoint-mutation",
122추가: "mutations::append_after_pinning_detected_before_data_read": "real-file-checkpoint-mutation",
123추가: "mutations::finalizing_append_detected_by_final_metadata": "real-file-checkpoint-mutation",
124추가: "mutations::hard_link_added_at_finalizing_rejected": "real-file-checkpoint-mutation",
125추가: "mutations::positive_short_read_is_accumulated_before_later_eof": "real-file-checkpoint-mutation",
126추가: "mutations::replaced_leaf_never_captures_replacement_bytes": "real-file-checkpoint-mutation",
127추가: "mutations::replaced_parent_keeps_pinned_inode_not_new_path_contents": "real-file-checkpoint-mutation",
128추가: "mutations::returned_snapshot_owns_bytes_after_source_changes": "real-file-checkpoint-mutation",
129추가: "mutations::same_size_overwrite_before_comparison_returns_content_change": "real-file-checkpoint-mutation",
130추가: "mutations::truncate_after_pinning_detected_before_data_read": "real-file-checkpoint-mutation",
131추가: "mutations::truncate_before_comparison_returns_early_eof": "real-file-checkpoint-mutation",
132추가: "mutations::truncate_before_copy_returns_early_eof": "real-file-checkpoint-mutation",
133추가: "paths::ancestor_symlink_rejected": "real-file-public-api",
134추가: "paths::component_255_bytes_is_supported": "real-file-public-api",
135추가: "paths::component_over_255": "public-validation-no-file",
136추가: "paths::dangling_symlink_preserves_eloop": "real-file-public-api",
137추가: "paths::directory_rejected_before_data_open": "real-file-public-api",
138추가: "paths::dot_component": "public-validation-no-file",
139추가: "paths::empty_path": "public-validation-no-file",
140추가: "paths::fifo_without_writer_rejected_before_data_open": "real-file-public-api",
141추가: "paths::leaf_symlink_rejected_without_reading_target": "real-file-public-api",
142추가: "paths::linux_backslash_and_colon_are_name_bytes": "real-file-public-api",
143추가: "paths::missing_path_preserves_enoent_and_stage": "real-file-public-api",
144추가: "paths::multiple_hard_links_rejected_and_contents_preserved": "real-file-public-api",
145추가: "paths::non_utf8_linux_name_is_supported": "real-file-public-api",
146추가: "paths::nul_byte": "public-validation-no-file",
147추가: "paths::parent_component": "public-validation-no-file",
148추가: "paths::path_over_4096": "public-validation-no-file",
149추가: "paths::regular_parent_component_preserves_enotdir": "real-file-public-api",
150추가: "paths::relative_path": "public-validation-no-file",
151추가: "paths::repeated_slash": "public-validation-no-file",
152추가: "paths::root_only": "public-validation-no-file",
153추가: "paths::trailing_slash": "public-validation-no-file",
154추가: "paths::unix_socket_rejected_before_data_open": "real-file-public-api"
155추가: },
156추가: "fixture_provenance": {
157추가: "input": "Only source-defined synthetic bytes: pattern(i)=(i*37+11)%251, fixed ASCII literals and generated boundary lengths. No archives, user files or external fixtures.",
158추가: "digest": "SHA256 known-answer for ASCII abc: ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad. Rust expected bytes are independent of the production digest implementation.",
159추가: "filesystem": "Future runs create mode-0700 runs/case-PID-counter exclusively below this test directory. File helpers create_new. Mutation cases intentionally alter only their own synthetic input. Root identity checked before cleanup; no Drop cleanup on failed assertions, so evidence remains. No hostile concurrent actor or same-UID deletion safety claim.",
160추가: "special_files": "FIFO via existing libc::mkfifo, local Unix socket inode without accepting connections, directory, hard links, and symlinks inside each owned sandbox. No device node creation, system special files or mounts.",
161추가: "boundary_lengths": [
162추가: 0,
163추가: 1,
164추가: 65535,
165추가: 65536,
166추가: 65537,
167추가: 16777215,
168추가: 16777216,
169추가: 16777217
170추가: ]
171추가: },
172추가: "contracts": {
173추가: "acquisition": "Frozen source remains unchanged. All Rust tests use the actual path dependency and public API. Callback mutations occur synchronously at real capture checkpoints, not timing races.",
174추가: "success": "Normal full-read accounting is 2*N+2 reserved, 2*N actual, N compared and 2*ceil(N/65536)+2 calls. EOF and failed attempt reservations are not refunded.",
175추가: "short_read": "Truncating at the first Copying checkpoint forces a positive one-byte read followed by EOF. The offset-1 checkpoint proves accumulation; the final expected outcome is Changed(Length), not successful short-read completion.",
176추가: "replacement": "Parent rename/replacement retains the old regular-file inode without re-resolving the caller path. Leaf replacement unlinks the old inode and therefore expects Unsupported(MultipleLinks) from the nlink!=1 guard. No original-path persistence guarantee.",
177추가: "cancellation": "Opening/Pinned/Copying/Comparing/Finalizing cancellation and typed callback error preserve usage. Callback errors win over next source observation and expired checkpoint deadline. Finalizing-to-return race remains uncovered.",
178추가: "timing": "Three deadline-priority cases use natural elapsed time after a 10 ms callback sleep against a 1 ms budget. They are not injected clocks, hard deadlines, scheduler/latency guarantees or worker cleanup proof.",
179추가: "panic": "One intentional callback panic is caught; source content is checked. This is not fd-close or OS cleanup evidence.",
180추가: "send": "One Rust test contains Send bounds for selected types; non-Send Rc callback E is separately preserved. No compile result until approved no-run. No universal 'static or Send E requirement is claimed.",
181추가: "privacy": "FileSnapshot Debug is checked against bytes/path/digest/identity exposure. Other generic callback/error Debug output is not covered.",
182추가: "cleanup": "Explicit sandbox finish on success; any panic/error/timeout leaves the case directory and stops later cases. No cleanup success inferred from Drop.",
183추가: "old_results": "Existing 16 classification failures and seven unverified cases remain unchanged and are not counted in these 72 declarations."
184추가: },
185추가: "unverified": [
186추가: "Successful positive-short-read sequence, read EINTR/EIO/permission errno, allocator failure and arbitrary syscall fault injection: no public injection boundary; no production hook or private include added.",
187추가: "Device and block nodes, procfs substitution, kernel primitive absence, privileged mounts and malicious same-process fd reuse.",
188추가: "Changed(Identity) from a correctly pinned FD, deterministic standalone Changed(Metadata), full ABA/same-inode mutation exclusion, atomic point-in-time copy.",
189추가: "Cancellation after final callback before return, final-metadata native failure vs deadline precedence.",
190추가: "Opaque-constructor compile-fail checks, non-Linux runtime/Unsupported branch, Windows/VM, strict syscall timeout, fd leak/cleanup proof.",
191추가: "OS worker launch/identity/EOF/reap, publication/commit/durability; execveat EACCES and held probes stay deferred."
192추가: ],
193추가: "future_execution": {
194추가: "gate": "Separate fixed-head review required before any Rust compile/no-run/discovery/runtime or fixture syscall execution.",
195추가: "order": "Verify source+test hashes -> locked/offline no-run -> list --format terse -> validate every nonempty line and exact unique name set -> execute each exact name once, --test-threads=1 --nocapture.",
196추가: "test_target": "snapshot_public_api",
197추가: "per_case_filtered": 71,
198추가: "cases_serial": true,
199추가: "max_parallel_publishers": 0,
200추가: "compile_timeout_seconds": 120,
201추가: "per_case_timeout_seconds": 30,
202추가: "logs_per_command_bytes": 8388608,
203추가: "max_case_data_bytes": 134217728,
204추가: "on_failure": "Stop at first compile/discovery/test/nonzero/unknown result; preserve logs and residual paths. No source/expectation edits or repeats. Deadline expiry requests termination only of the harness-owned test child; failure to reap is a separate blocked result.",
205추가: "limit_caveat": "Parent timeout is observation/control, not a guarantee of interrupting uninterruptible kernel I/O. No worker isolation claim.",
206추가: "records": "Exact argv/cwd/env allowlist, exit/status, raw stdout/stderr SHA256, binary SHA256, exact discovered/executed/pass/fail/ignored/filtered sets, source/test hashes before/after. Runs and validation output remain local and excluded from PR.",
207추가: "commands": [
208추가: "CARGO_TARGET_DIR=tests/rust-file-snapshot/target cargo test --manifest-path tests/rust-file-snapshot/Cargo.toml --locked --offline --test snapshot_public_api --no-run --message-format=json",
209추가: "<fixed-binary> --list --format terse",
210추가: "<fixed-binary> --exact <contract-name> --test-threads=1 --nocapture"
211추가: ],
212추가: "toolchain": "Existing 1.99.1-x86_64-unknown-linux-gnu explicitly selected; default stable lacks rustfmt. No toolchain installation or shared override.",
213추가: "sandbox_precondition": "Approved runner creates tests/rust-file-snapshot/runs with mode 0700 before tests, verifies no symlink and expected owner, and refuses leftover case directories. No sandbox or synthetic input has been created at source-only stage."
214추가: },
215추가: "static_validation": {
216추가: "allowed": [
217추가: "rustfmt --check",
218추가: "normal Python static checks and checker helper tests",
219추가: "cargo generate-lockfile --offline",
220추가: "cargo metadata --locked --offline"
221추가: ],
222추가: "python_guard": "Reject -O/PYTHONOPTIMIZE before argument parsing and file reads.",
223추가: "manifest": "SHA256SUMS enumerates every deliverable except itself; source-pins.json independently records all nine fixed production blobs/hashes.",
224추가: "deps": "Only production path dependency plus its existing libc version/features; no new registry package or feature. Cargo.lock must equal production packages plus test root."
225추가: }
226추가: }
추가tests/rust-file-snapshot/control.rs+288-0
@@ -0,0 +1,288 @@
1추가: use crate::support::*;
2추가: use snapshot::{
3추가: Checkpoint, Error, Failure, FileSnapshot, Identity, LimitKind, Limits, Request, Stage, Stop,
4추가: Usage, capture,
5추가: };
6추가: use std::{
7추가: cell::Cell,
8추가: fs,
9추가: panic::{AssertUnwindSafe, catch_unwind},
10추가: path::Path,
11추가: rc::Rc,
12추가: time::Duration,
13추가: };
14추가:
15추가: fn cancel(stage: Stage, reads: u64, actual: u64) {
16추가: let sandbox = Sandbox::new();
17추가: let path = sandbox.file("input", b"abc");
18추가: let mut stopped = false;
19추가: let failure = capture(
20추가: Request {
21추가: path: &path,
22추가: limits: Limits::default(),
23추가: },
24추가: |point| {
25추가: if point.stage == stage {
26추가: stopped = true;
27추가: Err(Stop::<()>::Cancelled)
28추가: } else {
29추가: Ok(())
30추가: }
31추가: },
32추가: )
33추가: .unwrap_err();
34추가: assert!(stopped);
35추가: assert!(matches!(failure.cause, Error::Cancelled));
36추가: assert_eq!(failure.usage.read_calls, reads);
37추가: assert_eq!(failure.usage.actual_read_bytes, actual);
38추가: assert_eq!(fs::read(&path).unwrap(), b"abc");
39추가: sandbox.finish();
40추가: }
41추가:
42추가: #[test]
43추가: fn cancel_at_opening() {
44추가: cancel(Stage::Opening, 0, 0);
45추가: }
46추가:
47추가: #[test]
48추가: fn cancel_at_pinned() {
49추가: cancel(Stage::Pinned, 0, 0);
50추가: }
51추가:
52추가: #[test]
53추가: fn cancel_at_copying() {
54추가: cancel(Stage::Copying, 0, 0);
55추가: }
56추가:
57추가: #[test]
58추가: fn cancel_at_comparing() {
59추가: cancel(Stage::Comparing, 2, 3);
60추가: }
61추가:
62추가: #[test]
63추가: fn cancel_at_finalizing() {
64추가: cancel(Stage::Finalizing, 4, 6);
65추가: }
66추가:
67추가: #[test]
68추가: fn cancel_after_first_chunk_preserves_accumulated_usage() {
69추가: let sandbox = Sandbox::new();
70추가: let path = sandbox.file("input", &pattern(65_537));
71추가: let failure = capture(
72추가: Request {
73추가: path: &path,
74추가: limits: Limits::default(),
75추가: },
76추가: |point| {
77추가: if point.stage == Stage::Copying && point.offset == 65_536 {
78추가: Err(Stop::<()>::Cancelled)
79추가: } else {
80추가: Ok(())
81추가: }
82추가: },
83추가: )
84추가: .unwrap_err();
85추가: assert!(matches!(failure.cause, Error::Cancelled));
86추가: assert_eq!(failure.usage.read_calls, 1);
87추가: assert_eq!(failure.usage.actual_read_bytes, 65_536);
88추가: assert_eq!(failure.usage.reserved_read_bytes, 65_536);
89추가: sandbox.finish();
90추가: }
91추가:
92추가: #[test]
93추가: fn callback_preserves_non_send_error_identity() {
94추가: let sandbox = Sandbox::new();
95추가: let path = sandbox.file("input", b"abc");
96추가: let marker = Rc::new(String::from("typed"));
97추가: let failure = capture(
98추가: Request {
99추가: path: &path,
100추가: limits: Limits::default(),
101추가: },
102추가: |point| {
103추가: if point.stage == Stage::Comparing {
104추가: Err(Stop::Callback(marker.clone()))
105추가: } else {
106추가: Ok(())
107추가: }
108추가: },
109추가: )
110추가: .unwrap_err();
111추가: match failure.cause {
112추가: Error::Callback(value) => assert!(Rc::ptr_eq(&value, &marker)),
113추가: other => panic!("unexpected: {other:?}"),
114추가: }
115추가: assert_eq!(failure.usage.actual_read_bytes, 3);
116추가: sandbox.finish();
117추가: }
118추가:
119추가: #[test]
120추가: fn callback_error_precedes_next_observed_source_change() {
121추가: let sandbox = Sandbox::new();
122추가: let path = sandbox.file("input", b"abc");
123추가: let failure = capture(
124추가: Request {
125추가: path: &path,
126추가: limits: Limits::default(),
127추가: },
128추가: |point| {
129추가: if point.stage == Stage::Comparing {
130추가: fs::write(&path, b"xyz").unwrap();
131추가: Err(Stop::Callback(73_u16))
132추가: } else {
133추가: Ok(())
134추가: }
135추가: },
136추가: )
137추가: .unwrap_err();
138추가: assert!(matches!(failure.cause, Error::Callback(73)));
139추가: assert_eq!(failure.usage.actual_read_bytes, 3);
140추가: assert_eq!(failure.usage.compared_bytes, 0);
141추가: sandbox.finish();
142추가: }
143추가:
144추가: fn expired(stop: Option<Stop<u16>>) -> Failure<u16> {
145추가: let mut stop = Some(stop);
146추가: capture(
147추가: Request {
148추가: path: Path::new("invalid"),
149추가: limits: Limits {
150추가: max_duration: Duration::from_millis(1),
151추가: ..Limits::default()
152추가: },
153추가: },
154추가: |_| {
155추가: std::thread::sleep(Duration::from_millis(10));
156추가: match stop.take().unwrap() {
157추가: Some(value) => Err(value),
158추가: None => Ok(()),
159추가: }
160추가: },
161추가: )
162추가: .unwrap_err()
163추가: }
164추가:
165추가: #[test]
166추가: fn natural_elapsed_deadline_precedes_path_validation() {
167추가: let failure = expired(None);
168추가: assert!(matches!(failure.cause, Error::Limit(LimitKind::Deadline)));
169추가: assert_eq!(failure.usage, Usage::default());
170추가: }
171추가:
172추가: #[test]
173추가: fn cancellation_precedes_expired_checkpoint_deadline() {
174추가: let failure = expired(Some(Stop::Cancelled));
175추가: assert!(matches!(failure.cause, Error::Cancelled));
176추가: assert_eq!(failure.usage, Usage::default());
177추가: }
178추가:
179추가: #[test]
180추가: fn callback_error_precedes_expired_checkpoint_deadline() {
181추가: let failure = expired(Some(Stop::Callback(91)));
182추가: assert!(matches!(failure.cause, Error::Callback(91)));
183추가: assert_eq!(failure.usage, Usage::default());
184추가: }
185추가:
186추가: #[test]
187추가: fn checkpoint_order_offsets_and_usage_are_observable() {
188추가: let sandbox = Sandbox::new();
189추가: let path = sandbox.file("input", b"abc");
190추가: let mut points: Vec<Checkpoint> = Vec::new();
191추가: let result = capture(
192추가: Request {
193추가: path: &path,
194추가: limits: Limits::default(),
195추가: },
196추가: |point| {
197추가: points.push(point);
198추가: Ok::<_, Stop<()>>(())
199추가: },
200추가: )
201추가: .unwrap();
202추가: assert_eq!(
203추가: points
204추가: .iter()
205추가: .map(|p| (p.stage, p.offset))
206추가: .collect::<Vec<_>>(),
207추가: vec![
208추가: (Stage::Opening, 0),
209추가: (Stage::Pinned, 0),
210추가: (Stage::Copying, 0),
211추가: (Stage::Copying, 0),
212추가: (Stage::Copying, 3),
213추가: (Stage::Comparing, 0),
214추가: (Stage::Comparing, 3),
215추가: (Stage::Finalizing, 3),
216추가: ]
217추가: );
218추가: assert_eq!(points[0].length, None);
219추가: assert!(points[1..].iter().all(|p| p.length == Some(3)));
220추가: for pair in points.windows(2) {
221추가: assert!(pair[0].usage.open_calls <= pair[1].usage.open_calls);
222추가: assert!(pair[0].usage.metadata_calls <= pair[1].usage.metadata_calls);
223추가: assert!(pair[0].usage.read_calls <= pair[1].usage.read_calls);
224추가: assert!(pair[0].usage.reserved_read_bytes <= pair[1].usage.reserved_read_bytes);
225추가: assert!(pair[0].usage.actual_read_bytes <= pair[1].usage.actual_read_bytes);
226추가: assert!(pair[0].usage.compared_bytes <= pair[1].usage.compared_bytes);
227추가: }
228추가: expect_usage(&result, 3);
229추가: sandbox.finish();
230추가: }
231추가:
232추가: #[test]
233추가: fn callback_panic_propagates_without_snapshot() {
234추가: let sandbox = Sandbox::new();
235추가: let path = sandbox.file("input", b"abc");
236추가: let result = catch_unwind(AssertUnwindSafe(|| {
237추가: let _: Result<FileSnapshot, Failure<()>> = capture(
238추가: Request {
239추가: path: &path,
240추가: limits: Limits::default(),
241추가: },
242추가: |point| {
243추가: if point.stage == Stage::Copying {
244추가: panic!("intentional-checkpoint-panic");
245추가: }
246추가: Ok(())
247추가: },
248추가: );
249추가: }));
250추가: assert!(result.is_err());
251추가: assert_eq!(fs::read(&path).unwrap(), b"abc");
252추가: sandbox.finish();
253추가: }
254추가:
255추가: #[test]
256추가: fn cancellation_requested_after_return_does_not_change_owned_result() {
257추가: let sandbox = Sandbox::new();
258추가: let path = sandbox.file("input", b"abc");
259추가: let requested = Cell::new(false);
260추가: let result = capture(
261추가: Request {
262추가: path: &path,
263추가: limits: Limits::default(),
264추가: },
265추가: |_| {
266추가: if requested.get() {
267추가: Err(Stop::<()>::Cancelled)
268추가: } else {
269추가: Ok(())
270추가: }
271추가: },
272추가: )
273추가: .unwrap();
274추가: requested.set(true);
275추가: assert_eq!(result.bytes(), b"abc");
276추가: expect_usage(&result, 3);
277추가: sandbox.finish();
278추가: }
279추가:
280추가: #[test]
281추가: fn selected_public_types_have_send_bounds() {
282추가: fn send<T: Send>() {}
283추가: send::<FileSnapshot>();
284추가: send::<Identity>();
285추가: send::<Request<'static>>();
286추가: send::<Failure<String>>();
287추가: send::<Stop<String>>();
288추가: }
추가tests/rust-file-snapshot/main.rs+7-0
@@ -0,0 +1,7 @@
1추가: #![cfg(target_os = "linux")]
2추가:
3추가: mod boundaries;
4추가: mod control;
5추가: mod mutations;
6추가: mod paths;
7추가: mod support;
추가tests/rust-file-snapshot/mutations.rs+248-0
@@ -0,0 +1,248 @@
1추가: use crate::support::*;
2추가: use snapshot::{Changed, Error, Limits, Request, Stage, Stop, Unsupported, capture};
3추가: use std::{
4추가: fs::{self, OpenOptions},
5추가: io::Write,
6추가: os::unix::fs::MetadataExt,
7추가: };
8추가:
9추가: fn alter(
10추가: stage: Stage,
11추가: offset: u64,
12추가: action: impl FnOnce(&std::path::Path),
13추가: ) -> snapshot::Failure<()> {
14추가: let sandbox = Sandbox::new();
15추가: let path = sandbox.file("input", &pattern(32));
16추가: let mut action = Some(action);
17추가: let result = capture(
18추가: Request {
19추가: path: &path,
20추가: limits: Limits::default(),
21추가: },
22추가: |point| {
23추가: if point.stage == stage && point.offset == offset {
24추가: if let Some(action) = action.take() {
25추가: action(&path);
26추가: }
27추가: }
28추가: Ok::<_, Stop<()>>(())
29추가: },
30추가: )
31추가: .unwrap_err();
32추가: assert!(action.is_none());
33추가: sandbox.finish();
34추가: result
35추가: }
36추가:
37추가: fn append(path: &std::path::Path) {
38추가: OpenOptions::new()
39추가: .append(true)
40추가: .open(path)
41추가: .unwrap()
42추가: .write_all(b"x")
43추가: .unwrap();
44추가: }
45추가:
46추가: fn truncate(path: &std::path::Path) {
47추가: OpenOptions::new()
48추가: .write(true)
49추가: .open(path)
50추가: .unwrap()
51추가: .set_len(0)
52추가: .unwrap();
53추가: }
54추가:
55추가: #[test]
56추가: fn append_after_pinning_detected_before_data_read() {
57추가: let usage = changed(alter(Stage::Pinned, 0, append), Changed::Length);
58추가: assert_eq!(usage.read_calls, 0);
59추가: }
60추가:
61추가: #[test]
62추가: fn truncate_after_pinning_detected_before_data_read() {
63추가: let usage = changed(alter(Stage::Pinned, 0, truncate), Changed::Length);
64추가: assert_eq!(usage.read_calls, 0);
65추가: }
66추가:
67추가: #[test]
68추가: fn append_after_copy_detected_by_first_eof_probe() {
69추가: let usage = changed(alter(Stage::Copying, 32, append), Changed::Length);
70추가: assert_eq!(usage.read_calls, 2);
71추가: assert_eq!(usage.actual_read_bytes, 33);
72추가: assert_eq!(usage.compared_bytes, 0);
73추가: }
74추가:
75추가: #[test]
76추가: fn truncate_before_copy_returns_early_eof() {
77추가: let usage = changed(alter(Stage::Copying, 0, truncate), Changed::Length);
78추가: assert_eq!(usage.read_calls, 1);
79추가: assert_eq!(usage.actual_read_bytes, 0);
80추가: assert_eq!(usage.reserved_read_bytes, 32);
81추가: }
82추가:
83추가: #[test]
84추가: fn positive_short_read_is_accumulated_before_later_eof() {
85추가: let sandbox = Sandbox::new();
86추가: let path = sandbox.file("input", &pattern(65_537));
87추가: let mut altered = false;
88추가: let mut saw_short = false;
89추가: let failure = capture(
90추가: Request {
91추가: path: &path,
92추가: limits: Limits::default(),
93추가: },
94추가: |point| {
95추가: if point.stage == Stage::Copying && !altered {
96추가: OpenOptions::new()
97추가: .write(true)
98추가: .open(&path)
99추가: .unwrap()
100추가: .set_len(1)
101추가: .unwrap();
102추가: altered = true;
103추가: }
104추가: if point.stage == Stage::Copying && point.offset == 1 {
105추가: assert_eq!(point.usage.actual_read_bytes, 1);
106추가: saw_short = true;
107추가: }
108추가: Ok::<_, Stop<()>>(())
109추가: },
110추가: )
111추가: .unwrap_err();
112추가: let usage = changed(failure, Changed::Length);
113추가: assert!(altered && saw_short);
114추가: assert_eq!(usage.read_calls, 2);
115추가: assert_eq!(usage.reserved_read_bytes, 131_072);
116추가: assert_eq!(usage.actual_read_bytes, 1);
117추가: sandbox.finish();
118추가: }
119추가:
120추가: #[test]
121추가: fn same_size_overwrite_before_comparison_returns_content_change() {
122추가: let usage = changed(
123추가: alter(Stage::Comparing, 0, |path| {
124추가: fs::write(path, vec![99; 32]).unwrap()
125추가: }),
126추가: Changed::Contents,
127추가: );
128추가: assert_eq!(usage.actual_read_bytes, 64);
129추가: assert_eq!(usage.compared_bytes, 32);
130추가: }
131추가:
132추가: #[test]
133추가: fn truncate_before_comparison_returns_early_eof() {
134추가: let usage = changed(alter(Stage::Comparing, 0, truncate), Changed::Length);
135추가: assert_eq!(usage.actual_read_bytes, 32);
136추가: assert_eq!(usage.compared_bytes, 0);
137추가: assert_eq!(usage.read_calls, 3);
138추가: }
139추가:
140추가: #[test]
141추가: fn append_after_comparison_detected_by_second_eof_probe() {
142추가: let usage = changed(alter(Stage::Comparing, 32, append), Changed::Length);
143추가: assert_eq!(usage.actual_read_bytes, 65);
144추가: assert_eq!(usage.compared_bytes, 32);
145추가: assert_eq!(usage.read_calls, 4);
146추가: }
147추가:
148추가: #[test]
149추가: fn finalizing_append_detected_by_final_metadata() {
150추가: let usage = changed(alter(Stage::Finalizing, 32, append), Changed::Length);
151추가: assert_eq!(usage.actual_read_bytes, 64);
152추가: assert_eq!(usage.metadata_calls, 5);
153추가: }
154추가:
155추가: #[test]
156추가: fn hard_link_added_at_finalizing_rejected() {
157추가: let sandbox = Sandbox::new();
158추가: let path = sandbox.file("input", b"abc");
159추가: let failure = capture(
160추가: Request {
161추가: path: &path,
162추가: limits: Limits::default(),
163추가: },
164추가: |point| {
165추가: if point.stage == Stage::Finalizing {
166추가: fs::hard_link(&path, sandbox.path("alias")).unwrap();
167추가: }
168추가: Ok::<_, Stop<()>>(())
169추가: },
170추가: )
171추가: .unwrap_err();
172추가: assert!(matches!(
173추가: failure.cause,
174추가: Error::Unsupported(Unsupported::MultipleLinks)
175추가: ));
176추가: assert_eq!(failure.usage.actual_read_bytes, 6);
177추가: sandbox.finish();
178추가: }
179추가:
180추가: #[test]
181추가: fn replaced_leaf_never_captures_replacement_bytes() {
182추가: let sandbox = Sandbox::new();
183추가: let path = sandbox.file("input", b"old");
184추가: let replacement = sandbox.file("replacement", b"new");
185추가: let failure = capture(
186추가: Request {
187추가: path: &path,
188추가: limits: Limits::default(),
189추가: },
190추가: |point| {
191추가: if point.stage == Stage::Pinned {
192추가: fs::rename(&replacement, &path).unwrap();
193추가: }
194추가: Ok::<_, Stop<()>>(())
195추가: },
196추가: )
197추가: .unwrap_err();
198추가: assert!(matches!(
199추가: failure.cause,
200추가: Error::Unsupported(Unsupported::MultipleLinks)
201추가: ));
202추가: assert_eq!(failure.usage.read_calls, 0);
203추가: assert_eq!(fs::read(&path).unwrap(), b"new");
204추가: sandbox.finish();
205추가: }
206추가:
207추가: #[test]
208추가: fn replaced_parent_keeps_pinned_inode_not_new_path_contents() {
209추가: let sandbox = Sandbox::new();
210추가: let parent = sandbox.dir("parent");
211추가: let path = sandbox.file("parent/input", b"old");
212추가: let original = fs::metadata(&path).unwrap();
213추가: let moved = sandbox.path("moved");
214추가: let result = capture(
215추가: Request {
216추가: path: &path,
217추가: limits: Limits::default(),
218추가: },
219추가: |point| {
220추가: if point.stage == Stage::Pinned {
221추가: fs::rename(&parent, &moved).unwrap();
222추가: sandbox.dir("parent");
223추가: sandbox.file("parent/input", b"new");
224추가: }
225추가: Ok::<_, Stop<()>>(())
226추가: },
227추가: )
228추가: .unwrap();
229추가: assert_eq!(result.bytes(), b"old");
230추가: assert_eq!(result.identity().inode(), original.ino());
231추가: assert_eq!(result.identity().device(), original.dev());
232추가: assert_eq!(fs::read(&path).unwrap(), b"new");
233추가: assert_eq!(fs::read(moved.join("input")).unwrap(), b"old");
234추가: sandbox.finish();
235추가: }
236추가:
237추가: #[test]
238추가: fn returned_snapshot_owns_bytes_after_source_changes() {
239추가: let sandbox = Sandbox::new();
240추가: let path = sandbox.file("input", b"old");
241추가: let result = get(&path, Limits::default()).unwrap();
242추가: let digest = result.sha256();
243추가: fs::write(&path, b"new").unwrap();
244추가: assert_eq!(result.bytes(), b"old");
245추가: assert_eq!(result.sha256(), digest);
246추가: assert_eq!(result.into_bytes(), b"old");
247추가: sandbox.finish();
248추가: }
추가tests/rust-file-snapshot/paths.rs+202-0
@@ -0,0 +1,202 @@
1추가: use crate::support::*;
2추가: use snapshot::{Error, IoOperation, Limits, Unsupported, Usage};
3추가: use std::{
4추가: ffi::{CString, OsString},
5추가: fs,
6추가: os::unix::{
7추가: ffi::{OsStrExt, OsStringExt},
8추가: fs::symlink,
9추가: net::UnixListener,
10추가: },
11추가: path::{Path, PathBuf},
12추가: };
13추가:
14추가: fn invalid(path: &Path) {
15추가: let failure = get(path, Limits::default()).unwrap_err();
16추가: assert!(matches!(failure.cause, Error::InvalidPath));
17추가: assert_eq!(failure.usage, Usage::default());
18추가: }
19추가:
20추가: #[test]
21추가: fn empty_path() {
22추가: invalid(Path::new(""));
23추가: }
24추가:
25추가: #[test]
26추가: fn relative_path() {
27추가: invalid(Path::new("relative"));
28추가: }
29추가:
30추가: #[test]
31추가: fn root_only() {
32추가: invalid(Path::new("/"));
33추가: }
34추가:
35추가: #[test]
36추가: fn dot_component() {
37추가: invalid(Path::new("/owned/./input"));
38추가: }
39추가:
40추가: #[test]
41추가: fn parent_component() {
42추가: invalid(Path::new("/owned/../input"));
43추가: }
44추가:
45추가: #[test]
46추가: fn repeated_slash() {
47추가: invalid(Path::new("/owned//input"));
48추가: }
49추가:
50추가: #[test]
51추가: fn trailing_slash() {
52추가: invalid(Path::new("/owned/input/"));
53추가: }
54추가:
55추가: #[test]
56추가: fn nul_byte() {
57추가: invalid(Path::new("/owned/in\0put"));
58추가: }
59추가:
60추가: #[test]
61추가: fn component_over_255() {
62추가: invalid(&PathBuf::from(format!("/{}", "x".repeat(256))));
63추가: }
64추가:
65추가: #[test]
66추가: fn path_over_4096() {
67추가: invalid(&PathBuf::from(format!("/{}", "x/".repeat(2049))));
68추가: }
69추가:
70추가: fn pin_error(path: &Path, code: i32) {
71추가: let failure = get(path, Limits::default()).unwrap_err();
72추가: match failure.cause {
73추가: Error::Io { operation, source } => {
74추가: assert_eq!(operation, IoOperation::PinPath);
75추가: assert_eq!(source.raw_os_error(), Some(code));
76추가: }
77추가: other => panic!("unexpected: {other:?}"),
78추가: }
79추가: assert_eq!(failure.usage.open_calls, 1);
80추가: assert_eq!(failure.usage.metadata_calls, 0);
81추가: assert_eq!(failure.usage.read_calls, 0);
82추가: }
83추가:
84추가: #[test]
85추가: fn missing_path_preserves_enoent_and_stage() {
86추가: let sandbox = Sandbox::new();
87추가: pin_error(&sandbox.path("missing"), libc::ENOENT);
88추가: sandbox.finish();
89추가: }
90추가:
91추가: #[test]
92추가: fn regular_parent_component_preserves_enotdir() {
93추가: let sandbox = Sandbox::new();
94추가: let file = sandbox.file("parent", b"unchanged");
95추가: pin_error(&file.join("input"), libc::ENOTDIR);
96추가: assert_eq!(fs::read(file).unwrap(), b"unchanged");
97추가: sandbox.finish();
98추가: }
99추가:
100추가: #[test]
101추가: fn leaf_symlink_rejected_without_reading_target() {
102추가: let sandbox = Sandbox::new();
103추가: let target = sandbox.file("target", b"unchanged");
104추가: let path = sandbox.path("link");
105추가: symlink(&target, &path).unwrap();
106추가: pin_error(&path, libc::ELOOP);
107추가: assert_eq!(fs::read(target).unwrap(), b"unchanged");
108추가: sandbox.finish();
109추가: }
110추가:
111추가: #[test]
112추가: fn ancestor_symlink_rejected() {
113추가: let sandbox = Sandbox::new();
114추가: let parent = sandbox.dir("parent");
115추가: sandbox.file("parent/input", b"unchanged");
116추가: let link = sandbox.path("alias");
117추가: symlink(parent, &link).unwrap();
118추가: pin_error(&link.join("input"), libc::ELOOP);
119추가: sandbox.finish();
120추가: }
121추가:
122추가: #[test]
123추가: fn dangling_symlink_preserves_eloop() {
124추가: let sandbox = Sandbox::new();
125추가: let path = sandbox.path("link");
126추가: symlink(sandbox.path("missing"), &path).unwrap();
127추가: pin_error(&path, libc::ELOOP);
128추가: sandbox.finish();
129추가: }
130추가:
131추가: fn unsupported(path: &Path, expected: Unsupported) {
132추가: let failure = get(path, Limits::default()).unwrap_err();
133추가: assert!(matches!(failure.cause, Error::Unsupported(value) if value == expected));
134추가: assert_eq!(failure.usage.open_calls, 1);
135추가: assert_eq!(failure.usage.metadata_calls, 1);
136추가: assert_eq!(failure.usage.read_calls, 0);
137추가: }
138추가:
139추가: #[test]
140추가: fn directory_rejected_before_data_open() {
141추가: let sandbox = Sandbox::new();
142추가: unsupported(&sandbox.dir("directory"), Unsupported::FileType);
143추가: sandbox.finish();
144추가: }
145추가:
146추가: #[test]
147추가: fn fifo_without_writer_rejected_before_data_open() {
148추가: let sandbox = Sandbox::new();
149추가: let path = sandbox.path("fifo");
150추가: let raw = CString::new(path.as_os_str().as_bytes()).unwrap();
151추가: // 작업 전용 경로에 합성 FIFO만 생성함.
152추가: assert_eq!(unsafe { libc::mkfifo(raw.as_ptr(), 0o600) }, 0);
153추가: unsupported(&path, Unsupported::FileType);
154추가: sandbox.finish();
155추가: }
156추가:
157추가: #[test]
158추가: fn unix_socket_rejected_before_data_open() {
159추가: let sandbox = Sandbox::new();
160추가: let path = sandbox.path("socket");
161추가: let socket = UnixListener::bind(&path).unwrap();
162추가: unsupported(&path, Unsupported::FileType);
163추가: drop(socket);
164추가: sandbox.finish();
165추가: }
166추가:
167추가: #[test]
168추가: fn multiple_hard_links_rejected_and_contents_preserved() {
169추가: let sandbox = Sandbox::new();
170추가: let path = sandbox.file("input", b"unchanged");
171추가: let link = sandbox.path("hardlink");
172추가: fs::hard_link(&path, &link).unwrap();
173추가: unsupported(&path, Unsupported::MultipleLinks);
174추가: assert_eq!(fs::read(path).unwrap(), b"unchanged");
175추가: assert_eq!(fs::read(link).unwrap(), b"unchanged");
176추가: sandbox.finish();
177추가: }
178추가:
179추가: #[test]
180추가: fn non_utf8_linux_name_is_supported() {
181추가: let sandbox = Sandbox::new();
182추가: let path = sandbox.root.join(OsString::from_vec(vec![b'i', 0xff]));
183추가: fs::write(&path, b"abc").unwrap();
184추가: assert_eq!(get(&path, Limits::default()).unwrap().bytes(), b"abc");
185추가: sandbox.finish();
186추가: }
187추가:
188추가: #[test]
189추가: fn linux_backslash_and_colon_are_name_bytes() {
190추가: let sandbox = Sandbox::new();
191추가: let path = sandbox.file("a\\b:c", b"abc");
192추가: assert_eq!(get(&path, Limits::default()).unwrap().bytes(), b"abc");
193추가: sandbox.finish();
194추가: }
195추가:
196추가: #[test]
197추가: fn component_255_bytes_is_supported() {
198추가: let sandbox = Sandbox::new();
199추가: let path = sandbox.file(&"x".repeat(255), b"abc");
200추가: assert_eq!(get(&path, Limits::default()).unwrap().bytes(), b"abc");
201추가: sandbox.finish();
202추가: }
추가tests/rust-file-snapshot/source-pins.json+59-0
@@ -0,0 +1,59 @@
1추가: {
2추가: "head": "b7c3d5575943f8caab8bbdcf465c278c3e7059d1",
3추가: "files": [
4추가: {
5추가: "path": "experiments/rust-file-snapshot/Cargo.lock",
6추가: "git_blob": "f78b06aafe24e649c3b8dbf1e80f84875665916d",
7추가: "sha256": "ba55ac17dc748d1f91d7a6e5d5ebb4c6b9c84d09173a17d4cac31cf149fb771b",
8추가: "mode": "100644"
9추가: },
10추가: {
11추가: "path": "experiments/rust-file-snapshot/Cargo.toml",
12추가: "git_blob": "5f13cef3e22861c18da16a0aa45ed990a448d1bf",
13추가: "sha256": "e641f091c0acabd3e6fbfa3ed6bf53e05be3ca6c2fc90d67980721b378840f0f",
14추가: "mode": "100644"
15추가: },
16추가: {
17추가: "path": "experiments/rust-file-snapshot/LICENSE",
18추가: "git_blob": "5014abac33298592fd3450b51a9b414191e1aabc",
19추가: "sha256": "0714945e52a4d5b560c02c9a18478519f8c4e2572cbf87bd6d52adcfb2b63c62",
20추가: "mode": "100644"
21추가: },
22추가: {
23추가: "path": "experiments/rust-file-snapshot/SHA256SUMS",
24추가: "git_blob": "76201cbad9d40111091cb320744f59bb07b4bc65",
25추가: "sha256": "668b1c3f140a033a6a0768b84ec52f111ee5fbfaf707632d2fc9a5a380758120",
26추가: "mode": "100644"
27추가: },
28추가: {
29추가: "path": "experiments/rust-file-snapshot/THIRD-PARTY-NOTICES.txt",
30추가: "git_blob": "c18cb9011479d97d247bf403c128e5923fa769c9",
31추가: "sha256": "066b8c0623b870c0c3998a0499b0323f3cfe8d3cfd60bf6bbc833be0e523a06e",
32추가: "mode": "100644"
33추가: },
34추가: {
35추가: "path": "experiments/rust-file-snapshot/contract.json",
36추가: "git_blob": "93c7b53f2441eee3d98db58dcca8ece47b1094d6",
37추가: "sha256": "8b54705382c3af1168b684fbcf3e25efd256eb145c636972fe6e26b8cb898ff2",
38추가: "mode": "100644"
39추가: },
40추가: {
41추가: "path": "experiments/rust-file-snapshot/dependencies.json",
42추가: "git_blob": "cf8c2f473069573ba29b9cf278d7a09eac83adca",
43추가: "sha256": "ea113f15ec27f9903eed985e1e55f49114b9867b0c7c707e2cd15009fa02c6c0",
44추가: "mode": "100644"
45추가: },
46추가: {
47추가: "path": "experiments/rust-file-snapshot/src/lib.rs",
48추가: "git_blob": "b119facbf8cef61cb1877b7cef9f921f4d63d311",
49추가: "sha256": "e087714fc3e30b8efdd1cf16e1d8944ebc3518c757b8917d6e32d3b3dc3936c9",
50추가: "mode": "100644"
51추가: },
52추가: {
53추가: "path": "experiments/rust-file-snapshot/src/linux.rs",
54추가: "git_blob": "ed9af89904de5a4b44673b098e944b35faa3075f",
55추가: "sha256": "88aa71907bfd07ef61697eb2c71e8ffbdc178c68ea9fcae8d26957be4751fa21",
56추가: "mode": "100644"
57추가: }
58추가: ]
59추가: }
추가tests/rust-file-snapshot/static_check.py+137-0
@@ -0,0 +1,137 @@
1추가: import argparse
2추가: import hashlib
3추가: import json
4추가: import pathlib
5추가: import re
6추가: import sys
7추가: import tomllib
8추가:
9추가: BASE = pathlib.Path(__file__).resolve().parent
10추가: ROOT = BASE.parents[1]
11추가: HEAD = "b7c3d5575943f8caab8bbdcf465c278c3e7059d1"
12추가: SOURCE = ROOT / "experiments/rust-file-snapshot"
13추가: SOURCE_MANIFEST = "668b1c3f140a033a6a0768b84ec52f111ee5fbfaf707632d2fc9a5a380758120"
14추가: FILES = {
15추가: "Cargo.toml", "Cargo.lock", "main.rs", "support.rs", "boundaries.rs",
16추가: "paths.rs", "mutations.rs", "control.rs", "source-pins.json",
17추가: "contract.json", "static_check.py", "static_check_helper_tests.py",
18추가: }
19추가: MODULES = ("boundaries", "paths", "mutations", "control")
20추가: GUARD = "최적화 모드에서는 정적 검사를 실행할 수 없음"
21추가:
22추가:
23추가: def require(condition, message):
24추가: if not condition:
25추가: raise RuntimeError(message)
26추가:
27추가:
28추가: def digest(raw):
29추가: return hashlib.sha256(raw).hexdigest()
30추가:
31추가:
32추가: def parse_manifest(text, expected_paths):
33추가: rows = {}
34추가: for line in text.splitlines():
35추가: match = re.fullmatch(r"([0-9a-f]{64}) ([A-Za-z0-9_./-]+)", line)
36추가: require(match is not None, "잘못된 manifest 행")
37추가: value, name = match.groups()
38추가: path = pathlib.PurePosixPath(name)
39추가: require(not path.is_absolute() and ".." not in path.parts
40추가: and str(path) == name and name not in rows, "중복 또는 잘못된 경로")
41추가: rows[name] = value
42추가: require(set(rows) == set(expected_paths), "manifest 경로 불일치")
43추가: return rows
44추가:
45추가:
46추가: def hashes():
47추가: result = {}
48추가: for name in sorted(FILES | {"SHA256SUMS"}):
49추가: path = BASE / name
50추가: require(not path.is_symlink(), "시험 파일 링크 거부")
51추가: result[name] = digest(path.read_bytes())
52추가: return result
53추가:
54추가:
55추가: def verify_sources():
56추가: pins = json.loads((BASE / "source-pins.json").read_text())
57추가: require(pins["head"] == HEAD and len(pins["files"]) == 9, "고정 source 기준 불일치")
58추가: names = [row["path"] for row in pins["files"]]
59추가: require(len(set(names)) == 9, "source 경로 중복")
60추가: result = {}
61추가: for row in pins["files"]:
62추가: path = ROOT / row["path"]
63추가: require(path.resolve().is_relative_to(SOURCE) and not path.is_symlink(), "source 경로 이탈")
64추가: raw = path.read_bytes()
65추가: require(digest(raw) == row["sha256"], "source SHA256 불일치")
66추가: blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
67추가: require(blob == row["git_blob"] and row["mode"] == "100644", "source blob 불일치")
68추가: result[row["path"]] = digest(raw)
69추가: manifest = (SOURCE / "SHA256SUMS").read_bytes()
70추가: require(digest(manifest) == SOURCE_MANIFEST, "source manifest 불일치")
71추가: entries = parse_manifest(manifest.decode(), set(names) - {"experiments/rust-file-snapshot/SHA256SUMS"})
72추가: for name, value in entries.items():
73추가: require(digest((ROOT / name).read_bytes()) == value, "source manifest 파일 불일치")
74추가: return result
75추가:
76추가:
77추가: def main():
78추가: if sys.flags.optimize:
79추가: raise RuntimeError(GUARD)
80추가: parser = argparse.ArgumentParser()
81추가: parser.add_argument("--manifest-sha256", required=True)
82추가: parser.add_argument("--metadata", type=pathlib.Path)
83추가: args = parser.parse_args()
84추가: before = hashes()
85추가: require(before["SHA256SUMS"] == args.manifest_sha256, "시험 manifest 불일치")
86추가: rows = parse_manifest((BASE / "SHA256SUMS").read_text(), FILES)
87추가: require(all(before[name] == value for name, value in rows.items()), "시험 파일 변경")
88추가: sources = verify_sources()
89추가: contract = json.loads((BASE / "contract.json").read_text())
90추가: require(contract["source_head"] == HEAD, "계약 head 불일치")
91추가: names = []
92추가: for module in MODULES:
93추가: source = (BASE / (module + ".rs")).read_text()
94추가: found = re.findall(r"#\[test\]\s*fn ([a-z0-9_]+)\(", source)
95추가: require(len(found) == source.count("#[test]"), "시험 선언 분석 실패")
96추가: names.extend(module + "::" + name for name in found)
97추가: require(len(names) == len(set(names)) == contract["declared_test_count"] == 72, "선언 수 불일치")
98추가: require(sorted(names) == contract["test_names"] == sorted(contract["evidence_classes"]), "이름 집합 불일치")
99추가: for path in BASE.glob("*.rs"):
100추가: source = path.read_text()
101추가: require("#[ignore" not in source and "#[should_panic" not in source, "시험 제외 금지")
102추가: require(not re.search(r"include!|#\[path|Command::|execveat|\bmknod\b", source), "범위 밖 Rust 경계")
103추가: manifest = tomllib.loads((BASE / "Cargo.toml").read_text())
104추가: require(manifest["package"]["autotests"] is False, "자동 시험 발견 금지")
105추가: require(manifest["test"] == [{"name": "snapshot_public_api", "path": "main.rs"}], "target 불일치")
106추가: require(manifest["dependencies"] == {
107추가: "snapshot": {"package": "zipelo-file-snapshot", "path": "../../experiments/rust-file-snapshot"},
108추가: "libc": {"version": "=0.2.191", "default-features": False, "features": ["std"]},
109추가: }, "직접 의존성 변경")
110추가: normal = lambda rows: sorted(rows, key=lambda row: (row["name"], row["version"]))
111추가: original = tomllib.loads((SOURCE / "Cargo.lock").read_text())["package"]
112추가: locked = tomllib.loads((BASE / "Cargo.lock").read_text())["package"]
113추가: root = {"name": "zipelo-file-snapshot-regressions", "version": "0.1.0", "dependencies": ["libc", "zipelo-file-snapshot"]}
114추가: require(normal(locked) == normal(original + [root]), "기존 lock graph 변경")
115추가: if args.metadata:
116추가: require(args.metadata.resolve().is_relative_to(BASE), "metadata 위치 이탈")
117추가: metadata = json.loads(args.metadata.read_text())
118추가: packages = {p["id"]: p for p in metadata["packages"]}
119추가: root_package = packages[metadata["resolve"]["root"]]
120추가: require(root_package["name"] == root["name"], "metadata root 불일치")
121추가: require(len(root_package["targets"]) == 1 and root_package["targets"][0]["kind"] == ["test"], "target 추가")
122추가: registry = {(p["name"], p["version"], p["checksum"]) for p in locked if "source" in p}
123추가: expected = {(p["name"], p["version"], p["checksum"]) for p in json.loads((SOURCE / "dependencies.json").read_text())["registry_packages"]}
124추가: require(registry == expected, "registry graph 변경")
125추가: for node in metadata["resolve"]["nodes"]:
126추가: package = packages[node["id"]]
127추가: if package["name"] == "sha2":
128추가: require(sorted(node["features"]) == ["force-soft", "std"], "sha2 feature 변경")
129추가: if package["name"] == "libc":
130추가: require(sorted(node["features"]) == ["std"], "libc feature 변경")
131추가: require(verify_sources() == sources and hashes() == before, "검사 중 입력 변경")
132추가: print(json.dumps({"head": HEAD, "source_files": 9, "declared": len(names),
133추가: "rust_compiled": False, "rust_executed": 0, "inputs_unchanged": True}))
134추가:
135추가:
136추가: if __name__ == "__main__":
137추가: main()
추가tests/rust-file-snapshot/static_check_helper_tests.py+102-0
@@ -0,0 +1,102 @@
1추가: import json
2추가: import os
3추가: import pathlib
4추가: import runpy
5추가: import subprocess
6추가: import sys
7추가: import unittest
8추가:
9추가: BASE = pathlib.Path(__file__).resolve().parent
10추가: CHECKER = BASE / "static_check.py"
11추가: CODE = """
12추가: import json, pathlib, runpy, sys
13추가: from unittest.mock import patch
14추가: scope = runpy.run_path(sys.argv[1])
15추가: calls = []
16추가: def blocked(*args, **kwargs):
17추가: calls.append("side_effect")
18추가: raise RuntimeError("side_effect")
19추가: with patch("argparse.ArgumentParser", blocked), \
20추가: patch.object(pathlib.Path, "read_bytes", blocked), \
21추가: patch.object(pathlib.Path, "read_text", blocked), \
22추가: patch.object(runpy, "run_path", blocked):
23추가: try:
24추가: scope["main"]()
25추가: except RuntimeError as error:
26추가: print(json.dumps({"message": str(error), "calls": calls, "optimize": sys.flags.optimize}))
27추가: """
28추가:
29추가:
30추가: class StaticHelperTests(unittest.TestCase):
31추가: def child(self, environment_mode=False, flag=False, cli=False):
32추가: environment = os.environ.copy()
33추가: environment.pop("PYTHONOPTIMIZE", None)
34추가: environment["PYTHONDONTWRITEBYTECODE"] = "1"
35추가: if environment_mode:
36추가: environment["PYTHONOPTIMIZE"] = "1"
37추가: command = [sys.executable, "-B"] + (["-O"] if flag else [])
38추가: command += [str(CHECKER)] if cli else ["-c", CODE, str(CHECKER)]
39추가: return subprocess.run(command, env=environment, cwd=BASE,
40추가: capture_output=True, text=True, timeout=10)
41추가:
42추가: def probe(self, **mode):
43추가: result = self.child(**mode)
44추가: self.assertEqual(result.returncode, 0, result.stderr)
45추가: self.assertEqual(result.stderr, "")
46추가: self.assertEqual(json.loads(result.stdout), {
47추가: "message": "최적화 모드에서는 정적 검사를 실행할 수 없음",
48추가: "calls": [], "optimize": 1,
49추가: })
50추가:
51추가: def test_flag_stops_before_reads_arguments_and_generation(self):
52추가: self.probe(flag=True)
53추가:
54추가: def test_environment_stops_before_reads_arguments_and_generation(self):
55추가: self.probe(environment_mode=True)
56추가:
57추가: def test_normal_mode_reaches_parser(self):
58추가: result = self.child()
59추가: self.assertEqual(result.returncode, 0, result.stderr)
60추가: self.assertEqual(json.loads(result.stdout), {
61추가: "message": "side_effect", "calls": ["side_effect"], "optimize": 0,
62추가: })
63추가:
64추가: def test_flag_cli_fails_before_required_arguments(self):
65추가: result = self.child(flag=True, cli=True)
66추가: self.assertNotEqual(result.returncode, 0)
67추가: self.assertEqual(result.stdout, "")
68추가: self.assertIn("RuntimeError: 최적화 모드", result.stderr)
69추가: self.assertNotIn("arguments are required", result.stderr)
70추가:
71추가: def test_environment_cli_fails_before_required_arguments(self):
72추가: result = self.child(environment_mode=True, cli=True)
73추가: self.assertNotEqual(result.returncode, 0)
74추가: self.assertEqual(result.stdout, "")
75추가: self.assertIn("RuntimeError: 최적화 모드", result.stderr)
76추가:
77추가: def reject(self, content, paths):
78추가: parse = runpy.run_path(str(CHECKER))["parse_manifest"]
79추가: with self.assertRaises(RuntimeError):
80추가: parse(content, paths)
81추가:
82추가: def test_duplicate_manifest_rows_rejected(self):
83추가: line = "a" * 64 + " main.rs\n"
84추가: self.reject(line + line, {"main.rs"})
85추가:
86추가: def test_missing_manifest_path_rejected(self):
87추가: self.reject("a" * 64 + " main.rs\n", {"main.rs", "support.rs"})
88추가:
89추가: def test_parent_path_rejected(self):
90추가: self.reject("a" * 64 + " ../main.rs\n", {"../main.rs"})
91추가:
92추가: def test_repository_relative_source_manifest_path(self):
93추가: parse = runpy.run_path(str(CHECKER))["parse_manifest"]
94추가: name = "experiments/rust-file-snapshot/src/lib.rs"
95추가: self.assertEqual(parse("a" * 64 + " " + name + "\n", {name}), {name: "a" * 64})
96추가:
97추가: def test_malformed_digest_rejected(self):
98추가: self.reject("g" * 64 + " main.rs\n", {"main.rs"})
99추가:
100추가:
101추가: if __name__ == "__main__":
102추가: unittest.main(verbosity=2)
추가tests/rust-file-snapshot/support.rs+90-0
@@ -0,0 +1,90 @@
1추가: use snapshot::{Error, Failure, FileSnapshot, Limits, Request, Stop, capture};
2추가: use std::{
3추가: fs::{self, DirBuilder, OpenOptions},
4추가: io::Write,
5추가: os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt},
6추가: path::{Path, PathBuf},
7추가: sync::atomic::{AtomicU64, Ordering},
8추가: };
9추가:
10추가: static NEXT: AtomicU64 = AtomicU64::new(1);
11추가:
12추가: pub struct Sandbox {
13추가: pub root: PathBuf,
14추가: identity: (u64, u64),
15추가: }
16추가:
17추가: impl Sandbox {
18추가: pub fn new() -> Self {
19추가: let parent = Path::new(env!("CARGO_MANIFEST_DIR")).join("runs");
20추가: let metadata = fs::symlink_metadata(&parent).expect("runner가 runs 디렉터리를 준비해야 함");
21추가: assert!(metadata.is_dir() && !metadata.file_type().is_symlink());
22추가: assert_eq!(metadata.mode() & 0o777, 0o700);
23추가: assert_eq!(parent.canonicalize().unwrap(), parent);
24추가: let root = parent.join(format!(
25추가: "case-{}-{}",
26추가: std::process::id(),
27추가: NEXT.fetch_add(1, Ordering::Relaxed)
28추가: ));
29추가: DirBuilder::new().mode(0o700).create(&root).unwrap();
30추가: let metadata = fs::symlink_metadata(&root).unwrap();
31추가: Self {
32추가: root,
33추가: identity: (metadata.dev(), metadata.ino()),
34추가: }
35추가: }
36추가:
37추가: pub fn path(&self, name: &str) -> PathBuf {
38추가: self.root.join(name)
39추가: }
40추가:
41추가: pub fn file(&self, name: &str, bytes: &[u8]) -> PathBuf {
42추가: let path = self.path(name);
43추가: let mut file = OpenOptions::new()
44추가: .write(true)
45추가: .create_new(true)
46추가: .mode(0o600)
47추가: .open(&path)
48추가: .unwrap();
49추가: file.write_all(bytes).unwrap();
50추가: file.sync_all().unwrap();
51추가: path
52추가: }
53추가:
54추가: pub fn dir(&self, name: &str) -> PathBuf {
55추가: let path = self.path(name);
56추가: DirBuilder::new().mode(0o700).create(&path).unwrap();
57추가: path
58추가: }
59추가:
60추가: pub fn finish(self) {
61추가: let metadata = fs::symlink_metadata(&self.root).unwrap();
62추가: assert!(metadata.is_dir() && !metadata.file_type().is_symlink());
63추가: assert_eq!((metadata.dev(), metadata.ino()), self.identity);
64추가: fs::remove_dir_all(&self.root).unwrap();
65추가: assert!(!self.root.exists());
66추가: }
67추가: }
68추가:
69추가: pub fn pattern(length: usize) -> Vec<u8> {
70추가: (0..length).map(|i| ((i * 37 + 11) % 251) as u8).collect()
71추가: }
72추가:
73추가: pub fn get(path: &Path, limits: Limits) -> Result<FileSnapshot, Failure<()>> {
74추가: capture(Request { path, limits }, |_| Ok::<_, Stop<()>>(()))
75추가: }
76추가:
77추가: pub fn expect_usage(snapshot: &FileSnapshot, length: usize) {
78추가: let usage = snapshot.usage();
79추가: assert_eq!(usage.open_calls, 4);
80추가: assert_eq!(usage.metadata_calls, 5);
81추가: assert_eq!(usage.read_calls, 2 * (length as u64).div_ceil(65_536) + 2);
82추가: assert_eq!(usage.reserved_read_bytes, 2 * length as u64 + 2);
83추가: assert_eq!(usage.actual_read_bytes, 2 * length as u64);
84추가: assert_eq!(usage.compared_bytes, length as u64);
85추가: }
86추가:
87추가: pub fn changed(failure: Failure<()>, expected: snapshot::Changed) -> snapshot::Usage {
88추가: assert!(matches!(failure.cause, Error::Changed(value) if value == expected));
89추가: failure.usage
90추가: }