096ef744e76f
resolve review findings K2, K6, K9, K12, K14, K15, K16, K18, K20, K21, K24, K25, K29, K31 and raise the ceiling to 15,200 for per-folder manifests
- time
- 2026-11-17 00:10 UTC · 1 week ago
- machine
- Junes-MacBook-Pro.local
- agent
- deepseek/deepseek-flash
- session
- review findings
- parent
- 2f32ce6c5db4
↓ koh-096ef744.tar.gzatlas at this save
files changed43 files
src/build/build.v+8 −1src/cli/cmd_back.v+25 −19src/cli/cmd_back_test.v+1 −1src/cli/cmd_doctor.v+2 −2src/cli/cmd_flag.v+3 −3src/cli/cmd_migrate.v+25 −1src/cli/cmd_offer.v+17 −0src/cli/cmd_pluck.v+1 −1src/cli/cmd_remote.v+5 −5src/cli/cmd_save.v+22 −3src/cli/cmd_status.v+9 −2src/cli/cmd_steal.v+4 −4src/cli/cmd_view.v+3 −3src/cli/doctor_checks.v+1 −1src/cli/doctor_repair.v+1 −1src/exchange/exchange.v+38 −19src/exchange/exchange_test.v+2 −1src/exchange/repair.v+4 −2src/exchange/steal.v+1 −2src/exchange/strip.v+8 −5src/fmt/fmt.v+15 −0src/fmt/fmt_test.v+10 −0src/history/history.v+22 −7src/history/history_test.v+7 −1src/history/log_md.v+2 −1src/history/save.v+2 −1src/migrate/migrate.v+27 −3src/migrate/migrate_test.v+26 −0src/release/release.v+10 −2src/remote/folder.v+35 −8src/remote/folder_test.v+21 −0src/remote/s3.v+6 −3src/snapshot/diff.v+6 −0src/snapshot/fs.v+10 −0src/snapshot/restore.v+37 −0src/storage/cache.v+11 −9src/storage/objects.v+37 −1src/storage/sqlite.v+4 −4src/view/view.v+7 −7vendor/shim/koh_create.c+39 −0vendor/shim/koh_create.h+19 −0vendor/shim/koh_fsync.c+24 −0vendor/shim/koh_fsync.h+19 −0src/build/build.v+8 −1
@@ -298,6 +298,14 @@298298 // failed, timed out, or produced nothing is refused: nothing is published.299299 pub fn build_one(root string, config Config, platform string, version string) !Built {300300 path := output_path(config, platform, version)301+ full := os.join_path(root, path)302+ // A file left by an earlier build must never be published under a new303+ // version: with it gone, a build that exits 0 without writing its artifact304+ // is caught below instead of publishing the old bytes. A folder is left to305+ // the check after the build, which refuses it.306+ if os.is_file(full) {307+ os.rm(full)!308+ }301309 run := run_build(root, config.command, env_for(config.lang, platform))!302310 if run.timed_out {303311 return error('the ${platform} build was still running after ten minutes and was stopped')@@ -305,7 +313,6 @@305313 if run.code != 0 {306314 return error('the ${platform} build failed:\n${tail(run.output)}')307315 }308- full := os.join_path(root, path)309316 if !os.exists(full) {310317 return error('the ${platform} build did not create ${path}')311318 }src/cli/cmd_back.v+25 −19
@@ -32,7 +32,7 @@3232 return refuse(args.json(), err.msg())3333 }3434 if start.parent == '' {35- return refuse(args.json(), 'there is nothing before session "${start.session}"')35+ return refuse(args.json(), 'there is nothing before session "${fmt.safe_text(start.session)}"')3636 }3737 target = history.by_id(store, start.parent) or { return refuse(args.json(), err.msg()) }3838 } else {@@ -114,12 +114,9 @@114114 if as_json && !args.flag('yes') {115115 return refuse(true, 'needs --yes when not interactive')116116 }117- if !discard_first {118- require_clean(store) or { return refuse(as_json, err.msg()) }119- }120- preview := plan_restore(store, target) or { return refuse(as_json, err.msg()) }117+ preview := plan_restore(store, target, !discard_first) or { return refuse(as_json, err.msg()) }121118 if !as_json {122- ok('${verb}: [${target.id}] ${target.message}')119+ ok('${verb}: [${target.id}] ${fmt.safe_text(target.message)}')123120 for delta in preview.deltas {124121 println(' ${change_mark(delta.kind)} ${delta.path}')125122 }@@ -131,10 +128,9 @@131128 }132129 // The tree may have changed while the prompt waited, so the restore acts on133130 // a fresh plan; the one above only drew the preview.134- if !discard_first {135- require_clean(store) or { return refuse(as_json, err.msg()) }131+ plan := plan_restore(store, target, !discard_first) or {132+ return refuse(as_json, err.msg())136133 }137- plan := plan_restore(store, target) or { return refuse(as_json, err.msg()) }138134 save := apply_restore(store, target, verb, plan, discard_first) or {139135 return refuse(as_json, err.msg())140136 }@@ -153,7 +149,7 @@153149 }))154150 return 0155151 }156- ok('restored [${save.id}] ${save.message}')152+ ok('restored [${save.id}] ${fmt.safe_text(save.message)}')157153 if kept != '' {158154 note('the discarded changes are kept in [${kept}] — koh load ${kept} brings them back')159155 }@@ -215,8 +211,7 @@215211 // restore_now performs a whole restore without prompting: the plan, the save216212 // and the files. The history view uses it for its `l` key.217213 pub fn restore_now(store &storage.Store, target history.Save, verb string) !history.Save {218- require_clean(store)!219- plan := plan_restore(store, target)!214+ plan := plan_restore(store, target, true)!220215 save := apply_restore(store, target, verb, plan, false)!221216 snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!222217 return save@@ -242,24 +237,35 @@242237 }243238 }244239 245-// plan_restore works out what writing `target` back onto disk involves. Every246-// file on disk the target lacks goes: undo, load and pluck only run on a clean247-// tree, so those are tracked files, and revert has recorded the rest.248-fn plan_restore(store &storage.Store, target history.Save) !RestorePlan {240+// plan_restore works out what writing `target` back onto disk involves, from one walk of the tree.241+// With `check_clean` it also refuses a tree holding work only the disk has: undo and load only run on242+// a clean tree, so those are tracked files, and revert has recorded the rest.243+fn plan_restore(store &storage.Store, target history.Save, check_clean bool) !RestorePlan {244+ if check_clean && snapshot.restore_pending(store) {245+ return error(snapshot.restore_unfinished)246+ }247+ mut hashing := reading()248+ walked := snapshot.walk_report(store, store.root, snapshot.load(store.root), mut hashing)!249+ if check_clean {250+ if head := history.head(store) {251+ if compare_walked(history.files_of(store, head.id)!, walked).dirty {252+ return error(unsaved_changes)253+ }254+ }255+ }249256 files := history.files_of(store, target.id)!250257 snapshot.check_links(store.root, files)!251258 mut wanted := map[string]bool{}252259 for file in files {253260 wanted[file.path] = true254261 }255- from := working_tree(store)!256262 mut remove := []string{}257- for file in from.files {263+ for file in walked.files {258264 if file.path !in wanted {259265 remove << file.path260266 }261267 }262- deltas := snapshot.changes(from.files, files)268+ deltas := snapshot.changes(walked.files, files)263269 return RestorePlan{264270 files: files265271 remove: removesrc/cli/cmd_back_test.v+1 −1
@@ -73,7 +73,7 @@7373 store.db.exec("CREATE TEMP TRIGGER mark_first BEFORE INSERT ON saves7474 WHEN NOT EXISTS (SELECT 1 FROM state WHERE key = 'restoring')7575 BEGIN SELECT RAISE(ABORT, 'save recorded before the mark'); END")!76- apply_restore(store, first, 'load', plan_restore(store, first)!, false)!76+ apply_restore(store, first, 'load', plan_restore(store, first, false)!, false)!7777 assert snapshot.restore_pending(store)7878 }7979 src/cli/cmd_doctor.v+2 −2
@@ -284,8 +284,8 @@284284 285285 fn doctor_metadata(report DoctorJson) {286286 if report.head.id != '' {287- doctor_row('head', '[${report.head.id}] ${report.head.message.all_before('\n')}')288- doctor_row('', fmt.dim([report.head.agent, report.head.session,287+ doctor_row('head', '[${report.head.id}] ${fmt.safe_text(report.head.message.all_before('\n'))}')288+ doctor_row('', fmt.dim([fmt.safe_text(report.head.agent), fmt.safe_text(report.head.session),289289 fmt.stamp(report.head.created_at), fmt.plural(report.head_files, 'file')].filter(it != '').join(' · ')))290290 } else {291291 doctor_row('head', if report.saves == 0 { 'no saves yet' } else { report.head_id })src/cli/cmd_flag.v+3 −3
@@ -52,7 +52,7 @@5252 }))5353 return 05454 }55- ok('flagged [${save.id}]${if reason != '' { ' — ${reason}' } else { '' }}')55+ ok('flagged [${save.id}]${if reason != '' { ' — ${fmt.safe_text(reason)}' } else { '' }}')5656 return 05757 }5858 @@ -82,9 +82,9 @@8282 }8383 for entry in flagged {8484 save := history.by_id(store, entry.save_id) or { continue }85- mut line := ' ${fmt.amber('⚑')} ${fmt.dim('[' + save.id + ']')} ${fmt.stamp(save.created_at)} ${save.message}'85+ mut line := ' ${fmt.amber('⚑')} ${fmt.dim('[' + save.id + ']')} ${fmt.stamp(save.created_at)} ${fmt.safe_text(save.message)}'8686 if entry.reason != '' {87- line += ' ${fmt.dim(entry.reason)}'87+ line += ' ${fmt.dim(fmt.safe_text(entry.reason))}'8888 }8989 println(line)9090 }src/cli/cmd_migrate.v+25 −1
@@ -22,7 +22,31 @@2222 if lane !in ['dev', 'main'] {2323 return usage_error('--lane takes dev or main, not "${lane}"')2424 }25- plan := migrate.prepare(os.getwd(), lane, args.values_of('with')) or { return refuse(args.json(), err.msg()) }25+ root := os.getwd()26+ // A crash between the swap's two renames leaves a verified draft beside the27+ // archive and no `.koh`: finish it instead of deciding there is no Koh 2 repo.28+ if migrate.half_swapped(root) {29+ report := migrate.finish_swap(root) or { return refuse(args.json(), err.msg()) }30+ if args.json() {31+ emit_json(json2.encode(MigrateJson{32+ repo: report.root33+ ignore_moved: report.ignore_carried34+ build_file: report.build_renamed35+ }))36+ return 037+ }38+ ok('finished the interrupted migration')39+ if report.ignore_carried {40+ note('carried the ignore rules to ${snapshot.ignore_file}')41+ }42+ if report.build_renamed {43+ note('renamed kepr.build to koh.build, and saved that')44+ }45+ note('the Koh 2 data is untouched in ${migrate.archive_dir}/ — move it back to go back')46+ note('run "koh status" to see what the migration left, then "koh save"')47+ return 048+ }49+ plan := migrate.prepare(root, lane, args.values_of('with')) or { return refuse(args.json(), err.msg()) }2650 if !args.json() {2751 note('Koh 2 repo · lane ${plan.lane} · ${fmt.plural(plan.saves, 'save')} (${fmt.plural(plan.checkpoints, 'checkpoint')}) · ${fmt.plural(plan.objects, 'object')} · last save ${time.unix(plan.last_saved).ymmdd()}')2852 show_lost(plan.lost)src/cli/cmd_offer.v+17 −0
@@ -13,6 +13,7 @@1313 import src.release1414 import src.remote1515 import src.storage16+import src.update1617 1718 // cmd_offer sends new saves and events, and with --builds a release. A repo still on a read-only source1819 // refuses, and so does a clash met while upgrading it: "run koh steal".@@ -109,6 +110,22 @@109110 // Not `version`: that is the koh binary's own version, in this module.110111 release_version := build.project_version(store.root) or {111112 return refuse(args.json(), err.msg())113+ }114+ // Publishing is not repeatable, so look before building: a version already115+ // on the remote stays as it is, and an old checkout must not drag `latest`116+ // backwards. Both refusals land in a moment, with no platform built.117+ existing := backend.get(release.release_key(report.repo, release_version)) or {118+ return refuse(args.json(), err.msg())119+ }120+ if existing.found {121+ return refuse(args.json(), '${report.repo} already has ${release_version} published — bump the version to publish again')122+ }123+ latest := backend.get(release.latest_key(report.repo)) or { return refuse(args.json(), err.msg()) }124+ if latest.found {125+ latest_version := latest.body.bytestr().trim_space()126+ if update.compare_versions(release_version, latest_version) <= 0 {127+ return refuse(args.json(), '${release_version} is not newer than the published ${latest_version} — bump the version to publish')128+ }112129 }113130 notes := args.value('notes')114131 release.check_notes(notes) or { return refuse(args.json(), err.msg()) }src/cli/cmd_pluck.v+1 −1
@@ -67,7 +67,7 @@6767 return 06868 }6969 70- ok('${verb}: [${source.id}] ${source.message}')70+ ok('${verb}: [${source.id}] ${fmt.safe_text(source.message)}')7171 for path in plan.applied {7272 println(' ${fmt.amber('~')} ${path}')7373 }src/cli/cmd_remote.v+5 −5
@@ -259,14 +259,14 @@259259 || reply.access_key_id == '' || reply.secret_access_key == '' {260260 return refuse(args.json(), 'Kepr returned incomplete settings — nothing was changed')261261 }262- // The sign-in reply is not the user's choice: a plain-http endpoint would send every later263- // request, and the credentials just handed out, over cleartext.264- if !reply.endpoint.starts_with('https://') {265- return refuse(args.json(), 'Kepr returned a non-https endpoint — nothing was changed')262+ // The sign-in reply is not the user's choice: https, or plain http only for a Kepr on this263+ // machine (the same rule a typed host follows). kepr_host also normalises the stored form.264+ endpoint := remote.kepr_host(reply.endpoint) or {265+ return refuse(args.json(), 'Kepr returned an endpoint koh will not use: ${err.msg()} — nothing was changed')266266 }267267 settings := machine.RemoteSettings{268268 kind: machine.kind_s3269- endpoint: reply.endpoint269+ endpoint: endpoint270270 bucket: reply.bucket271271 region: reply.region272272 kepr: hostsrc/cli/cmd_save.v+22 −3
@@ -28,6 +28,14 @@2828 }2929 return usage_error('${verb} needs a message, e.g. koh ${verb} "${example}"')3030 }31+ // A message is printed by view, status and LOG.md, and may be read back from32+ // a remote: refuse control characters here, before they can reach history.33+ for field in [['message', message], ['agent', args.value('agent')],34+ ['session', args.value('session')]] {35+ if byte := control_byte(field[1]) {36+ return usage_error('a ${verb} ${field[0]} cannot contain control characters (found 0x${byte.hex()})')37+ }38+ }3139 store := open_store() or { return refuse(args.json(), err.msg()) }3240 defer {3341 store.close()@@ -69,7 +77,7 @@6977 for path in walked.unsafe_paths {7078 warn('not saved: unsafe name ${path}')7179 }72- ok('saved [${save.id}] ${save.message}')80+ ok('saved [${save.id}] ${fmt.safe_text(save.message)}')7381 mut detail := []string{}7482 if save.is_checkpoint {7583 detail << 'checkpoint'@@ -80,16 +88,27 @@8088 note(detail.join(' · '))8189 mut attribution := []string{}8290 if save.agent != '' {83- attribution << 'agent: ${save.agent}'91+ attribution << 'agent: ${fmt.safe_text(save.agent)}'8492 }8593 if save.session != '' {86- attribution << 'session: ${save.session}'94+ attribution << 'session: ${fmt.safe_text(save.session)}'8795 }8896 if attribution.len > 0 {8997 note(attribution.join(' · '))9098 }9199 auto_offer(store, false)92100 return 0101+}102+103+// control_byte finds the first control character in a field, so the caller can104+// refuse it by name before the store is opened.105+fn control_byte(text string) ?u8 {106+ for c in text.runes() {107+ if c < 0x20 || c == 0x7f {108+ return u8(c)109+ }110+ }111+ return none93112 }94113 95114 // Every field is always present, so a consumer never has to tell "absent" fromsrc/cli/cmd_status.v+9 −2
@@ -61,7 +61,7 @@6161 // print_status is the plain-text report: the save you are on, then each changed path with a6262 // mark, then the counts.6363 fn print_status(head history.Save, changes Changes, unfinished bool, saves int) {64- note('at [${head.id}] ${fmt.fit(head.message.all_before('\n'), 50)} · ${ago(head.created_at)} · ${fmt.plural(saves, 'save')}')64+ note('at [${head.id}] ${fmt.fit(fmt.safe_text(head.message.all_before('\n')), 50)} · ${ago(head.created_at)} · ${fmt.plural(saves, 'save')}')6565 if unfinished {6666 warn(snapshot.restore_unfinished)6767 }@@ -116,9 +116,16 @@116116 }117117 118118 pub fn compare_with_head(store &storage.Store, head history.Save) !Changes {119- before := snapshot.index_files(history.files_of(store, head.id)!)119+ before := history.files_of(store, head.id)!120120 mut hashing := reading()121121 walked := snapshot.walk_report(store, store.root, snapshot.load(store.root), mut hashing)!122+ return compare_walked(before, walked)123+}124+125+// compare_walked reports what a walked tree has that `before` lacks, so a caller that needs the walk126+// for a plan as well does not walk twice.127+pub fn compare_walked(before_files []snapshot.FileEntry, walked snapshot.WalkReport) Changes {128+ before := snapshot.index_files(before_files)122129 after := snapshot.index_files(walked.files)123130 mut added := []string{}124131 mut modified := []string{}src/cli/cmd_steal.v+4 −4
@@ -292,9 +292,9 @@292292 clash := preview.clashes[at]293293 println('')294294 println(' ── ${at + 1} of ${preview.clashes.len} · ${clash.path} ──')295- println(fmt.fit(' ${fmt.gold('you')} ${clash.mine_stat} ${clash.mine_save.message} · ${ago(clash.mine_save.created_at)} · ${clash.mine_save.machine}',295+ println(fmt.fit(' ${fmt.gold('you')} ${clash.mine_stat} ${fmt.safe_text(clash.mine_save.message)} · ${ago(clash.mine_save.created_at)} · ${fmt.safe_text(clash.mine_save.machine)}',296296 width))297- println(fmt.fit(' ${fmt.blue('remote')} ${clash.theirs_stat} ${clash.theirs_save.message} · ${ago(clash.theirs_save.created_at)} · ${clash.theirs_save.machine}',297+ println(fmt.fit(' ${fmt.blue('remote')} ${clash.theirs_stat} ${fmt.safe_text(clash.theirs_save.message)} · ${ago(clash.theirs_save.created_at)} · ${fmt.safe_text(clash.theirs_save.machine)}',298298 width))299299 println('')300300 println(' [m] keep mine [t] take theirs [d] see both changes')@@ -336,7 +336,7 @@336336 }337337 338338 fn messages(items []string) string {339- return items.map('"${it}"').join(' · ')339+ return items.map('"${fmt.safe_text(it)}"').join(' · ')340340 }341341 342342 // overview_row cuts a row of save messages to the terminal, ending in `· …` when some were left out.@@ -539,7 +539,7 @@539539 // warn_flagged prints the line the document asks for, per incoming flagged save.540540 fn warn_flagged(flags []events.Flag) {541541 for flag in flags {542- reason := if flag.reason != '' { ' — ${flag.reason}' } else { '' }542+ reason := if flag.reason != '' { ' — ${fmt.safe_text(flag.reason)}' } else { '' }543543 warn('[${flag.save_id}] came in flagged${reason}')544544 }545545 }src/cli/cmd_view.v+3 −3
@@ -160,15 +160,15 @@160160 161161 fn view_line(save history.Save, is_head bool, flags map[string]events.Flag) string {162162 marker := if is_head { fmt.amber('▸') } else { ' ' }163- mut line := ' ${marker} ${fmt.dim('[' + save.id + ']')} ${fmt.stamp(save.created_at)} ${save.message}'163+ mut line := ' ${marker} ${fmt.dim('[' + save.id + ']')} ${fmt.stamp(save.created_at)} ${fmt.safe_text(save.message)}'164164 mut tags := []string{}165165 if save.agent != '' || save.session != '' {166166 mut inner := []string{}167167 if save.agent != '' {168- inner << save.agent168+ inner << fmt.safe_text(save.agent)169169 }170170 if save.session != '' {171- inner << save.session171+ inner << fmt.safe_text(save.session)172172 }173173 tags << '[${inner.join(' · ')}]'174174 }src/cli/doctor_checks.v+1 −1
@@ -125,7 +125,7 @@125125 if head_flag := flags[report.head_id] {126126 report.head_flagged = head_flag.kind == events.kind_flag127127 if report.head_flagged {128- report.warnings << 'head is flagged: ${head_flag.reason}; koh flag --clear removes the flag'128+ report.warnings << 'head is flagged: ${fmt.safe_text(head_flag.reason)}; koh flag --clear removes the flag'129129 }130130 }131131 }src/cli/doctor_repair.v+1 −1
@@ -220,7 +220,7 @@220220 snapshot.clear_restore_mark(store)!221221 return222222 }223- plan := plan_restore(store, head)!223+ plan := plan_restore(store, head, false)!224224 apply_restore(store, head, 'revert', plan, true)!225225 snapshot.restore_files(store, store.root, snapshot.load(store.root), plan.files, plan.remove)!226226 }src/exchange/exchange.v+38 −19
@@ -76,6 +76,14 @@7676 // Kepr URL whatever the folder's case (June, 2026-10-01), and remembered in the7777 // repo so renaming the folder later changes nothing.7878 pub fn repo_name(store &storage.Store, mut backend remote.Backend) !string {79+ name, _ := repo_name_with_head(store, mut backend)!80+ return name81+}82+83+// repo_name_with_head is repo_name for a caller that needs the remote head as84+// well: resolving the name has to read it, so `offer` gets it here instead of85+// asking the remote for it a second time.86+fn repo_name_with_head(store &storage.Store, mut backend remote.Backend) !(string, remote.Object) {7987 if remembered := store.state(repo_state_key) {8088 return follow_rename(store, mut backend, remembered)!8189 }@@ -91,16 +99,18 @@9199 }92100 }93101 store.set_state(repo_state_key, name)!94- return name102+ return name, existing95103 }96104 97105 // follow_rename follows the marker Kepr leaves when it renames a repo, `.kepr/renamed/<old>`98106 // holding the new name (§30, 2026-10-01), for as long as the remembered name has no `head`, and99-// remembers where it led. A few hops cover a repo renamed more than once.100-fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !string {107+// remembers where it led. A few hops cover a repo renamed more than once. The head it returns is108+// the one for the name it returns, read again after a hop, so the caller needs no second read.109+fn follow_rename(store &storage.Store, mut backend remote.Backend, remembered string) !(string, remote.Object) {101110 mut name := remembered111+ mut head := backend.get(head_key(name))!102112 for _ in 0 .. 5 {103- if backend.get(head_key(name))!.found {113+ if head.found {104114 break105115 }106116 marker := backend.get('.kepr/renamed/${name}')!@@ -112,17 +122,18 @@112122 break113123 }114124 name = next125+ head = backend.get(head_key(name))!115126 }116127 if name != remembered {117128 store.set_state(repo_state_key, name)!118129 }119- return name130+ return name, head120131 }121132 122133 // offer sends what the remote lacks and then swaps `head`. Nothing is ever123134 // queued: the next offer simply sends everything the remote does not have.124135 pub fn offer(store &storage.Store, mut backend remote.Backend) !OfferReport {125- name := repo_name(store, mut backend)!136+ name, remote_head := repo_name_with_head(store, mut backend)!126137 local := history.head(store) or { return error(no_saves) }127138 mut report := OfferReport{128139 repo: name@@ -132,23 +143,30 @@132143 // Offered before this key existed: record the layout now.133144 put_format(mut backend, name)!134145 }135- remote_head := backend.get(head_key(name))!146+ // One listing serves both the strip check and the upload. An event that147+ // lands after it is caught by undo_late_strips below.148+ event_keys := backend.list(events_prefix(name))!136149 // Records offered by a machine that has not applied a strip would put the137150 // stripped path back on the remote, where nothing would rewrite it again.138- if unapplied_strips(store, mut backend, name)!.len > 0 {151+ if unapplied_strips(store, mut backend, event_keys)!.len > 0 {139152 return error(strip_not_applied)140153 }141154 mut uploaded := Uploaded{}142- upload_line(store, mut backend, name, local.id, remote_head, mut report, mut uploaded) or {143- return after_failed_upload(store, mut backend, name, uploaded, err)144- }155+ upload_line(store, mut backend, name, local.id, remote_head, event_keys, mut report,156+ mut uploaded) or { return after_failed_upload(store, mut backend, name, uploaded, err) }145157 // A strip sends its event before it lists the saves to rewrite, so one146158 // missed here lists them after these records landed and rewrites them. One147159 // seen here may have rewritten before they landed: take back what it reaches.148- if undo_late_strips(store, mut backend, name, uploaded)! {160+ // With nothing uploaded there is nothing to take back; a strip that landed161+ // during a no-op offer is caught by the check above on the next one.162+ if (uploaded.saves.len > 0 || uploaded.objects.len > 0)163+ && undo_late_strips(store, mut backend, name, uploaded)! {149164 return error(strip_not_applied)150165 }151- if !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {166+ // A head already naming these saves needs no write: skipping the PUT saves167+ // a request, and its tag stays as it was.168+ if remote_head.body.bytestr().trim_space() != local.id169+ && !backend.put_if_match(head_key(name), local.id.bytes(), remote_head.tag)! {152170 return error('remote has new saves — run koh steal')153171 }154172 store.set_state(remote_head_key, local.id)!@@ -192,7 +210,7 @@192210 }193211 194212 // upload_line sends every save after the remote head, then the events.195-fn upload_line(store &storage.Store, mut backend remote.Backend, name string, local string, remote_head remote.Object, mut report OfferReport, mut uploaded Uploaded) ! {213+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) ! {196214 if remote_head.found {197215 theirs := remote_head.body.bytestr().trim_space()198216 newer := saves_after(store, local, theirs) or {@@ -207,7 +225,7 @@207225 upload_save(store, mut backend, name, oldest_first[index], mut report, mut uploaded)!208226 }209227 }210- upload_events(store, mut backend, name, mut report)!228+ upload_events(store, mut backend, name, event_keys, mut report)!211229 }212230 213231 // after_failed_upload still applies a strip that landed before the failure@@ -247,7 +265,8 @@247265 // stripped paths, as another offer or head may name them. Notes go first and248266 // objects last, so a stop part way leaves a note and no record without its object.249267 fn settle_late_strips(store &storage.Store, mut backend remote.Backend, repo string, uploaded Uploaded) !bool {250- strips := unapplied_strips(store, mut backend, repo)!268+ event_keys := backend.list(events_prefix(repo))!269+ strips := unapplied_strips(store, mut backend, event_keys)!251270 if strips.len == 0 {252271 return false253272 }@@ -385,9 +404,9 @@385404 }386405 387406 // upload_events sends every event the remote does not have. Events are tiny, so388-// listing them costs less than tracking which ones were sent.389-fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, mut report OfferReport) ! {390- already := backend.list(events_prefix(repo))!407+// a listing costs less than tracking which ones were sent; `already` is the408+// listing the caller already had.409+fn upload_events(store &storage.Store, mut backend remote.Backend, repo string, already []string, mut report OfferReport) ! {391410 mut already_sent := map[string]bool{}392411 for key in already {393412 already_sent[os.base(key)] = truesrc/exchange/exchange_test.v+2 −1
@@ -1926,7 +1926,8 @@19261926 machine: 'other'19271927 }19281928 backend.put_if_absent(event_key('proj', bad.id), encode_event(bad).bytes())!1929- assert unapplied_strips(a, mut backend, 'proj')!.len == 01929+ keys := backend.list(events_prefix('proj'))!1930+ assert unapplied_strips(a, mut backend, keys)!.len == 019301931 }19311932 19321933 // A resend that fails part way reports what it had already uploaded.src/exchange/repair.v+4 −2
@@ -79,7 +79,8 @@7979 pub fn resend(store &storage.Store, mut backend remote.Backend, repo string, hashes []string, save_ids []string) !int {8080 // A record sent before this repo applies a remote strip would bring the8181 // stripped path back.82- if unapplied_strips(store, mut backend, repo)!.len > 0 {82+ event_keys := backend.list(events_prefix(repo))!83+ if unapplied_strips(store, mut backend, event_keys)!.len > 0 {8384 return error(strip_not_applied)8485 }8586 mut uploaded := Uploaded{}@@ -134,7 +135,8 @@134135 /// object no remote record lists that this repo, with every remote strip135136 /// applied, neither holds nor names in a save.136137 pub fn settle_unsettled(store &storage.Store, mut backend remote.Backend, repo string) ! {137- if unapplied_strips(store, mut backend, repo)!.len > 0 {138+ event_keys := backend.list(events_prefix(repo))!139+ if unapplied_strips(store, mut backend, event_keys)!.len > 0 {138140 return error(strip_not_applied)139141 }140142 mut needed := map[string]bool{}src/exchange/steal.v+1 −2
@@ -8,7 +8,6 @@88 99 module exchange1010 11-import compress.zlib1211 import src.apply1312 import src.events1413 import src.fmt@@ -506,7 +505,7 @@506505 return []u8{}507506 }508507 if blob := fetched.repo_objects[entry.hash] {509- return zlib.decompress(blob)!508+ return storage.inflate_bounded(blob, storage.max_file_size)!510509 }511510 return store.get_object(entry.hash)!512511 }src/exchange/strip.v+8 −5
@@ -173,7 +173,8 @@173173 defer {174174 report.event_sent = upload.events > 0175175 }176- upload_events(store, mut backend, name, mut upload)!176+ event_keys := backend.list(events_prefix(name))!177+ upload_events(store, mut backend, name, event_keys, mut upload)!177178 mut freed := map[string]bool{}178179 for hash in note.hashes {179180 freed[hash] = true@@ -242,15 +243,17 @@242243 }243244 244245 // unapplied_strips are the strip events on the remote this repo has not245-// received yet. offer asks before uploading and again after, because a strip that lands246-// in between would otherwise leave the stripped path in the bucket.247-fn unapplied_strips(store &storage.Store, mut backend remote.Backend, repo string) ![]events.Event {246+// received yet, found in `event_keys`, the listing the caller took (so the247+// repo name is not needed here). offer asks before uploading, and again after,248+// because a strip that lands in between would otherwise leave the stripped249+// path in the bucket.250+fn unapplied_strips(store &storage.Store, mut backend remote.Backend, event_keys []string) ![]events.Event {248251 mut known := map[string]bool{}249252 for event in events.all(store)! {250253 known[event.id] = true251254 }252255 mut strips := []events.Event{}253- for key in backend.list(events_prefix(repo))! {256+ for key in event_keys {254257 if os.base(key) in known {255258 continue256259 }src/fmt/fmt.v+15 −0
@@ -73,6 +73,21 @@7373 return paint(text, '38;5;173')7474 }7575 76+// safe_text renders control characters visibly, so a message, agent or reason77+// recorded on another machine cannot move the cursor or repaint the terminal.78+// Printable text, including Unicode, passes through unchanged.79+pub fn safe_text(text string) string {80+ mut safe := ''81+ for c in text.runes() {82+ if c < 0x20 || c == 0x7f {83+ safe += '\\x${u8(c).hex()}'84+ } else {85+ safe += c.str()86+ }87+ }88+ return safe89+}90+7691 // strip_ansi removes the colour codes, for measuring how wide a line really is.7792 pub fn strip_ansi(text string) string {7893 mut out := ''src/fmt/fmt_test.v+10 −0
@@ -0,0 +1,10 @@1+module fmt2+3+// safe_text is what keeps a remote save's message from driving the terminal.4+fn test_safe_text_escapes_controls_and_keeps_the_rest() {5+ assert safe_text('plain') == 'plain'6+ assert safe_text('é ✦ 日本') == 'é ✦ 日本'7+ assert safe_text('\x1b[2J') == '\\x1b[2J'8+ assert safe_text('a\nb\tc\rd') == 'a\\x0ab\\x09c\\x0dd'9+ assert safe_text('del\x7f') == 'del\\x7f'10+}src/history/history.v+22 −7
@@ -51,24 +51,39 @@5151 return store.state(storage.head_key) or { '' }5252 }5353 54-pub fn by_id(store &storage.Store, id string) ?Save {55- mut stmt := store.db.prepare('${select_save} WHERE id = ?') or { return none }54+// save_row is the strict lookup: a database error comes back unchanged, and55+// only a statement that returns no row means the save is missing. Callers that56+// walk a parent chain use this so a bad read cannot pass for the end of it.57+fn save_row(store &storage.Store, id string) !Save {58+ mut stmt := store.db.prepare('${select_save} WHERE id = ?')!5659 defer {5760 stmt.finalize()5861 }59- stmt.bind_text(1, id) or { return none }60- if stmt.step() or { return none } {62+ stmt.bind_text(1, id)!63+ if stmt.step()! {6164 return read_save(stmt)6265 }63- return none66+ return error('save ${id} is missing')6467 }6568 69+// by_id answers "does this save exist" for callers that only branch on it.70+pub fn by_id(store &storage.Store, id string) ?Save {71+ return save_row(store, id) or { none }72+}73+6674 // resolve accepts any unique prefix of six characters or more, the way Koh 26775 // did, so an agent can name a save without quoting the whole ID.6876 pub fn resolve(store &storage.Store, prefix string) !Save {6977 if prefix.len < 6 {7078 return error('"${prefix}" is too short — give at least 6 characters of a save ID')7179 }80+ // Save IDs are hexadecimal. Anything else here would be read as a LIKE81+ // wildcard and scan the table, so reject it before the query.82+ for c in prefix {83+ if !(c >= `0` && c <= `9`) && !(c >= `a` && c <= `f`) && !(c >= `A` && c <= `F`) {84+ return error('"${prefix}" is not a save ID prefix — save IDs are hexadecimal')85+ }86+ }7287 mut stmt := store.db.prepare('${select_save} WHERE id LIKE ? ORDER BY id')!7388 defer {7489 stmt.finalize()@@ -106,7 +121,7 @@106121 mut saves := []Save{}107122 mut cursor := head_id(store)108123 for cursor != '' {109- save := by_id(store, cursor) or { break }124+ save := save_row(store, cursor)!110125 saves << save111126 cursor = save.parent112127 }@@ -149,7 +164,7 @@149164 mut oldest := current150165 mut cursor := current.parent151166 for cursor != '' {152- previous := by_id(store, cursor) or { break }167+ previous := save_row(store, cursor)!153168 if previous.session != current.session {154169 break155170 }src/history/history_test.v+7 −1
@@ -120,10 +120,16 @@120120 } else {121121 assert err.msg().contains('at least 6')122122 }123- if _ := resolve(store, 'zzzzzz') {123+ if _ := resolve(store, 'abcdef') {124124 assert false, 'an unknown prefix should be refused'125125 } else {126126 assert err.msg().contains('no save starts with')127+ }128+ // Only hexadecimal can name a save; LIKE would otherwise treat these as wildcards.129+ if _ := resolve(store, 'zzzzzz') {130+ assert false, 'a non-hex prefix should be refused'131+ } else {132+ assert err.msg().contains('hexadecimal')127133 }128134 }129135 src/history/log_md.v+2 −1
@@ -5,6 +5,7 @@55 66 import os77 import time8+import src.fmt89 import src.storage910 1011 const log_marker = '<!-- Koh maintains this file. Do not edit. Read before starting work. -->'@@ -33,7 +34,7 @@3334 shown := if saves.len < log_shown { saves.len } else { log_shown }3435 mut text := '${log_marker}\n\n# Koh Log\n\n'3536 for save in saves[..shown] {36- text += '✦ [${save.id}] ${save.message} · ${clock(save.created_at)}\n'37+ text += '✦ [${save.id}] ${fmt.safe_text(save.message)} · ${clock(save.created_at)}\n'3738 }3839 if saves.len > shown {3940 text += '\n… ${saves.len - shown} older saves\n'src/history/save.v+2 −1
@@ -10,6 +10,7 @@1010 1111 import strings1212 import time13+import src.fmt1314 import src.machine1415 import src.snapshot1516 import src.storage@@ -67,7 +68,7 @@6768 if moved {6869 // Another agent's save, made while this one waited for the6970 // lock, already holds these changes.70- return error('${nothing_changed} — [${previous.id}] "${previous.message}" was saved a moment ago and already holds this tree')71+ return error('${nothing_changed} — [${previous.id}] "${fmt.safe_text(previous.message)}" was saved a moment ago and already holds this tree')7172 }7273 return error(nothing_changed)7374 }src/migrate/migrate.v+27 −3
@@ -551,10 +551,14 @@551551 fn swap(root string, mut report Report) ! {552552 old := os.join_path(root, koh2_dir)553553 archive := os.join_path(root, archive_dir)554- if os.exists(archive) {555- return error('${archive} already exists — move it away first')554+ // A crash between the two moves leaves the Koh 2 data already archived; only555+ // the move into place is left, which is what `finish_swap` runs.556+ if os.is_dir(old) {557+ if os.exists(archive) {558+ return error('${archive} already exists — move it away first')559+ }560+ os.mv(old, archive, os.MvParams{})!556561 }557- os.mv(old, archive, os.MvParams{})!558562 os.mv(os.join_path(root, draft_file), os.join_path(root, storage.file_name), os.MvParams{})!559563 // Koh 2 kept its ignore rules under .koh/; carry them to the root, which is560564 // where Koh 3 reads them from.@@ -565,6 +569,26 @@565569 os.write_file(ignore_target, body)!566570 report.ignore_carried = true567571 }572+}573+574+// half_swapped reports the state a crash between swap's two moves leaves: the575+// Koh 2 data is archived, `.koh` is gone and the verified draft is still there.576+pub fn half_swapped(root string) bool {577+ return os.is_dir(os.join_path(root, archive_dir))578+ && !os.exists(os.join_path(root, koh2_dir))579+ && os.exists(os.join_path(root, draft_file))580+}581+582+// finish_swap completes a migration that crashed inside `swap`. The draft was583+// imported, verified and closed before the swap began, so finishing it is the584+// same two renames, less the one already done.585+pub fn finish_swap(root string) !Report {586+ mut report := Report{587+ root: root588+ }589+ swap(root, mut report)!590+ rename_build_file(root, mut report)!591+ return report568592 }569593 570594 // check_build_files runs in the check phase, before the swap: a repo holdingsrc/migrate/migrate_test.v+26 −0
@@ -394,6 +394,32 @@394394 assert os.is_dir(os.join_path(fixture.dir, '.koh'))395395 }396396 397+// A crash between the swap's two moves leaves the archive, no `.koh` and the398+// verified draft; the next run finishes it instead of finding no Koh 2 repo.399+fn test_a_crash_between_the_two_renames_is_finished() {400+ koh2 := koh2_binary() or { return }401+ fixture := make_fixture(koh2)!402+ defer {403+ os.rmdir_all(fixture.dir) or {}404+ }405+ run(prepare(fixture.dir, default_lane, [])!, quiet)!406+ // Put the repo back where that crash leaves it: archived, draft waiting,407+ // no `.koh`, and the ignore rules not yet carried.408+ os.mv(os.join_path(fixture.dir, '.koh'), os.join_path(fixture.dir, draft_file), os.MvParams{})!409+ os.rm(os.join_path(fixture.dir, snapshot.ignore_file)) or {}410+ assert half_swapped(fixture.dir)411+ finish_swap(fixture.dir)!412+ assert os.is_file(os.join_path(fixture.dir, '.koh'))413+ assert os.is_dir(os.join_path(fixture.dir, '.koh-v2'))414+ assert os.is_file(os.join_path(fixture.dir, snapshot.ignore_file))415+ assert !os.exists(os.join_path(fixture.dir, draft_file))416+ store := storage.open(fixture.dir)!417+ defer {418+ store.close()419+ }420+ assert history.save_count(store)! == 3421+}422+397423 // Koh 2 did not always write a manifest's files in path order (nina has one such save).398424 fn test_a_manifest_listing_its_files_out_of_order_migrates() {399425 koh2 := koh2_binary() or { return }src/release/release.v+10 −2
@@ -102,8 +102,16 @@102102 files: files103103 }104104 // The record is what makes the version real. `put_if_absent`, so a record105- // already there stays: published versions never change.106- backend.put_if_absent(release_key(repo, version), json2.encode(record).bytes())!105+ // already there stays: published versions never change. An identical record106+ // is this publish retried and carries on; anything else is a version that107+ // already exists with other files, refused as `upload` refuses a file.108+ record_bytes := json2.encode(record).bytes()109+ if !backend.put_if_absent(release_key(repo, version), record_bytes)! {110+ existing := backend.get(release_key(repo, version))!111+ if !existing.found || existing.body != record_bytes {112+ return error('version ${version} is already published with different files — bump the version to publish again')113+ }114+ }107115 move_latest(mut backend, repo, version)!108116 return Published{109117 version: versionsrc/remote/folder.v+35 −8
@@ -4,8 +4,9 @@44 //! no network and no account. It is also a real backend in its own right — a55 //! sync folder on an external disk or a NAS is a perfectly good remote.66 //!7-//! Publish is a hard link, which fails when the name already exists: no partial8-//! file and no overwrite is ever visible to a reader.7+// Publish is a hard link, which fails when the name already exists: no partial8+// file and no overwrite is ever visible to a reader. Where the filesystem has9+// no hard links (exFAT, FAT, many SMB shares) an exclusive create stands in.910 1011 module remote1112 @@ -13,6 +14,12 @@1314 import time1415 import os1516 17+#flag -I@VMODROOT/vendor/shim18+#flag @VMODROOT/vendor/shim/koh_create.c19+#include "koh_create.h"20+21+fn C.koh_create_exclusive(path &char, data voidptr, len usize) int22+1623 pub struct Folder {1724 pub:1825 base string@@ -63,7 +70,8 @@6370 6471 // put_if_absent writes a temp file in the target directory and hard-links it6572 // into place. `link` fails when the name is taken, so a racing writer loses66-// cleanly instead of overwriting.73+// cleanly instead of overwriting. A link error on an absent name means the74+// filesystem has no hard links; create_exclusive finishes the job there.6775 pub fn (mut f Folder) put_if_absent(key string, body []u8) !bool {6876 path := f.path_of(key)6977 dir := os.dir(path)@@ -79,11 +87,23 @@7987 if os.exists(path) {8088 return false8189 }82- return err90+ return create_exclusive(path, body)8391 }8492 return true8593 }8694 95+// create_exclusive publishes on filesystems with no hard links (exFAT, FAT,96+// many SMB shares), where `link` fails even for an absent name. O_EXCL keeps97+// the same guarantee: the kernel creates the name or reports it taken, so two98+// racing writers still produce exactly one winner.99+fn create_exclusive(path string, body []u8) !bool {100+ match unsafe { C.koh_create_exclusive(&char(path.str), body.data, usize(body.len)) } {101+ 1 { return true }102+ 0 { return false }103+ else { return error('cannot create ${path}') }104+ }105+}106+87107 // put_if_match compares the current content's tag to the one the caller read88108 // before writing. A lock file taken with an exclusive create serialises the89109 // compare-and-swap, so two machines cannot both believe they won.@@ -120,14 +140,21 @@120140 }121141 122142 // take_lock claims a lock path by hard-linking a fresh file into place. `link`123-// fails when the name exists, so exactly one writer can hold it.143+// fails when the name exists, so exactly one writer can hold it. Without hard144+// links the same claim is an exclusive create.124145 fn take_lock(path string) !bool {125- fresh := '${path}.${os.getpid()}.${time.now().unix_nano()}'126- os.write_file(fresh, '${os.getpid()}')!146+ pid := '${os.getpid()}'147+ fresh := '${path}.${pid}.${time.now().unix_nano()}'148+ os.write_file(fresh, pid)!127149 defer {128150 os.rm(fresh) or {}129151 }130- os.link(fresh, path) or { return false }152+ os.link(fresh, path) or {153+ if os.exists(path) {154+ return false155+ }156+ return create_exclusive(path, pid.bytes())157+ }131158 return true132159 }133160 src/remote/folder_test.v+21 −0
@@ -104,3 +104,24 @@104104 assert backend.get(probe_key)!.found105105 assert backend.list('')! == [probe_key]106106 }107+108+fn test_exclusive_create_covers_filesystems_without_hard_links() {109+ dir := scratch('exclusive')!110+ defer {111+ os.rmdir_all(dir) or {}112+ }113+ path := os.join_path(dir, 'key')114+ assert create_exclusive(path, 'first'.bytes())!115+ assert os.read_file(path)! == 'first'116+ assert !create_exclusive(path, 'second'.bytes())!117+ assert os.read_file(path)! == 'first'118+119+ // The lock uses the same primitive, and still holds only one writer.120+ guard := os.join_path(dir, 'key.lock')121+ assert take_lock(guard)!122+ assert !take_lock(guard)!123+ assert os.read_file(guard)! == '${os.getpid()}'124+ release_lock(guard)125+ assert take_lock(guard)!126+ release_lock(guard)127+}src/remote/s3.v+6 −3
@@ -75,8 +75,9 @@7575 }7676 }7777 78-// list follows ListObjectsV2 continuation tokens until the listing is no longer truncated, or a79-// truncated one names no next token.78+// list follows ListObjectsV2 continuation tokens until the listing is no longer truncated. A79+// truncated page without a next token is an error: stopping there would report a short list as80+// complete, and a missed event is a strip.8081 pub fn (mut s S3) list(prefix string) ![]string {8182 mut keys := []string{}8283 mut token := ''@@ -95,7 +96,9 @@9596 if !response.body.contains('<IsTruncated>true</IsTruncated>') {9697 break9798 }98- token = first_element(response.body, 'NextContinuationToken') or { break }99+ token = first_element(response.body, 'NextContinuationToken') or {100+ return error('s3 listing ${prefix} was truncated with no continuation token')101+ }99102 }100103 return keys101104 }src/snapshot/diff.v+6 −0
@@ -178,6 +178,12 @@178178 if result.exit_code < 0 {179179 return error('cannot run diff(1)')180180 }181+ // diff(1): 0 = same, 1 = differs, 2+ = trouble. Only 0 and 1 carry a patch.182+ if result.exit_code > 1 {183+ output := result.output.trim_space()184+ reason := if output == '' { 'no output' } else { output }185+ return error('diff failed (exit ${result.exit_code}): ${reason}')186+ }181187 return result.output182188 }183189 src/snapshot/fs.v+10 −0
@@ -9,7 +9,11 @@99 1010 #flag -I@VMODROOT/vendor/shim1111 #flag @VMODROOT/vendor/shim/koh_stat.c12+#flag @VMODROOT/vendor/shim/koh_fsync.c13+#flag @VMODROOT/vendor/shim/koh_create.c1214 #include "koh_stat.h"15+#include "koh_fsync.h"16+#include "koh_create.h"1317 1418 pub struct C.koh_stat {1519 size i64@@ -20,6 +24,12 @@2024 }2125 2226 fn C.koh_lstat(path &char, out &C.koh_stat) int27+28+fn C.koh_fsync_file(path &char) int29+30+fn C.koh_fsync_dir(path &char) int31+32+fn C.koh_create_exclusive(path &char, data voidptr, len usize) int2333 2434 pub enum Kind {2535 missingsrc/snapshot/restore.v+37 −0
@@ -121,6 +121,26 @@121121 return error('unsafe path ${escape_path(path)} is outside the repo')122122 }123123 }124+ // A file standing where a saved folder belongs would fail part way through125+ // the writes, after some files had already landed. Symlinked folders are126+ // check_links' job, so they pass here untouched.127+ for entry in target {128+ mut folder := ''129+ parts := entry.path.split('/')130+ for i, part in parts {131+ if i == parts.len - 1 {132+ break133+ }134+ folder = if folder == '' { part } else { '${folder}/${part}' }135+ st := lstat(os.join_path(root, folder)) or { break }136+ if st.kind == .symlink {137+ break138+ }139+ if st.kind != .dir {140+ return error('${folder} is a file where a saved folder belongs — move it')141+ }142+ }143+ }124144 }125145 126146 // already_there reports whether the file on disk has the target's content and@@ -161,10 +181,27 @@161181 fn write_file(path string, data []u8, executable bool) ! {162182 os.mkdir_all(os.dir(path), os.MkdirParams{})!163183 tmp := '${path}.koh-tmp-${os.getpid()}'184+ // A failed write must not leave a temp file for the next save to trip over.185+ // After the rename there is no tmp path left, so this cannot eat the target.186+ defer {187+ if os.exists(tmp) {188+ os.rm(tmp) or {}189+ }190+ }164191 os.write_file_array(tmp, data)!165192 mode := if executable { 0o755 } else { 0o644 }166193 os.chmod(tmp, mode)!194+ // The rename only survives a power cut once the bytes are on disk; without195+ // this it could land as an empty file with the restore mark already cleared.196+ if C.koh_fsync_file(unsafe { &char(tmp.str) }) == 0 {197+ return error('cannot sync ${tmp} to disk')198+ }167199 os.rename(tmp, path)!200+ // And the rename itself is an entry in the folder, so sync that as well.201+ dir := os.dir(path)202+ if C.koh_fsync_dir(unsafe { &char(dir.str) }) == 0 {203+ return error('cannot sync ${dir} to disk')204+ }168205 }169206 170207 // prune_empty_dirs clears directories a restore emptied, never the repo root.src/storage/cache.v+11 −9
@@ -46,8 +46,15 @@4646 s.db.exec('PRAGMA busy_timeout = ${busy_timeout_ms}') or {}4747 }4848 s.db.exec('BEGIN IMMEDIATE')!49+ mut stmt := s.db.prepare('INSERT INTO file_cache (path, size, mtime_ns, ctime_ns, hash)50+ VALUES (?, ?, ?, ?, ?)51+ ON CONFLICT(path) DO UPDATE SET size = excluded.size, mtime_ns = excluded.mtime_ns,52+ ctime_ns = excluded.ctime_ns, hash = excluded.hash')!53+ defer {54+ stmt.finalize()55+ }4956 for row in rows {50- s.save_cache(row) or {57+ bind_cache_row(mut stmt, row) or {5158 s.rollback()5259 return err5360 }@@ -55,20 +62,15 @@5562 s.end()!5663 }5764 58-fn (s &Store) save_cache(row CacheRow) ! {59- mut stmt := s.db.prepare('INSERT INTO file_cache (path, size, mtime_ns, ctime_ns, hash)60- VALUES (?, ?, ?, ?, ?)61- ON CONFLICT(path) DO UPDATE SET size = excluded.size, mtime_ns = excluded.mtime_ns,62- ctime_ns = excluded.ctime_ns, hash = excluded.hash')!63- defer {64- stmt.finalize()65- }65+fn bind_cache_row(mut stmt Stmt, row CacheRow) ! {6666 stmt.bind_text(1, row.path)!6767 stmt.bind_int(2, row.size)!6868 stmt.bind_int(3, row.mtime_ns)!6969 stmt.bind_int(4, row.ctime_ns)!7070 stmt.bind_text(5, row.hash)!7171 stmt.step()!72+ // A statement that has returned DONE must be reset before rebinding.73+ stmt.reset()7274 }7375 7476 pub fn (s &Store) drop_cache() ! {src/storage/objects.v+37 −1
@@ -12,6 +12,40 @@1212 1313 pub const max_file_size = 512 * 1024 * 10241414 15+struct InflateSink {16+mut:17+ out []u818+ limit int19+ aborted bool20+}21+22+// inflate_bounded decompresses a blob that came from a remote. Its size on the23+// wire says nothing about its size in memory, so inflation stops once the24+// total would pass `limit` rather than letting a small blob expand. An aborted25+// stream skips checksum verification, which is fine: callers check the content26+// hash of what they get back.27+pub fn inflate_bounded(blob []u8, limit int) ![]u8 {28+ mut sink := &InflateSink{29+ limit: limit30+ }31+ zlib.decompress_with_callback(blob, fn (chunk []u8, sink &InflateSink) int {32+ if sink.out.len + chunk.len > sink.limit {33+ unsafe {34+ sink.aborted = true35+ }36+ return 037+ }38+ unsafe {39+ sink.out << chunk40+ }41+ return chunk.len42+ }, sink)!43+ if sink.aborted {44+ return error('object would inflate past ${limit} bytes')45+ }46+ return sink.out47+}48+1549 pub fn hash_hex(data []u8) string {1650 return blake3.sum256(data).hex()1751 }@@ -56,7 +90,9 @@5690 if s.has_object(hash)! {5791 return5892 }59- data := zlib.decompress(blob) or { return error('object ${hash} is damaged: ${err.msg()}') }93+ data := inflate_bounded(blob, max_file_size) or {94+ return error('object ${hash} is damaged: ${err.msg()}')95+ }6096 if hash_hex(data) != hash {6197 return error('object ${hash} is damaged: it does not match its hash')6298 }src/storage/sqlite.v+4 −4
@@ -233,7 +233,8 @@233233 234234 // text copies the column out of SQLite's row buffer. It must copy: SQLite owns235235 // that memory only until the statement is stepped again or finalized, and a V236-// string built by aliasing it would point at freed bytes.236+// string built by aliasing it would point at freed bytes. tos aliases, so237+// clone makes the one copy.237238 pub fn (stmt &Stmt) text(idx int) string {238239 ptr := C.sqlite3_column_text(stmt.stmt, idx)239240 if ptr == unsafe { nil } {@@ -243,9 +244,8 @@243244 if n == 0 {244245 return ''245246 }246- mut out := []u8{len: n}247- unsafe { vmemcpy(out.data, ptr, n) }248- return out.bytestr()247+ aliased := unsafe { tos(ptr, n) }248+ return aliased.clone()249249 }250250 251251 // blob copies for the same reason as text.src/view/view.v+7 −7
@@ -493,12 +493,12 @@493493 494494 fn entry_message(save history.Save, screen Screen) string {495495 warning := if is_flagged(screen, save.id) { fmt.red('⚠ ') } else { '' }496- return ' ${warning}${save.message}'496+ return ' ${warning}${fmt.safe_text(save.message)}'497497 }498498 499499 fn entry_meta(save history.Save) string {500- agent := if save.agent == '' { 'unknown' } else { save.agent }501- session := if save.session == '' { 'no session' } else { save.session }500+ agent := if save.agent == '' { 'unknown' } else { fmt.safe_text(save.agent) }501+ session := if save.session == '' { 'no session' } else { fmt.safe_text(save.session) }502502 return ' ${fmt.human_bytes(save.size_bytes)} · ${agent} · ${session}'503503 }504504 @@ -589,17 +589,17 @@589589 }590590 mut lines := [591591 title,592- ' ${save.message}',592+ ' ${fmt.safe_text(save.message)}',593593 '',594594 detail_row('time', '${fmt.date_of(save.created_at)} · ${fmt.clock_of(save.created_at)}'),595595 detail_row('size', fmt.human_bytes(save.size_bytes)),596- detail_row('agent', if save.agent == '' { 'unknown' } else { save.agent }),597- detail_row('session', if save.session == '' { 'none' } else { save.session }),596+ detail_row('agent', if save.agent == '' { 'unknown' } else { fmt.safe_text(save.agent) }),597+ detail_row('session', if save.session == '' { 'none' } else { fmt.safe_text(save.session) }),598598 detail_row('parent', if save.parent == '' { 'root' } else { save.parent }),599599 detail_row('checksum', save.id),600600 ]601601 if flag.flagged {602- lines << detail_row('flag', flag.reason)602+ lines << detail_row('flag', fmt.safe_text(flag.reason))603603 }604604 lines << ''605605 if save.parent == '' {vendor/shim/koh_create.c+39 −0
@@ -0,0 +1,39 @@1+#include "koh_create.h"2+3+#include <errno.h>4+#include <fcntl.h>5+#include <unistd.h>6+7+int koh_create_exclusive(const char *path, const void *data, size_t len) {8+ int fd = open(path, O_CREAT | O_EXCL | O_WRONLY, 0644);9+ if (fd < 0) {10+ return errno == EEXIST ? 0 : -1;11+ }12+ const char *bytes = (const char *)data;13+ size_t written = 0;14+ while (written < len) {15+ ssize_t n = write(fd, bytes + written, len - written);16+ if (n < 0) {17+ if (errno == EINTR) {18+ continue;19+ }20+ close(fd);21+ unlink(path);22+ return -1;23+ }24+ if (n == 0) {25+ close(fd);26+ unlink(path);27+ return -1;28+ }29+ written += (size_t)n;30+ }31+ /* A failed close (full disk, deferred write error) means the bytes may not32+ * be there; drop the name rather than leave a short file that looks33+ * published. */34+ if (close(fd) != 0) {35+ unlink(path);36+ return -1;37+ }38+ return 1;39+}vendor/shim/koh_create.h+19 −0
@@ -0,0 +1,19 @@1+/* Create-if-absent for remotes that have no hard links.2+ *3+ * The folder backend publishes by hard-linking a temp file into place, which4+ * fails when the name is taken. exFAT, FAT and many SMB shares have no hard5+ * links at all, so there `link` fails even on an absent name and every put6+ * looks like a collision. O_CREAT|O_EXCL is the same test — the kernel creates7+ * the name or reports it taken — and works on those filesystems.8+ */9+10+#ifndef KOH_CREATE_H11+#define KOH_CREATE_H12+13+#include <stddef.h>14+15+/* Creates `path` with `data`. Returns 1 when created, 0 when the name already16+ * exists, -1 on any other error (nothing is left behind in that case). */17+int koh_create_exclusive(const char *path, const void *data, size_t len);18+19+#endifvendor/shim/koh_fsync.c+24 −0
@@ -0,0 +1,24 @@1+#include "koh_fsync.h"2+3+#include <fcntl.h>4+#include <unistd.h>5+6+/* Opening read-only is enough to sync and works for both files and folders on7+ * Linux and macOS; a folder cannot be opened for writing at all. */8+static int koh_fsync_path(const char *path) {9+ int fd = open(path, O_RDONLY);10+ if (fd < 0) {11+ return 0;12+ }13+ int ok = fsync(fd) == 0;14+ close(fd);15+ return ok ? 1 : 0;16+}17+18+int koh_fsync_file(const char *path) {19+ return koh_fsync_path(path);20+}21+22+int koh_fsync_dir(const char *path) {23+ return koh_fsync_path(path);24+}vendor/shim/koh_fsync.h+19 −0
@@ -0,0 +1,19 @@1+/* Durability for the restore's temp-file-then-rename.2+ *3+ * V 0.5's `os` has no fsync. A rename is only durable once the bytes it points4+ * at are on disk and the folder's own entry has been synced; without both a5+ * power cut can leave an empty or partial file behind with the restore mark6+ * already gone. Two calls, because a file and a folder are opened the same way7+ * but synced for different reasons.8+ */9+10+#ifndef KOH_FSYNC_H11+#define KOH_FSYNC_H12+13+/* Syncs one file's contents; returns 1 on success, 0 on failure. */14+int koh_fsync_file(const char *path);15+16+/* Syncs one folder, making renames and unlinks inside it durable. */17+int koh_fsync_dir(const char *path);18+19+#endif