exchange_test.v

53.6 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}11241125fn (mut r StripRace) get(key string) !remote.Object {1126	return r.inner.get(key)!1127}11281129fn (mut r StripRace) list(prefix string) ![]string {1130	return r.inner.list(prefix)!1131}11321133fn (mut r StripRace) put_if_absent(key string, body []u8) !bool {1134	if !r.done && key.contains('/saves/') {1135		r.done = true1136		strip_local(r.other, r.path, '')!1137		send_strip(r.other, mut r.inner, r.path)!1138	}1139	return r.inner.put_if_absent(key, body)!1140}11411142fn (mut r StripRace) put_if_match(key string, body []u8, tag string) !bool {1143	return r.inner.put_if_match(key, body, tag)!1144}11451146fn (mut r StripRace) delete(key string) ! {1147	r.inner.delete(key)!1148}11491150// A strip that finishes on another machine while an offer uploads has already1151// rewritten the remote without the offer's records, so the offer takes back1152// what the strip reaches and leaves head where it was.1153fn test_an_offer_racing_a_strip_leaves_no_stripped_path_behind() {1154	base := scratch('strip_race')!1155	defer {1156		os.rmdir_all(base) or {}1157	}1158	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1159	mut a := open_repo(machine('strip_race_a')!)!1160	defer {1161		a.close()1162	}1163	mut b := open_repo(machine('strip_race_b')!)!1164	defer {1165		b.close()1166	}1167	put(a.root, 'secrets.env', 'api_key=1\n')!1168	first := make_save(a, 'leak the key')!1169	offer_now(a, mut backend)!1170	join(b, mut backend)!1171	put(a.root, 'secrets.env', 'api_key=2\n')!1172	later := make_save(a, 'rotate the key')!1173	secret := history.files_of(a, later.id)!.filter(it.path == 'secrets.env')[0].hash1174	mut race := StripRace{1175		inner: backend1176		other: &b1177		path:  'secrets.env'1178	}1179	if _ := offer(a, mut race) {1180		assert false, 'an offer that raced a strip must refuse'1181	} else {1182		assert err.msg().contains('koh steal'), err.msg()1183	}1184	assert backend.get(head_key('proj'))!.body.bytestr() == first.id1185	assert !backend.get(object_key('proj', secret))!.found1186	for key in backend.list('proj/saves')! {1187		record := decode_save(backend.get(key)!.body)!1188		assert 'secrets.env' !in record.files.map(it.path), record.id1189	}1190}11911192// The local half lands before the remote hears anything, so a remote failure1193// leaves nothing to find locally; the pending note is what lets a re-run1194// finish. Objects a remote-only save still needs must survive the strip.1195fn test_an_interrupted_remote_strip_finishes_when_re_run() {1196	base := scratch('strip_resume')!1197	defer {1198		os.rmdir_all(base) or {}1199	}1200	remote_dir := os.join_path(base, 'remote')1201	mut backend := remote.new_folder(remote_dir)!1202	mut a := open_repo(machine('resume_a')!)!1203	defer {1204		a.close()1205	}1206	mut b := open_repo(machine('resume_b')!)!1207	defer {1208		b.close()1209	}1210	put(a.root, 'secrets.env', 'api_key=1\n')!1211	put(a.root, 'shared.env', 'same bytes on B\n')!1212	save := make_save(a, 'add secrets')!1213	offer_now(a, mut backend)!1214	join(b, mut backend)!1215	put(b.root, 'copy.txt', 'same bytes on B\n')!1216	b_save := make_save(b, 'B keeps a copy')!1217	offer_now(b, mut backend)!1218	shared_hash := storage.hash_hex('same bytes on B\n'.bytes())1219	secret_hash := storage.hash_hex('api_key=1\n'.bytes())12201221	strip_local(a, 'secrets.env', '')!1222	// Write 1 uploads the event and write 2 rewrites the first record; B's save,1223	// made from A's tree, lists the file too, and its rewrite (write 3) fails.1224	mut flaky := FaultyBackend{1225		inner:      remote.new_folder(remote_dir)!1226		fail_write: 31227	}1228	if _ := send_strip(a, mut flaky, 'secrets.env') {1229		assert false, 'the injected failure should have surfaced'1230	}1231	assert strip_pending(a, 'secrets.env')1232	assert strip_local(a, 'secrets.env', '')!.files_removed == 01233	report := send_strip(a, mut backend, 'secrets.env')!1234	assert report.records == 11235	assert !strip_pending(a, 'secrets.env')1236	assert !backend.get(object_key('proj', secret_hash))!.found1237	record := decode_save(backend.get(save_key('proj', save.id))!.body)!1238	assert 'secrets.env' !in record.files.map(it.path)1239	b_record := decode_save(backend.get(save_key('proj', b_save.id))!.body)!1240	assert 'secrets.env' !in b_record.files.map(it.path)12411242	// B's save still names the shared bytes, so stripping A's copy keeps them.1243	strip_local(a, 'shared.env', '')!1244	send_strip(a, mut backend, 'shared.env')!1245	assert backend.get(object_key('proj', shared_hash))!.found1246}12471248// A machine that has not heard of a strip must not offer: its records still1249// list the stripped path, and nothing would rewrite them on the remote again.1250fn test_offer_waits_for_an_unapplied_strip() {1251	base := scratch('strip_first')!1252	defer {1253		os.rmdir_all(base) or {}1254	}1255	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1256	mut a := open_repo(machine('strip_first_a')!)!1257	defer {1258		a.close()1259	}1260	mut b := open_repo(machine('strip_first_b')!)!1261	defer {1262		b.close()1263	}1264	put(a.root, 'secrets.env', 'api_key=1\n')!1265	make_save(a, 'add secrets')!1266	offer_now(a, mut backend)!1267	join(b, mut backend)!1268	strip_local(a, 'secrets.env', '')!1269	send_strip(a, mut backend, 'secrets.env')!1270	put(b.root, 'more.txt', 'B keeps working\n')!1271	later := make_save(b, 'B saves with the secret still in its tree')!1272	if _ := offer_now(b, mut backend) {1273		assert false, 'B offered records that still list the stripped path'1274	}1275	steal_now(b, mut backend)!1276	offer_now(b, mut backend)!1277	record := decode_save(backend.get(save_key('proj', later.id))!.body)!1278	assert 'secrets.env' !in record.files.map(it.path)1279}12801281// A strip whose object deletions failed must still delete them when it is run1282// again, and meanwhile the banned path cannot come back in through a save.1283fn test_a_strip_whose_deletes_failed_finishes_when_run_again() {1284	base := scratch('strip_twice')!1285	defer {1286		os.rmdir_all(base) or {}1287	}1288	remote_dir := os.join_path(base, 'remote')1289	mut backend := remote.new_folder(remote_dir)!1290	mut a := open_repo(machine('strip_twice_a')!)!1291	defer {1292		a.close()1293	}1294	put(a.root, 'secrets.env', 'first key\n')!1295	make_save(a, 'first key')!1296	offer_now(a, mut backend)!1297	strip_local(a, 'secrets.env', '')!1298	mut flaky := FaultyBackend{1299		inner:       remote.new_folder(remote_dir)!1300		fail_delete: true1301	}1302	if _ := send_strip(a, mut flaky, 'secrets.env') {1303		assert false, 'the injected delete failure should have surfaced'1304	}1305	put(a.root, 'secrets.env', 'second key\n')!1306	put(a.root, 'other.txt', 'more work\n')!1307	make_save(a, 'more work')!1308	offer_now(a, mut backend)!1309	send_strip(a, mut backend, 'secrets.env')!1310	for key in ['first key\n', 'second key\n'] {1311		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1312	}1313}13141315// Unfinished strips of one path in different scopes finish together.1316fn test_unfinished_strips_of_one_path_in_different_saves_finish_together() {1317	base := scratch('strip_scopes')!1318	defer {1319		os.rmdir_all(base) or {}1320	}1321	remote_dir := os.join_path(base, 'remote')1322	mut backend := remote.new_folder(remote_dir)!1323	mut a := open_repo(machine('strip_scopes_a')!)!1324	defer {1325		a.close()1326	}1327	put(a.root, 'secrets.env', 'first key\n')!1328	first := make_save(a, 'first key')!1329	put(a.root, 'secrets.env', 'second key\n')!1330	second := make_save(a, 'second key')!1331	offer_now(a, mut backend)!1332	strip_local(a, 'secrets.env', first.id)!1333	// Write 1 uploads the event; write 2, the record rewrite, fails.1334	mut flaky := FaultyBackend{1335		inner:      remote.new_folder(remote_dir)!1336		fail_write: 21337	}1338	if _ := send_strip(a, mut flaky, 'secrets.env') {1339		assert false, 'the injected failure should have surfaced'1340	}1341	strip_local(a, 'secrets.env', second.id)!1342	send_strip(a, mut backend, 'secrets.env')!1343	assert !strip_pending(a, 'secrets.env')1344	for save in [first, second] {1345		record := decode_save(backend.get(save_key('proj', save.id))!.body)!1346		assert 'secrets.env' !in record.files.map(it.path)1347	}1348	for key in ['first key\n', 'second key\n'] {1349		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1350	}1351}13521353// A strip bans its path on every machine that has heard of it: written again,1354// the file makes no save, here or there, so there is never a second copy to strip.1355fn test_a_stripped_path_cannot_be_saved_again_on_any_machine() {1356	base := scratch('strip_again')!1357	defer {1358		os.rmdir_all(base) or {}1359	}1360	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1361	mut a := open_repo(machine('strip_again_a')!)!1362	defer {1363		a.close()1364	}1365	mut b := open_repo(machine('strip_again_b')!)!1366	defer {1367		b.close()1368	}1369	put(a.root, 'secrets.env', 'first key\n')!1370	make_save(a, 'first key')!1371	offer_now(a, mut backend)!1372	join(b, mut backend)!1373	strip_local(a, 'secrets.env', '')!1374	send_strip(a, mut backend, 'secrets.env')!1375	steal_now(b, mut backend)!1376	for repo in [a, b] {1377		put(repo.root, 'secrets.env', 'second key\n')!1378		if _ := make_save(repo, 'second key') {1379			assert false, 'a banned path must not make a save'1380		}1381	}1382}13831384// A clash on a path the other machine stripped is no clash: the strip removes1385// the path from every save, so there is nothing to choose.1386fn test_a_stripped_path_is_not_asked_about() {1387	base := scratch('clash_strip')!1388	defer {1389		os.rmdir_all(base) or {}1390	}1391	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1392	mut a := open_repo(machine('clash_strip_a')!)!1393	defer {1394		a.close()1395	}1396	mut b := open_repo(machine('clash_strip_b')!)!1397	defer {1398		b.close()1399	}1400	put(a.root, 'secrets.env', 'key one\n')!1401	make_save(a, 'base')!1402	offer_now(a, mut backend)!1403	join(b, mut backend)!1404	put(a.root, 'secrets.env', 'key two\n')!1405	make_save(a, 'A rotates')!1406	offer_now(a, mut backend)!1407	strip_local(a, 'secrets.env', '')!1408	send_strip(a, mut backend, 'secrets.env')!1409	put(b.root, 'secrets.env', 'key three\n')!1410	mine := make_save(b, 'B rotates')!1411	report := steal(b, mut backend, StealOptions{})!1412	assert report.clashes.len == 01413	for save in history.all_saves(b)! {1414		assert 'secrets.env' !in history.files_of(b, save.id)!.map(it.path)1415	}1416	assert history.by_id(b, mine.id) != none1417}14181419// A strip scoped to the shared base save changes what the replay sees; the1420// clashes must be found on the same trees, or the replay meets a conflict.1421fn test_a_strip_of_the_shared_base_is_seen_before_asking() {1422	base := scratch('clash_base_strip')!1423	defer {1424		os.rmdir_all(base) or {}1425	}1426	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1427	mut a := open_repo(machine('base_strip_a')!)!1428	defer {1429		a.close()1430	}1431	mut b := open_repo(machine('base_strip_b')!)!1432	defer {1433		b.close()1434	}1435	put(a.root, 'notes.txt', 'shared\n')!1436	common := make_save(a, 'base')!1437	offer_now(a, mut backend)!1438	join(b, mut backend)!1439	put(a.root, 'other.txt', 'A moves on\n')!1440	make_save(a, 'A moves on')!1441	offer_now(a, mut backend)!1442	strip_local(a, 'notes.txt', common.id)!1443	send_strip(a, mut backend, 'notes.txt')!1444	put(b.root, 'notes.txt', 'B edits\n')!1445	make_save(b, 'B edits notes')!1446	if _ := steal(b, mut backend, StealOptions{}) {1447		assert false, 'with the base stripped, notes.txt differs on both sides'1448	} else {1449		assert err.msg().contains('notes.txt changed on both machines')1450	}1451	report := steal(b, mut backend, StealOptions{1452		mine: true1453	})!1454	assert report.clashes == ['notes.txt']1455	assert os.read_file(os.join_path(b.root, 'notes.txt'))! == 'B edits\n'1456}14571458// A folder with files but no saves has nothing to combine with; a steal that1459// fast-forwarded into it would overwrite whatever shares a name.1460fn test_steal_into_a_folder_with_unsaved_files_refuses() {1461	base := scratch('steal_unsaved')!1462	defer {1463		os.rmdir_all(base) or {}1464	}1465	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1466	mut a := open_repo(machine('unsaved_a')!)!1467	defer {1468		a.close()1469	}1470	put(a.root, 'notes.txt', 'from A\n')!1471	make_save(a, 'A writes')!1472	offer_now(a, mut backend)!1473	b_root := machine('unsaved_b')!1474	mut b := storage.create(b_root)!1475	defer {1476		b.close()1477	}1478	put(b_root, 'notes.txt', 'never saved\n')!1479	// Only a repo that already knows its remote name gets this far.1480	b.set_state('remote_repo', 'proj')!1481	if _ := steal(b, mut backend, StealOptions{}) {1482		assert false, 'steal overwrote a folder with unsaved files'1483	} else {1484		assert err.msg() == no_saves_here1485	}1486	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'never saved\n'1487	// A fresh `koh init` folder, holding only the default ignore list, is fine.1488	os.rm(os.join_path(b_root, 'notes.txt'))!1489	put(b_root, snapshot.ignore_file, snapshot.default_ignore)!1490	steal(b, mut backend, StealOptions{})!1491	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'from A\n'1492}14931494// The document asks steal to warn about every incoming flagged save, so the1495// report names them.1496fn test_steal_reports_incoming_flagged_saves() {1497	base := scratch('flag_warn')!1498	defer {1499		os.rmdir_all(base) or {}1500	}1501	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1502	mut a := open_repo(machine('flag_warn_a')!)!1503	defer {1504		a.close()1505	}1506	mut b := open_repo(machine('flag_warn_b')!)!1507	defer {1508		b.close()1509	}1510	put(a.root, 'a.txt', 'one\n')!1511	make_save(a, 'fine')!1512	offer_now(a, mut backend)!1513	join(b, mut backend)!1514	put(a.root, 'a.txt', 'two\n')!1515	suspect := make_save(a, 'suspect')!1516	put(a.root, 'a.txt', 'three\n')!1517	make_save(a, 'also fine')!1518	events.flag(a, suspect.id, 'broke the build')!1519	offer_now(a, mut backend)!1520	report := steal_now(b, mut backend)!1521	assert report.flagged.map(it.save_id) == [suspect.id]1522	assert report.flagged[0].reason == 'broke the build'1523}15241525// head_of unwraps the head for tests that know the repo has saves.1526fn head_of(store &storage.Store) history.Save {1527	return history.head(store) or { panic('this repo has no head') }1528}15291530// A remote says what it is, so two koh versions never half-understand one1531// bucket. The first offer of a repo records the layout.1532fn test_the_first_offer_records_the_remote_format() {1533	base := scratch('format_write')!1534	defer {1535		os.rmdir_all(base) or {}1536	}1537	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1538	mut a := open_repo(machine('format_write_a')!)!1539	defer {1540		a.close()1541	}1542	put(a.root, 'a.txt', 'one\n')!1543	make_save(a, 'first')!1544	offer_now(a, mut backend)!1545	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1546}15471548// A repo offered before the key existed is version 1: it still syncs, and the1549// next offer records the key then.1550fn test_a_remote_without_a_format_still_syncs() {1551	base := scratch('format_old')!1552	defer {1553		os.rmdir_all(base) or {}1554	}1555	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1556	mut a := open_repo(machine('format_old_a')!)!1557	defer {1558		a.close()1559	}1560	put(a.root, 'a.txt', 'one\n')!1561	make_save(a, 'first')!1562	offer_now(a, mut backend)!1563	// Stand in for a bucket offered before the key existed.1564	backend.delete(format_key('proj'))!1565	mut b := open_repo(machine('format_old_b')!)!1566	defer {1567		b.close()1568	}1569	join(b, mut backend)!1570	assert head_of(b).id == head_of(a).id1571	put(a.root, 'a.txt', 'two\n')!1572	make_save(a, 'second')!1573	offer_now(a, mut backend)!1574	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1575	report := steal_now(b, mut backend)!1576	assert report.head == head_of(a).id1577}15781579// A remote that speaks another layout is refused loudly, on offer and on1580// steal, rather than half-read.1581fn test_an_unknown_remote_format_is_refused() {1582	base := scratch('format_unknown')!1583	defer {1584		os.rmdir_all(base) or {}1585	}1586	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1587	mut a := open_repo(machine('format_bad_a')!)!1588	defer {1589		a.close()1590	}1591	put(a.root, 'a.txt', 'one\n')!1592	make_save(a, 'first')!1593	offer_now(a, mut backend)!1594	backend.delete(format_key('proj'))!1595	backend.put_if_absent(format_key('proj'), 'koh-remote 2'.bytes())!1596	if _ := offer_now(a, mut backend) {1597		assert false, 'offer must refuse a format it does not speak'1598	} else {1599		assert err.msg().contains('koh-remote 2')1600	}1601	if _ := steal_now(a, mut backend) {1602		assert false, 'steal must refuse a format it does not speak'1603	} else {1604		assert err.msg().contains('koh-remote 2')1605	}1606	if _ := fetch_repo(mut backend, 'proj') {1607		assert false, 'a steal must refuse a format it does not speak'1608	} else {1609		assert err.msg().contains('koh-remote 2')1610	}1611}16121613// Two machines offering a new repo at once both find no format key; the loser1614// of the conditional write must read back the winner's value and refuse it,1615// not carry on against a remote it cannot read.1616fn test_a_lost_format_write_is_read_back_and_refused() {1617	base := scratch('format_race')!1618	defer {1619		os.rmdir_all(base) or {}1620	}1621	mut inner := remote.new_folder(os.join_path(base, 'remote'))!1622	mut a := open_repo(machine('format_race_a')!)!1623	defer {1624		a.close()1625	}1626	put(a.root, 'a.txt', 'one\n')!1627	make_save(a, 'first')!1628	mut backend := remote.Backend(FaultyBackend{1629		inner:       inner1630		race_format: true1631	})1632	if _ := offer_now(a, mut backend) {1633		assert false, 'offer must refuse the format another machine wrote first'1634	} else {1635		assert err.msg().contains('koh-remote 2')1636	}1637}16381639fn test_a_bundle_lands_each_entry_however_it_is_split_and_refuses_a_cut_or_foreign_one() {1640	whole := 'objects/aa 3\nabcobjects/bb 0\nend 0\n'1641	for size in [1, 2, 5, whole.len] {1642		mut bundle := Bundle{}1643		for at := 0; at < whole.len; at += size {1644			bundle.feed(whole[at..int_min(at + size, whole.len)].bytes())!1645		}1646		bundle.finish()!1647		assert bundle.fetched.repo_objects == {1648			'aa': 'abc'.bytes()1649			'bb': []u8{}1650		}1651	}1652	for cut in ['objects/aa 3\nabc', 'objects/aa 4\nabc', 'objects/aa 3', 'objects/aa x\nabc',1653		'releases/v1 1\nx', 'end 0\nobjects/aa 3\nabc'] {1654		mut bundle := Bundle{}1655		bundle.feed(cut.bytes()) or { continue }1656		bundle.finish() or { continue }1657		assert false, cut1658	}1659}16601661fn test_strip_batch_rolls_back_all_paths_and_handles_overlap() {1662	mut store := open_repo(machine('strip_batch')!)!1663	defer { store.close() }1664	put(store.root, 'private/a', 'a')!1665	put(store.root, 'secret', 'secret')!1666	put(store.root, 'keep', 'keep')!1667	save := make_save(store, 'initial')!1668	store.db.exec("CREATE TRIGGER block_secret BEFORE DELETE ON save_files1669		WHEN OLD.path = 'secret' BEGIN SELECT RAISE(ABORT, 'blocked'); END")!1670	if _ := strip_local_batch(store, ['private', 'secret'], '') {1671		assert false, 'batch succeeded despite the second path failing'1672	}1673	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep', 'private/a',1674		'secret']1675	assert events.strip_events(store)!.len == 01676	assert !strip_pending(store, 'private')1677	store.db.exec('DROP TRIGGER block_secret')!1678	reports := strip_local_batch(store, ['private', 'private/a', 'secret'], '')!1679	assert reports.map(it.files_removed) == [1, 0, 1]1680	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep']1681	assert events.strip_events(store)!.len == 21682}16831684fn test_strip_batch_limits_every_path_to_selected_save() {1685	mut store := open_repo(machine('strip_batch_scope')!)!1686	defer { store.close() }1687	put(store.root, 'one', 'one')!1688	put(store.root, 'two', 'two')!1689	first := make_save(store, 'initial')!1690	put(store.root, 'keep', 'keep')!1691	second := make_save(store, 'next')!1692	strip_local_batch(store, ['one', 'two'], first.id)!1693	assert history.files_of(store, first.id)!.map(it.path) == ['.kohignore']1694	assert history.files_of(store, second.id)!.map(it.path) == ['.kohignore', 'keep', 'one', 'two']1695	assert events.strip_events(store)!.all(it.save_id == first.id)1696}16971698fn test_strip_batch_keeps_independent_remote_retry_notes() {1699	mut backend := remote.new_folder(scratch('strip_batch_remote')!)!1700	mut store := open_repo(machine('strip_batch_retry')!)!1701	defer { store.close() }1702	put(store.root, 'one', 'secret')!1703	put(store.root, 'two', 'secret')!1704	save := make_save(store, 'initial')!1705	offer_now(store, mut backend)!1706	strip_local_batch(store, ['one', 'two'], '')!1707	mut flaky := FaultyBackend{ inner: backend, fail_write: 1 }1708	if _ := send_strip(store, mut flaky, 'one') {1709		assert false, 'injected remote failure was not reported'1710	}1711	send_strip(store, mut backend, 'two')!1712	assert strip_pending(store, 'one') && !strip_pending(store, 'two')1713	partial := decode_save(backend.get(save_key('proj', save.id))!.body)!1714	assert partial.files.map(it.path) == ['.kohignore', 'one']1715	assert backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found1716	send_strip(store, mut backend, 'one')!1717	assert !strip_pending(store, 'one')1718	finished := decode_save(backend.get(save_key('proj', save.id))!.body)!1719	assert finished.files.map(it.path) == ['.kohignore']1720	assert !backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found1721}