team-ljyzipelo

공개

분할 원본 재검증을 첫 실제 게시 직전 한 번으로 제한한다

작성자
시로사키 하나
작성 시각
커밋
12294c3efe95b1ade8b261edc52b6b4827b0b498
부모
859f064
이 시점의 파일 보기

변경된 파일 5개

+319-21
수정experiments/rust-archive-worker/README.md+1-0
@@ -196,6 +196,7 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
196196- 각 파일의 핸들 식별자, 길이와 수정 시각을 읽기 전후에 비교하고 읽는 동안 SHA256을 구한다. 동일 파일 식별자가 여러 조각 이름으로 나타나는 별칭도 거부한다. 내용 검사를 수정 시각 비교만으로 대신하지 않는다.
197197- 논리 입력은 기존 이름 없는 임시 Snapshot에 64 KiB 이하 청크로 캡처한다. 파일 경계를 넘는 헤더와 데이터도 이어 읽으며 전체 크기의 메모리 배열이나 합친 영구 파일을 만들지 않는다. 원본 조각을 쓰거나 이름을 바꾸지 않는다. 입력 사본과 해독 스테이징 및 목적지 공간을 기존 정책으로 계산하고 임시 공간 실패를 보고한다.
198198- 캡처 뒤 모든 조각을 다시 열어 부모 및 파일 식별자, 길이와 내용 해시를 대조한다. 목록의 ListEnd 전과 해제의 첫 목적지 게시 전에도 전체 조각을 재검증한다. 목록 뒤 중간 또는 마지막 조각의 내용, 파일 식별자와 길이가 달라지거나 조각 수가 바뀌면 SourceChanged이며 확정된 중간 누락은 MissingVolume이다. 첫 게시 전 발견한 실패에는 Output을 보내지 않는다.
199추가: - 첫 게시 검증 여부는 출력 생성 개수와 별도로 보관한다. 기존 폴더를 건너뛸 때는 전체 원본을 다시 읽지 않고 실제 첫 폴더 생성 또는 파일 게시 직전에 한 번만 검증한다. 실제 게시가 없는 작업은 정상 완료 전에 한 번 검증하며, 충돌 질문에서 취소하면 게시용 검증을 시작하지 않는다.
199200- 이후 해독과 게시에는 검증한 불변 Snapshot만 사용한다. 마지막 재검증 직후 발생하는 동일 계정의 경합을 원자적으로 차단하거나 파일 시스템 전체의 동시 스냅샷을 제공한다고 보장하지 않는다. 이미 게시한 출력이 있는 일반 실패와 취소는 기존 실제 게시 및 정리 집계를 유지하며 작업 전체를 되돌린다고 안내하지 않는다.
200201
201202### 묶음 ListId와 바이트 계약
수정experiments/rust-archive-worker/src/filesystem.rs+16-4
@@ -614,17 +614,29 @@ pub(crate) fn directory_with(
614614 name: &str,
615615 check: &mut impl Monitor,
616616) -> Result<(bool, Durability, Option<ErrorCode>)> {
617삭제: let (d, leaf) = parent_with(root, name, false, check)?.ok_or(ErrorCode::Io)?;
618삭제: if completed(d.child(&leaf, false), check)?.is_some() {
617추가: directory_steps(root, name, &mut |step| match step {
618추가: PublishStep::Check | PublishStep::Commit => check.check(),
619추가: PublishStep::Activity => check.activity(),
620추가: })
621추가: }
622추가: pub(crate) fn directory_steps(
623추가: root: &Dir,
624추가: name: &str,
625추가: check: &mut impl FnMut(PublishStep) -> Result<()>,
626추가: ) -> Result<(bool, Durability, Option<ErrorCode>)> {
627추가: let (d, leaf) =
628추가: parent_with(root, name, false, &mut PublicationMonitor(check))?.ok_or(ErrorCode::Io)?;
629추가: if completed(d.child(&leaf, false), &mut PublicationMonitor(check))?.is_some() {
619630 return Ok((false, Durability::NotApplicable, None));
620631 }
632추가: check(PublishStep::Commit)?;
621633 d.child(&leaf, true)?.ok_or(ErrorCode::Io)?;
622삭제: let progress_error = completed(Ok(()), check).err();
634추가: let progress_error = completed(Ok(()), &mut PublicationMonitor(check)).err();
623635 Ok(match d.sync_checked() {
624636 Ok(durability) => (
625637 true,
626638 durability,
627삭제: progress_error.or_else(|| completed(Ok(()), check).err()),
639추가: progress_error.or_else(|| completed(Ok(()), &mut PublicationMonitor(check)).err()),
628640 ),
629641 Err(error) => (true, Durability::Failed, Some(error)),
630642 })
수정experiments/rust-archive-worker/src/runtime.rs+25-17
@@ -40,6 +40,7 @@ struct Job<W> {
4040 watchdog: Watchdog,
4141 remaining_choice: Option<ConflictChoice>,
4242 source_group: Option<crate::split_seven_zip::Group>,
43추가: source_verified_for_publication: bool,
4344 started: Instant,
4445 terminal: Terminal,
4546 parent: crate::parent::Parent,
@@ -282,6 +283,23 @@ impl<W: Write> Job<W> {
282283 self.source_group = Some(group);
283284 self.split_result(result)
284285 }
286추가: fn verify_before_publication(&mut self) -> Result<()> {
287추가: if !self.source_verified_for_publication {
288추가: self.verify_split()?;
289추가: self.source_verified_for_publication = true;
290추가: }
291추가: Ok(())
292추가: }
293추가: fn publication_step(&mut self, step: filesystem::PublishStep, last: bool) -> Result<()> {
294추가: match step {
295추가: filesystem::PublishStep::Check => self.check(),
296추가: filesystem::PublishStep::Activity => completed(Ok(()), self),
297추가: filesystem::PublishStep::Commit => {
298추가: self.verify_before_publication()?;
299추가: if last { self.cutoff() } else { self.check() }
300추가: }
301추가: }
302추가: }
285303 fn check(&mut self) -> Result<()> {
286304 self.parent.check()?;
287305 let state = self.state.lock().map_err(|_| ErrorCode::Internal)?;
@@ -334,16 +352,7 @@ impl<W: Write> Job<W> {
334352 self.terminal.created_count as u32,
335353 )?;
336354 let p = filesystem::publish_reader_steps(root, name, data, length, replace, &mut |step| {
337삭제: match step {
338삭제: filesystem::PublishStep::Check => self.check(),
339삭제: filesystem::PublishStep::Activity => completed(Ok(()), self),
340삭제: filesystem::PublishStep::Commit => {
341삭제: if self.terminal.created_count == 0 {
342삭제: self.verify_split()?;
343삭제: }
344삭제: if last { self.cutoff() } else { self.check() }
345삭제: }
346삭제: }
355추가: self.publication_step(step, last)
347356 });
348357 self.terminal.retained_partial_count += p.retained;
349358 if p.cleanup != Cleanup::Complete {
@@ -782,11 +791,10 @@ impl<W: Write> Job<W> {
782791 .collect::<Result<BTreeSet<_>>>()?;
783792 for name in dirs {
784793 self.check()?;
785삭제: if self.terminal.created_count == 0 {
786삭제: self.verify_split()?;
787삭제: }
788794 let (created, durability, sync_error) =
789삭제: filesystem::directory_with(&root, &name, self)?;
795추가: filesystem::directory_steps(&root, &name, &mut |step| {
796추가: self.publication_step(step, false)
797추가: })?;
790798 if created {
791799 self.terminal.created_count += 1;
792800 self.terminal.publication = Publication::Partial;
@@ -856,9 +864,8 @@ impl<W: Write> Job<W> {
856864 replace,
857865 )?;
858866 }
859삭제: if self.terminal.created_count == 0 {
860삭제: self.verify_split()?;
861삭제: }
867추가: // 건너뛰기 등 실제 게시가 없을 때도 완료 전에 원본을 확인함.
868추가: self.verify_before_publication()?;
862869 if !self.interactive || self.terminal.created_count != 0 {
863870 self.terminal.publication = Publication::Complete;
864871 }
@@ -1100,6 +1107,7 @@ pub fn serve<R: Read + Send + 'static, W: Write + Send + 'static>(
11001107 watchdog: Watchdog::new(),
11011108 remaining_choice: None,
11021109 source_group: None,
1110추가: source_verified_for_publication: false,
11031111 parent,
11041112 started: Instant::now(),
11051113 terminal: Terminal {
추가tests/rust-archive-worker/split_publication_cases.py+23-0
@@ -0,0 +1,23 @@
1추가: """기존 폴더 16개와 1 MiB 파일의 분할 7z 회귀 표본을 생성함."""
2추가:
3추가: from pathlib import Path
4추가: import sys
5추가:
6추가: from seven_zip_fixtures import archive
7추가:
8추가:
9추가: def main():
10추가: root = Path(sys.argv[1])
11추가: entries = [(f"d{index:03}", b"", 0x10) for index in range(16)]
12추가: if sys.argv[2] == "file":
13추가: entries.append(("payload.bin", bytes(range(256)) * 4096, 0x20))
14추가: else:
15추가: assert sys.argv[2] == "directories"
16추가: data = archive(entries, method="copy")
17추가: width = 256 * 1024
18추가: for index, begin in enumerate(range(0, len(data), width), start=1):
19추가: (root / f"sample.7z.{index:03}").write_bytes(data[begin:begin + width])
20추가:
21추가:
22추가: if __name__ == "__main__":
23추가: main()
수정tests/rust-archive-worker/split_runtime.rs+254-0
@@ -553,3 +553,257 @@ fn encrypted_seven_zip_volumes_keep_the_existing_unsupported_policy() {
553553 assert_eq!(hashes(&paths), before);
554554 }
555555}
556추가:
557추가: fn publication_fixture(s: &Scratch, existing: bool, with_file: bool) -> Vec<PathBuf> {
558추가: assert!(
559추가: Command::new("python3")
560추가: .env("PYTHONDONTWRITEBYTECODE", "1")
561추가: .arg(
562추가: PathBuf::from(env!("CARGO_MANIFEST_DIR"))
563추가: .join("../../tests/rust-archive-worker/split_publication_cases.py")
564추가: )
565추가: .arg(&s.0)
566추가: .arg(if with_file { "file" } else { "directories" })
567추가: .status()
568추가: .unwrap()
569추가: .success()
570추가: );
571추가: directory(s, "output");
572추가: if existing {
573추가: for index in 0..16 {
574추가: directory(s, &format!("output/d{index:03}"));
575추가: }
576추가: }
577추가: (1..=5)
578추가: .map(|index| s.0.join(format!("sample.7z.{index:03}")))
579추가: .take_while(|path| path.is_file())
580추가: .collect()
581추가: }
582추가: fn publication_verifications(events: &[Message]) -> Vec<usize> {
583추가: events
584추가: .iter()
585추가: .enumerate()
586추가: .filter_map(|(index, event)| {
587추가: matches!(
588추가: event,
589추가: Message::Progress {
590추가: stage: Stage::Verify,
591추가: processed_bytes: 0,
592추가: total_bytes: None,
593추가: ..
594추가: }
595추가: )
596추가: .then_some(index)
597추가: })
598추가: .collect()
599추가: }
600추가: fn publication_request(s: &Scratch) -> GuardedStart {
601추가: GuardedStart {
602추가: start: request(s, None, Selection::All),
603추가: ceiling: Limits::default(),
604추가: interactive: true,
605추가: }
606추가: }
607추가:
608추가: #[test]
609추가: fn split_publication_verifies_once_for_fresh_or_many_existing_directories() {
610추가: for existing in [false, true] {
611추가: let s = Scratch::new();
612추가: let paths = publication_fixture(&s, existing, true);
613추가: let before = hashes(&paths);
614추가: let events = guarded::run(&s, publication_request(&s), |_| None);
615추가: assert_eq!(terminal(&events).outcome, Outcome::Completed, "{events:?}");
616추가: let verifies = publication_verifications(&events);
617추가: assert_eq!(verifies.len(), 1, "existing={existing}: {events:?}");
618추가: let first_output = events
619추가: .iter()
620추가: .position(|event| matches!(event, Message::Output { .. }))
621추가: .unwrap();
622추가: assert!(verifies[0] < first_output);
623추가: if existing {
624추가: let write = events
625추가: .iter()
626추가: .position(|event| {
627추가: matches!(
628추가: event,
629추가: Message::Progress {
630추가: stage: Stage::Write,
631추가: ..
632추가: }
633추가: )
634추가: })
635추가: .unwrap();
636추가: assert!(write < verifies[0]);
637추가: }
638추가: assert_eq!(
639추가: terminal(&events).created_count,
640추가: if existing { 1 } else { 17 }
641추가: );
642추가: assert_eq!(
643추가: fs::read(s.0.join("output/payload.bin")).unwrap(),
644추가: (0..=255u8).cycle().take(1024 * 1024).collect::<Vec<_>>()
645추가: );
646추가: assert_eq!(hashes(&paths), before);
647추가: }
648추가: }
649추가:
650추가: #[test]
651추가: fn split_publication_existing_directories_do_not_cache_before_conflict_changes() {
652추가: let s = Scratch::new();
653추가: let paths = publication_fixture(&s, true, true);
654추가: fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
655추가: let mut changed = None;
656추가: let events = guarded::run(&s, publication_request(&s), |event| {
657추가: if let Message::ConflictRequired { challenge_id, .. } = event {
658추가: let mut data = fs::read(&paths[1]).unwrap();
659추가: data[0] ^= 1;
660추가: fs::write(&paths[1], data).unwrap();
661추가: changed = Some(hashes(&paths));
662추가: return Some(vec![Message::ConflictReply {
663추가: challenge_id: *challenge_id,
664추가: choice: ConflictChoice::Overwrite,
665추가: apply_to_remaining: false,
666추가: }]);
667추가: }
668추가: None
669추가: });
670추가: failure(&events, ErrorCode::SourceChanged);
671추가: let verifies = publication_verifications(&events);
672추가: assert_eq!(verifies.len(), 1, "{events:?}");
673추가: let conflict = events
674추가: .iter()
675추가: .position(|event| matches!(event, Message::ConflictRequired { .. }))
676추가: .unwrap();
677추가: assert!(conflict < verifies[0]);
678추가: assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
679추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 17);
680추가: assert_eq!(hashes(&paths), changed.unwrap());
681추가: assert_eq!(terminal(&events).cleanup, Cleanup::Complete);
682추가: }
683추가:
684추가: #[test]
685추가: fn split_publication_no_outputs_verify_once_and_cancel_does_not_rehash() {
686추가: for mode in 0..3 {
687추가: let s = Scratch::new();
688추가: let paths = publication_fixture(&s, true, mode != 0);
689추가: let before = hashes(&paths);
690추가: if mode != 0 {
691추가: fs::write(s.0.join("output/payload.bin"), b"keep").unwrap();
692추가: }
693추가: let events = guarded::run(&s, publication_request(&s), |event| {
694추가: if let Message::ConflictRequired { challenge_id, .. } = event {
695추가: return Some(if mode == 2 {
696추가: vec![Message::Cancel]
697추가: } else {
698추가: vec![Message::ConflictReply {
699추가: challenge_id: *challenge_id,
700추가: choice: ConflictChoice::Skip,
701추가: apply_to_remaining: false,
702추가: }]
703추가: });
704추가: }
705추가: None
706추가: });
707추가: assert_eq!(
708추가: terminal(&events).outcome,
709추가: if mode == 2 {
710추가: Outcome::Cancelled
711추가: } else {
712추가: Outcome::Completed
713추가: },
714추가: "{events:?}"
715추가: );
716추가: assert_eq!(
717추가: publication_verifications(&events).len(),
718추가: usize::from(mode != 2),
719추가: "{events:?}"
720추가: );
721추가: assert_eq!(terminal(&events).publication, Publication::None);
722추가: assert_eq!(terminal(&events).created_count, 0);
723추가: assert!(
724추가: !events
725추가: .iter()
726추가: .any(|event| matches!(event, Message::Output { .. }))
727추가: );
728추가: if mode != 0 {
729추가: assert_eq!(fs::read(s.0.join("output/payload.bin")).unwrap(), b"keep");
730추가: }
731추가: assert_eq!(hashes(&paths), before);
732추가: }
733추가: }
734추가:
735추가: #[test]
736추가: fn split_publication_changed_source_stops_before_creating_the_first_directory() {
737추가: use std::sync::{Arc, Mutex};
738추가: struct ChangingOutput {
739추가: frame: Vec<u8>,
740추가: output: Arc<Mutex<Vec<u8>>>,
741추가: path: PathBuf,
742추가: changed: bool,
743추가: }
744추가: impl Write for ChangingOutput {
745추가: fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
746추가: self.frame.extend_from_slice(bytes);
747추가: Ok(bytes.len())
748추가: }
749추가: fn flush(&mut self) -> std::io::Result<()> {
750추가: let event = {
751추가: let mut output = self.output.lock().unwrap();
752추가: output.extend_from_slice(&self.frame);
753추가: let mut reader = Reader::new(output.as_slice());
754추가: let mut last = None;
755추가: while let Some((_, _, event)) = reader.read()? {
756추가: last = Some(event);
757추가: }
758추가: last.unwrap()
759추가: };
760추가: if !self.changed
761추가: && matches!(
762추가: event,
763추가: Message::Progress {
764추가: stage: Stage::Verify,
765추가: processed_bytes: 0,
766추가: total_bytes: None,
767추가: ..
768추가: }
769추가: )
770추가: {
771추가: // 검증 시작 프레임을 보낼 때 바꿔 스케줄링 경합 없이 생성 직전을 재현함.
772추가: let mut data = fs::read(&self.path)?;
773추가: data[0] ^= 1;
774추가: fs::write(&self.path, data)?;
775추가: self.changed = true;
776추가: }
777추가: self.frame.clear();
778추가: Ok(())
779추가: }
780추가: }
781추가: let s = Scratch::new();
782추가: let paths = publication_fixture(&s, false, true);
783추가: let before = hashes(&paths);
784추가: let mut input = Vec::new();
785추가: Writer::new(&mut input, 17)
786추가: .send(&Message::Start(request(&s, None, Selection::All)))
787추가: .unwrap();
788추가: let output = Arc::new(Mutex::new(Vec::new()));
789추가: zipelo_archive_worker::runtime::serve(
790추가: std::io::Cursor::new(input),
791추가: ChangingOutput {
792추가: frame: Vec::new(),
793추가: output: Arc::clone(&output),
794추가: path: paths[1].clone(),
795추가: changed: false,
796추가: },
797추가: )
798추가: .unwrap();
799추가: let output = output.lock().unwrap();
800추가: let mut reader = Reader::new(output.as_slice());
801추가: let mut events = Vec::new();
802추가: while let Some((_, _, event)) = reader.read().unwrap() {
803추가: events.push(event);
804추가: }
805추가: failure(&events, ErrorCode::SourceChanged);
806추가: assert_eq!(publication_verifications(&events).len(), 1);
807추가: assert_eq!(fs::read_dir(s.0.join("output")).unwrap().count(), 0);
808추가: assert_ne!(hashes(&paths), before);
809추가: }