exchange_test.v

63.8 KB · raw

1//! Two-machine tests: two repos and one folder remote standing in for the Mac2//! and the PC. This is where offer, steal and combine are actually proven —3//! the folder backend exists so these run offline.45module exchange67import os8import src.events9import src.history10import src.remote11import src.snapshot12import src.storage1314// Global rules must not make source fixtures depend on the developer’s home.15fn testsuite_begin() {16	os.setenv('HOME', os.join_path(os.temp_dir(), 'koh3-test-home-${os.getpid()}'), true)17}1819fn test_arriving_record_drops_unsafe_paths_and_reports_them() {20	mut record := SaveRecord{21		files: [22			FileRecord{ path: 'safe.txt' },23			FileRecord{ path: '../outside.txt' },24			FileRecord{ path: 'bad\\name.txt' },25			FileRecord{ path: 'Icon\r' },26		]27	}28	dropped := drop_unsafe_paths(mut record)29	assert record.files.map(it.path) == ['safe.txt']30	assert dropped == ['../outside.txt', 'Icon\\x0d', 'bad\\\\name.txt']31}3233// An unpaired surrogate escape stands for its three bytes, so the record still34// decodes and only the path holding it is dropped; a real pair is kept.35fn test_a_record_with_unpaired_surrogate_escapes_drops_only_those_paths() {36	body := '{"id":"abcdefabcdef","files":[{"path":"ok\\ud83d\\ude00"},{"path":"lead\\ud800"},{"path":"trail\\udc00x"},{"path":"back\\\\ud800"}]}'37	mut record := decode_save(body.bytes())!38	dropped := drop_unsafe_paths(mut record)39	assert record.files.map(it.path) == ['ok😀']40	assert dropped == ['back\\\\ud800', 'lead\\xed\\xa0\\x80', 'trail\\xed\\xb0\\x80x']41}4243// Machines keep their repo in a folder of the same NAME, because the remote key44// is the folder's name; that is what makes them the same repo to the remote.45fn machine(name string) !string {46	dir := os.join_path(os.temp_dir(), 'koh3_sync_${os.getpid()}_${name}', 'proj')47	os.rmdir_all(os.dir(dir)) or {}48	os.mkdir_all(dir, os.MkdirParams{})!49	return dir50}5152fn scratch(name string) !string {53	dir := os.join_path(os.temp_dir(), 'koh3_sync_${os.getpid()}_${name}')54	os.rmdir_all(dir) or {}55	os.mkdir_all(dir, os.MkdirParams{})!56	return dir57}5859fn open_repo(dir string) !storage.Store {60	mut store := storage.create(dir)!61	os.write_file(os.join_path(dir, '.kohignore'), '*.log\n')!62	return store63}6465fn put(root string, rel string, text string) ! {66	full := os.join_path(root, rel)67	os.mkdir_all(os.dir(full), os.MkdirParams{})!68	os.write_file(full, text)!69}7071fn make_save(store &storage.Store, message string) !history.Save {72	return history.save_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{73		message: message74	})!75}7677fn offer_now(store &storage.Store, mut backend remote.Backend) !OfferReport {78	return offer(store, mut backend)!79}8081fn steal_now(store &storage.Store, mut backend remote.Backend) !StealReport {82	return steal(store, mut backend, StealOptions{83		theirs: true84	})!85}8687fn test_first_offer_publishes_the_whole_line() {88	base := scratch('first')!89	defer {90		os.rmdir_all(base) or {}91	}92	mut a := open_repo(machine('first_a')!)!93	defer {94		a.close()95	}96	put(a.root, 'a.txt', 'one\n')!97	make_save(a, 'first')!98	put(a.root, 'a.txt', 'two\n')!99	make_save(a, 'second')!100	mut backend := remote.new_folder(os.join_path(base, 'remote'))!101102	report := offer_now(a, mut backend)!103	assert report.repo == 'proj'104	assert report.saves == 2105	assert report.objects >= 2106	assert backend.get(head_key('proj'))!.found107	assert backend.list('proj/saves')!.len == 2108109	// A second offer with nothing new uploads nothing and still succeeds.110	again := offer_now(a, mut backend)!111	assert again.saves == 0112}113114fn test_the_repo_name_is_remembered_and_head_offered() {115	base := scratch('remember')!116	defer {117		os.rmdir_all(base) or {}118	}119	mut a := open_repo(machine('remember_a')!)!120	defer {121		a.close()122	}123	put(a.root, 'a.txt', 'one\n')!124	make_save(a, 'first')!125	mut backend := remote.new_folder(os.join_path(base, 'remote'))!126	offer_now(a, mut backend)!127	assert a.state('remote_repo') or { '' } == 'proj'128	assert backend.get(head_key('proj'))!.body.bytestr() == head_of(a).id129	// Offer's step 3: the new remote head is recorded in state.130	assert a.state('remote_head') or { '' } == head_of(a).id131132	// A second offer, with the remote already holding our head, must not133	// refuse: the name is remembered, so the remote is ours.134	put(a.root, 'a.txt', 'two\n')!135	make_save(a, 'second')!136	offer_now(a, mut backend)!137	assert backend.get(head_key('proj'))!.body.bytestr() == head_of(a).id138}139140fn test_a_repo_name_is_lowercased_at_first_offer() {141	base := scratch('lower')!142	defer {143		os.rmdir_all(base) or {}144	}145	dir := os.join_path(base, 'Haven')146	os.mkdir_all(dir, os.MkdirParams{})!147	mut a := open_repo(dir)!148	defer {149		a.close()150	}151	put(a.root, 'a.txt', 'one\n')!152	make_save(a, 'first')!153	mut backend := remote.new_folder(os.join_path(base, 'remote'))!154	assert offer_now(a, mut backend)!.repo == 'haven'155	assert backend.get(head_key('haven'))!.found156}157158fn test_an_offer_follows_a_rename_kepr_marked_on_the_remote() {159	base := scratch('renamed')!160	defer {161		os.rmdir_all(base) or {}162	}163	mut a := open_repo(machine('renamed_a')!)!164	defer {165		a.close()166	}167	put(a.root, 'a.txt', 'one\n')!168	make_save(a, 'first')!169	remote_dir := os.join_path(base, 'remote')170	mut backend := remote.new_folder(remote_dir)!171	offer_now(a, mut backend)!172	// What Kepr's rename leaves: the history under the new name, a marker, no old name.173	os.mv(os.join_path(remote_dir, 'proj'), os.join_path(remote_dir, 'tool'))!174	os.mkdir_all(os.join_path(remote_dir, '.kepr', 'renamed'), os.MkdirParams{})!175	os.write_file(os.join_path(remote_dir, '.kepr', 'renamed', 'proj'), 'tool\n')!176177	put(a.root, 'a.txt', 'two\n')!178	make_save(a, 'second')!179	assert offer_now(a, mut backend)!.repo == 'tool'180	assert a.state('remote_repo') or { '' } == 'tool'181	assert backend.get(head_key('tool'))!.body.bytestr() == head_of(a).id182	assert !backend.get(head_key('proj'))!.found183}184185fn test_a_rename_marker_naming_a_path_is_not_followed() {186	base := scratch('badmarker')!187	defer {188		os.rmdir_all(base) or {}189	}190	mut a := open_repo(machine('badmarker_a')!)!191	defer {192		a.close()193	}194	put(a.root, 'a.txt', 'one\n')!195	make_save(a, 'first')!196	remote_dir := os.join_path(base, 'remote')197	mut backend := remote.new_folder(remote_dir)!198	offer_now(a, mut backend)!199	os.rmdir_all(os.join_path(remote_dir, 'proj'))!200	os.mkdir_all(os.join_path(remote_dir, '.kepr', 'renamed'), os.MkdirParams{})!201	os.write_file(os.join_path(remote_dir, '.kepr', 'renamed', 'proj'), '../elsewhere\n')!202	assert offer_now(a, mut backend)!.repo == 'proj'203}204205fn test_steal_fast_forwards_a_machine_that_has_nothing_of_its_own() {206	base := scratch('forward')!207	defer {208		os.rmdir_all(base) or {}209	}210	mut backend := remote.new_folder(os.join_path(base, 'remote'))!211	mut a := open_repo(machine('fwd_a')!)!212	defer {213		a.close()214	}215	put(a.root, 'a.txt', 'from A\n')!216	make_save(a, 'A writes')!217	offer_now(a, mut backend)!218219	// B starts empty and takes the whole repo.220	mut b := open_repo(machine('fwd_b')!)!221	defer {222		b.close()223	}224	fetched := fetch_repo(mut backend, 'proj')!225	b.begin()!226	write_fetched(b, fetched)!227	history.set_head(b, fetched.head)!228	b.end()!229	snapshot.restore_files(b, b.root, snapshot.load(b.root), history.files_of(b, fetched.head)!, [])!230	assert os.read_file(os.join_path(b.root, 'a.txt'))! == 'from A\n'231	assert head_of(b).id == fetched.head232}233234// A machine that is only ahead has nothing to combine: stealing must leave its235// saves, and their IDs, exactly where they are.236fn test_steal_while_only_ahead_leaves_the_line_alone() {237	base := scratch('ahead')!238	defer {239		os.rmdir_all(base) or {}240	}241	mut backend := remote.new_folder(os.join_path(base, 'remote'))!242	mut a := open_repo(machine('ahead_a')!)!243	defer {244		a.close()245	}246	put(a.root, 'a.txt', 'one\n')!247	make_save(a, 'offered')!248	offer_now(a, mut backend)!249	put(a.root, 'a.txt', 'two\n')!250	ahead := make_save(a, 'not offered yet')!251	report := steal_now(a, mut backend)!252	assert report.replayed == 0253	assert head_of(a).id == ahead.id254	// Nothing was restored, so nothing is left marked as half-restored.255	assert !snapshot.restore_pending(a)256	assert history.all_saves(a)!.len == 2257	offer_now(a, mut backend)!258	assert backend.get(head_key('proj'))!.body.bytestr() == ahead.id259}260261// A link is invisible to the walk, so a tree holding one is clean; the files262// a steal brings in must still never land in the folder it points at.263fn test_steal_never_writes_through_a_symlinked_folder() {264	base := scratch('steal_link')!265	defer {266		os.rmdir_all(base) or {}267	}268	mut backend := remote.new_folder(os.join_path(base, 'remote'))!269	mut a := open_repo(machine('steal_link_a')!)!270	defer {271		a.close()272	}273	mut b := open_repo(machine('steal_link_b')!)!274	defer {275		b.close()276	}277	put(a.root, 'a.txt', 'one\n')!278	make_save(a, 'first')!279	offer_now(a, mut backend)!280	join(b, mut backend)!281	outside := os.join_path(base, 'outside')282	put(outside, 'a.md', 'precious\n')!283	os.symlink(outside, os.join_path(b.root, 'docs'))!284	put(a.root, 'docs/a.md', 'from A\n')!285	make_save(a, 'A adds docs')!286	offer_now(a, mut backend)!287	head_before := head_of(b).id288	if _ := steal_now(b, mut backend) {289		assert false, 'a steal writing through a symlinked folder must refuse'290	} else {291		assert err.msg().contains('docs')292	}293	assert os.read_file(os.join_path(outside, 'a.md'))! == 'precious\n'294	assert head_of(b).id == head_before295}296297// A steal onto a half-restored tree would replay it as somebody's work.298fn test_steal_refuses_after_a_restore_cut_short() {299	base := scratch('steal_cut')!300	defer {301		os.rmdir_all(base) or {}302	}303	mut backend := remote.new_folder(os.join_path(base, 'remote'))!304	mut a := open_repo(machine('steal_cut_a')!)!305	defer {306		a.close()307	}308	put(a.root, 'a.txt', 'one\n')!309	make_save(a, 'first')!310	offer_now(a, mut backend)!311	a.set_state('restoring', 'yes')!312	if _ := steal_now(a, mut backend) {313		assert false, 'steal must refuse while a restore is unfinished'314	} else {315		assert err.msg().contains('koh revert')316	}317}318319// A replayed save keeps its original time but sits on a newer parent, so a320// steal cannot order saves by time.321fn test_a_steal_imports_parents_before_children() {322	base := scratch('steal_order')!323	defer {324		os.rmdir_all(base) or {}325	}326	mut backend := remote.new_folder(os.join_path(base, 'remote'))!327	mut a := open_repo(machine('order_a')!)!328	defer {329		a.close()330	}331	put(a.root, 'a.txt', 'one\n')!332	parent := make_save(a, 'parent')!333	child := history.save_tree(a, '', history.files_of(a, parent.id)!, history.SaveInput{334		message:    'replayed, older than its parent'335		created_at: parent.created_at - 3600336	})!337	offer_now(a, mut backend)!338	mut b := open_repo(machine('order_b')!)!339	defer {340		b.close()341	}342	join(b, mut backend)!343	assert head_of(b).id == child.id344}345346// A chmod is unsaved work too: a steal would restore the old mode over it.347fn test_steal_refuses_an_unsaved_executable_bit_change() {348	base := scratch('chmod')!349	defer {350		os.rmdir_all(base) or {}351	}352	mut backend := remote.new_folder(os.join_path(base, 'remote'))!353	mut a := open_repo(machine('chmod_a')!)!354	defer {355		a.close()356	}357	put(a.root, 'run.sh', 'echo hi\n')!358	make_save(a, 'script')!359	offer_now(a, mut backend)!360	os.chmod(os.join_path(a.root, 'run.sh'), 0o755)!361	if _ := steal_now(a, mut backend) {362		assert false, 'a chmod-only change should make the tree dirty'363	} else {364		assert err.msg() == dirty_tree365	}366}367368fn test_divergence_without_clashes_keeps_both_machines_work() {369	base := scratch('diverge')!370	defer {371		os.rmdir_all(base) or {}372	}373	mut backend := remote.new_folder(os.join_path(base, 'remote'))!374	mut a := open_repo(machine('div_a')!)!375	defer {376		a.close()377	}378	mut b := open_repo(machine('div_b')!)!379	defer {380		b.close()381	}382	put(a.root, 'shared.txt', 'base\n')!383	make_save(a, 'base')!384	offer_now(a, mut backend)!385386	// B joins, then both machines change a different file.387	join(b, mut backend)!388	put(a.root, 'fromA.txt', 'A\n')!389	make_save(a, 'A adds a file')!390	put(b.root, 'fromB.txt', 'B\n')!391	make_save(b, 'B adds a file')!392	offer_now(a, mut backend)!393394	// B's offer is refused: the remote has moved on.395	if _ := offer_now(b, mut backend) {396		assert false, 'offering on top of unknown remote saves should be refused'397	} else {398		assert err.msg().contains('run koh steal')399	}400401	report := steal_now(b, mut backend)!402	assert !report.forward403	assert report.replayed == 1404	assert report.clashes.len == 0405	// Both files are on B's line now, and on disk.406	assert os.read_file(os.join_path(b.root, 'fromA.txt'))! == 'A\n'407	assert os.read_file(os.join_path(b.root, 'fromB.txt'))! == 'B\n'408	assert os.read_file(os.join_path(b.root, 'shared.txt'))! == 'base\n'409	// B's own save was replayed, not erased.410	mut saw_replay := false411	for save in history.all_saves(b)! {412		if save.replayed_from != '' {413			saw_replay = true414		}415	}416	assert saw_replay417	// And the remote now has B's work too.418	offer_now(b, mut backend)!419	line_head := backend.get(head_key('proj'))!.body.bytestr().trim_space()420	assert line_head == head_of(b).id421}422423// An agent that edits a file and then undoes the edit leaves no net change, so424// the file is not a clash when the other machine changed it. Replaying the425// edit itself must not stop the steal: the remote's version simply stands.426// Likewise a file both machines ended up changing the same way.427fn test_a_local_change_undone_does_not_block_a_combine() {428	base := scratch('undone')!429	defer {430		os.rmdir_all(base) or {}431	}432	mut backend := remote.new_folder(os.join_path(base, 'remote'))!433	mut a := open_repo(machine('undone_a')!)!434	defer {435		a.close()436	}437	mut b := open_repo(machine('undone_b')!)!438	defer {439		b.close()440	}441	put(a.root, 'f.txt', 'base\n')!442	put(a.root, 'g.txt', 'base\n')!443	make_save(a, 'base')!444	offer_now(a, mut backend)!445	join(b, mut backend)!446447	put(a.root, 'f.txt', 'from A\n')!448	put(a.root, 'g.txt', 'same\n')!449	make_save(a, 'A edits both')!450	offer_now(a, mut backend)!451452	put(b.root, 'f.txt', 'tried on B\n')!453	put(b.root, 'g.txt', 'first try\n')!454	tried := make_save(b, 'B tries')!455	put(b.root, 'f.txt', 'base\n')!456	put(b.root, 'g.txt', 'same\n')!457	put(b.root, 'h.txt', 'B\n')!458	undone := make_save(b, 'B undoes f, lands on the same g, adds h')!459460	report := steal_now(b, mut backend)!461	assert report.clashes.len == 0462	assert os.read_file(os.join_path(b.root, 'f.txt'))! == 'from A\n'463	assert os.read_file(os.join_path(b.root, 'g.txt'))! == 'same\n'464	assert os.read_file(os.join_path(b.root, 'h.txt'))! == 'B\n'465	// "B tries" only touched files A changed, so it has nothing left to466	// replay; the second save carries h.txt. Both originals stay in history.467	assert report.replayed == 1468	assert head_of(b).replayed_from == undone.id469	ids := history.all_saves(b)!.map(it.id)470	assert tried.id in ids && undone.id in ids471	assert history.files_of(b, tried.id)!.any(it.path == 'f.txt')472}473474// A person deciding a clash may take minutes; the question must come before475// the write lock, or every agent's save on this repo waits and then fails.476fn test_clash_questions_are_asked_before_the_write_lock() {477	base := scratch('ask_unlocked')!478	defer {479		os.rmdir_all(base) or {}480	}481	mut backend := remote.new_folder(os.join_path(base, 'remote'))!482	mut a := open_repo(machine('ask_a')!)!483	defer {484		a.close()485	}486	mut b := open_repo(machine('ask_b')!)!487	defer {488		b.close()489	}490	put(a.root, 'same.txt', 'base\n')!491	make_save(a, 'base')!492	offer_now(a, mut backend)!493	join(b, mut backend)!494	put(a.root, 'same.txt', 'A version\n')!495	make_save(a, 'A edits same')!496	offer_now(a, mut backend)!497	put(b.root, 'same.txt', 'B version\n')!498	make_save(b, 'B edits same')!499	root := b.root500	// An agent saves while the person is still choosing.501	if _ := steal(b, mut backend, StealOptions{502		guide: fn [root] (preview StealPreview) !map[string]Side {503			other := storage.open(root) or { panic(err) }504			defer {505				other.close()506			}507			os.write_file(os.join_path(root, 'agent.txt'), 'saved meanwhile\n') or { panic(err) }508			history.save_worktree(other, root, snapshot.load(root), history.SaveInput{509				message: 'agent saves during the question'510			}) or { panic('steal held the write lock while asking: ${err}') }511			return {512				preview.clashes[0].path: Side.mine513			}514		}515	})516	{517		assert false, 'a steal whose line moved during the question must refuse'518	} else {519		assert err.msg().contains('changed while')520	}521	// The agent's save is still head, and a second steal combines it too.522	assert head_of(b).message == 'agent saves during the question'523	report := steal(b, mut backend, StealOptions{524		mine: true525	})!526	assert report.kept_mine == 1527	assert os.read_file(os.join_path(b.root, 'agent.txt'))! == 'saved meanwhile\n'528	assert os.read_file(os.join_path(b.root, 'same.txt'))! == 'B version\n'529}530531fn test_clashing_files_are_chosen_one_at_a_time() {532	base := scratch('clash')!533	defer {534		os.rmdir_all(base) or {}535	}536	mut backend := remote.new_folder(os.join_path(base, 'remote'))!537	mut a := open_repo(machine('clash_a')!)!538	defer {539		a.close()540	}541	mut b := open_repo(machine('clash_b')!)!542	defer {543		b.close()544	}545	put(a.root, 'same.txt', 'base\n')!546	put(a.root, 'other.txt', 'quiet\n')!547	make_save(a, 'base')!548	offer_now(a, mut backend)!549	join(b, mut backend)!550551	// Both machines edit the same file, differently.552	put(a.root, 'same.txt', 'A version\n')!553	make_save(a, 'A edits same')!554	offer_now(a, mut backend)!555	put(b.root, 'same.txt', 'B version\n')!556	make_save(b, 'B edits same')!557558	// Without a decision, steal refuses and says which files clash.559	if _ := steal(b, mut backend, StealOptions{}) {560		assert false, 'an undecided clash must be refused'561	} else {562		assert err.msg().contains('--mine') || err.msg().contains('--theirs')563		// `koh offer` has no --mine or --theirs, so it needs the paths, not this sentence.564		if err is ClashError {565			assert err.paths == ['same.txt']566		} else {567			assert false, 'an undecided clash must be a ClashError, not ${err}'568		}569	}570	assert find_clashes(history.files_of(b, head_of(b).id)!, history.files_of(b, head_of(b).id)!, history.files_of(b,571		head_of(b).id)!).len == 0572573	// Choosing the remote's version ends with A's content.574	report := steal_now(b, mut backend)!575	assert report.clashes == ['same.txt']576	assert report.kept_mine == 0577	assert report.kept_versions == ['same.txt:${report.previous_head}']578	assert os.read_file(os.join_path(b.root, 'same.txt'))! == 'A version\n'579	assert os.read_file(os.join_path(b.root, 'other.txt'))! == 'quiet\n'580}581582fn test_cancelling_a_guided_steal_keeps_the_line_and_can_retry() {583	base := scratch('guided_cancel')!584	defer { os.rmdir_all(base) or {} }585	mut backend := remote.new_folder(os.join_path(base, 'remote'))!586	mut a := open_repo(machine('guided_cancel_a')!)!587	defer { a.close() }588	mut b := open_repo(machine('guided_cancel_b')!)!589	defer { b.close() }590	put(a.root, 'same.txt', 'base\n')!591	make_save(a, 'base')!592	offer_now(a, mut backend)!593	join(b, mut backend)!594	put(a.root, 'same.txt', 'remote\n')!595	remote_head := make_save(a, 'remote change')!596	offer_now(a, mut backend)!597	put(b.root, 'same.txt', 'mine\n')!598	local_head := make_save(b, 'local change')!599600	if _ := steal(b, mut backend, StealOptions{601		guide: fn (preview StealPreview) !map[string]Side {602			assert preview.clashes.len == 1603			return error('cancelled')604		}605	}) {606		assert false, 'the guide cancelled'607	} else {608		assert err.msg() == 'cancelled'609	}610	assert head_of(b).id == local_head.id611	assert os.read_file(os.join_path(b.root, 'same.txt'))! == 'mine\n'612	assert history.by_id(b, remote_head.id) != none613	assert steal(b, mut backend, StealOptions{ mine: true })!.kept_mine == 1614}615616fn test_choosing_mine_keeps_the_local_version() {617	base := scratch('mine')!618	defer {619		os.rmdir_all(base) or {}620	}621	mut backend := remote.new_folder(os.join_path(base, 'remote'))!622	mut a := open_repo(machine('mine_a')!)!623	defer {624		a.close()625	}626	mut b := open_repo(machine('mine_b')!)!627	defer {628		b.close()629	}630	put(a.root, 'same.txt', 'base\n')!631	make_save(a, 'base')!632	offer_now(a, mut backend)!633	join(b, mut backend)!634	put(a.root, 'same.txt', 'A version\n')!635	make_save(a, 'A edits')!636	offer_now(a, mut backend)!637	put(b.root, 'same.txt', 'B version\n')!638	make_save(b, 'B edits')!639640	report := steal(b, mut backend, StealOptions{641		mine: true642	})!643	assert report.kept_mine == 1644	assert os.read_file(os.join_path(b.root, 'same.txt'))! == 'B version\n'645	// The final save says what it kept.646	assert head_of(b).message.contains('combine: kept mine for 1 file')647	// The pre-combine tree is still reachable in history.648	assert head_of(b).restores == ''649	assert history.all_saves(b)!.len >= 4650}651652fn test_flags_travel_with_the_saves() {653	base := scratch('flags')!654	defer {655		os.rmdir_all(base) or {}656	}657	mut backend := remote.new_folder(os.join_path(base, 'remote'))!658	mut a := open_repo(machine('flag_a')!)!659	defer {660		a.close()661	}662	mut b := open_repo(machine('flag_b')!)!663	defer {664		b.close()665	}666	put(a.root, 'a.txt', 'one\n')!667	save := make_save(a, 'suspect save')!668	events.flag(a, save.id, 'look at this')!669	offer_now(a, mut backend)!670671	// B has nothing yet, so a fetch brings the save and its flag across.672	fetched := fetch_back_to_known(b, mut backend, 'proj')!673	assert fetched.events_out.len == 1674	assert fetched.events_out[0].kind == events.kind_flag675	b.begin()!676	write_fetched(b, fetched)!677	history.set_head(b, fetched.head)!678	b.end()!679	state := events.flag_state(b, save.id)!680	assert state.flagged681	assert state.reason == 'look at this'682}683684fn test_a_second_offer_racing_head_is_refused_not_forced() {685	base := scratch('race')!686	defer {687		os.rmdir_all(base) or {}688	}689	mut backend := remote.new_folder(os.join_path(base, 'remote'))!690	mut a := open_repo(machine('race_a')!)!691	defer {692		a.close()693	}694	put(a.root, 'a.txt', 'one\n')!695	make_save(a, 'base')!696	offer_now(a, mut backend)!697698	// Someone else replaces head behind our back.699	assert backend.put_if_match(head_key('proj'), 'a-save-we-do-not-have'.bytes(),700		backend.get(head_key('proj'))!.tag)!701702	put(a.root, 'a.txt', 'two\n')!703	make_save(a, 'second')!704	if _ := offer_now(a, mut backend) {705		assert false, 'offering while the remote head moved must be refused'706	} else {707		assert err.msg().contains('run koh steal')708	}709}710711// join makes a brand new machine share the remote's line.712fn join(store &storage.Store, mut backend remote.Backend) ! {713	fetched := fetch_repo(mut backend, 'proj')!714	store.begin()!715	write_fetched(store, fetched)!716	history.set_head(store, fetched.head)!717	store.end()!718	snapshot.restore_files(store, store.root, snapshot.load(store.root), history.files_of(store,719		fetched.head)!, [])!720	store.set_state('remote_repo', 'proj')!721}722723struct FaultyBackend {724mut:725	inner      remote.Backend726	writes     int727	reads      int728	fail_write int // fail when the write counter reaches this, 0 never729	fail_read  int730	// fail every delete while set731	fail_delete bool732	// race_format stands in for another machine writing the format key first:733	// the first `format` write loses, to a value this koh does not speak.734	race_format bool735	raced       bool736}737738fn (mut f FaultyBackend) get(key string) !remote.Object {739	f.reads++740	if f.fail_read > 0 && f.reads >= f.fail_read {741		return error('injected read failure')742	}743	return f.inner.get(key)!744}745746fn (mut f FaultyBackend) list(prefix string) ![]string {747	return f.inner.list(prefix)!748}749750fn (mut f FaultyBackend) put_if_absent(key string, body []u8) !bool {751	f.writes++752	if f.fail_write > 0 && f.writes >= f.fail_write {753		return error('injected write failure')754	}755	if f.race_format && !f.raced && key.ends_with('/format') {756		f.raced = true757		f.inner.put_if_absent(key, 'koh-remote 2'.bytes())!758		return false759	}760	return f.inner.put_if_absent(key, body)!761}762763fn (mut f FaultyBackend) put_if_match(key string, body []u8, tag string) !bool {764	f.writes++765	if f.fail_write > 0 && f.writes >= f.fail_write {766		return error('injected write failure')767	}768	return f.inner.put_if_match(key, body, tag)!769}770771fn (mut f FaultyBackend) delete(key string) ! {772	if f.fail_delete {773		return error('injected delete failure')774	}775	f.inner.delete(key)!776}777778// Every save offers after it is made, so a one-file change must cost one779// object, not one conditional write per file in the repo: on S3 each of those780// is a round trip.781fn test_an_offer_sends_only_the_objects_a_save_adds() {782	base := scratch('offer_diff')!783	defer {784		os.rmdir_all(base) or {}785	}786	mut a := open_repo(machine('offer_diff_a')!)!787	defer {788		a.close()789	}790	for i in 0 .. 20 {791		put(a.root, 'f${i}.txt', 'file ${i}\n')!792	}793	make_save(a, 'twenty files')!794	mut backend := FaultyBackend{795		inner: remote.new_folder(os.join_path(base, 'remote'))!796	}797	offer(a, mut backend)!798	put(a.root, 'f3.txt', 'changed\n')!799	make_save(a, 'one change')!800	before := backend.writes801	report := offer(a, mut backend)!802	assert report.objects == 1803	// One object, one save record, one head swap.804	assert backend.writes - before == 3805}806807fn test_a_failed_offer_is_safe_to_re_run() {808	base := scratch('fault_offer')!809	defer {810		os.rmdir_all(base) or {}811	}812	remote_dir := os.join_path(base, 'remote')813	mut a := open_repo(machine('fault_a')!)!814	defer {815		a.close()816	}817	put(a.root, 'a.txt', 'one\n')!818	make_save(a, 'first')!819	put(a.root, 'a.txt', 'two\n')!820	make_save(a, 'second')!821822	// The first offer dies after the first write.823	mut flaky := FaultyBackend{824		inner:      remote.new_folder(remote_dir)!825		fail_write: 2826	}827	if _ := offer(a, mut flaky) {828		assert false, 'the injected failure should have surfaced'829	}830831	// Re-running with a healthy remote finishes the job: "already exists" is832	// success, so nothing is lost and nothing is duplicated.833	mut healthy := remote.new_folder(remote_dir)!834	report := offer(a, mut healthy)!835	assert report.saves == 2836	assert healthy.get(head_key('proj'))!.body.bytestr().trim_space() == head_of(a).id837	assert healthy.list('proj/saves')!.len == 2838}839840// A strip whose path breaks §5.5 names nothing a save can hold; Koh and Kepr both leave it out,841// and it must neither remove anything nor hold up an offer.842fn test_a_strip_with_an_illegal_path_is_ignored() {843	base := scratch('illegal_strip')!844	defer {845		os.rmdir_all(base) or {}846	}847	mut backend := remote.new_folder(os.join_path(base, 'remote'))!848	mut a := open_repo(machine('illegal_strip_a')!)!849	defer {850		a.close()851	}852	mut b := open_repo(machine('illegal_strip_b')!)!853	defer {854		b.close()855	}856	put(a.root, 'a/x.txt', 'kept\n')!857	make_save(a, 'add a folder')!858	offer_now(a, mut backend)!859	for id, path in {860		'aaaaaaaaaaaa': 'a//'861		'bbbbbbbbbbbb': 'a\\ud800'862	} {863		backend.put_if_absent(event_key('proj', id), '{"id":"${id}","kind":"strip","save_id":"","path":"${path}","reason":"","created_at":1,"machine":"crafted"}'.bytes())!864	}865	join(b, mut backend)!866	assert 'a/x.txt' in history.files_of(b, history.head(b)!.id)!.map(it.path)867	put(a.root, 'more.txt', 'more\n')!868	make_save(a, 'more')!869	offer_now(a, mut backend)!870}871872fn test_a_failed_steal_leaves_nothing_behind() {873	base := scratch('fault_steal')!874	defer {875		os.rmdir_all(base) or {}876	}877	remote_dir := os.join_path(base, 'remote')878	mut a := open_repo(machine('fault_s_a')!)!879	defer {880		a.close()881	}882	mut b := open_repo(machine('fault_s_b')!)!883	defer {884		b.close()885	}886	put(a.root, 'a.txt', 'from A\n')!887	make_save(a, 'A writes')!888	mut healthy := remote.new_folder(remote_dir)!889	offer(a, mut healthy)!890891	// B's fetch fails half way through reading the remote.892	mut flaky := FaultyBackend{893		inner:     remote.new_folder(remote_dir)!894		fail_read: 2895	}896	if _ := fetch_back_to_known(b, mut flaky, 'proj') {897		assert false, 'the injected read failure should have surfaced'898	}899	// Nothing was written: the store is untouched and still has no saves.900	assert history.head(b) == none901	assert b.object_count()! == 0902903	// A healthy retry works.904	fetched := fetch_back_to_known(b, mut healthy, 'proj')!905	b.begin()!906	write_fetched(b, fetched)!907	history.set_head(b, fetched.head)!908	b.end()!909	snapshot.restore_files(b, b.root, snapshot.load(b.root), history.files_of(b, fetched.head)!, [])!910	assert os.read_file(os.join_path(b.root, 'a.txt'))! == 'from A\n'911}912913fn test_an_interrupted_strip_is_idempotent() {914	// The local half of a strip is one transaction, so an interrupted strip is915	// simply a strip that did not happen; re-running it must land the same916	// result once, not twice.917	base := scratch('fault_strip')!918	defer {919		os.rmdir_all(base) or {}920	}921	mut a := open_repo(machine('fault_strip_a')!)!922	defer {923		a.close()924	}925	put(a.root, 'secret.txt', 'shh\n')!926	put(a.root, 'keep.txt', 'fine\n')!927	save := make_save(a, 'add both')!928929	for _ in 0 .. 2 {930		strip_local(a, 'secret.txt', '')!931	}932	files := history.files_of(a, save.id)!933	// The repo's own `.kohignore` is tracked content, so it stays; only the934	// stripped path goes.935	assert files.map(it.path) == ['.kohignore', 'keep.txt']936	assert events.strip_events(a)!.len == 1937}938939// SQLite's LIKE ignores ASCII case, so a strip of `docs` must not reach into940// `Docs/`, and `a_b` must not reach `aXb`: strip destroys, so it matches exactly.941// The tree is built by hand: on macOS `Docs` and `docs` are one folder on disk,942// but a save made on Linux can hold both.943fn test_a_strip_matches_the_path_exactly() {944	mut a := open_repo(machine('strip_exact')!)!945	defer {946		a.close()947	}948	hash := a.put_object('x\n'.bytes())!949	mut files := []snapshot.FileEntry{}950	for path in ['DOCS.txt', 'Docs/keep.txt', 'a_b/x.txt', 'aXb/y.txt', 'docs/secret.txt'] {951		files << snapshot.FileEntry{952			path: path953			hash: hash954		}955	}956	save := history.save_tree(a, '', files, history.SaveInput{957		message: 'add all'958	})!959	assert strip_scope(a, 'docs', '')!.files == 1960	strip_local(a, 'docs', '')!961	strip_local(a, 'a_b', '')!962	assert history.files_of(a, save.id)!.map(it.path) == ['DOCS.txt', 'Docs/keep.txt', 'aXb/y.txt']963}964965fn test_a_strip_reaches_the_remote_and_other_machines() {966	base := scratch('strip_sync')!967	defer {968		os.rmdir_all(base) or {}969	}970	mut a := open_repo(machine('strip_a')!)!971	defer {972		a.close()973	}974	mut b := open_repo(machine('strip_b')!)!975	defer {976		b.close()977	}978	put(a.root, 'secrets.env', 'api_key=1\n')!979	put(a.root, 'keep.txt', 'fine\n')!980	save := make_save(a, 'add both')!981	mut backend := remote.new_folder(os.join_path(base, 'remote'))!982	offer_now(a, mut backend)!983	join(b, mut backend)!984	assert b.object_count()! > 0985986	// A strips the path locally, the way `koh strip` does, then tells the987	// remote.988	mut secret_hash := ''989	for file in history.files_of(a, save.id)! {990		if file.path == 'secrets.env' {991			secret_hash = file.hash992		}993	}994	assert secret_hash != ''995	strip_local(a, 'secrets.env', '')!996	report := send_strip(a, mut backend, 'secrets.env')!997	assert report.event_sent998	assert report.records == 19991000	// The remote's copy of the save no longer lists the file, and the object is1001	// gone from the remote.1002	record := decode_save(backend.get(save_key('proj', save.id))!.body)!1003	for file in record.files {1004		assert file.path != 'secrets.env'1005	}1006	// The stripped object is gone from the remote; the ones still referenced1007	// are not.1008	assert !backend.get(object_key('proj', secret_hash))!.found1009	assert backend.list('proj/objects')!.len == 210101011	// Another machine hears about it on its next steal and applies it.1012	b.begin()!1013	fetched := fetch_back_to_known(b, mut backend, 'proj')!1014	write_fetched(b, fetched)!1015	b.end()!1016	mut paths := []string{}1017	for file in history.files_of(b, save.id)! {1018		paths << file.path1019	}1020	assert 'secrets.env' !in paths1021	assert 'keep.txt' in paths10221023	// The event arrives under its own ID, so it is applied once: B's offer adds1024	// no second copy. The path is banned for good: written again, the file is1025	// neither unsaved work nor ever walked into a save.1026	assert events.strip_events(b)!.map(it.id) == events.strip_events(a)!.map(it.id)1027	put(b.root, 'secrets.env', 'rotated\n')!1028	assert !dirty(b, history.head(b))!1029	put(b.root, 'keep.txt', 'still fine\n')!1030	later := make_save(b, 'edit keep')!1031	offer_now(b, mut backend)!1032	assert backend.list('proj/events')!.len == 11033	assert 'secrets.env' !in history.files_of(b, later.id)!.map(it.path)1034}10351036// A strip removes a path from all of history, whenever a save was made. A1037// machine that saved the file after the strip, before it heard of it, loses1038// it from that save too on its next steal, so no copy anywhere keeps it.1039fn test_a_strip_reaches_saves_made_after_it_by_a_machine_that_had_not_heard() {1040	base := scratch('strip_later')!1041	defer {1042		os.rmdir_all(base) or {}1043	}1044	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1045	mut a := open_repo(machine('strip_later_a')!)!1046	defer {1047		a.close()1048	}1049	mut b := open_repo(machine('strip_later_b')!)!1050	defer {1051		b.close()1052	}1053	put(a.root, 'secrets.env', 'api_key=1\n')!1054	old := make_save(a, 'leak the key')!1055	offer_now(a, mut backend)!1056	join(b, mut backend)!1057	strip_local(a, 'secrets.env', '')!1058	send_strip(a, mut backend, 'secrets.env')!1059	// B has not heard, and saves the file again an hour after the strip.1060	put(b.root, 'secrets.env', 'api_key=2\n')!1061	later := history.save_tree(b, b.root, snapshot.walk(b, b.root, snapshot.load(b.root))!, history.SaveInput{1062		message:    'rotate the key'1063		created_at: events.strip_events(a)!.last().created_at + 36001064	})!1065	assert 'secrets.env' in history.files_of(b, later.id)!.map(it.path)1066	b.begin()!1067	write_fetched(b, fetch_back_to_known(b, mut backend, 'proj')!)!1068	b.end()!1069	assert 'secrets.env' !in history.files_of(b, later.id)!.map(it.path)1070	offer_now(b, mut backend)!10711072	mut c := open_repo(machine('strip_later_c')!)!1073	defer {1074		c.close()1075	}1076	join(c, mut backend)!1077	for save in [old.id, later.id] {1078		assert 'secrets.env' !in history.files_of(c, save)!.map(it.path)1079	}1080	assert !os.exists(os.join_path(c.root, 'secrets.env'))1081}10821083// A strip this machine already holds bans its path from saves that arrive1084// later too, not only from those a fetch brings with the strip.1085fn test_a_held_strip_reaches_saves_arriving_after_it() {1086	base := scratch('strip_held')!1087	defer {1088		os.rmdir_all(base) or {}1089	}1090	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1091	mut a := open_repo(machine('strip_held_a')!)!1092	defer {1093		a.close()1094	}1095	mut b := open_repo(machine('strip_held_b')!)!1096	defer {1097		b.close()1098	}1099	put(a.root, 'secrets.env', 'api_key=1\n')!1100	make_save(a, 'leak the key')!1101	offer_now(a, mut backend)!1102	join(b, mut backend)!1103	strip_local(b, 'secrets.env', '')!1104	put(a.root, 'keep.txt', 'fine\n')!1105	later := make_save(a, 'add keep')!1106	offer_now(a, mut backend)!1107	b.begin()!1108	write_fetched(b, fetch_back_to_known(b, mut backend, 'proj')!)!1109	b.end()!1110	paths := history.files_of(b, later.id)!.map(it.path)1111	assert 'secrets.env' !in paths1112	assert 'keep.txt' in paths1113}11141115// StripRace stands in for another machine that strips `path` completely, event1116// and rewrite, just before this machine's first save record lands.1117struct StripRace {1118mut:1119	inner remote.Backend1120	other &storage.Store1121	path  string1122	done  bool1123	// fail every put after the one the strip raced1124	fail_after_race bool1125	raced_put       bool1126	fail_delete     bool1127}11281129fn (mut r StripRace) get(key string) !remote.Object {1130	return r.inner.get(key)!1131}11321133fn (mut r StripRace) list(prefix string) ![]string {1134	return r.inner.list(prefix)!1135}11361137fn (mut r StripRace) put_if_absent(key string, body []u8) !bool {1138	if r.fail_after_race && r.raced_put {1139		return error('injected write failure')1140	}1141	if !r.done && key.contains('/saves/') {1142		r.done = true1143		r.raced_put = true1144		strip_local(r.other, r.path, '')!1145		send_strip(r.other, mut r.inner, r.path)!1146	}1147	return r.inner.put_if_absent(key, body)!1148}11491150fn (mut r StripRace) put_if_match(key string, body []u8, tag string) !bool {1151	return r.inner.put_if_match(key, body, tag)!1152}11531154fn (mut r StripRace) delete(key string) ! {1155	if r.fail_delete {1156		return error('injected delete failure')1157	}1158	r.inner.delete(key)!1159}11601161// A strip that finishes on another machine while an offer uploads has already1162// rewritten the remote without the offer's records, so the offer takes back1163// what the strip reaches and leaves head where it was.1164fn test_an_offer_racing_a_strip_leaves_no_stripped_path_behind() {1165	base := scratch('strip_race')!1166	defer {1167		os.rmdir_all(base) or {}1168	}1169	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1170	mut a := open_repo(machine('strip_race_a')!)!1171	defer {1172		a.close()1173	}1174	mut b := open_repo(machine('strip_race_b')!)!1175	defer {1176		b.close()1177	}1178	put(a.root, 'secrets.env', 'api_key=1\n')!1179	first := make_save(a, 'leak the key')!1180	offer_now(a, mut backend)!1181	join(b, mut backend)!1182	put(a.root, 'secrets.env', 'api_key=2\n')!1183	later := make_save(a, 'rotate the key')!1184	secret := history.files_of(a, later.id)!.filter(it.path == 'secrets.env')[0].hash1185	mut race := StripRace{1186		inner: backend1187		other: &b1188		path:  'secrets.env'1189	}1190	if _ := offer(a, mut race) {1191		assert false, 'an offer that raced a strip must refuse'1192	} else {1193		assert err.msg().contains('koh steal'), err.msg()1194	}1195	assert backend.get(head_key('proj'))!.body.bytestr() == first.id1196	assert !backend.get(object_key('proj', secret))!.found1197	// Another offer may already have published it, so the record stays, stripped.1198	assert backend.get(save_key('proj', later.id))!.found1199	for key in backend.list('proj/saves')! {1200		record := decode_save(backend.get(key)!.body)!1201		assert 'secrets.env' !in record.files.map(it.path), record.id1202	}1203}12041205// Doctor's resend of a missing record can race a strip just as an offer can,1206// and takes back what the strip reaches in the same way.1207fn test_a_resend_racing_a_strip_leaves_no_stripped_path_behind() {1208	base := scratch('resend_race')!1209	defer {1210		os.rmdir_all(base) or {}1211	}1212	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1213	mut a := open_repo(machine('resend_race_a')!)!1214	defer {1215		a.close()1216	}1217	mut b := open_repo(machine('resend_race_b')!)!1218	defer {1219		b.close()1220	}1221	put(a.root, 'secrets.env', 'api_key=1\n')!1222	first := make_save(a, 'leak the key')!1223	offer_now(a, mut backend)!1224	join(b, mut backend)!1225	backend.delete(save_key('proj', first.id))!1226	mut race := StripRace{1227		inner: backend1228		other: &b1229		path:  'secrets.env'1230	}1231	if _ := resend(a, mut race, 'proj', [], [first.id]) {1232		assert false, 'a resend that raced a strip must refuse'1233	} else {1234		assert err.msg().contains('koh steal'), err.msg()1235		// The restored record is still a repair Doctor made.1236		assert (err as Partway).done == 'uploaded 0 objects and 1 save record'1237	}1238	// Head names the restored record, so it stays, less the stripped path.1239	record := decode_save(backend.get(save_key('proj', first.id))!.body)!1240	assert 'secrets.env' !in record.files.map(it.path)1241	assert !backend.get(object_key('proj', storage.hash_hex('api_key=1\n'.bytes())))!.found1242}12431244// An object a strip reaches stays while a remote record still lists it under1245// another path, and a strip that landed before an upload failed is still applied.1246fn test_a_resend_keeps_shared_bytes_and_settles_a_strip_after_a_failure() {1247	base := scratch('resend_shared')!1248	defer {1249		os.rmdir_all(base) or {}1250	}1251	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1252	mut a := open_repo(machine('resend_shared_a')!)!1253	defer {1254		a.close()1255	}1256	mut b := open_repo(machine('resend_shared_b')!)!1257	defer {1258		b.close()1259	}1260	put(a.root, 'secrets.env', 'same\n')!1261	put(a.root, 'copy.txt', 'same\n')!1262	first := make_save(a, 'two paths, one object')!1263	offer_now(a, mut backend)!1264	join(b, mut backend)!1265	put(a.root, 'later.txt', 'later\n')!1266	second := make_save(a, 'not offered')!1267	shared := object_key('proj', storage.hash_hex('same\n'.bytes()))1268	backend.delete(save_key('proj', first.id))!1269	backend.delete(shared)!1270	mut race := StripRace{1271		inner:           backend1272		other:           &b1273		path:            'secrets.env'1274		fail_after_race: true1275	}1276	if _ := resend(a, mut race, 'proj', [], [first.id, second.id]) {1277		assert false, 'the injected failure should have surfaced'1278	} else {1279		assert err.msg().contains('injected'), err.msg()1280	}1281	record := decode_save(backend.get(save_key('proj', first.id))!.body)!1282	paths := record.files.map(it.path)1283	assert 'secrets.env' !in paths && 'copy.txt' in paths, paths.str()1284	assert backend.get(shared)!.found1285}12861287// A note that does not parse, or that no recorded strip of its path backs, is1288// kept and changes nothing remote: sending it would lose the retry or strip1289// where no strip asked.1290fn test_an_untrusted_strip_note_is_kept_and_sends_nothing() {1291	base := scratch('strip_note')!1292	defer {1293		os.rmdir_all(base) or {}1294	}1295	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1296	mut a := open_repo(machine('strip_note_a')!)!1297	defer {1298		a.close()1299	}1300	put(a.root, 'app', 'app\n')!1301	save := make_save(a, 'app')!1302	offer_now(a, mut backend)!1303	events.strip(a, '', 'other')!1304	for note in ['not JSON', '{"saves":[""],"hashes":[]}'] {1305		a.set_state(pending_key('app'), note)!1306		if _ := send_strip(a, mut backend, 'app') {1307			assert false, 'an untrusted note must be refused'1308		} else {1309			assert err.msg().contains('kept for recovery'), err.msg()1310		}1311		assert a.state(pending_key('app')) or { '' } == note1312		assert backend.list(events_prefix('proj'))!.len == 01313		assert 'app' in decode_save(backend.get(save_key('proj', save.id))!.body)!.files.map(it.path)1314	}1315	// Even behind a recorded strip, a note's hashes may name only objects.1316	events.strip(a, '', 'app')!1317	victim := os.join_path(base, 'remote', 'victim', 'head')1318	os.mkdir_all(os.dir(victim))!1319	os.write_file(victim, 'another repo')!1320	a.set_state(pending_key('app'), '{"saves":[""],"hashes":["../../victim/head"]}')!1321	if _ := send_strip(a, mut backend, 'app') {1322		assert false, 'a note naming a path outside the objects must be refused'1323	}1324	assert os.read_file(victim)! == 'another repo'1325}13261327// A settlement that stops part way leaves the record naming the stripped1328// path, which is what lets Doctor send the strip again once this repo has it.1329fn test_a_failed_settlement_leaves_residue_doctor_can_finish() {1330	base := scratch('settle_fail')!1331	defer {1332		os.rmdir_all(base) or {}1333	}1334	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1335	mut a := open_repo(machine('settle_fail_a')!)!1336	defer {1337		a.close()1338	}1339	mut b := open_repo(machine('settle_fail_b')!)!1340	defer {1341		b.close()1342	}1343	put(a.root, 'secrets.env', 'api_key=1\n')!1344	first := make_save(a, 'leak the key')!1345	offer_now(a, mut backend)!1346	join(b, mut backend)!1347	secret := object_key('proj', storage.hash_hex('api_key=1\n'.bytes()))1348	backend.delete(save_key('proj', first.id))!1349	backend.delete(secret)!1350	mut race := StripRace{1351		inner:       backend1352		other:       &b1353		path:        'secrets.env'1354		fail_delete: true1355	}1356	if _ := resend(a, mut race, 'proj', [], [first.id]) {1357		assert false, 'the injected delete failure should have surfaced'1358	}1359	record := decode_save(backend.get(save_key('proj', first.id))!.body)!1360	assert 'secrets.env' in record.files.map(it.path)1361	steal_now(a, mut backend)!1362	requeue_strip(a, 'secrets.env')!1363	send_strip(a, mut backend, 'secrets.env')!1364	cleaned := decode_save(backend.get(save_key('proj', first.id))!.body)!1365	assert 'secrets.env' !in cleaned.files.map(it.path)1366	assert !backend.get(secret)!.found1367}13681369// A strip whose deletes fail after its rewrite keeps, in its note, the objects1370// the rewritten record no longer names, so the retry still deletes them.1371fn test_a_strip_retry_deletes_objects_its_rewrite_found() {1372	base := scratch('strip_found')!1373	defer {1374		os.rmdir_all(base) or {}1375	}1376	remote_dir := os.join_path(base, 'remote')1377	mut backend := remote.new_folder(remote_dir)!1378	mut a := open_repo(machine('strip_found_a')!)!1379	defer {1380		a.close()1381	}1382	put(a.root, 'secrets.env', 'api_key=1\n')!1383	make_save(a, 'leak the key')!1384	offer_now(a, mut backend)!1385	strip_local(a, 'secrets.env', '')!1386	// A note rebuilt from the event alone, as Doctor's residue repair writes it.1387	a.remove_state(pending_key('secrets.env'))!1388	requeue_strip(a, 'secrets.env')!1389	mut flaky := FaultyBackend{1390		inner:       remote.new_folder(remote_dir)!1391		fail_delete: true1392	}1393	if _ := send_strip(a, mut flaky, 'secrets.env') {1394		assert false, 'the injected delete failure should have surfaced'1395	}1396	send_strip(a, mut backend, 'secrets.env')!1397	assert !backend.get(object_key('proj', storage.hash_hex('api_key=1\n'.bytes())))!.found1398	assert !strip_pending(a, 'secrets.env')1399}14001401// MovingRecord stands in for another machine rewriting a record between this1402// machine's read and its conditional write: the first conditional write finds1403// `other` already removed from the record.1404struct MovingRecord {1405mut:1406	inner remote.Backend1407	other string1408	moved bool1409}14101411fn (mut m MovingRecord) get(key string) !remote.Object {1412	return m.inner.get(key)!1413}14141415fn (mut m MovingRecord) list(prefix string) ![]string {1416	return m.inner.list(prefix)!1417}14181419fn (mut m MovingRecord) put_if_absent(key string, body []u8) !bool {1420	return m.inner.put_if_absent(key, body)!1421}14221423fn (mut m MovingRecord) put_if_match(key string, body []u8, tag string) !bool {1424	if !m.moved {1425		m.moved = true1426		current := m.inner.get(key)!1427		record := decode_save(current.body)!1428		other := record.files.filter(it.path != m.other)1429		m.inner.put_if_match(key, encode_save(rewrite(record, other)).bytes(), current.tag)!1430	}1431	return m.inner.put_if_match(key, body, tag)!1432}14331434fn (mut m MovingRecord) delete(key string) ! {1435	m.inner.delete(key)!1436}14371438fn test_a_stripped_record_that_moves_is_read_again() {1439	base := scratch('moving_record')!1440	defer {1441		os.rmdir_all(base) or {}1442	}1443	mut folder := remote.new_folder(os.join_path(base, 'remote'))!1444	key := save_key('proj', 'aaaaaaaaaaaa')1445	folder.put_if_absent(key, encode_save(SaveRecord{1446		id:    'aaaaaaaaaaaa'1447		files: [FileRecord{1448			path: 'secret-a'1449		}, FileRecord{1450			path: 'secret-b'1451		}, FileRecord{1452			path: 'keep'1453		}]1454	}).bytes())!1455	mut moving := MovingRecord{1456		inner: folder1457		other: 'secret-b'1458	}1459	strip_record(mut moving, key, 'aaaaaaaaaaaa', [1460		events.Event{1461			kind: events.kind_strip1462			path: 'secret-a'1463		},1464	])!1465	assert decode_save(folder.get(key)!.body)!.files.map(it.path) == ['keep']1466}14671468// An invalid strip event on the remote cannot make an upload take anything back.1469fn test_an_invalid_remote_strip_event_is_not_unapplied() {1470	base := scratch('invalid_remote_strip')!1471	defer {1472		os.rmdir_all(base) or {}1473	}1474	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1475	mut a := open_repo(machine('invalid_remote_strip_a')!)!1476	defer {1477		a.close()1478	}1479	bad := events.Event{1480		id:         'badstripevnt'1481		kind:       events.kind_strip1482		path:       'app'1483		created_at: -11484		machine:    'other'1485	}1486	backend.put_if_absent(event_key('proj', bad.id), encode_event(bad).bytes())!1487	assert unapplied_strips(a, mut backend, 'proj')!.len == 01488}14891490// A resend that fails part way reports what it had already uploaded.1491fn test_a_failed_resend_reports_what_landed() {1492	base := scratch('resend_partway')!1493	defer {1494		os.rmdir_all(base) or {}1495	}1496	remote_dir := os.join_path(base, 'remote')1497	mut a := open_repo(machine('resend_partway_a')!)!1498	defer {1499		a.close()1500	}1501	put(a.root, 'one.txt', 'one\n')!1502	put(a.root, 'two.txt', 'two\n')!1503	make_save(a, 'two objects')!1504	hashes := ['one\n', 'two\n'].map(storage.hash_hex(it.bytes()))1505	mut flaky := FaultyBackend{1506		inner:      remote.new_folder(remote_dir)!1507		fail_write: 21508	}1509	if _ := resend(a, mut flaky, 'proj', hashes, []) {1510		assert false, 'the injected failure should have surfaced'1511	} else {1512		assert err is Partway1513		assert (err as Partway).done == 'uploaded 1 object and 0 save records', (err as Partway).done1514	}1515}15161517// The local half lands before the remote hears anything, so a remote failure1518// leaves nothing to find locally; the pending note is what lets a re-run1519// finish. Objects a remote-only save still needs must survive the strip.1520fn test_an_interrupted_remote_strip_finishes_when_re_run() {1521	base := scratch('strip_resume')!1522	defer {1523		os.rmdir_all(base) or {}1524	}1525	remote_dir := os.join_path(base, 'remote')1526	mut backend := remote.new_folder(remote_dir)!1527	mut a := open_repo(machine('resume_a')!)!1528	defer {1529		a.close()1530	}1531	mut b := open_repo(machine('resume_b')!)!1532	defer {1533		b.close()1534	}1535	put(a.root, 'secrets.env', 'api_key=1\n')!1536	put(a.root, 'shared.env', 'same bytes on B\n')!1537	save := make_save(a, 'add secrets')!1538	offer_now(a, mut backend)!1539	join(b, mut backend)!1540	put(b.root, 'copy.txt', 'same bytes on B\n')!1541	b_save := make_save(b, 'B keeps a copy')!1542	offer_now(b, mut backend)!1543	shared_hash := storage.hash_hex('same bytes on B\n'.bytes())1544	secret_hash := storage.hash_hex('api_key=1\n'.bytes())15451546	strip_local(a, 'secrets.env', '')!1547	// Write 1 uploads the event and write 2 rewrites the first record; B's save,1548	// made from A's tree, lists the file too, and its rewrite (write 3) fails.1549	mut flaky := FaultyBackend{1550		inner:      remote.new_folder(remote_dir)!1551		fail_write: 31552	}1553	if _ := send_strip(a, mut flaky, 'secrets.env') {1554		assert false, 'the injected failure should have surfaced'1555	}1556	assert strip_pending(a, 'secrets.env')1557	assert strip_local(a, 'secrets.env', '')!.files_removed == 01558	report := send_strip(a, mut backend, 'secrets.env')!1559	assert report.records == 11560	assert !strip_pending(a, 'secrets.env')1561	assert !backend.get(object_key('proj', secret_hash))!.found1562	record := decode_save(backend.get(save_key('proj', save.id))!.body)!1563	assert 'secrets.env' !in record.files.map(it.path)1564	b_record := decode_save(backend.get(save_key('proj', b_save.id))!.body)!1565	assert 'secrets.env' !in b_record.files.map(it.path)15661567	// B's save still names the shared bytes, so stripping A's copy keeps them.1568	strip_local(a, 'shared.env', '')!1569	send_strip(a, mut backend, 'shared.env')!1570	assert backend.get(object_key('proj', shared_hash))!.found1571}15721573// A machine that has not heard of a strip must not offer: its records still1574// list the stripped path, and nothing would rewrite them on the remote again.1575fn test_offer_waits_for_an_unapplied_strip() {1576	base := scratch('strip_first')!1577	defer {1578		os.rmdir_all(base) or {}1579	}1580	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1581	mut a := open_repo(machine('strip_first_a')!)!1582	defer {1583		a.close()1584	}1585	mut b := open_repo(machine('strip_first_b')!)!1586	defer {1587		b.close()1588	}1589	put(a.root, 'secrets.env', 'api_key=1\n')!1590	make_save(a, 'add secrets')!1591	offer_now(a, mut backend)!1592	join(b, mut backend)!1593	strip_local(a, 'secrets.env', '')!1594	send_strip(a, mut backend, 'secrets.env')!1595	put(b.root, 'more.txt', 'B keeps working\n')!1596	later := make_save(b, 'B saves with the secret still in its tree')!1597	if _ := offer_now(b, mut backend) {1598		assert false, 'B offered records that still list the stripped path'1599	}1600	steal_now(b, mut backend)!1601	offer_now(b, mut backend)!1602	record := decode_save(backend.get(save_key('proj', later.id))!.body)!1603	assert 'secrets.env' !in record.files.map(it.path)1604}16051606// A strip whose object deletions failed must still delete them when it is run1607// again, and meanwhile the banned path cannot come back in through a save.1608fn test_a_strip_whose_deletes_failed_finishes_when_run_again() {1609	base := scratch('strip_twice')!1610	defer {1611		os.rmdir_all(base) or {}1612	}1613	remote_dir := os.join_path(base, 'remote')1614	mut backend := remote.new_folder(remote_dir)!1615	mut a := open_repo(machine('strip_twice_a')!)!1616	defer {1617		a.close()1618	}1619	put(a.root, 'secrets.env', 'first key\n')!1620	make_save(a, 'first key')!1621	offer_now(a, mut backend)!1622	strip_local(a, 'secrets.env', '')!1623	mut flaky := FaultyBackend{1624		inner:       remote.new_folder(remote_dir)!1625		fail_delete: true1626	}1627	if _ := send_strip(a, mut flaky, 'secrets.env') {1628		assert false, 'the injected delete failure should have surfaced'1629	}1630	put(a.root, 'secrets.env', 'second key\n')!1631	put(a.root, 'other.txt', 'more work\n')!1632	make_save(a, 'more work')!1633	offer_now(a, mut backend)!1634	send_strip(a, mut backend, 'secrets.env')!1635	for key in ['first key\n', 'second key\n'] {1636		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1637	}1638}16391640// Unfinished strips of one path in different scopes finish together.1641fn test_unfinished_strips_of_one_path_in_different_saves_finish_together() {1642	base := scratch('strip_scopes')!1643	defer {1644		os.rmdir_all(base) or {}1645	}1646	remote_dir := os.join_path(base, 'remote')1647	mut backend := remote.new_folder(remote_dir)!1648	mut a := open_repo(machine('strip_scopes_a')!)!1649	defer {1650		a.close()1651	}1652	put(a.root, 'secrets.env', 'first key\n')!1653	first := make_save(a, 'first key')!1654	put(a.root, 'secrets.env', 'second key\n')!1655	second := make_save(a, 'second key')!1656	offer_now(a, mut backend)!1657	strip_local(a, 'secrets.env', first.id)!1658	// Write 1 uploads the event; write 2, the record rewrite, fails.1659	mut flaky := FaultyBackend{1660		inner:      remote.new_folder(remote_dir)!1661		fail_write: 21662	}1663	if _ := send_strip(a, mut flaky, 'secrets.env') {1664		assert false, 'the injected failure should have surfaced'1665	}1666	strip_local(a, 'secrets.env', second.id)!1667	send_strip(a, mut backend, 'secrets.env')!1668	assert !strip_pending(a, 'secrets.env')1669	for save in [first, second] {1670		record := decode_save(backend.get(save_key('proj', save.id))!.body)!1671		assert 'secrets.env' !in record.files.map(it.path)1672	}1673	for key in ['first key\n', 'second key\n'] {1674		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1675	}1676}16771678// A strip bans its path on every machine that has heard of it: written again,1679// the file makes no save, here or there, so there is never a second copy to strip.1680fn test_a_stripped_path_cannot_be_saved_again_on_any_machine() {1681	base := scratch('strip_again')!1682	defer {1683		os.rmdir_all(base) or {}1684	}1685	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1686	mut a := open_repo(machine('strip_again_a')!)!1687	defer {1688		a.close()1689	}1690	mut b := open_repo(machine('strip_again_b')!)!1691	defer {1692		b.close()1693	}1694	put(a.root, 'secrets.env', 'first key\n')!1695	make_save(a, 'first key')!1696	offer_now(a, mut backend)!1697	join(b, mut backend)!1698	strip_local(a, 'secrets.env', '')!1699	send_strip(a, mut backend, 'secrets.env')!1700	steal_now(b, mut backend)!1701	for repo in [a, b] {1702		put(repo.root, 'secrets.env', 'second key\n')!1703		if _ := make_save(repo, 'second key') {1704			assert false, 'a banned path must not make a save'1705		}1706	}1707}17081709// A clash on a path the other machine stripped is no clash: the strip removes1710// the path from every save, so there is nothing to choose.1711fn test_a_stripped_path_is_not_asked_about() {1712	base := scratch('clash_strip')!1713	defer {1714		os.rmdir_all(base) or {}1715	}1716	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1717	mut a := open_repo(machine('clash_strip_a')!)!1718	defer {1719		a.close()1720	}1721	mut b := open_repo(machine('clash_strip_b')!)!1722	defer {1723		b.close()1724	}1725	put(a.root, 'secrets.env', 'key one\n')!1726	make_save(a, 'base')!1727	offer_now(a, mut backend)!1728	join(b, mut backend)!1729	put(a.root, 'secrets.env', 'key two\n')!1730	make_save(a, 'A rotates')!1731	offer_now(a, mut backend)!1732	strip_local(a, 'secrets.env', '')!1733	send_strip(a, mut backend, 'secrets.env')!1734	put(b.root, 'secrets.env', 'key three\n')!1735	mine := make_save(b, 'B rotates')!1736	report := steal(b, mut backend, StealOptions{})!1737	assert report.clashes.len == 01738	for save in history.all_saves(b)! {1739		assert 'secrets.env' !in history.files_of(b, save.id)!.map(it.path)1740	}1741	assert history.by_id(b, mine.id) != none1742}17431744// A strip scoped to the shared base save changes what the replay sees; the1745// clashes must be found on the same trees, or the replay meets a conflict.1746fn test_a_strip_of_the_shared_base_is_seen_before_asking() {1747	base := scratch('clash_base_strip')!1748	defer {1749		os.rmdir_all(base) or {}1750	}1751	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1752	mut a := open_repo(machine('base_strip_a')!)!1753	defer {1754		a.close()1755	}1756	mut b := open_repo(machine('base_strip_b')!)!1757	defer {1758		b.close()1759	}1760	put(a.root, 'notes.txt', 'shared\n')!1761	common := make_save(a, 'base')!1762	offer_now(a, mut backend)!1763	join(b, mut backend)!1764	put(a.root, 'other.txt', 'A moves on\n')!1765	make_save(a, 'A moves on')!1766	offer_now(a, mut backend)!1767	strip_local(a, 'notes.txt', common.id)!1768	send_strip(a, mut backend, 'notes.txt')!1769	put(b.root, 'notes.txt', 'B edits\n')!1770	make_save(b, 'B edits notes')!1771	if _ := steal(b, mut backend, StealOptions{}) {1772		assert false, 'with the base stripped, notes.txt differs on both sides'1773	} else {1774		assert err.msg().contains('notes.txt changed on both machines')1775	}1776	report := steal(b, mut backend, StealOptions{1777		mine: true1778	})!1779	assert report.clashes == ['notes.txt']1780	assert os.read_file(os.join_path(b.root, 'notes.txt'))! == 'B edits\n'1781}17821783// A folder with files but no saves has nothing to combine with; a steal that1784// fast-forwarded into it would overwrite whatever shares a name.1785fn test_steal_into_a_folder_with_unsaved_files_refuses() {1786	base := scratch('steal_unsaved')!1787	defer {1788		os.rmdir_all(base) or {}1789	}1790	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1791	mut a := open_repo(machine('unsaved_a')!)!1792	defer {1793		a.close()1794	}1795	put(a.root, 'notes.txt', 'from A\n')!1796	make_save(a, 'A writes')!1797	offer_now(a, mut backend)!1798	b_root := machine('unsaved_b')!1799	mut b := storage.create(b_root)!1800	defer {1801		b.close()1802	}1803	put(b_root, 'notes.txt', 'never saved\n')!1804	// Only a repo that already knows its remote name gets this far.1805	b.set_state('remote_repo', 'proj')!1806	if _ := steal(b, mut backend, StealOptions{}) {1807		assert false, 'steal overwrote a folder with unsaved files'1808	} else {1809		assert err.msg() == no_saves_here1810	}1811	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'never saved\n'1812	// A fresh `koh init` folder, holding only the default ignore list, is fine.1813	os.rm(os.join_path(b_root, 'notes.txt'))!1814	put(b_root, snapshot.ignore_file, snapshot.default_ignore)!1815	steal(b, mut backend, StealOptions{})!1816	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'from A\n'1817}18181819// The document asks steal to warn about every incoming flagged save, so the1820// report names them.1821fn test_steal_reports_incoming_flagged_saves() {1822	base := scratch('flag_warn')!1823	defer {1824		os.rmdir_all(base) or {}1825	}1826	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1827	mut a := open_repo(machine('flag_warn_a')!)!1828	defer {1829		a.close()1830	}1831	mut b := open_repo(machine('flag_warn_b')!)!1832	defer {1833		b.close()1834	}1835	put(a.root, 'a.txt', 'one\n')!1836	make_save(a, 'fine')!1837	offer_now(a, mut backend)!1838	join(b, mut backend)!1839	put(a.root, 'a.txt', 'two\n')!1840	suspect := make_save(a, 'suspect')!1841	put(a.root, 'a.txt', 'three\n')!1842	make_save(a, 'also fine')!1843	events.flag(a, suspect.id, 'broke the build')!1844	offer_now(a, mut backend)!1845	report := steal_now(b, mut backend)!1846	assert report.flagged.map(it.save_id) == [suspect.id]1847	assert report.flagged[0].reason == 'broke the build'1848}18491850// head_of unwraps the head for tests that know the repo has saves.1851fn head_of(store &storage.Store) history.Save {1852	return history.head(store) or { panic('this repo has no head') }1853}18541855// A remote says what it is, so two koh versions never half-understand one1856// bucket. The first offer of a repo records the layout.1857fn test_the_first_offer_records_the_remote_format() {1858	base := scratch('format_write')!1859	defer {1860		os.rmdir_all(base) or {}1861	}1862	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1863	mut a := open_repo(machine('format_write_a')!)!1864	defer {1865		a.close()1866	}1867	put(a.root, 'a.txt', 'one\n')!1868	make_save(a, 'first')!1869	offer_now(a, mut backend)!1870	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1871}18721873// A repo offered before the key existed is version 1: it still syncs, and the1874// next offer records the key then.1875fn test_a_remote_without_a_format_still_syncs() {1876	base := scratch('format_old')!1877	defer {1878		os.rmdir_all(base) or {}1879	}1880	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1881	mut a := open_repo(machine('format_old_a')!)!1882	defer {1883		a.close()1884	}1885	put(a.root, 'a.txt', 'one\n')!1886	make_save(a, 'first')!1887	offer_now(a, mut backend)!1888	// Stand in for a bucket offered before the key existed.1889	backend.delete(format_key('proj'))!1890	mut b := open_repo(machine('format_old_b')!)!1891	defer {1892		b.close()1893	}1894	join(b, mut backend)!1895	assert head_of(b).id == head_of(a).id1896	put(a.root, 'a.txt', 'two\n')!1897	make_save(a, 'second')!1898	offer_now(a, mut backend)!1899	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1900	report := steal_now(b, mut backend)!1901	assert report.head == head_of(a).id1902}19031904// A remote that speaks another layout is refused loudly, on offer and on1905// steal, rather than half-read.1906fn test_an_unknown_remote_format_is_refused() {1907	base := scratch('format_unknown')!1908	defer {1909		os.rmdir_all(base) or {}1910	}1911	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1912	mut a := open_repo(machine('format_bad_a')!)!1913	defer {1914		a.close()1915	}1916	put(a.root, 'a.txt', 'one\n')!1917	make_save(a, 'first')!1918	offer_now(a, mut backend)!1919	backend.delete(format_key('proj'))!1920	backend.put_if_absent(format_key('proj'), 'koh-remote 2'.bytes())!1921	if _ := offer_now(a, mut backend) {1922		assert false, 'offer must refuse a format it does not speak'1923	} else {1924		assert err.msg().contains('koh-remote 2')1925	}1926	if _ := steal_now(a, mut backend) {1927		assert false, 'steal must refuse a format it does not speak'1928	} else {1929		assert err.msg().contains('koh-remote 2')1930	}1931	if _ := fetch_repo(mut backend, 'proj') {1932		assert false, 'a steal must refuse a format it does not speak'1933	} else {1934		assert err.msg().contains('koh-remote 2')1935	}1936}19371938// Two machines offering a new repo at once both find no format key; the loser1939// of the conditional write must read back the winner's value and refuse it,1940// not carry on against a remote it cannot read.1941fn test_a_lost_format_write_is_read_back_and_refused() {1942	base := scratch('format_race')!1943	defer {1944		os.rmdir_all(base) or {}1945	}1946	mut inner := remote.new_folder(os.join_path(base, 'remote'))!1947	mut a := open_repo(machine('format_race_a')!)!1948	defer {1949		a.close()1950	}1951	put(a.root, 'a.txt', 'one\n')!1952	make_save(a, 'first')!1953	mut backend := remote.Backend(FaultyBackend{1954		inner:       inner1955		race_format: true1956	})1957	if _ := offer_now(a, mut backend) {1958		assert false, 'offer must refuse the format another machine wrote first'1959	} else {1960		assert err.msg().contains('koh-remote 2')1961	}1962}19631964fn test_a_bundle_lands_each_entry_however_it_is_split_and_refuses_a_cut_or_foreign_one() {1965	whole := 'objects/aa 3\nabcobjects/bb 0\nend 0\n'1966	for size in [1, 2, 5, whole.len] {1967		mut bundle := Bundle{}1968		for at := 0; at < whole.len; at += size {1969			bundle.feed(whole[at..int_min(at + size, whole.len)].bytes())!1970		}1971		bundle.finish()!1972		assert bundle.fetched.repo_objects == {1973			'aa': 'abc'.bytes()1974			'bb': []u8{}1975		}1976	}1977	for cut in ['objects/aa 3\nabc', 'objects/aa 4\nabc', 'objects/aa 3', 'objects/aa x\nabc',1978		'releases/v1 1\nx', 'end 0\nobjects/aa 3\nabc'] {1979		mut bundle := Bundle{}1980		bundle.feed(cut.bytes()) or { continue }1981		bundle.finish() or { continue }1982		assert false, cut1983	}1984}19851986fn test_strip_batch_rolls_back_all_paths_and_handles_overlap() {1987	mut store := open_repo(machine('strip_batch')!)!1988	defer { store.close() }1989	put(store.root, 'private/a', 'a')!1990	put(store.root, 'secret', 'secret')!1991	put(store.root, 'keep', 'keep')!1992	save := make_save(store, 'initial')!1993	store.db.exec("CREATE TRIGGER block_secret BEFORE DELETE ON save_files1994		WHEN OLD.path = 'secret' BEGIN SELECT RAISE(ABORT, 'blocked'); END")!1995	if _ := strip_local_batch(store, ['private', 'secret'], '') {1996		assert false, 'batch succeeded despite the second path failing'1997	}1998	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep', 'private/a',1999		'secret']2000	assert events.strip_events(store)!.len == 02001	assert !strip_pending(store, 'private')2002	store.db.exec('DROP TRIGGER block_secret')!2003	reports := strip_local_batch(store, ['private', 'private/a', 'secret'], '')!2004	assert reports.map(it.files_removed) == [1, 0, 1]2005	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep']2006	assert events.strip_events(store)!.len == 22007}20082009fn test_strip_batch_limits_every_path_to_selected_save() {2010	mut store := open_repo(machine('strip_batch_scope')!)!2011	defer { store.close() }2012	put(store.root, 'one', 'one')!2013	put(store.root, 'two', 'two')!2014	first := make_save(store, 'initial')!2015	put(store.root, 'keep', 'keep')!2016	second := make_save(store, 'next')!2017	strip_local_batch(store, ['one', 'two'], first.id)!2018	assert history.files_of(store, first.id)!.map(it.path) == ['.kohignore']2019	assert history.files_of(store, second.id)!.map(it.path) == ['.kohignore', 'keep', 'one', 'two']2020	assert events.strip_events(store)!.all(it.save_id == first.id)2021}20222023fn test_strip_batch_keeps_independent_remote_retry_notes() {2024	mut backend := remote.new_folder(scratch('strip_batch_remote')!)!2025	mut store := open_repo(machine('strip_batch_retry')!)!2026	defer { store.close() }2027	put(store.root, 'one', 'secret')!2028	put(store.root, 'two', 'secret')!2029	save := make_save(store, 'initial')!2030	offer_now(store, mut backend)!2031	strip_local_batch(store, ['one', 'two'], '')!2032	mut flaky := FaultyBackend{ inner: backend, fail_write: 1 }2033	if _ := send_strip(store, mut flaky, 'one') {2034		assert false, 'injected remote failure was not reported'2035	}2036	send_strip(store, mut backend, 'two')!2037	assert strip_pending(store, 'one') && !strip_pending(store, 'two')2038	partial := decode_save(backend.get(save_key('proj', save.id))!.body)!2039	assert partial.files.map(it.path) == ['.kohignore', 'one']2040	assert backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found2041	send_strip(store, mut backend, 'one')!2042	assert !strip_pending(store, 'one')2043	finished := decode_save(backend.get(save_key('proj', save.id))!.body)!2044	assert finished.files.map(it.path) == ['.kohignore']2045	assert !backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found2046}