4ab979d1a1e4

land steal objects in batches, list repos by folder, reuse the save walk and read back a refused head swap

time
2026-11-17 01:51 UTC · 1 week ago
machine
Junes-MacBook-Pro.local
agent
deepseek/deepseek-flash
session
review findings
parent
694ae2cf655a
21 files src/cli/cmd_doctor_test.v+19 −0src/cli/cmd_save.v+3 −2src/cli/cmd_steal.v+22 −28src/cli/cmd_strip.v+15 −1src/cli/doctor_remote.v+18 −3src/cli/progress.v+4 −0src/exchange/exchange.v+207 −42src/exchange/exchange_test.v+244 −33src/exchange/records.v+49 −15src/exchange/repair.v+20 −4src/exchange/steal.v+45 −6src/exchange/strip.v+57 −13src/exchange/strip_test.v+50 −0src/history/save.v+16 −2src/remote/folder.v+17 −0src/remote/remote.v+1 −0src/remote/s3.v+31 −0src/remote/web.v+14 −0src/storage/manifest.v+31 −0src/storage/storage.v+17 −1tests/cli_test.v+3 −0
src/cli/cmd_doctor_test.v+19 −0
@@ -81,6 +81,21 @@8181 	return backend.items.keys().filter(it.starts_with('${prefix}/'))8282 }8383 84+fn (mut backend DoctorReadOnly) list_dirs(prefix string) ![]string {85+	return dirs_of(backend.list(prefix)!, prefix)86+}87+88+fn dirs_of(keys []string, prefix string) []string {89+	mut names := map[string]bool{}90+	for key in keys {91+		rest := key[prefix.len..].trim_left('/')92+		if rest.contains('/') {93+			names[rest.all_before('/')] = true94+		}95+	}96+	return names.keys()97+}98+8499 fn (mut backend DoctorReadOnly) put_if_absent(key string, body []u8) !bool {85100 	panic('Doctor attempted a remote write')86101 }@@ -201,6 +216,10 @@201216 202217 fn (mut backend DoctorMemory) list(prefix string) ![]string {203218 	return backend.items.keys().filter(it.starts_with('${prefix}/'))219+}220+221+fn (mut backend DoctorMemory) list_dirs(prefix string) ![]string {222+	return dirs_of(backend.list(prefix)!, prefix)204223 }205224 206225 fn (mut backend DoctorMemory) put_if_absent(key string, body []u8) !bool {

view file

src/cli/cmd_save.v+3 −2
@@ -41,10 +41,11 @@4141 		store.close()4242 	}4343 	mut hashing := reading()44+	walked_head := history.head_id(store)4445 	walked := snapshot.walk_report(store, store.root, snapshot.load(store.root), mut hashing) or {4546 		return refuse(args.json(), err.msg())4647 	}47-	save := history.save_worktree(store, store.root, snapshot.load(store.root), history.SaveInput{48+	save := history.save_walked(store, store.root, history.SaveInput{4849 		message:       message4950 		agent:         args.value('agent')5051 		session:       args.value('session')@@ -54,7 +55,7 @@5455 				working('storing ${done} / ${total} files')5556 			}5657 		}57-	}) or { return refuse(args.json(), err.msg()) }58+	}, walked_head, walked.files) or { return refuse(args.json(), err.msg()) }5859 5960 	files := history.files_of(store, save.id) or { []snapshot.FileEntry{} }6061 	if args.json() {

view file

src/cli/cmd_steal.v+22 −28
@@ -378,32 +378,31 @@378378 	return false379379 }380380 381-// list_repos names the repos on this machine's remote: the first path segment of every key.381+// list_repos names the repos on this machine's remote: one delimiter listing382+// for the folders, then the folders that carry a `head`. Paging every key in383+// the bucket would cost a request per thousand files.382384 fn list_repos(args Args) int {383385 	mut backend := this_machine_backend() or { return refuse(args.json(), err.msg()) }384-	keys := backend.list('') or { return refuse(args.json(), err.msg()) }385-	mut names := map[string]bool{}386-	for key in keys {386+	mut names := []string{}387+	for name in backend.list_dirs('') or { return refuse(args.json(), err.msg()) } {387388 		// A repo is a folder with a `head`. Anything else at the top of the remote, such as388389 		// Kepr's own `.kepr/` folder of uploads, is not one and cannot be stolen.389-		parts := key.trim_left('/').split('/')390-		if parts.len == 2 && parts[0] != '' && parts[1] == 'head' {391-			names[parts[0]] = true390+		head := backend.get(exchange.head_key(name)) or { remote.Object{} }391+		if exchange.valid_repo_name(name) && head.found {392+			names << name392393 		}393394 	}394-	mut sorted := names.keys()395-	sorted.sort()396395 	if args.json() {397396 		emit_json(json2.encode(ReposJson{398-			repos: sorted397+			repos: names399398 		}))400399 		return 0401400 	}402-	if sorted.len == 0 {401+	if names.len == 0 {403402 		ok('the remote has no repos yet')404403 		return 0405404 	}406-	for name in sorted {405+	for name in names {407406 		println('  ${name}')408407 	}409408 	return 0@@ -462,8 +461,10 @@462461 		return refuse(args.json(), '${name} already exists here — run steal inside it instead')463462 	}464463 	mut backend := chosen465-	fetched := exchange.fetch_repo(mut backend, name) or { return refuse(args.json(), err.msg()) }466-	store := land_repo(target, name, fetched, source) or {464+	// The repo is made before the fetch so objects can be written in batches as465+	// they arrive instead of all being held; a failure removes the whole folder.466+	os.mkdir_all(target, os.MkdirParams{}) or { return refuse(args.json(), err.msg()) }467+	mut store := storage.create(target) or {467468 		os.rmdir_all(target) or {}468469 		return refuse(args.json(), err.msg())469470 	}@@ -476,6 +477,11 @@476477 			os.rmdir_all(target) or {}477478 		}478479 	}480+	fetched := exchange.fetch_repo_into(mut backend, name, store) or { return refuse(args.json(), err.msg()) }481+	fill_repo(store, name, fetched, source) or {482+		store.rollback()483+		return refuse(args.json(), err.msg())484+	}479485 	files := history.files_of(store, fetched.head) or { return refuse(args.json(), err.msg()) }480486 	snapshot.restore_files(store, target, snapshot.Ignore{}, files, []) or {481487 		return refuse(args.json(), err.msg())@@ -511,20 +517,8 @@511517 	return 0512518 }513519 514-// land_repo creates ./<name> and writes the fetched history into it. Objects515-// are checked on the way in, so a damaged remote fails here.516-fn land_repo(target string, name string, fetched exchange.Fetched, source string) !storage.Store {517-	// SQLite creates the file, not the folder holding it.518-	os.mkdir_all(target, os.MkdirParams{})!519-	mut store := storage.create(target)!520-	fill_repo(store, name, fetched, source) or {521-		store.rollback()522-		store.close()523-		return err524-	}525-	return store526-}527-520+// fill_repo writes the fetched history into the new repo in one transaction.521+// Objects are checked as they were written, so a damaged remote failed earlier.528522 fn fill_repo(store &storage.Store, name string, fetched exchange.Fetched, source string) ! {529523 	store.begin()!530524 	exchange.write_fetched(store, fetched)!

view file

src/cli/cmd_strip.v+15 −1
@@ -96,9 +96,18 @@9696 	locals := exchange.strip_local_batch(store, active.map(it.path), only_save) or {9797 		return refuse(args.json(), err.msg())9898 	}99+	// The rows are gone but the pages that held them are not, until the file is100+	// rewritten. A failed scrub does not undo the strip, so it is a warning and101+	// the batch carries on: the remote half still runs.102+	mut exit_code := 0103+	if locals.any(it.files_removed > 0 || it.objects_dropped > 0) {104+		store.scrub() or {105+			strip_warn(args.json(), 'could not scrub ${storage.file_name}: ${err.msg()} — the strip is done, but the removed bytes may still be in the file')106+			exit_code = 1107+		}108+	}99109 	mut reports := []StripJson{}100110 	mut index := 0101-	mut exit_code := 0102111 	for plan in plans {103112 		if plan.scope.files == 0 && !plan.pending {104113 			reports << StripJson{ path: plan.path, save: only_save }@@ -202,4 +211,9 @@202211 203212 fn strip_note(as_json bool, message string) {204213 	if as_json { eprintln('  ${message}') } else { note(message) }214+}215+216+// strip_warn keeps --json readable: warnings go to stderr beside the report.217+fn strip_warn(as_json bool, message string) {218+	if as_json { eprintln('  ! ${message}') } else { warn(message) }205219 }

view file

src/cli/doctor_remote.v+18 −3
@@ -64,7 +64,9 @@6464 6565 fn doctor_remote_content(mut backend remote.Backend, repo string, mut report DoctorJson) ! {6666 	format := backend.get(exchange.format_key(repo))!67-	if format.found && format.body.bytestr().trim_space() != 'koh-remote 1' {67+	// A repo with no format key counts as version 1 (spec §9.2).68+	layout := if format.found { format.body.bytestr().trim_space() } else { exchange.format_v1 }69+	if layout !in [exchange.format_v1, exchange.format_v2] {6870 		return error('remote format is unsupported; update Koh')6971 	}7072 	head := backend.get(exchange.head_key(repo))!@@ -74,6 +76,7 @@7476 	mut files := map[string][]snapshot.FileEntry{}7577 	mut hashes := map[string]bool{}7678 	mut event_list := []events.Event{}79+	mut manifests := map[string]string{}7780 	for key in backend.list('${repo}/saves')! {7881 		if !snapshot.legal_path(key) || !key.starts_with('${repo}/saves/') {7982 			return error('unsafe remote key ${key}')@@ -94,8 +97,20 @@9497 			restores:      record.restores9598 			replayed_from: record.replayed_from9699 		}97-		files[record.id] = record.files.map(snapshot.FileEntry{ path: it.path, hash: it.hash })98-		for file in record.files {100+		record_layout := if record.manifest == '' { exchange.format_v1 } else { exchange.format_v2 }101+		if record_layout != layout {102+			record_problems << 'remote save ${record.id} is a ${record_layout} record on a ${layout} remote'103+		}104+		// A version-2 record names a tree: its files and objects come from it.105+		mut listed := record.files.clone()106+		if record.manifest != '' {107+			listed = exchange.record_files(mut backend, repo, record, mut manifests) or {108+				record_problems << err.msg()109+				[]exchange.FileRecord{}110+			}111+		}112+		files[record.id] = listed.map(snapshot.FileEntry{ path: it.path, hash: it.hash })113+		for file in listed {99114 			hashes[file.hash] = true100115 		}101116 	}

view file

src/cli/progress.v+4 −0
@@ -117,6 +117,10 @@117117 	return if kind == 'objects' { 'files' } else { kind }118118 }119119 120+fn (mut w Watched) list_dirs(prefix string) ![]string {121+	return w.inner.list_dirs(prefix)!122+}123+120124 fn (mut w Watched) put_if_absent(key string, body []u8) !bool {121125 	put := w.inner.put_if_absent(key, body)!122126 	w.sent++

view file

src/exchange/exchange.v+207 −42
@@ -28,18 +28,13 @@2828 2929 pub const no_saves = 'this repo has no saves yet — nothing to offer'3030 31-// The only remote layout this koh reads or writes. A repo offered before the32-// key existed has no `format` key and counts as this version.33-const format_value = 'koh-remote 1'34-35-// put_format records the layout on a repo that has none. put_if_absent never36-// overwrites, so a machine that wrote one while this one read wins the race:37-// its value is read back and checked, never assumed.38-fn put_format(mut backend remote.Backend, repo string) ! {39-	if backend.put_if_absent(format_key(repo), format_value.bytes())! {40-		return31+// put_format records the layout on a repo that has none and returns the value in32+// force: a machine that wrote one first wins the race, and its value is used.33+fn put_format(mut backend remote.Backend, repo string, value string) !string {34+	if backend.put_if_absent(format_key(repo), value.bytes())! {35+		return value4136 	}42-	check_format(mut backend, repo)!37+	return check_format(mut backend, repo)!4338 }4439 4540 // check_format reads <repo>/format and refuses a remote written by a koh that@@ -51,8 +46,8 @@5146 		return ''5247 	}5348 	value := existing.body.bytestr().trim_space()54-	if value != format_value {55-		return error('the remote "${repo}" is "${value}" — this koh speaks "${format_value}"; update koh')49+	if value !in [format_v1, format_v2] {50+		return error('the remote "${repo}" is "${value}" — this koh speaks "${format_v1}" and "${format_v2}"; update koh')5651 	}5752 	return value5853 }@@ -151,9 +146,10 @@151146 		repo: name152147 		head: local.id153148 	}154-	if check_format(mut backend, name)! == '' {155-		// Offered before this key existed: record the layout now.156-		put_format(mut backend, name)!149+	mut format := check_format(mut backend, name)!150+	if format == '' {151+		// A repo with a head keeps version 1; only a new repo starts at 2 (§9.2).152+		format = put_format(mut backend, name, if remote_head.found { format_v1 } else { format_v2 })!157153 	}158154 	// One listing serves both the strip check and the upload. An event that159155 	// lands after it is caught by undo_late_strips below.@@ -164,7 +160,7 @@164160 		return error(strip_not_applied)165161 	}166162 	mut uploaded := Uploaded{}167-	upload_line(store, mut backend, name, local.id, remote_head, event_keys, mut report,163+	upload_line(store, mut backend, name, local.id, remote_head, format, event_keys, mut report,168164 		mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }169165 	// A strip sends its event before it lists the saves to rewrite, so one170166 	// missed here lists them after these records landed and rewrites them. One@@ -179,7 +175,12 @@179175 	// a request, and its tag stays as it was.180176 	if remote_head.body.bytestr().trim_space() != local.id181177 		&& !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {182-		return error('remote has new saves — run koh steal')178+		// A lost answer to a retried PUT lands here too: the tag is stale because179+		// the write already happened. Read the head back before calling it a clash.180+		again := backend.get(head_key(name))!181+		if !again.found || again.body.bytestr().trim_space() != local.id {182+			return error('remote has new saves — run koh steal')183+		}183184 	}184185 	store.set_state(remote_head_key, local.id)!185186 	return report@@ -221,20 +222,24 @@221222 	return done222223 }223224 224-// upload_line sends every save after the remote head, then the events.225-fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, event_keys []string, mut report OfferReport, mut uploaded Uploaded) ! {225+// upload_line sends every save after the remote head, then the events. `sent_manifests`226+// is kept across the whole line so a folder two saves share is uploaded once.227+fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, format string, event_keys []string, mut report OfferReport, mut uploaded Uploaded) ! {228+	mut sent_manifests := map[string]bool{}226229 	if remote_head.found {227230 		theirs := remote_head.body.bytestr().trim_space()228231 		newer := saves_after(store, local, theirs) or {229232 			return error('remote has new saves — run koh steal')230233 		}231234 		for save in newer {232-			upload_save(store, mut backend, name, save, mut report, mut uploaded)!235+			upload_save(store, mut backend, name, save, format, mut sent_manifests, mut report,236+				mut uploaded)!233237 		}234238 	} else {235239 		oldest_first := history.line(store)!236240 		for index := oldest_first.len - 1; index >= 0; index-- {237-			upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!241+			upload_save(store, mut backend, name, oldest_first[index], format, mut sent_manifests,242+				mut report, mut uploaded)!238243 		}239244 	}240245 	upload_events(store, mut backend, name, event_keys, mut report)!@@ -286,27 +291,52 @@286291 		queue_strip(store, strip.path, [strip.save_id], uploaded.objects.keys())!287292 	}288293 	for id in uploaded.saves {289-		strip_record(mut backend, save_key(repo, id), id, strips)!294+		strip_record(store, mut backend, repo, save_key(repo, id), id, strips)!290295 	}291296 	drop_stripped_objects(store, mut backend, repo, uploaded, strips)!292297 	return true293298 }294299 295-// strip_record rewrites one remote record without what `strips` cover. A296-// record that moved meanwhile is read again, since the other writer may have297-// kept a path these strips name.298-fn strip_record(mut backend remote.Backend, key string, id string, strips []events.Event) ! {300+// strip_record rewrites one remote record without what `strips` cover, reading301+// it again when it moved. A version-2 record is rewritten as its tree: the new302+// folders go up before the record names a new root.303+fn strip_record(store &storage.Store, mut backend remote.Backend, repo string, key string, id string, strips []events.Event) ! {304+	mut manifests := map[string]string{}305+	mut sent := map[string]bool{}306+	mut rewriter := Rewriter{}299307 	for _ in 0 .. 5 {300308 		object := backend.get(key)!301309 		if !object.found {302310 			return303311 		}304312 		record := decode_save(object.body)!313+		if record.manifest != '' {314+			fetch_manifests(mut backend, repo, record.manifest, mut manifests)!315+			store_manifests(store, manifests)!316+			mut root := record.manifest317+			for strip in strips {318+				if !reaches(strip, id) {319+					continue320+				}321+				rewritten := rewriter.rewrite(store, root, strip.path.trim_right('/'))!322+				if rewritten.changed {323+					root = rewritten.hash324+				}325+			}326+			if root == record.manifest {327+				return328+			}329+			upload_manifests(store, mut backend, repo, root, mut sent)!330+			if backend.put_if_match(key, encode_save(rewrite(record, record.files, root)).bytes(), object.tag)! {331+				return332+			}333+			continue334+		}305335 		kept := record.files.filter(fn [strips, id] (file FileRecord) bool {306336 			return !strips.any(reaches(it, id) && covers(it.path, file.path))307337 		})308338 		if kept.len == record.files.len309-			|| backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), object.tag)! {339+			|| backend.put_if_match(key, encode_save(rewrite(record, kept, '')).bytes(), object.tag)! {310340 			return311341 		}312342 	}@@ -366,11 +396,12 @@366396 	if reached.len == 0 {367397 		return368398 	}399+	mut manifests := map[string]string{}369400 	for key in backend.list('${repo}/saves')! {370401 		object := backend.get(key)!371402 		if object.found {372403 			record := decode_save(object.body)!373-			for file in record.files {404+			for file in record_files(mut backend, repo, record, mut manifests)! {374405 				if !strips.any(reaches(it, record.id) && covers(it.path, file.path)) {375406 					reached.delete(file.hash)376407 				}@@ -384,10 +415,10 @@384415 	}385416 }386417 387-// upload_save puts a save's new objects, then its record, so a record on the remote always finds its388-// objects there. Both are put_if_absent, so a retry after a partial offer is safe; `uploaded` keeps389-// what this call created, which is all undo_late_strips may delete.390-fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, mut report OfferReport, mut uploaded Uploaded) ! {418+// upload_save puts a save's new objects, its manifest tree, then its record, so a record on the419+// remote finds both. Retrying after a partial offer is safe; `uploaded` keeps what this call420+// created, which is all undo_late_strips may delete.421+fn upload_save(store &storage.Store, mut backend remote.Backend, repo string, save history.Save, format string, mut sent_manifests map[string]bool, mut report OfferReport, mut uploaded Uploaded) ! {391422 	files := history.files_of(store, save.id)!392423 	// Saves go up oldest first and head moves only once all of them landed, so393424 	// the parent and its objects are on the remote already: only content new@@ -408,13 +439,101 @@408439 			uploaded.objects[file.hash] = true409440 		}410441 	}411-	record := save_record(store, save)!442+	// Manifests travel before the record naming them (spec §9.2).443+	mut record := SaveRecord{}444+	if format == format_v2 {445+		upload_manifests(store, mut backend, repo, save.manifest, mut sent_manifests)!446+		record = save_record_v2(store, save)!447+	} else {448+		record = save_record(store, save)!449+	}412450 	if backend.put_if_absent(save_key(repo, save.id), encode_save(record).bytes())! {413451 		report.saves++414452 		uploaded.saves << save.id415453 	}416454 }417455 456+// upload_manifests sends every folder a save's tree names, once per offer: a457+// key is the same body however many saves reach it.458+fn upload_manifests(store &storage.Store, mut backend remote.Backend, repo string, root string, mut sent map[string]bool) ! {459+	mut pending := [root]460+	for pending.len > 0 {461+		hash := pending.pop()462+		if hash in sent {463+			continue464+		}465+		sent[hash] = true466+		backend.put_if_absent(manifest_key(repo, hash), store.manifest_body(hash)!.bytes())!467+		for entry in store.manifest_entries(hash)! {468+			if entry.kind == storage.folder_kind {469+				pending << entry.manifest470+			}471+		}472+	}473+}474+475+// fetch_manifests reads every folder a version-2 tree names, checking each body476+// against its key. A fetch writes nothing until its transaction.477+pub fn fetch_manifests(mut backend remote.Backend, repo string, root string, mut manifests map[string]string) ! {478+	mut pending := [root]479+	for pending.len > 0 {480+		hash := pending.pop()481+		if hash in manifests {482+			continue483+		}484+		object := backend.get(manifest_key(repo, hash))!485+		if !object.found {486+			return error('the remote is missing manifest ${hash}')487+		}488+		if storage.hash_hex(object.body) != hash {489+			return error('remote manifest ${hash} fails Blake3 verification')490+		}491+		body := object.body.bytestr()492+		manifests[hash] = body493+		entries := json2.decode[storage.Manifest](body) or {494+			return error('remote manifest ${hash} is unreadable: ${err.msg()}')495+		}496+		for entry in entries.entries {497+			if entry.kind == storage.folder_kind {498+				pending << entry.manifest499+			}500+		}501+	}502+}503+504+// store_manifests writes freshly read bodies into the local table for a505+// rewriter. An identical body is already there, so writing it again is a no-op.506+fn store_manifests(store &storage.Store, manifests map[string]string) ! {507+	for _, body in manifests {508+		store.put_manifest(body)!509+	}510+}511+512+// flatten_files is a fetched tree as record entries; a record carries no sizes.513+fn flatten_files(manifests map[string]string, root string) ![]FileRecord {514+	files := storage.flatten_bodies(manifests, root)!515+	mut records := []FileRecord{cap: files.len}516+	for file in files {517+		records << FileRecord{518+			path:       file.path519+			hash:       file.hash520+			executable: file.executable521+		}522+	}523+	return records524+}525+526+// record_files reads a record's list from the remote, flattening its tree when527+// it names one, whatever layout wrote it. `manifests` is the caller's cache, so528+// a walk over many records fetches each shared folder once.529+pub fn record_files(mut backend remote.Backend, repo string, record SaveRecord, mut manifests map[string]string) ![]FileRecord {530+	if record.manifest == '' {531+		return record.files532+	}533+	fetch_manifests(mut backend, repo, record.manifest, mut manifests)!534+	return flatten_files(manifests, record.manifest)535+}536+418537 // upload_events sends every event the remote does not have. Events are tiny, so419538 // a listing costs less than tracking which ones were sent; `already` is the420539 // listing the caller already had.@@ -439,6 +558,9 @@439558 pub struct Fetched {440559 pub mut:441560 	repo_objects map[string][]u8561+	// A version-2 record's tree, read before anything is written.562+	manifests    map[string]string563+	object_bytes int          // repo_objects, so a big steal is written in batches442564 	saves        []SaveRecord // oldest first443565 	events_out   []events.Event444566 	head         string@@ -446,11 +568,32 @@446568 	unsafe_paths []string447569 }448570 571+// Objects that arrived are written once this much is held. They are572+// content-addressed, so an interrupted steal leaves only unreferenced rows,573+// which Doctor can remove; the saves and events still land in one transaction.574+const object_batch_bytes = 64 * 1024 * 1024575+576+fn (mut f Fetched) add_object(store &storage.Store, hash string, blob []u8) ! {577+	f.repo_objects[hash] = blob578+	f.object_bytes += blob.len579+	if f.object_bytes >= object_batch_bytes {580+		for key, bytes in f.repo_objects {581+			store.put_object_blob(key, bytes)!582+		}583+		f.repo_objects.clear()584+		f.object_bytes = 0585+	}586+}587+449588 // fetch_back_to_known walks from the remote head along parents until it meets a save on this line450-// (`base`), reading only the objects this repo lacks. Nothing is written here: write_fetched lands it.589+// (`base`), reading only the objects this repo lacks. Objects are written in batches as they590+// arrive; the saves and events land together in write_fetched's transaction.451591 // A save held locally but off the line, from an earlier steal, is taken from the local copy.452592 pub fn fetch_back_to_known(store &storage.Store, mut backend remote.Backend, repo string) !Fetched {453-	check_format(mut backend, repo)!593+	format := check_format(mut backend, repo)!594+	// A repo with no format key counts as version 1 (spec §9.2), so a record595+	// must match its repo's layout either way.596+	layout := if format == '' { format_v1 } else { format }454597 	remote_head := backend.get(head_key(repo))!455598 	if !remote_head.found {456599 		return error('the remote has no "${repo}" yet — run koh offer here first')@@ -482,8 +625,16 @@482625 			if !record_object.found {483626 				return error('the remote is missing save ${cursor} — run koh offer there')484627 			}485-			decoded := decode_save(record_object.body)!628+			mut decoded := decode_save(record_object.body)!486629 			validate_save(decoded, cursor)!630+			record_layout := if decoded.manifest == '' { format_v1 } else { format_v2 }631+			if record_layout != layout {632+				return error('the remote "${repo}" is ${layout} but save ${cursor} is a ${record_layout} record — update koh on the machine that offered it')633+			}634+			if decoded.manifest != '' {635+				fetch_manifests(mut backend, repo, decoded.manifest, mut fetched.manifests)!636+				decoded.files = flatten_files(fetched.manifests, decoded.manifest)!637+			}487638 			decoded488639 		}489640 		fetched.unsafe_paths << drop_unsafe_paths(mut record)@@ -495,7 +646,7 @@495646 				if !blob.found {496647 					return error('the remote is missing object ${file.hash} that save ${record.id} needs')497648 				}498-				fetched.repo_objects[file.hash] = blob.body649+				fetched.add_object(store, file.hash, blob.body)!499650 			}500651 		}501652 		fetched.saves << record@@ -536,9 +687,10 @@536687 	return incoming537688 }538689 539-// write_fetched lands a fetch in one transaction: objects first (verified),540-// then the events, then the saves they belong to. A strip bans its path from541-// all of history, so it reaches every save, here or arriving, whenever made.690+// write_fetched lands a fetch in one transaction: objects (verified), events,691+// manifests, saves. A strip reaches every save, here or arriving, whenever692+// made; its rewrite collects the folders no save reaches, and the arriving693+// saves are not rows yet, so their manifests go in after it and before them.542694 pub fn write_fetched(store &storage.Store, fetched Fetched) ! {543695 	for hash, blob in fetched.repo_objects {544696 		store.put_object_blob(hash, blob)!@@ -553,6 +705,9 @@553705 			remove_path(store, event.path, event.save_id)!554706 		}555707 	}708+	for hash, body in fetched.manifests {709+		store.put_manifest(body)!710+	}556711 	strips := known_strips(store, fetched)!557712 	for record in fetched.saves {558713 		for file in record.files {@@ -569,6 +724,9 @@569724 // write_fetched_records makes network work durable without changing the line.570725 // Events wait for the combine transaction because a strip can rewrite history.571726 pub fn write_fetched_records(store &storage.Store, fetched Fetched) ! {727+	for hash, body in fetched.manifests {728+		store.put_manifest(body)!729+	}572730 	for hash, blob in fetched.repo_objects {573731 		store.put_object_blob(hash, blob)!574732 	}@@ -599,7 +757,14 @@599757 		return snapshot.legal_path(file.path)600758 			&& !strips.any(reaches(it, record.id) && covers(it.path, file.path))601759 	})602-	history.import_save(store, to_save(record), files)!760+	// Nothing was filtered, so the arriving manifests are exactly this list and761+	// the save names that tree; a strip that removed something rebuilds it.762+	mut save := to_save(record)763+	save.manifest = ''764+	if record.manifest != '' && files.len == record.files.len {765+		save.manifest = record.manifest766+	}767+	history.import_save(store, save, files)!603768 }604769 605770 // reaches reports whether a strip event applies to a save: its one save, or

view file

src/exchange/exchange_test.v+244 −33
@@ -744,6 +744,14 @@744744 	}745745 }746746 747+// remote_paths is what a remote record names as a flat path list, whichever748+// layout wrote it: a version-1 list or the tree a version-2 record points at.749+fn remote_paths(mut backend remote.Backend, key string) ![]string {750+	record := decode_save(backend.get(key)!.body)!751+	mut manifests := map[string]string{}752+	return record_files(mut backend, 'proj', record, mut manifests)!.map(it.path)753+}754+747755 // join makes a brand new machine share the remote's line.748756 fn join(store &storage.Store, mut backend remote.Backend) ! {749757 	fetched := fetch_repo(mut backend, 'proj')!@@ -791,6 +799,10 @@791799 	return f.inner.list(prefix)!792800 }793801 802+fn (mut f FaultyBackend) list_dirs(prefix string) ![]string {803+	return f.inner.list_dirs(prefix)!804+}805+794806 fn (mut f FaultyBackend) put_if_absent(key string, body []u8) !bool {795807 	f.writes++796808 	if f.fail_write > 0 && f.writes >= f.fail_write {@@ -798,7 +810,7 @@798810 	}799811 	if f.race_format && !f.raced && key.ends_with('/format') {800812 		f.raced = true801-		f.inner.put_if_absent(key, 'koh-remote 2'.bytes())!813+		f.inner.put_if_absent(key, 'koh-remote 9'.bytes())!802814 		return false803815 	}804816 	return f.inner.put_if_absent(key, body)!@@ -845,8 +857,9 @@845857 	before := backend.writes846858 	report := offer(a, mut backend)!847859 	assert report.objects == 1848-	// One object, one save record, one head swap.849-	assert backend.writes - before == 3860+	// One object, one new root manifest (f3.txt sits at the root), one save861+	// record, one head swap — not one write per file in the repo.862+	assert backend.writes - before == 4850863 }851864 852865 fn test_a_failed_offer_is_safe_to_re_run() {@@ -1268,10 +1281,9 @@12681281 12691282 	// The remote's copy of the save no longer lists the file, and the object is12701283 	// gone from the remote.1271-	record := decode_save(backend.get(save_key('proj', save.id))!.body)!1272-	for file in record.files {1273-		assert file.path != 'secrets.env'1274-	}1284+	listed := remote_paths(mut backend, save_key('proj', save.id))!1285+	assert 'secrets.env' !in listed1286+	assert 'keep.txt' in listed12751287 	// The stripped object is gone from the remote; the ones still referenced12761288 	// are not.12771289 	assert !backend.get(object_key('proj', secret_hash))!.found@@ -1411,6 +1423,10 @@14111423 	return r.inner.list(prefix)!14121424 }14131425 1426+fn (mut r StripRace) list_dirs(prefix string) ![]string {1427+	return r.inner.list_dirs(prefix)!1428+}1429+14141430 fn (mut r StripRace) put_if_absent(key string, body []u8) !bool {14151431 	if r.fail_after_race && r.raced_put {14161432 		return error('injected write failure')@@ -1477,8 +1493,7 @@14771493 	// Another offer may already have published it, so the record stays, stripped.14781494 	assert backend.get(save_key('proj', later.id))!.found14791495 	for key in backend.list('proj/saves')! {1480-		record := decode_save(backend.get(key)!.body)!1481-		assert 'secrets.env' !in record.files.map(it.path), record.id1496+		assert 'secrets.env' !in remote_paths(mut backend, key)!, key14821497 	}14831498 }14841499 @@ -1516,8 +1531,7 @@15161531 		assert (err as Partway).done == 'uploaded 0 objects and 1 save record'15171532 	}15181533 	// Head names the restored record, so it stays, less the stripped path.1519-	record := decode_save(backend.get(save_key('proj', first.id))!.body)!1520-	assert 'secrets.env' !in record.files.map(it.path)1534+	assert 'secrets.env' !in remote_paths(mut backend, save_key('proj', first.id))!15211535 	assert !backend.get(object_key('proj', storage.hash_hex('api_key=1\n'.bytes())))!.found15221536 }15231537 @@ -1558,8 +1572,14 @@15581572 	} else {15591573 		assert err.msg().contains('injected'), err.msg()15601574 	}1561-	record := decode_save(backend.get(save_key('proj', first.id))!.body)!1562-	paths := record.files.map(it.path)1575+	// A version-2 rewrite has to put its new tree up first, and this backend1576+	// fails every write after the race, so the settlement stops here. The note1577+	// it left is what finishes it once the strip has arrived.1578+	assert 'secrets.env' in remote_paths(mut backend, save_key('proj', first.id))!1579+	assert backend.get(shared)!.found1580+	steal_now(a, mut backend)!1581+	send_strip(a, mut backend, 'secrets.env')!1582+	paths := remote_paths(mut backend, save_key('proj', first.id))!15631583 	assert 'secrets.env' !in paths && 'copy.txt' in paths, paths.str()15641584 	assert backend.get(shared)!.found15651585 }@@ -1573,6 +1593,7 @@15731593 		os.rmdir_all(base) or {}15741594 	}15751595 	mut backend := remote.new_folder(os.join_path(base, 'remote'))!1596+	backend.put_if_absent(format_key('proj'), format_v1.bytes())!15761597 	mut a := open_repo(machine('strip_note_a')!)!15771598 	defer {15781599 		a.close()@@ -1590,7 +1611,7 @@15901611 		}15911612 		assert a.state(pending_key('app')) or { '' } == note15921613 		assert backend.list(events_prefix('proj'))!.len == 01593-		assert 'app' in decode_save(backend.get(save_key('proj', save.id))!.body)!.files.map(it.path)1614+		assert 'app' in remote_paths(mut backend, save_key('proj', save.id))!15941615 	}15951616 	// Even behind a recorded strip, a note's hashes may name only objects.15961617 	events.strip(a, '', 'app')!@@ -1658,14 +1679,13 @@16581679 	if _ := resend(a, mut race, 'proj', [], [leak.id]) {16591680 		assert false, 'the injected rewrite failure should have surfaced'16601681 	}1661-	assert 'secrets.env' in decode_save(backend.get(save_key('proj', leak.id))!.body)!.files.map(it.path)1682+	assert 'secrets.env' in remote_paths(mut backend, save_key('proj', leak.id))!16621683 	steal_now(c, mut backend)!16631684 	assert history.head(c) or { history.Save{} }.id == leak.id16641685 	assert strip_pending(a, 'secrets.env')16651686 	steal_now(a, mut backend)!16661687 	send_strip(a, mut backend, 'secrets.env')!1667-	cleaned := decode_save(backend.get(save_key('proj', leak.id))!.body)!1668-	assert 'secrets.env' !in cleaned.files.map(it.path)1688+	assert 'secrets.env' !in remote_paths(mut backend, save_key('proj', leak.id))!16691689 	assert !backend.get(secret)!.found16701690 }16711691 @@ -1893,6 +1913,10 @@18931913 	return m.inner.list(prefix)!18941914 }18951915 1916+fn (mut m MovingRecord) list_dirs(prefix string) ![]string {1917+	return m.inner.list_dirs(prefix)!1918+}1919+18961920 fn (mut m MovingRecord) put_if_absent(key string, body []u8) !bool {18971921 	return m.inner.put_if_absent(key, body)!18981922 }@@ -1903,7 +1927,7 @@19031927 		current := m.inner.get(key)!19041928 		record := decode_save(current.body)!19051929 		other := record.files.filter(it.path != m.other)1906-		m.inner.put_if_match(key, encode_save(rewrite(record, other)).bytes(), current.tag)!1930+		m.inner.put_if_match(key, encode_save(rewrite(record, other, '')).bytes(), current.tag)!19071931 	}19081932 	return m.inner.put_if_match(key, body, tag)!19091933 }@@ -1918,6 +1942,10 @@19181942 		os.rmdir_all(base) or {}19191943 	}19201944 	mut folder := remote.new_folder(os.join_path(base, 'remote'))!1945+	mut store := open_repo(machine('moving_record_store')!)!1946+	defer {1947+		store.close()1948+	}19211949 	key := save_key('proj', 'aaaaaaaaaaaa')19221950 	folder.put_if_absent(key, encode_save(SaveRecord{19231951 		id:    'aaaaaaaaaaaa'@@ -1933,7 +1961,7 @@19331961 		inner: folder19341962 		other: 'secret-b'19351963 	}1936-	strip_record(mut moving, key, 'aaaaaaaaaaaa', [1964+	strip_record(store, mut moving, 'proj', key, 'aaaaaaaaaaaa', [19371965 		events.Event{19381966 			kind: events.kind_strip19391967 			path: 'secret-a'@@ -2002,6 +2030,9 @@20022030 	}20032031 	remote_dir := os.join_path(base, 'remote')20042032 	mut backend := remote.new_folder(remote_dir)!2033+	// Version 1 on purpose: the number of writes a record rewrite costs is what2034+	// this test pins, and a flat record costs exactly one.2035+	backend.put_if_absent(format_key('proj'), format_v1.bytes())!20052036 	mut a := open_repo(machine('resume_a')!)!20062037 	defer {20072038 		a.close()@@ -2331,7 +2362,7 @@23312362 }23322363 23332364 // A remote says what it is, so two koh versions never half-understand one2334-// bucket. The first offer of a repo records the layout.2365+// bucket. A new repo starts at the version-2 layout: records name a manifest tree.23352366 fn test_the_first_offer_records_the_remote_format() {23362367 	base := scratch('format_write')!23372368 	defer {@@ -2345,17 +2376,20 @@23452376 	put(a.root, 'a.txt', 'one\n')!23462377 	make_save(a, 'first')!23472378 	offer_now(a, mut backend)!2348-	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value2379+	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_v223492380 }23502381 23512382 // A repo offered before the key existed is version 1: it still syncs, and the2352-// next offer records the key then.2383+// next offer records the key then. A repo that already has a head keeps version2384+// 1, because its records are flat lists.23532385 fn test_a_remote_without_a_format_still_syncs() {23542386 	base := scratch('format_old')!23552387 	defer {23562388 		os.rmdir_all(base) or {}23572389 	}23582390 	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2391+	// Stand in for a bucket written before the key existed: flat records only.2392+	backend.put_if_absent(format_key('proj'), format_v1.bytes())!23592393 	mut a := open_repo(machine('format_old_a')!)!23602394 	defer {23612395 		a.close()@@ -2363,7 +2397,6 @@23632397 	put(a.root, 'a.txt', 'one\n')!23642398 	make_save(a, 'first')!23652399 	offer_now(a, mut backend)!2366-	// Stand in for a bucket offered before the key existed.23672400 	backend.delete(format_key('proj'))!23682401 	mut b := open_repo(machine('format_old_b')!)!23692402 	defer {@@ -2374,7 +2407,8 @@23742407 	put(a.root, 'a.txt', 'two\n')!23752408 	make_save(a, 'second')!23762409 	offer_now(a, mut backend)!2377-	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_value2410+	// The head was there before the key, so the repo stays version 1.2411+	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_v123782412 	report := steal_now(b, mut backend)!23792413 	assert report.head == head_of(a).id23802414 }@@ -2395,21 +2429,21 @@23952429 	make_save(a, 'first')!23962430 	offer_now(a, mut backend)!23972431 	backend.delete(format_key('proj'))!2398-	backend.put_if_absent(format_key('proj'), 'koh-remote 2'.bytes())!2432+	backend.put_if_absent(format_key('proj'), 'koh-remote 9'.bytes())!23992433 	if _ := offer_now(a, mut backend) {24002434 		assert false, 'offer must refuse a format it does not speak'24012435 	} else {2402-		assert err.msg().contains('koh-remote 2')2436+		assert err.msg().contains('koh-remote 9')24032437 	}24042438 	if _ := steal_now(a, mut backend) {24052439 		assert false, 'steal must refuse a format it does not speak'24062440 	} else {2407-		assert err.msg().contains('koh-remote 2')2441+		assert err.msg().contains('koh-remote 9')24082442 	}24092443 	if _ := fetch_repo(mut backend, 'proj') {24102444 		assert false, 'a steal must refuse a format it does not speak'24112445 	} else {2412-		assert err.msg().contains('koh-remote 2')2446+		assert err.msg().contains('koh-remote 9')24132447 	}24142448 }24152449 @@ -2435,7 +2469,7 @@24352469 	if _ := offer_now(a, mut backend) {24362470 		assert false, 'offer must refuse the format another machine wrote first'24372471 	} else {2438-		assert err.msg().contains('koh-remote 2')2472+		assert err.msg().contains('koh-remote 9')24392473 	}24402474 }24412475 @@ -2518,12 +2552,189 @@25182552 	}25192553 	send_strip(store, mut backend, 'two')!25202554 	assert strip_pending(store, 'one') && !strip_pending(store, 'two')2521-	partial := decode_save(backend.get(save_key('proj', save.id))!.body)!2522-	assert partial.files.map(it.path) == ['.kohignore', 'one']2555+	partial := remote_paths(mut backend, save_key('proj', save.id))!2556+	assert partial == ['.kohignore', 'one']25232557 	assert backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found25242558 	send_strip(store, mut backend, 'one')!25252559 	assert !strip_pending(store, 'one')2526-	finished := decode_save(backend.get(save_key('proj', save.id))!.body)!2527-	assert finished.files.map(it.path) == ['.kohignore']2560+	finished := remote_paths(mut backend, save_key('proj', save.id))!2561+	assert finished == ['.kohignore']25282562 	assert !backend.get(object_key('proj', storage.hash_hex('secret'.bytes())))!.found2563+}2564+2565+// A new repo is version 2: the record names a root manifest, its whole tree2566+// sits beside it, and a steal lands the same saves and files.2567+fn test_a_new_repo_offers_a_manifest_record_that_steal_lands() {2568+	base := scratch('v2_offer')!2569+	defer {2570+		os.rmdir_all(base) or {}2571+	}2572+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2573+	mut a := open_repo(machine('v2_a')!)!2574+	defer {2575+		a.close()2576+	}2577+	put(a.root, 'a.txt', 'one\n')!2578+	put(a.root, 'src/deep/b.txt', 'two\n')!2579+	first := make_save(a, 'first')!2580+	put(a.root, 'src/deep/b.txt', 'three\n')!2581+	head := make_save(a, 'second')!2582+	offer_now(a, mut backend)!2583+	assert backend.get(format_key('proj'))!.body.bytestr().trim_space() == format_v22584+2585+	record := decode_save(backend.get(save_key('proj', head.id))!.body)!2586+	assert record.manifest != ''2587+	assert record.files.len == 02588+	assert backend.get(save_key('proj', head.id))!.body.bytestr().contains('"files":[]')2589+	assert backend.get(manifest_key('proj', record.manifest))!.found2590+	// Save two changed one file, so only the folders on its path are new: the2591+	// first save costs root, `src` and `deep`; the second costs those three again.2592+	assert backend.list('proj/manifests')!.len == 62593+	paths := remote_paths(mut backend, save_key('proj', head.id))!2594+	assert paths == ['.kohignore', 'a.txt', 'src/deep/b.txt']2595+2596+	// Nothing new: no record and no manifest travels.2597+	again := offer_now(a, mut backend)!2598+	assert again.saves == 02599+	assert backend.list('proj/manifests')!.len == 62600+2601+	mut b := open_repo(machine('v2_b')!)!2602+	defer {2603+		b.close()2604+	}2605+	join(b, mut backend)!2606+	assert head_of(b).id == head.id2607+	assert history.files_of(b, head.id)!.map(it.path) == paths2608+	assert history.files_of(b, first.id)!.map(it.path) == ['.kohignore', 'a.txt', 'src/deep/b.txt']2609+	assert os.read_file(os.join_path(b.root, 'src/deep/b.txt'))! == 'three\n'2610+}2611+2612+// A save that changes one folder uploads only that folder and its ancestors; a2613+// folder elsewhere in the tree is already up and is skipped.2614+fn test_a_changed_save_uploads_only_its_changed_folders() {2615+	base := scratch('v2_diff')!2616+	defer {2617+		os.rmdir_all(base) or {}2618+	}2619+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2620+	mut a := open_repo(machine('v2_diff_a')!)!2621+	defer {2622+		a.close()2623+	}2624+	put(a.root, 'docs/c.txt', 'c\n')!2625+	put(a.root, 'src/a.txt', 'a\n')!2626+	make_save(a, 'first')!2627+	offer_now(a, mut backend)!2628+	assert backend.list('proj/manifests')!.len == 32629+	put(a.root, 'src/a.txt', 'b\n')!2630+	make_save(a, 'second')!2631+	report := offer_now(a, mut backend)!2632+	assert report.saves == 12633+	// Only the root and `src` changed; `docs` is untouched.2634+	assert backend.list('proj/manifests')!.len == 52635+}2636+2637+// A repo whose format is version 1 keeps flat records: they are written and2638+// read as before, and no manifest key is ever created.2639+fn test_a_version_1_repo_keeps_flat_records() {2640+	base := scratch('v1_sync')!2641+	defer {2642+		os.rmdir_all(base) or {}2643+	}2644+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2645+	backend.put_if_absent(format_key('proj'), format_v1.bytes())!2646+	mut a := open_repo(machine('v1_a')!)!2647+	defer {2648+		a.close()2649+	}2650+	put(a.root, 'a.txt', 'one\n')!2651+	put(a.root, 'src/b.txt', 'two\n')!2652+	save := make_save(a, 'first')!2653+	offer_now(a, mut backend)!2654+	record := decode_save(backend.get(save_key('proj', save.id))!.body)!2655+	assert record.manifest == ''2656+	assert record.files.map(it.path) == ['.kohignore', 'a.txt', 'src/b.txt']2657+	assert backend.list('proj/manifests')!.len == 02658+2659+	mut b := open_repo(machine('v1_b')!)!2660+	defer {2661+		b.close()2662+	}2663+	join(b, mut backend)!2664+	assert head_of(b).id == save.id2665+	assert history.files_of(b, save.id)!.map(it.path) == ['.kohignore', 'a.txt', 'src/b.txt']2666+}2667+2668+// A v2 record on a v1 repo, or a v1 record on a v2 repo, is refused rather than2669+// half-read: one record type per bucket is what the format key promises.2670+fn test_a_record_of_the_wrong_layout_is_refused() {2671+	base := scratch('v2_wrong_record')!2672+	defer {2673+		os.rmdir_all(base) or {}2674+	}2675+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2676+	mut a := open_repo(machine('v2_wrong_a')!)!2677+	defer {2678+		a.close()2679+	}2680+	put(a.root, 'a.txt', 'one\n')!2681+	save := make_save(a, 'first')!2682+	offer_now(a, mut backend)!2683+	// A hand-written flat record on a version-2 remote.2684+	backend.delete(save_key('proj', save.id))!2685+	backend.put_if_absent(save_key('proj', save.id), encode_save(SaveRecord{2686+		id:    save.id2687+		files: [FileRecord{2688+			path: 'a.txt'2689+			hash: storage.hash_hex('one\n'.bytes())2690+		}]2691+	}).bytes())!2692+	mut b := open_repo(machine('v2_wrong_b')!)!2693+	defer {2694+		b.close()2695+	}2696+	if _ := fetch_back_to_known(b, mut backend, 'proj') {2697+		assert false, 'a flat record on a version-2 remote must be refused'2698+	} else {2699+		assert err.msg().contains(format_v2)2700+	}2701+}2702+2703+// A strip on a version-2 remote rewrites only the folders on the stripped2704+// path: the record names a new root, a folder it does not touch survives2705+// byte-for-byte, and no tree a record reaches names the path.2706+fn test_a_strip_on_a_version_2_remote_rewrites_only_its_path() {2707+	base := scratch('v2_strip')!2708+	defer {2709+		os.rmdir_all(base) or {}2710+	}2711+	mut backend := remote.new_folder(os.join_path(base, 'remote'))!2712+	mut a := open_repo(machine('v2_strip_a')!)!2713+	defer {2714+		a.close()2715+	}2716+	put(a.root, 'secret/key.txt', 'k\n')!2717+	put(a.root, 'docs/readme.md', 'r\n')!2718+	save := make_save(a, 'both')!2719+	offer_now(a, mut backend)!2720+	old_root := decode_save(backend.get(save_key('proj', save.id))!.body)!.manifest2721+	assert backend.list('proj/manifests')!.len == 32722+2723+	strip_local(a, 'secret', '')!2724+	report := send_strip(a, mut backend, 'secret')!2725+	assert report.records == 12726+	new_root := decode_save(backend.get(save_key('proj', save.id))!.body)!.manifest2727+	assert new_root != old_root2728+	// Removing a top-level folder rewrites the root alone; `docs` stays as it was.2729+	assert backend.list('proj/manifests')!.len == 42730+	assert remote_paths(mut backend, save_key('proj', save.id))! == ['.kohignore', 'docs/readme.md']2731+2732+	mut bodies := map[string]string{}2733+	fetch_manifests(mut backend, 'proj', new_root, mut bodies)!2734+	assert bodies.len == 22735+	for _, body in bodies {2736+		assert !body.contains('secret')2737+	}2738+	assert !backend.get(object_key('proj', storage.hash_hex('k\n'.bytes())))!.found2739+	assert backend.get(object_key('proj', storage.hash_hex('r\n'.bytes())))!.found25292740 }

view file

src/exchange/records.v+49 −15
@@ -3,9 +3,10 @@33 //! Records are JSON so a person can read the bucket, and the layout is the44 //! same for every backend:55 //!6-//   <repo>/format          the remote layout, `koh-remote 1`6+//   <repo>/format          the remote layout, `koh-remote 1` or `koh-remote 2`77 //   <repo>/objects/<hash>   the object's compressed bytes, as in the table8-//   <repo>/saves/<id>       the full save record, including its file list8+//   <repo>/manifests/<hash> one folder of a version-2 save's tree9+//   <repo>/saves/<id>       the save record: a file list, or a root manifest910 //   <repo>/events/<id>      one flag, clear or strip event1011 //   <repo>/head             the ID of the newest save on the line1112 //@@ -20,6 +21,11 @@2021 import src.storage2122 import strconv2223 24+// The two layouts this koh reads and writes. A version-2 record names a root25+// manifest; a version-1 record carries its flat file list.26+pub const format_v1 = 'koh-remote 1'27+pub const format_v2 = 'koh-remote 2'28+2329 // One spelling for each key of the layout above (spec §9.2), so no caller builds a path by hand.2430 pub fn format_key(repo string) string {2531 	return '${repo}/format'@@ -29,6 +35,10 @@2935 	return '${repo}/objects/${hash}'3036 }3137 38+pub fn manifest_key(repo string, hash string) string {39+	return '${repo}/manifests/${hash}'40+}41+3242 pub fn save_key(repo string, id string) string {3343 	return '${repo}/saves/${id}'3444 }@@ -71,20 +81,12 @@7181 	replayed_from string7282 pub mut:7383 	files []FileRecord84+	// A version-2 record's root manifest, omitted from a version-1 record's bytes.85+	manifest string @[omitempty]7486 }7587 76-// save_record turns a local save into what travels. The file list is part of77-// the record, which is why a save needs one round trip, not one per file.78-pub fn save_record(store &storage.Store, save history.Save) !SaveRecord {79-	files := history.files_of(store, save.id)!80-	mut records := []FileRecord{}81-	for file in files {82-		records << FileRecord{83-			path:       file.path84-			hash:       file.hash85-			executable: file.executable86-		}87-	}88+// record_fields is every field both layouts share, so a record is built once.89+fn record_fields(save history.Save) SaveRecord {8890 	return SaveRecord{8991 		id:            save.id9092 		parent:        save.parent@@ -97,14 +99,38 @@9799 		session:       save.session98100 		restores:      save.restores99101 		replayed_from: save.replayed_from100-		files:         records101102 	}102103 }103104 105+// save_record is the version-1 record: its file list travels with it.106+pub fn save_record(store &storage.Store, save history.Save) !SaveRecord {107+	mut record := record_fields(save)108+	for file in history.files_of(store, save.id)! {109+		record.files << FileRecord{110+			path:       file.path111+			hash:       file.hash112+			executable: file.executable113+		}114+	}115+	return record116+}117+104118 pub fn encode_save(record SaveRecord) string {105119 	return json2.encode(record)106120 }107121 122+// save_record_v2 names the root manifest instead of listing files; `store`123+// proves the tree is here first.124+pub fn save_record_v2(store &storage.Store, save history.Save) !SaveRecord {125+	if save.manifest == '' {126+		return error('save ${save.id} has no manifest to name on a ${format_v2} remote')127+	}128+	store.manifest_body(save.manifest)!129+	mut record := record_fields(save)130+	record.manifest = save.manifest131+	return record132+}133+108134 pub fn valid_save_id(id string) bool {109135 	return id.len in [6, 12]110136 		&& id.bytes().all((it >= `0` && it <= `9`) || (it >= `a` && it <= `f`))@@ -127,6 +153,9 @@127153 	if record.created_at < 0 || record.size_bytes < 0 {128154 		return error('remote save ${record.id} has invalid metadata')129155 	}156+	if record.manifest != '' && !storage.valid_hash(record.manifest) {157+		return error('remote save ${record.id} has an invalid manifest hash ${record.manifest}')158+	}130159 }131160 132161 pub fn validate_hashes(id string, files []FileRecord) ! {@@ -187,6 +216,7 @@187216 }188217 189218 // drop_unsafe_paths applies the shared path contract before an arriving record is used.219+// Dropping a path drops the record's manifest too: it must be rebuilt from what lands.190220 pub fn drop_unsafe_paths(mut record SaveRecord) []string {191221 	mut kept := []FileRecord{}192222 	mut dropped := []string{}@@ -198,6 +228,9 @@198228 		}199229 	}200230 	record.files = kept231+	if dropped.len > 0 {232+		record.manifest = ''233+	}201234 	dropped.sort()202235 	return dropped203236 }@@ -206,6 +239,7 @@206239 	return history.Save{207240 		id:            record.id208241 		parent:        record.parent242+		manifest:      record.manifest209243 		message:       record.message210244 		created_at:    record.created_at211245 		machine:       record.machine

view file

src/exchange/repair.v+20 −4
@@ -33,6 +33,10 @@3333 		}3434 		mut record := decode_save(object.body)!3535 		validate_save(record, id)!36+		if record.manifest != '' {37+			fetch_manifests(mut backend, repo, record.manifest, mut fetched.manifests)!38+			record.files = flatten_files(fetched.manifests, record.manifest)!39+		}3640 		drop_unsafe_paths(mut record)3741 		validate_hashes(record.id, record.files)!3842 		for file in record.files {@@ -83,8 +87,10 @@8387 	if unapplied_strips(store, mut backend, event_keys)!.len > 0 {8488 		return error(strip_not_applied)8589 	}90+	format := check_format(mut backend, repo)!91+	layout := if format == '' { format_v1 } else { format }8692 	mut uploaded := Uploaded{}87-	upload_copies(store, mut backend, repo, hashes, save_ids, mut uploaded) or {93+	upload_copies(store, mut backend, repo, hashes, save_ids, layout, mut uploaded) or {8894 		return partway(uploaded.done(), after_failed_upload(store, mut backend, repo, uploaded,8995 			err))9096 	}@@ -97,7 +103,7 @@97103 	return uploaded.objects.len + uploaded.saves.len98104 }99105 100-fn upload_copies(store &storage.Store, mut backend remote.Backend, repo string, hashes []string, save_ids []string, mut uploaded Uploaded) ! {106+fn upload_copies(store &storage.Store, mut backend remote.Backend, repo string, hashes []string, save_ids []string, layout string, mut uploaded Uploaded) ! {101107 	for hash in hashes {102108 		key := object_key(repo, hash)103109 		existing := backend.get(key)!@@ -117,6 +123,7 @@117123 			uploaded.objects[hash] = true118124 		}119125 	}126+	mut sent_manifests := map[string]bool{}120127 	for id in save_ids {121128 		save := history.by_id(store, id) or { return error('save ${id} is missing here too') }122129 		for file in history.files_of(store, id)! {@@ -125,7 +132,14 @@125132 				uploaded.objects[file.hash] = true126133 			}127134 		}128-		if backend.put_if_absent(save_key(repo, id), encode_save(save_record(store, save)!).bytes())! {135+		mut record := SaveRecord{}136+		if layout == format_v2 {137+			upload_manifests(store, mut backend, repo, save.manifest, mut sent_manifests)!138+			record = save_record_v2(store, save)!139+		} else {140+			record = save_record(store, save)!141+		}142+		if backend.put_if_absent(save_key(repo, id), encode_save(record).bytes())! {129143 			uploaded.saves << id130144 		}131145 	}@@ -140,10 +154,12 @@140154 		return error(strip_not_applied)141155 	}142156 	mut needed := map[string]bool{}157+	mut manifests := map[string]string{}143158 	for key in backend.list('${repo}/saves')! {144159 		object := backend.get(key)!145160 		if object.found {146-			for file in decode_save(object.body)!.files {161+			record := decode_save(object.body)!162+			for file in record_files(mut backend, repo, record, mut manifests)! {147163 				needed[file.hash] = true148164 			}149165 		}

view file

src/exchange/steal.v+45 −6
@@ -578,7 +578,15 @@578578 // fetch_repo takes a whole repo — head, saves, objects and events — for579579 // `koh steal <name>`, which lands a copy in a new folder.580580 pub fn fetch_repo(mut backend remote.Backend, name string) !Fetched {581-	check_format(mut backend, name)!581+	return fetch_repo_into(mut backend, name, unsafe { nil })582+}583+584+// fetch_repo_into is fetch_repo with somewhere to put arriving objects: a new585+// folder's store is made before the fetch so a big clone is not held in memory.586+pub fn fetch_repo_into(mut backend remote.Backend, name string, store &storage.Store) !Fetched {587+	format := check_format(mut backend, name)!588+	// A repo with no format key counts as version 1 (spec §9.2).589+	layout := if format == '' { format_v1 } else { format }582590 	remote_head := backend.get(head_key(name))!583591 	if !remote_head.found {584592 		return error('the remote has no repo called "${name}"')@@ -591,15 +599,16 @@591599 	}592600 	mut bundle := &Bundle{593601 		fetched: fetched602+		store:   store594603 	}595604 	if fetch_bundle(mut backend, bundle_key(name), mut bundle)! {596605 		fetched = bundle.fetched597606 	} else {598-		for kind in ['objects', 'saves', 'events'] {607+		for kind in ['objects', 'saves', 'events', 'manifests'] {599608 			for key in backend.list('${name}/${kind}')! {600609 				body := backend.get(key)!601610 				if body.found {602-					take(mut fetched, key.all_after('${name}/'), body.body)!611+					take(mut fetched, store, key.all_after('${name}/'), body.body)!603612 				}604613 			}605614 		}@@ -608,6 +617,21 @@608617 	if !fetched.saves.any(it.id == fetched.head) {609618 		return error('the remote is missing its head save ${fetched.head}')610619 	}620+	// A version-2 record's list is its tree, read before anything is written.621+	for index in 0 .. fetched.saves.len {622+		mut record := fetched.saves[index]623+		record_layout := if record.manifest == '' { format_v1 } else { format_v2 }624+		if record_layout != layout {625+			return error('the remote "${name}" is ${layout} but save ${record.id} is a ${record_layout} record — update koh on the machine that offered it')626+		}627+		if record.manifest == '' {628+			continue629+		}630+		fetch_manifests(mut backend, name, record.manifest, mut fetched.manifests)!631+		record.files = flatten_files(fetched.manifests, record.manifest)!632+		fetched.unsafe_paths << drop_unsafe_paths(mut record)633+		fetched.saves[index] = record634+	}611635 	fetched.events_out.sort(a.id < b.id)612636 	return fetched613637 }@@ -641,6 +665,8 @@641665 	fetched Fetched642666 	pending []u8 // the start of an entry still arriving643667 	ended   bool668+	// Objects landing in batches need somewhere to go; a test may leave it nil.669+	store &storage.Store = unsafe { nil }644670 }645671 646672 fn (mut b Bundle) feed(piece []u8) ! {@@ -672,7 +698,7 @@672698 		if length > b.pending.len - start {673699 			break674700 		}675-		take(mut b.fetched, header.all_before(' '), b.pending[start..start + length])!701+		take(mut b.fetched, b.store, header.all_before(' '), b.pending[start..start + length])!676702 		at = start + length677703 	}678704 	if at > 0 {@@ -687,14 +713,18 @@687713 }688714 689715 // take files one fetched key, relative to the repo: an object, a save or an event.690-fn take(mut fetched Fetched, key string, body []u8) ! {716+fn take(mut fetched Fetched, store &storage.Store, key string, body []u8) ! {691717 	id := key.all_after('/')692718 	match key.all_before('/') {693719 		'objects' {694720 			if !storage.valid_hash(id) {695721 				return error('the remote has invalid object hash ${id}')696722 			}697-			fetched.repo_objects[id] = body723+			if store != unsafe { nil } {724+				fetched.add_object(store, id, body)!725+			} else {726+				fetched.repo_objects[id] = body727+			}698728 		}699729 		'saves' {700730 			mut record := decode_save(body)!@@ -702,6 +732,15 @@702732 			fetched.unsafe_paths << drop_unsafe_paths(mut record)703733 			validate_hashes(record.id, record.files)!704734 			fetched.saves << record735+		}736+		'manifests' {737+			if !storage.valid_hash(id) {738+				return error('the remote has invalid manifest hash ${id}')739+			}740+			if storage.hash_hex(body) != id {741+				return error('remote manifest ${id} fails Blake3 verification')742+			}743+			fetched.manifests[id] = body.bytestr()705744 		}706745 		'events' {707746 			if !valid_event_id(id) {

view file

src/exchange/strip.v+57 −13
@@ -163,6 +163,8 @@163163 fn send_steps(store &storage.Store, mut backend remote.Backend, path string, mut report SendReport) ! {164164 	note := read_pending(store, path)!165165 	name := repo_name(store, mut backend)!166+	// Reading the layout refuses a bucket this koh does not speak, before a rewrite.167+	check_format(mut backend, name)!166168 	mut upload := OfferReport{167169 		repo: name168170 	}@@ -176,31 +178,71 @@176178 		freed[hash] = true177179 	}178180 	every_save := '' in note.saves181+	target := path.trim_right('/')179182 	mut needed := map[string]bool{}183+	// One copy of each remote tree serves every record that shares it: `manifests`184+	// the bodies read, `sent` what is already on the remote.185+	mut manifests := map[string]string{}186+	mut sent := map[string]bool{}187+	mut rewriter := Rewriter{}180188 	for key in backend.list('${name}/saves')! {181189 		remote_object := backend.get(key)!182190 		if !remote_object.found {183191 			continue184192 		}185193 		record := decode_save(remote_object.body)!186-		mut kept := []FileRecord{}194+		mut before := record.files.map(storage.ManifestFile{195+			path:       it.path196+			hash:       it.hash197+			executable: it.executable198+		})199+		if record.manifest != '' {200+			fetch_manifests(mut backend, name, record.manifest, mut manifests)!201+			store_manifests(store, manifests)!202+			before = store.manifest_files(record.manifest)!203+		}204+		reached := every_save || record.id in note.saves205+		// One rule for both layouts: what the record names now, and what it named.206+		after := before.filter(fn [reached, path] (file storage.ManifestFile) bool {207+			return !reached || !covers(path, file.path)208+		})209+		if after.len == before.len {210+			for file in before {211+				needed[file.hash] = true212+			}213+			continue214+		}215+		mut still := map[string]bool{}216+		for file in after {217+			still[file.hash] = true218+			needed[file.hash] = true219+		}220+		// A hash the record still names elsewhere is not freed; the path goes221+		// whatever the object's fate.187222 		mut dropped := []string{}188-		for file in record.files {189-			if (every_save || record.id in note.saves) && covers(path, file.path) {190-				freed[file.hash] = true223+		for file in before {224+			if file.hash !in still && file.hash !in dropped {191225 				dropped << file.hash192-				continue226+				freed[file.hash] = true193227 			}194-			kept << file195-			needed[file.hash] = true196228 		}197-		if kept.len == record.files.len {198-			continue229+		mut next := rewrite(record, after.map(FileRecord{230+			path:       it.path231+			hash:       it.hash232+			executable: it.executable233+		}), '')234+		if record.manifest != '' {235+			// The folders on the path are new bodies, up before the record that236+			// names them. Old ones stay: no manifest is ever deleted.237+			rewritten := rewriter.rewrite(store, record.manifest, target)!238+			upload_manifests(store, mut backend, name, rewritten.hash, mut sent)!239+			next = rewrite(record, record.files, rewritten.hash)199240 		}200241 		// Once rewritten, the record no longer names these objects; the note201242 		// keeps them so a retry can still delete them.202243 		queue_strip(store, path, []string{}, dropped)!203-		if !backend.put_if_match(key, encode_save(rewrite(record, kept)).bytes(), remote_object.tag)! {244+		encoded := encode_save(next)245+		if !backend.put_if_match(key, encoded.bytes(), remote_object.tag)! {204246 			return error('the remote copy of save ${record.id} moved while stripping — run koh steal, then strip again')205247 		}206248 		report.records++@@ -265,11 +307,13 @@265307 	return strips266308 }267309 268-// rewrite returns the save record with a new file list.269-fn rewrite(record SaveRecord, files []FileRecord) SaveRecord {310+// rewrite returns the save record with a new file list and root manifest. A311+// version-2 record keeps its empty list and names the tree it now has.312+fn rewrite(record SaveRecord, files []FileRecord, manifest string) SaveRecord {270313 	return SaveRecord{271314 		...record272-		files: files315+		files:    files316+		manifest: manifest273317 	}274318 }275319 

view file

src/exchange/strip_test.v+50 −0
@@ -67,3 +67,53 @@6767 	gone := store.has_object(storage.hash_hex('secret'.bytes()))!6868 	assert !gone6969 }70+71+// strip removes rows, not bytes: SQLite keeps the freed pages and the WAL keeps72+// the frames. After a scrub the object's compressed bytes are out of the file.73+fn test_stripped_object_bytes_leave_the_file() {74+	mut store := strip_test_repo('scrub')!75+	defer {76+		store.close()77+		os.rmdir_all(store.root) or {}78+	}79+	fresh := storage.open(store.root)!80+	secure_delete := strip_test_pragma(fresh, 'PRAGMA secure_delete')81+	fresh.close()82+	assert secure_delete == 183+	mut secret_text := ''84+	for i in 0 .. 12 {85+		mut text := 'strip-canary-${i} '86+		for j in 0 .. 20 + i {87+			text += 'koh-strip-${i}-${j} '88+		}89+		strip_test_put(store.root, 'secrets/f${i}', text)!90+		if i == 0 {91+			secret_text = text92+		}93+	}94+	strip_test_save(store, 'secrets')!95+	hash := storage.hash_hex(secret_text.bytes())96+	blob := store.object_blob(hash)!.bytestr()97+	strip_local(store, 'secrets', '')!98+	assert !store.has_object(hash)!99+	store.scrub()!100+	raw := os.read_bytes(os.join_path(store.root, storage.file_name))!.bytestr()101+	assert !raw.contains(blob)102+	wal := os.join_path(store.root, '${storage.file_name}-wal')103+	if os.exists(wal) {104+		assert !os.read_bytes(wal)!.bytestr().contains(blob)105+	}106+	assert strip_test_pragma(store, 'PRAGMA freelist_count') == 0107+}108+109+// strip_test_pragma reads the first column of a one-row PRAGMA.110+fn strip_test_pragma(store &storage.Store, query string) i64 {111+	mut stmt := store.db.prepare(query) or { panic(err.msg()) }112+	defer {113+		stmt.finalize()114+	}115+	if !stmt.step() or { return -1 } {116+		return -1117+	}118+	return stmt.int(0)119+}

view file

src/history/save.v+16 −2
@@ -37,8 +37,16 @@3737 pub fn save_worktree(store &storage.Store, root string, ig snapshot.Ignore, input SaveInput) !Save {3838 	walked_head := head_id(store)3939 	files := snapshot.walk(store, root, ig)!40+	return save_walked(store, root, input, walked_head, files)41+}42+43+// save_walked records a tree its caller already walked, so a save does not read44+// the whole tree twice. `walked_head` must be read before that walk: if another45+// command moved head meanwhile, save_walk reads the tree again under the lock46+// rather than recording a stale one.47+pub fn save_walked(store &storage.Store, root string, input SaveInput, walked_head string, walked []snapshot.FileEntry) !Save {4048 	store.begin()!41-	save := save_walk(store, root, input, walked_head, files) or {49+	save := save_walk(store, root, input, walked_head, walked) or {4250 		store.rollback()4351 		return err4452 	}@@ -173,7 +181,13 @@173181 // foreign key to `objects`, so this is the check that a half-written save174182 // cannot exist. Its callers hold the transaction.175183 fn insert_save(store &storage.Store, save Save, files []snapshot.FileEntry) ! {176-	manifest := store.manifest_tree(manifest_files(files))!184+	mut manifest := save.manifest185+	if manifest != '' {186+		// A stolen save names the tree that came with it: the rows are here.187+		store.manifest_body(manifest)!188+	} else {189+		manifest = store.manifest_tree(manifest_files(files))!190+	}177191 	mut seen := map[string]bool{}178192 	mut lookup := store.db.prepare('SELECT 1 FROM objects WHERE hash = ?')!179193 	defer {

view file

src/remote/folder.v+17 −0
@@ -46,6 +46,23 @@4646 	}4747 }4848 49+// list_dirs names the immediate folders under `prefix`, one level down, in one50+// read: `koh steal --list` needs the repo folders, not every key under them.51+pub fn (mut f Folder) list_dirs(prefix string) ![]string {52+	dir := f.path_of(prefix)53+	if !os.is_dir(dir) {54+		return []string{}55+	}56+	mut names := []string{}57+	for name in os.ls(dir)! {58+		if os.is_dir(os.join_path(dir, name)) && !is_scratch(name) {59+			names << name60+		}61+	}62+	names.sort()63+	return names64+}65+4966 pub fn (mut f Folder) list(prefix string) ![]string {5067 	dir := os.join_path(f.base, prefix)5168 	if !os.is_dir(dir) {

view file

src/remote/remote.v+1 −0
@@ -26,6 +26,7 @@2626 mut:2727 	get(key string) !Object2828 	list(prefix string) ![]string29+	list_dirs(prefix string) ![]string2930 	put_if_absent(key string, body []u8) !bool3031 	put_if_match(key string, body []u8, tag string) !bool3132 	delete(key string) !

view file

src/remote/s3.v+31 −0
@@ -75,6 +75,37 @@7575 	}7676 }7777 78+// list_dirs asks for one level of folders with a delimiter, so a bucket of79+// thousands of keys answers with its repo names in a request or two.80+pub fn (mut s S3) list_dirs(prefix string) ![]string {81+	mut names := []string{}82+	mut token := ''83+	for {84+		mut query := 'list-type=2&delimiter=/&prefix=${prefix}'85+		if token != '' {86+			query += '&continuation-token=${token}'87+		}88+		response := s.send('GET', '', query, map[string]string{}, []u8{})!89+		if response.status_code != 200 {90+			return error('s3 list failed: ${response.status_code} ${short_body(response)}')91+		}92+		for raw in elements(response.body, 'Prefix') {93+			rest := raw[prefix.len..].trim_right('/')94+			if rest != '' && !rest.contains('/') {95+				names << rest96+			}97+		}98+		if !response.body.contains('<IsTruncated>true</IsTruncated>') {99+			break100+		}101+		token = first_element(response.body, 'NextContinuationToken') or {102+			return error('s3 listing ${prefix} was truncated with no continuation token')103+		}104+	}105+	names.sort()106+	return names107+}108+78109 // list follows ListObjectsV2 continuation tokens until the listing is no longer truncated. A79110 // truncated page without a next token is an error: stopping there would report a short list as80111 // complete, and a missed event is a strip.

view file

src/remote/web.v+14 −0
@@ -122,6 +122,20 @@122122 	return result123123 }124124 125+pub fn (mut w Web) list_dirs(prefix string) ![]string {126+	mut names := map[string]bool{}127+	for key in w.list(prefix)! {128+		rest := key[prefix.len..].trim_left('/')129+		name := rest.all_before('/')130+		if name != '' && rest.contains('/') {131+			names[name] = true132+		}133+	}134+	mut out := names.keys()135+	out.sort()136+	return out137+}138+125139 pub fn (mut w Web) put_if_absent(key string, body []u8) !bool {126140 	return error('${w.repo(key)} is read-only.')127141 }

view file

src/storage/manifest.v+31 −0
@@ -184,6 +184,37 @@184184 	}185185 }186186 187+// flatten_bodies flattens a tree from bodies read off the remote. A tree that188+// names itself is refused rather than walked forever.189+pub fn flatten_bodies(bodies map[string]string, root string) ![]ManifestFile {190+	mut files := []ManifestFile{}191+	flatten_body(bodies, root, '', mut files, []string{})!192+	files.sort(a.path < b.path)193+	return files194+}195+196+fn flatten_body(bodies map[string]string, hash string, prefix string, mut out []ManifestFile, ancestors []string) ! {197+	if hash in ancestors {198+		return error('manifest ${hash} refers to itself')199+	}200+	body := bodies[hash] or { return error('manifest ${hash} is missing') }201+	entries := decode_manifest(body) or { return error('manifest ${hash} is invalid: ${err.msg()}') }202+	mut deeper := ancestors.clone()203+	deeper << hash204+	for entry in entries {205+		if entry.kind == file_kind {206+			out << ManifestFile{207+				path:       prefix + entry.name208+				hash:       entry.hash209+				size:       entry.size210+				executable: entry.executable211+			}212+		} else {213+			flatten_body(bodies, entry.manifest, '${prefix}${entry.name}/', mut out, deeper)!214+		}215+	}216+}217+187218 pub fn (s &Store) manifest_count() !i64 {188219 	mut stmt := s.db.prepare('SELECT COUNT(*) FROM manifests')!189220 	defer {

view file

src/storage/storage.v+17 −1
@@ -147,10 +147,12 @@147147 148148 fn apply_settings(db &Db) ! {149149 	// WAL for crash safety, full sync so a finished save is on disk, foreign150-	// keys so a half-written save cannot exist.150+	// keys so a half-written save cannot exist, and secure_delete so a deleted151+	// row's bytes are zeroed rather than left in a free page.151152 	db.exec('PRAGMA journal_mode=WAL')!152153 	db.exec('PRAGMA synchronous=FULL')!153154 	db.exec('PRAGMA foreign_keys=ON')!155+	db.exec('PRAGMA secure_delete=ON')!154156 }155157 156158 fn check_version(db &Db) ! {@@ -182,6 +184,9 @@182184 	}183185 	db.exec('COMMIT')!184186 	db.exec('PRAGMA foreign_keys=ON')!187+	// Dropping save_files freed its pages but left them in the file; a one-time188+	// VACUUM hands that space back, and it cannot run inside the transaction.189+	db.exec('VACUUM')!185190 }186191 187192 struct V1Save {@@ -352,6 +357,17 @@352357 		return error('${path} already exists')353358 	}354359 	s.db.exec("VACUUM INTO '${path.replace("'", "''")}'")!360+}361+362+// scrub rewrites the file and empties the write-ahead log, so the bytes a strip363+// freed leave neither the free pages nor the WAL frames. The checkpoint comes364+// first because VACUUM would otherwise carry the old frames along; the second365+// one moves VACUUM's own writes out of the WAL and truncates it. VACUUM cannot366+// run inside a transaction, so this is only called with none open.367+pub fn (s &Store) scrub() ! {368+	s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')!369+	s.db.exec('VACUUM')!370+	s.db.exec('PRAGMA wal_checkpoint(TRUNCATE)')!355371 }356372 357373 // integrity_check returns SQLite's complaints; empty means the file is sound.

view file

tests/cli_test.v+3 −0
@@ -1121,6 +1121,9 @@11211121 	init_repo(a)11221122 	write(a, 'safe.txt', 'safe\n')11231123 	assert run_home(a, home, 'remote', 'folder', remote).code == 01124+	// This test crafts a record's flat file list, which only a format-1 repo carries.1125+	os.mkdir_all(os.join_path(remote, 'proj')) or { panic(err) }1126+	os.write_file(os.join_path(remote, 'proj', 'format'), 'koh-remote 1') or { panic(err) }11241127 	id := run_home(a, home, 'save', 'crafted', '--json').out.all_after('"id":"')[..12]11251128 	assert run_home(a, home, 'offer').code == 011261129 	record_path := os.join_path(remote, 'proj', 'saves', id)

view file