exchange_test.v

55.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// Doctor's resend of a missing record can race a strip just as an offer can,1193// and takes back what the strip reaches in the same way.1194fn test_a_resend_racing_a_strip_leaves_no_stripped_path_behind() {1195	base := scratch('resend_race')!1196	defer {1197		os.rmdir_all(base) or {}1198	}1199	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1200	mut a := open_repo(machine('resend_race_a')!)!1201	defer {1202		a.close()1203	}1204	mut b := open_repo(machine('resend_race_b')!)!1205	defer {1206		b.close()1207	}1208	put(a.root, 'secrets.env', 'api_key=1\n')!1209	first := make_save(a, 'leak the key')!1210	offer_now(a, mut backend)!1211	join(b, mut backend)!1212	backend.delete(save_key('proj', first.id))!1213	mut race := StripRace{1214		inner: backend1215		other: &b1216		path:  'secrets.env'1217	}1218	if _ := resend(a, mut race, 'proj', [], [first.id]) {1219		assert false, 'a resend that raced a strip must refuse'1220	} else {1221		assert err.msg().contains('koh steal'), err.msg()1222	}1223	assert !backend.get(save_key('proj', first.id))!.found1224	assert !backend.get(object_key('proj', storage.hash_hex('api_key=1\n'.bytes())))!.found1225}12261227// A note that does not parse, or that no recorded strip of its path backs, is1228// kept and changes nothing remote: sending it would lose the retry or strip1229// where no strip asked.1230fn test_an_untrusted_strip_note_is_kept_and_sends_nothing() {1231	base := scratch('strip_note')!1232	defer {1233		os.rmdir_all(base) or {}1234	}1235	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1236	mut a := open_repo(machine('strip_note_a')!)!1237	defer {1238		a.close()1239	}1240	put(a.root, 'app', 'app\n')!1241	save := make_save(a, 'app')!1242	offer_now(a, mut backend)!1243	events.strip(a, '', 'other')!1244	for note in ['not JSON', '{"saves":[""],"hashes":[]}'] {1245		a.set_state(pending_key('app'), note)!1246		if _ := send_strip(a, mut backend, 'app') {1247			assert false, 'an untrusted note must be refused'1248		} else {1249			assert err.msg().contains('kept for recovery'), err.msg()1250		}1251		assert a.state(pending_key('app')) or { '' } == note1252		assert backend.list(events_prefix('proj'))!.len == 01253		assert 'app' in decode_save(backend.get(save_key('proj', save.id))!.body)!.files.map(it.path)1254	}1255}12561257// The local half lands before the remote hears anything, so a remote failure1258// leaves nothing to find locally; the pending note is what lets a re-run1259// finish. Objects a remote-only save still needs must survive the strip.1260fn test_an_interrupted_remote_strip_finishes_when_re_run() {1261	base := scratch('strip_resume')!1262	defer {1263		os.rmdir_all(base) or {}1264	}1265	remote_dir := os.join_path(base, 'remote')1266	mut backend := remote.new_folder(remote_dir)!1267	mut a := open_repo(machine('resume_a')!)!1268	defer {1269		a.close()1270	}1271	mut b := open_repo(machine('resume_b')!)!1272	defer {1273		b.close()1274	}1275	put(a.root, 'secrets.env', 'api_key=1\n')!1276	put(a.root, 'shared.env', 'same bytes on B\n')!1277	save := make_save(a, 'add secrets')!1278	offer_now(a, mut backend)!1279	join(b, mut backend)!1280	put(b.root, 'copy.txt', 'same bytes on B\n')!1281	b_save := make_save(b, 'B keeps a copy')!1282	offer_now(b, mut backend)!1283	shared_hash := storage.hash_hex('same bytes on B\n'.bytes())1284	secret_hash := storage.hash_hex('api_key=1\n'.bytes())12851286	strip_local(a, 'secrets.env', '')!1287	// Write 1 uploads the event and write 2 rewrites the first record; B's save,1288	// made from A's tree, lists the file too, and its rewrite (write 3) fails.1289	mut flaky := FaultyBackend{1290		inner:      remote.new_folder(remote_dir)!1291		fail_write: 31292	}1293	if _ := send_strip(a, mut flaky, 'secrets.env') {1294		assert false, 'the injected failure should have surfaced'1295	}1296	assert strip_pending(a, 'secrets.env')1297	assert strip_local(a, 'secrets.env', '')!.files_removed == 01298	report := send_strip(a, mut backend, 'secrets.env')!1299	assert report.records == 11300	assert !strip_pending(a, 'secrets.env')1301	assert !backend.get(object_key('proj', secret_hash))!.found1302	record := decode_save(backend.get(save_key('proj', save.id))!.body)!1303	assert 'secrets.env' !in record.files.map(it.path)1304	b_record := decode_save(backend.get(save_key('proj', b_save.id))!.body)!1305	assert 'secrets.env' !in b_record.files.map(it.path)13061307	// B's save still names the shared bytes, so stripping A's copy keeps them.1308	strip_local(a, 'shared.env', '')!1309	send_strip(a, mut backend, 'shared.env')!1310	assert backend.get(object_key('proj', shared_hash))!.found1311}13121313// A machine that has not heard of a strip must not offer: its records still1314// list the stripped path, and nothing would rewrite them on the remote again.1315fn test_offer_waits_for_an_unapplied_strip() {1316	base := scratch('strip_first')!1317	defer {1318		os.rmdir_all(base) or {}1319	}1320	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1321	mut a := open_repo(machine('strip_first_a')!)!1322	defer {1323		a.close()1324	}1325	mut b := open_repo(machine('strip_first_b')!)!1326	defer {1327		b.close()1328	}1329	put(a.root, 'secrets.env', 'api_key=1\n')!1330	make_save(a, 'add secrets')!1331	offer_now(a, mut backend)!1332	join(b, mut backend)!1333	strip_local(a, 'secrets.env', '')!1334	send_strip(a, mut backend, 'secrets.env')!1335	put(b.root, 'more.txt', 'B keeps working\n')!1336	later := make_save(b, 'B saves with the secret still in its tree')!1337	if _ := offer_now(b, mut backend) {1338		assert false, 'B offered records that still list the stripped path'1339	}1340	steal_now(b, mut backend)!1341	offer_now(b, mut backend)!1342	record := decode_save(backend.get(save_key('proj', later.id))!.body)!1343	assert 'secrets.env' !in record.files.map(it.path)1344}13451346// A strip whose object deletions failed must still delete them when it is run1347// again, and meanwhile the banned path cannot come back in through a save.1348fn test_a_strip_whose_deletes_failed_finishes_when_run_again() {1349	base := scratch('strip_twice')!1350	defer {1351		os.rmdir_all(base) or {}1352	}1353	remote_dir := os.join_path(base, 'remote')1354	mut backend := remote.new_folder(remote_dir)!1355	mut a := open_repo(machine('strip_twice_a')!)!1356	defer {1357		a.close()1358	}1359	put(a.root, 'secrets.env', 'first key\n')!1360	make_save(a, 'first key')!1361	offer_now(a, mut backend)!1362	strip_local(a, 'secrets.env', '')!1363	mut flaky := FaultyBackend{1364		inner:       remote.new_folder(remote_dir)!1365		fail_delete: true1366	}1367	if _ := send_strip(a, mut flaky, 'secrets.env') {1368		assert false, 'the injected delete failure should have surfaced'1369	}1370	put(a.root, 'secrets.env', 'second key\n')!1371	put(a.root, 'other.txt', 'more work\n')!1372	make_save(a, 'more work')!1373	offer_now(a, mut backend)!1374	send_strip(a, mut backend, 'secrets.env')!1375	for key in ['first key\n', 'second key\n'] {1376		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1377	}1378}13791380// Unfinished strips of one path in different scopes finish together.1381fn test_unfinished_strips_of_one_path_in_different_saves_finish_together() {1382	base := scratch('strip_scopes')!1383	defer {1384		os.rmdir_all(base) or {}1385	}1386	remote_dir := os.join_path(base, 'remote')1387	mut backend := remote.new_folder(remote_dir)!1388	mut a := open_repo(machine('strip_scopes_a')!)!1389	defer {1390		a.close()1391	}1392	put(a.root, 'secrets.env', 'first key\n')!1393	first := make_save(a, 'first key')!1394	put(a.root, 'secrets.env', 'second key\n')!1395	second := make_save(a, 'second key')!1396	offer_now(a, mut backend)!1397	strip_local(a, 'secrets.env', first.id)!1398	// Write 1 uploads the event; write 2, the record rewrite, fails.1399	mut flaky := FaultyBackend{1400		inner:      remote.new_folder(remote_dir)!1401		fail_write: 21402	}1403	if _ := send_strip(a, mut flaky, 'secrets.env') {1404		assert false, 'the injected failure should have surfaced'1405	}1406	strip_local(a, 'secrets.env', second.id)!1407	send_strip(a, mut backend, 'secrets.env')!1408	assert !strip_pending(a, 'secrets.env')1409	for save in [first, second] {1410		record := decode_save(backend.get(save_key('proj', save.id))!.body)!1411		assert 'secrets.env' !in record.files.map(it.path)1412	}1413	for key in ['first key\n', 'second key\n'] {1414		assert !backend.get(object_key('proj', storage.hash_hex(key.bytes())))!.found1415	}1416}14171418// A strip bans its path on every machine that has heard of it: written again,1419// the file makes no save, here or there, so there is never a second copy to strip.1420fn test_a_stripped_path_cannot_be_saved_again_on_any_machine() {1421	base := scratch('strip_again')!1422	defer {1423		os.rmdir_all(base) or {}1424	}1425	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1426	mut a := open_repo(machine('strip_again_a')!)!1427	defer {1428		a.close()1429	}1430	mut b := open_repo(machine('strip_again_b')!)!1431	defer {1432		b.close()1433	}1434	put(a.root, 'secrets.env', 'first key\n')!1435	make_save(a, 'first key')!1436	offer_now(a, mut backend)!1437	join(b, mut backend)!1438	strip_local(a, 'secrets.env', '')!1439	send_strip(a, mut backend, 'secrets.env')!1440	steal_now(b, mut backend)!1441	for repo in [a, b] {1442		put(repo.root, 'secrets.env', 'second key\n')!1443		if _ := make_save(repo, 'second key') {1444			assert false, 'a banned path must not make a save'1445		}1446	}1447}14481449// A clash on a path the other machine stripped is no clash: the strip removes1450// the path from every save, so there is nothing to choose.1451fn test_a_stripped_path_is_not_asked_about() {1452	base := scratch('clash_strip')!1453	defer {1454		os.rmdir_all(base) or {}1455	}1456	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1457	mut a := open_repo(machine('clash_strip_a')!)!1458	defer {1459		a.close()1460	}1461	mut b := open_repo(machine('clash_strip_b')!)!1462	defer {1463		b.close()1464	}1465	put(a.root, 'secrets.env', 'key one\n')!1466	make_save(a, 'base')!1467	offer_now(a, mut backend)!1468	join(b, mut backend)!1469	put(a.root, 'secrets.env', 'key two\n')!1470	make_save(a, 'A rotates')!1471	offer_now(a, mut backend)!1472	strip_local(a, 'secrets.env', '')!1473	send_strip(a, mut backend, 'secrets.env')!1474	put(b.root, 'secrets.env', 'key three\n')!1475	mine := make_save(b, 'B rotates')!1476	report := steal(b, mut backend, StealOptions{})!1477	assert report.clashes.len == 01478	for save in history.all_saves(b)! {1479		assert 'secrets.env' !in history.files_of(b, save.id)!.map(it.path)1480	}1481	assert history.by_id(b, mine.id) != none1482}14831484// A strip scoped to the shared base save changes what the replay sees; the1485// clashes must be found on the same trees, or the replay meets a conflict.1486fn test_a_strip_of_the_shared_base_is_seen_before_asking() {1487	base := scratch('clash_base_strip')!1488	defer {1489		os.rmdir_all(base) or {}1490	}1491	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1492	mut a := open_repo(machine('base_strip_a')!)!1493	defer {1494		a.close()1495	}1496	mut b := open_repo(machine('base_strip_b')!)!1497	defer {1498		b.close()1499	}1500	put(a.root, 'notes.txt', 'shared\n')!1501	common := make_save(a, 'base')!1502	offer_now(a, mut backend)!1503	join(b, mut backend)!1504	put(a.root, 'other.txt', 'A moves on\n')!1505	make_save(a, 'A moves on')!1506	offer_now(a, mut backend)!1507	strip_local(a, 'notes.txt', common.id)!1508	send_strip(a, mut backend, 'notes.txt')!1509	put(b.root, 'notes.txt', 'B edits\n')!1510	make_save(b, 'B edits notes')!1511	if _ := steal(b, mut backend, StealOptions{}) {1512		assert false, 'with the base stripped, notes.txt differs on both sides'1513	} else {1514		assert err.msg().contains('notes.txt changed on both machines')1515	}1516	report := steal(b, mut backend, StealOptions{1517		mine: true1518	})!1519	assert report.clashes == ['notes.txt']1520	assert os.read_file(os.join_path(b.root, 'notes.txt'))! == 'B edits\n'1521}15221523// A folder with files but no saves has nothing to combine with; a steal that1524// fast-forwarded into it would overwrite whatever shares a name.1525fn test_steal_into_a_folder_with_unsaved_files_refuses() {1526	base := scratch('steal_unsaved')!1527	defer {1528		os.rmdir_all(base) or {}1529	}1530	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1531	mut a := open_repo(machine('unsaved_a')!)!1532	defer {1533		a.close()1534	}1535	put(a.root, 'notes.txt', 'from A\n')!1536	make_save(a, 'A writes')!1537	offer_now(a, mut backend)!1538	b_root := machine('unsaved_b')!1539	mut b := storage.create(b_root)!1540	defer {1541		b.close()1542	}1543	put(b_root, 'notes.txt', 'never saved\n')!1544	// Only a repo that already knows its remote name gets this far.1545	b.set_state('remote_repo', 'proj')!1546	if _ := steal(b, mut backend, StealOptions{}) {1547		assert false, 'steal overwrote a folder with unsaved files'1548	} else {1549		assert err.msg() == no_saves_here1550	}1551	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'never saved\n'1552	// A fresh `koh init` folder, holding only the default ignore list, is fine.1553	os.rm(os.join_path(b_root, 'notes.txt'))!1554	put(b_root, snapshot.ignore_file, snapshot.default_ignore)!1555	steal(b, mut backend, StealOptions{})!1556	assert os.read_file(os.join_path(b_root, 'notes.txt'))! == 'from A\n'1557}15581559// The document asks steal to warn about every incoming flagged save, so the1560// report names them.1561fn test_steal_reports_incoming_flagged_saves() {1562	base := scratch('flag_warn')!1563	defer {1564		os.rmdir_all(base) or {}1565	}1566	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1567	mut a := open_repo(machine('flag_warn_a')!)!1568	defer {1569		a.close()1570	}1571	mut b := open_repo(machine('flag_warn_b')!)!1572	defer {1573		b.close()1574	}1575	put(a.root, 'a.txt', 'one\n')!1576	make_save(a, 'fine')!1577	offer_now(a, mut backend)!1578	join(b, mut backend)!1579	put(a.root, 'a.txt', 'two\n')!1580	suspect := make_save(a, 'suspect')!1581	put(a.root, 'a.txt', 'three\n')!1582	make_save(a, 'also fine')!1583	events.flag(a, suspect.id, 'broke the build')!1584	offer_now(a, mut backend)!1585	report := steal_now(b, mut backend)!1586	assert report.flagged.map(it.save_id) == [suspect.id]1587	assert report.flagged[0].reason == 'broke the build'1588}15891590// head_of unwraps the head for tests that know the repo has saves.1591fn head_of(store &storage.Store) history.Save {1592	return history.head(store) or { panic('this repo has no head') }1593}15941595// A remote says what it is, so two koh versions never half-understand one1596// bucket. The first offer of a repo records the layout.1597fn test_the_first_offer_records_the_remote_format() {1598	base := scratch('format_write')!1599	defer {1600		os.rmdir_all(base) or {}1601	}1602	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1603	mut a := open_repo(machine('format_write_a')!)!1604	defer {1605		a.close()1606	}1607	put(a.root, 'a.txt', 'one\n')!1608	make_save(a, 'first')!1609	offer_now(a, mut backend)!1610	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1611}16121613// A repo offered before the key existed is version 1: it still syncs, and the1614// next offer records the key then.1615fn test_a_remote_without_a_format_still_syncs() {1616	base := scratch('format_old')!1617	defer {1618		os.rmdir_all(base) or {}1619	}1620	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1621	mut a := open_repo(machine('format_old_a')!)!1622	defer {1623		a.close()1624	}1625	put(a.root, 'a.txt', 'one\n')!1626	make_save(a, 'first')!1627	offer_now(a, mut backend)!1628	// Stand in for a bucket offered before the key existed.1629	backend.delete(format_key('proj'))!1630	mut b := open_repo(machine('format_old_b')!)!1631	defer {1632		b.close()1633	}1634	join(b, mut backend)!1635	assert head_of(b).id == head_of(a).id1636	put(a.root, 'a.txt', 'two\n')!1637	make_save(a, 'second')!1638	offer_now(a, mut backend)!1639	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value1640	report := steal_now(b, mut backend)!1641	assert report.head == head_of(a).id1642}16431644// A remote that speaks another layout is refused loudly, on offer and on1645// steal, rather than half-read.1646fn test_an_unknown_remote_format_is_refused() {1647	base := scratch('format_unknown')!1648	defer {1649		os.rmdir_all(base) or {}1650	}1651	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1652	mut a := open_repo(machine('format_bad_a')!)!1653	defer {1654		a.close()1655	}1656	put(a.root, 'a.txt', 'one\n')!1657	make_save(a, 'first')!1658	offer_now(a, mut backend)!1659	backend.delete(format_key('proj'))!1660	backend.put_if_absent(format_key('proj'), 'koh-remote 2'.bytes())!1661	if _ := offer_now(a, mut backend) {1662		assert false, 'offer must refuse a format it does not speak'1663	} else {1664		assert err.msg().contains('koh-remote 2')1665	}1666	if _ := steal_now(a, mut backend) {1667		assert false, 'steal must refuse a format it does not speak'1668	} else {1669		assert err.msg().contains('koh-remote 2')1670	}1671	if _ := fetch_repo(mut backend, 'proj') {1672		assert false, 'a steal must refuse a format it does not speak'1673	} else {1674		assert err.msg().contains('koh-remote 2')1675	}1676}16771678// Two machines offering a new repo at once both find no format key; the loser1679// of the conditional write must read back the winner's value and refuse it,1680// not carry on against a remote it cannot read.1681fn test_a_lost_format_write_is_read_back_and_refused() {1682	base := scratch('format_race')!1683	defer {1684		os.rmdir_all(base) or {}1685	}1686	mut inner := remote.new_folder(os.join_path(base, 'remote'))!1687	mut a := open_repo(machine('format_race_a')!)!1688	defer {1689		a.close()1690	}1691	put(a.root, 'a.txt', 'one\n')!1692	make_save(a, 'first')!1693	mut backend := remote.Backend(FaultyBackend{1694		inner:       inner1695		race_format: true1696	})1697	if _ := offer_now(a, mut backend) {1698		assert false, 'offer must refuse the format another machine wrote first'1699	} else {1700		assert err.msg().contains('koh-remote 2')1701	}1702}17031704fn test_a_bundle_lands_each_entry_however_it_is_split_and_refuses_a_cut_or_foreign_one() {1705	whole := 'objects/aa 3\nabcobjects/bb 0\nend 0\n'1706	for size in [1, 2, 5, whole.len] {1707		mut bundle := Bundle{}1708		for at := 0; at < whole.len; at += size {1709			bundle.feed(whole[at..int_min(at + size, whole.len)].bytes())!1710		}1711		bundle.finish()!1712		assert bundle.fetched.repo_objects == {1713			'aa': 'abc'.bytes()1714			'bb': []u8{}1715		}1716	}1717	for cut in ['objects/aa 3\nabc', 'objects/aa 4\nabc', 'objects/aa 3', 'objects/aa x\nabc',1718		'releases/v1 1\nx', 'end 0\nobjects/aa 3\nabc'] {1719		mut bundle := Bundle{}1720		bundle.feed(cut.bytes()) or { continue }1721		bundle.finish() or { continue }1722		assert false, cut1723	}1724}17251726fn test_strip_batch_rolls_back_all_paths_and_handles_overlap() {1727	mut store := open_repo(machine('strip_batch')!)!1728	defer { store.close() }1729	put(store.root, 'private/a', 'a')!1730	put(store.root, 'secret', 'secret')!1731	put(store.root, 'keep', 'keep')!1732	save := make_save(store, 'initial')!1733	store.db.exec("CREATE TRIGGER block_secret BEFORE DELETE ON save_files1734		WHEN OLD.path = 'secret' BEGIN SELECT RAISE(ABORT, 'blocked'); END")!1735	if _ := strip_local_batch(store, ['private', 'secret'], '') {1736		assert false, 'batch succeeded despite the second path failing'1737	}1738	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep', 'private/a',1739		'secret']1740	assert events.strip_events(store)!.len == 01741	assert !strip_pending(store, 'private')1742	store.db.exec('DROP TRIGGER block_secret')!1743	reports := strip_local_batch(store, ['private', 'private/a', 'secret'], '')!1744	assert reports.map(it.files_removed) == [1, 0, 1]1745	assert history.files_of(store, save.id)!.map(it.path) == ['.kohignore', 'keep']1746	assert events.strip_events(store)!.len == 21747}17481749fn test_strip_batch_limits_every_path_to_selected_save() {1750	mut store := open_repo(machine('strip_batch_scope')!)!1751	defer { store.close() }1752	put(store.root, 'one', 'one')!1753	put(store.root, 'two', 'two')!1754	first := make_save(store, 'initial')!1755	put(store.root, 'keep', 'keep')!1756	second := make_save(store, 'next')!1757	strip_local_batch(store, ['one', 'two'], first.id)!1758	assert history.files_of(store, first.id)!.map(it.path) == ['.kohignore']1759	assert history.files_of(store, second.id)!.map(it.path) == ['.kohignore', 'keep', 'one', 'two']1760	assert events.strip_events(store)!.all(it.save_id == first.id)1761}17621763fn test_strip_batch_keeps_independent_remote_retry_notes() {1764	mut backend := remote.new_folder(scratch('strip_batch_remote')!)!1765	mut store := open_repo(machine('strip_batch_retry')!)!1766	defer { store.close() }1767	put(store.root, 'one', 'secret')!1768	put(store.root, 'two', 'secret')!1769	save := make_save(store, 'initial')!1770	offer_now(store, mut backend)!1771	strip_local_batch(store, ['one', 'two'], '')!1772	mut flaky := FaultyBackend{ inner: backend, fail_write: 1 }1773	if _ := send_strip(store, mut flaky, 'one') {1774		assert false, 'injected remote failure was not reported'1775	}1776	send_strip(store, mut backend, 'two')!1777	assert strip_pending(store, 'one') && !strip_pending(store, 'two')1778	partial := decode_save(backend.get(save_key('proj', save.id))!.body)!1779	assert partial.files.map(it.path) == ['.kohignore', 'one']1780	assert backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found1781	send_strip(store, mut backend, 'one')!1782	assert !strip_pending(store, 'one')1783	finished := decode_save(backend.get(save_key('proj', save.id))!.body)!1784	assert finished.files.map(it.path) == ['.kohignore']1785	assert !backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found1786}