Repository navigation
cut: whole-repo LOC round, plus a stable image list order - #347
Merged
Merged
Conversation
Generate is the only caller and writes meta-data, user-data and network-config: all three are lowercase and longer than eight characters, so every name took the long-name path. needsLFN, toShortName and splitName go; a name that would fit 8.3 now gets a long-name entry and a numbered short name, which is valid VFAT.
…n interface and five forwarders The runner interface had one implementation, Module[S], and existed only so that the orchestrator could hold modules of different S. Register is a generic method, so it builds the erased form itself. gc.Module, gc.New and Register are unchanged.
…and load The three verbs opened with the same sequence: resolve the ref, take the VM ops lock, load the record through the entry guard, unlock on error. lockEntry owns it. Order and errors are unchanged; capture and restore still validate the record invariants after it.
Each backend carried the same closure: force terminates, otherwise ask the guest to power off, wait the stop timeout, then terminate. Backend.GracefulStop now builds that hook from the two calls that differ (the power-off request and the terminate). StopSpec had one field, so the stop sequence takes the hook itself.
… clone's disks in one pass activeDisks built a second slice that buildVMConfig ranged once; the skip moves into that loop and the launch path loses one allocation. patchRawObject was a generic decode-edit-encode helper with one caller. The COW, data and cidata path updates were three loops over the same slice; retargetCloneStorage does them in one, as the Firecracker clone already does. The cidata path is now set before the blob lookup, which reads only layer paths or the overlay header.
The error for a bad value now starts with "invalid", like every other size flag.
…convergeDeadRecord use it Both wrote updateVM's get, mutate, put and publish-after-commit transaction by hand only because each has a no-op branch that must not write. The mutate closure now returns whether to write; the no-op branches return before Put as before, metering entries still publish only after commit, and gen is still reset at the start of every attempt. emitAll had no caller left.
The hand-written view that copied out the VM and its generation is the same single-record read PeekRecord already does. Same skip conditions, same VM pointer handed to the quiesce, same fenced clear and error text.
finalizeCreate spelled out UpdateRecord's get, mutate and put by hand; FinalizeClone already finalizes through UpdateRecord. The written record is the same: the VM is replaced whole, boot config and blob IDs are set, run and log dirs are kept, and the creating placeholder never carries a quarantine or a pending quiesce, so keeping those fields changes nothing.
The hand-written view with its two-variable block is the shape viewValue already provides, as its sibling readers in the same file use. One view transaction, the same resolve and load errors, and the same id and record on every path.
…ugh utils.OrDefault Both methods hand-rolled OrDefault's value-or-default-when-not-positive on an int. The defaults become seconds and the result is the same duration for every input.
…e backends progress/oci and progress/cloudimg each declared a Phase and an Event, and NewTracker type-asserted every event so a tracker dropped the other backend's type. Every tracker is paired statically with its backend, so the filter never fired; one Event carries the union of the fields and each emitter fills the same fields as before. progress.Nop keeps its name.
…r import importTarLayers and importTarFromReader each emitted the pull event, made the import work dir, built a tarImportJob and finished the import; they now share importTars and differ only in how one job reads its tar. The file form is unchanged; the stream form runs its single job through utils.Map, and its error prefix changes from "process layer" to "process layers".
…' gc.go go Each backend kept a gc.go whose GCModule and RegisterGC only built images.BuildGCModule from the embedded Ops config. Ops now owns RegisterGC and takes the OCI boot-dir scan and remover as ExtraDisk and ExtraRemovers, so BuildGCModule receives the same config field for field, with the removers in the same order.
pullOCI and pullCloudimg each built a tracker, called the backend's Pull and wrapped the error as "pull <ref>"; the loop now picks the backend and tracker and makes that call once, and pullCloudimg becomes the tracker constructor cloudimgPullTracker. OCI now receives the force flag, which its Pull ignores; log lines, logger name and error text are unchanged.
… and terminate primitives Both backends carried the same Stop, stopOneLocked and stopHook and a Delete that forwarded to DeleteAll, differing only in the shutdown press and the terminate method. Backend now holds those two primitives, set in each New, and builds the same GracefulStop hook per call from the same config pointer, so stop and delete run the same calls in the same order.
…e directly Each backend re-wrapped its terminate method as HibernateSpec.Terminate and as the killForRestore PID hook (Firecracker through one more terminateVMM forwarder), every copy computing the socket path from the same record. HibernateSequence and KillForRestore now call b.Terminate with the same ctx, socket path and pid at the same point, so HibernateSpec and the per-backend wrappers go.
Cloud Hypervisor's getVMInfo and getVMCounters and Firecracker's getJSON were the same GET, expect 200, decode, with the same "query"/"decode" error wraps, differing only in endpoint and result type. utils.GetJSON[T] does it once with the same URL and error text; the only difference is that Firecracker's getters now return a nil result alongside an error, and every caller checks the error first.
DoAPIOnce only picked a default 204 primary code and turned a status in codes[1:] into a nil result after DoAPI built an APIError for it; neither retries. DoAPI now takes the codes itself and returns the tolerated status as a nil body at the same point, so single-code callers and every error value and text are unchanged.
…unning copies Cloud Hypervisor's runningInfo and Firecracker's BalloonStatus both resolved a running VM's client, mapped ErrNotRunning to a nil result and then ran one API query. Backend.RunningQuery[T] runs the same calls in the same order and returns the same values, with the query passed in.
chDebugSpec and buildCHDebugSpec only moved four flag reads from Debug into printCHDebug and printCommonCHArgs; the print functions now read the flags themselves, as printFCDebug already takes its inputs directly. The --ch precedence over ch_binary, the balloon gate and every printed byte are unchanged.
… subcommands The three detach subcommands were built from the same nine lines and differed only in Short, the key flag, its usage and RunE. The command tree, flags, required marks and --output are unchanged; help and error output of all three are byte-identical.
List restated the one-shot branch of Status: list takes no args and defines no --watch, --event or --interval, and the cliutil flag readers return false and 0 for an undefined flag, so Status lists once with no filters. The only order change: an invalid --format is now reported before a hypervisor init failure; both errors keep their text.
…OutputJSON MaybeOutputJSON only wrapped WantJSON and OutputJSON in a (bool, error) pair that both callers unpacked again; runClone already writes the direct form. The same JSON is written in the same cases and the same error is returned, the JSON write error first.
Run restated refreshVM's inspect-or-keep inline; Inspect never returns a nil VM without an error, so the JSON payload is the same in every case. refreshVM now logs at warn level with "refresh VM <id>: <err> (output may be stale)", replacing run's "inspect after start failed" warning; a failed refresh after a clone NIC resize, logged at debug before, is now a warning too.
…re tail The stream path of Restore restated runDirectRestore line for line except for the backend call; runRestore now takes that call as a restoreFn, named like cloneFn. Log text, error wrap, reseed and output are byte-identical, and the closures do not escape, so restore gains no allocation.
copyNamespace rescanned every table of the source namespace right after canonicalDigest had scanned it under the same exclusive lock; canonicalDigest now returns its rows, sorted by id per table, and copyNamespace writes those. The digest bytes are unchanged, so manifests written by an earlier binary still verify; the copy now writes exactly the rows that were hashed, in id order inside the same durable update.
The nil-checked testCrashStep var plus its crashStep wrapper become one var whose default returns nil; every protocol step calls it as before. The test hook saves and restores the default instead of resetting it to nil.
…default and usage Each flag was written three times: its definition, its BindPFlag and the SetDefault of the same key further down. The table registers the same flags with the same usage, binds the same keys and sets the same defaults, so every key stays registered for the environment binding; resolved settings under defaults, COCOON_* overrides and flags, and the help output, are unchanged.
…s one segment tarFileMaybeSparse and rewindAndTarFull both built the same FileInfoHeader and wrote the entry. sparseSegments now decides the map: the whole file is one segment when sparse cannot help, and the single writer seeks to each segment start, so the rewind is the first seek. Archive bytes are the same for sparse and plain entries; on the plain path the seek and copy errors now read "seek X to 0" and "copy segment at 0 len N from X".
The reflink copy and both SparseCopy builds each ended their callback with the same dst fsync in Sync mode. CopyWithCleanup now takes the SyncMode and runs that fsync after the callback and before the deferred close, so a sync failure still removes dst; NoSync returns at the same point with no extra syscall. The darwin SparseCopy sync error gains the "sync dst: " prefix the Linux builds already had.
…ated SyncParentDir repeated SyncFile's open, fsync and close and only added the EINVAL, ENOTSUP and EBADF tolerance. It now calls SyncFile and filters the same errnos; errors.Is sees through SyncFile's join. The close error of the read-only directory fd, ignored before, is now returned.
…ing firstNIC ResolvedNetnsPath and ResolvedNetBridgeDev each repeated the nil-NIC branch that returned the VM-level field. firstNIC now returns NIC 0 by value, zero when there is none or it is nil, so cmp.Or with an empty NIC field yields the VM-level field as before. ResolvedNetBackend keeps its explicit branch because its no-NIC answer is the VM-level backend, not the CNI default.
…cni in-netns delete call it Both looked a TAP up by name, treated LinkNotFoundError as success and deleted it, the cni copy inside the netns. DeleteTAP owns that sequence with the bridge's error texts, and the cni teardown drops its own "delete tap" wrap so a LinkDel failure still carries one prefix. The cni lookup error now reads "find tap X" (was "find X"), and a netns-entry error in teardown no longer gains the "delete tap X" prefix.
…Scope goes View and Update walked the scope against the declarations before forScope, whose fast path can only hit namespaces it prepared from those same declarations. forScope now checks them on its slow path before preparing anything, with the same error text; the fast path does less than before.
Both readers checked the read scope and then looked up the table statements, each with its own early return. readable does both in the same order with the same errors, replacing checkRead.
…sting InitIfMissing's locked closure and InitForRecoveryIfNeeded ran initNeeded and then initStore, which ran it again. initStore now returns nil for an existing store unless refuseExisting (Init) is set; the lock, the busy retry and the unlocked fast path are unchanged. A not-needed path now also runs EnsureDirs and CheckFS first, which can refuse only what the next open refuses with the same text.
Both verbs resolved the namespace set, took the flocks through withLocked and loaded every model before their own work. withLoaded does the three in the same order with the same errors and replaces withLocked; Update now reads its target state before resolve, a plain map read that is unused when resolve fails.
… default Each package kept a nil hook var plus a six-line wrapper that nil-checked it before every protocol step. The wrapper's name is now the var itself, defaulting to a func that returns nil, so every step returns what it returned before; tests restore the saved default instead of nil.
…ollect Collect took an accessor, and BlobIDs and VMIDs were two identical type-assert adapters for it; all five callers wrote gc.Collect(others, gc.BlobIDs|gc.VMIDs). BlobIDs and VMIDs now take the snapshot map and share collect, which skips snapshots that do not implement the interface where the adapters returned a nil map, so the union is the same.
convergeDead and convergeExit both took the ops lock, peeked the record, confirmed the VMM dead and landed ConvergeDead with the same error and warning lines. convergeLocked does it once; a nil exit event is the reconcile path (record generation, time.Now, warn only on an open interval), a non-nil one fences on its generation and dates the stop from its observation. The two log lines now carry the daemon.convergeLocked tag; their text is unchanged.
…List It read cpuset.cpus, skipped an empty value and parsed it by hand, which ReadCPUList already does; an empty placement parses to nil and never matches. The error renders the parsed set with FormatCPUList, the same canonical range form the kernel prints.
List walked the index map, so the images of one backend came back in a different order on each call, in the table and in JSON. It now walks the refs in sorted order. Found on hardware: two reads of one store by the same binary printed the two cloud images in swapped order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A whole-repo volume round on v0.8.1 + #346. Every production file was read twice: once for dead code, duplication, single-user abstractions, hand-rolled standard library and unreachable guards, and once for code that exists two or three times in slightly different types. The folds that survived a check against the source are here, one commit each: 42
cutcommits. No feature, no new mechanism, no behaviour change beyond the eight text and log changes listed below.One more commit is not a cut:
fix(images): image list prints in a stable order. The hardware run compared this branch with master and foundimage listprinting the two cloud images in a different order from one call to the next. The bug is in master too (the list walked a Go map). It is fixed here as its own commit with a test that fails without it; say the word and it moves to its own PR.Comments are 4 % of the production code, so this is logic, not comments. No test was deleted and no assertion was changed; the 76 test lines that changed follow renamed symbols and changed signatures.
Where the lines went
One owner for code both backends repeated (-142)
Backend.GracefulStop.Backendholds the two calls that differ per VMM (Press,Terminate), soStop,Delete, the hibernate terminate and the restore kill are written once.StopSpecandHibernateSpecare gone.utils.GetJSON[T]replaces three copies of GET, check 200, decode.Backend.RunningQuery[T]replaces two copies of "query a running VM, nil when stopped".utils.DoAPItakes the tolerated status codes thatDoAPIOnceadded.activeDisksandpatchRawObjecthad one caller each and are inlined.lockEntry).The shared
hypervisorpackage (-54)updateVMtakes a write flag, soReconcileToRunningandconvergeDeadRecordno longer restate its transaction.quiesceIfPending,finalizeCreateandResolveAndLoadusePeekRecord,UpdateRecordandviewValue, which already existed.Images, progress and gc (-108)
progresspackage with oneEventand a typedTracker;progress/oci,progress/cloudimgand the runtime type filter are gone.progress.Nopkeeps its name.images.Ops, which both backends already embed; bothgc.gofiles are gone. The OCI tar import has one driver for its file and stream forms.image pullmakes onePullcall through the interface.gc.Registererases the snapshot type with closures, without an interface and five forwarders.gc.BlobIDsandgc.VMIDsshare one generic collector.CLI (-106)
vm debugprints from its flags without a carrier struct. The three detach subcommands share one builder.vm listrunsStatus. The two restore forms share one tail.meta convertwrites the rows its digest pass already read, which drops one full scan of the source per namespace. The seven root flags are one table instead of three runs of lines.Meta store (-50)
ViewandUpdateshare the resolve, lock and load. The three test crash hooks are func vars with a no-op default.The rest (-91)
CopyWithCleanupowns the fsync its three callers repeated.network.DeleteTAPnext toCreateTAP. The daemon's reconcile and exit paths share one locked converge. The FAT12 writer drops an 8.3 short-name branch that no caller reached.What changes for a user
Eight texts, nothing else:
gc --snapshot-sizewith a bad value saysinvalid --snapshot-size ..., like every other size flag.image importfrom stdin: the error prefix isprocess layers:(wasprocess layer:).vm run -o jsonor after a clone's NIC resize logs a warningrefresh VM <id>: ... (output may be stale)(the run path warned with other words; the clone path logged at debug).daemon.convergeLocked.find tap <name>(wasfind <name>), and a failure to enter the netns no longer carries thedelete tap <name>:prefix.SparseCopy's fsync error gains thesync dst:prefix it has on Linux.copy segment at 0 len <size> from <path>: ...(waswrite data <name>: ...), and a failed seek readsseek <path> to 0: ....meta.json.withLoaded(wasmeta.json.withLocked).One more difference has no reachable trigger:
SyncParentDirnow returns the error of closing the directory handle, which it used to ignore. Closing a read-only directory handle does not fail on a local filesystem.Go API, for importers:
progress.Trackerisfunc(progress.Event)andprogress.NewTrackeris gone;gc.Collectis gone andgc.BlobIDs/gc.VMIDstake the peer map;cliutil.MaybeOutputJSON,utils.DoAPIOnce,hypervisor.StopSpecandhypervisor.HibernateSpecare gone;utils.CopyWithCleanuptakes the sync mode;hypervisor.BackendConfiggainsStopTimeoutandForceStop. cocoon-macos uses none of the removed symbols (it usesprogress.Nop,gc.New,gc.Module,cloudimg.New,ReflinkCopy, which are unchanged).Hot paths
No fold adds a syscall, a store transaction, a fork or a heap allocation to clone, start, stop, restore or rm. Three remove work: the sqlite transaction entry loses a map walk, Cloud Hypervisor's launch loses one slice allocation,
meta convertloses a scan. Readers proposed five more folds that would have added a closure allocation or changed a crash window on those paths; they are in the list below, not in the diff.Proposed and not taken
Each was worked out with arithmetic and then rejected against the source:
Collection.Getreturning nil when absent, removingCollection.Replace, folding the stderr metering recorder into the file recorder,signalReseed's result,meta.Seq,NamedTx.NameDel,utils.CheckSocket,convert.Spec.MetaRoot.tombstone.Acquireland the deleting phase in one commit (it changes what a crash between the two commits leaves, and an earlier measurement found no gain from the merge).network/cni, the restore compute-stop throughupdateVM, a variadic check list onlockEntry.release(*error)func for the two snapshot sequences.meta.ErrIO/meta.ErrNoSpace, the json engine's undeclared-table refusal, thedisk_attach_fileskey of the export format.A mechanism inventory over the 48 commits since the last cut round found 78 protective or recovery mechanisms and nothing to cut: each has an incident, a measurement or a feature contract behind it, or costs three lines or fewer. One is left for the maintainer:
vm resizelanding its record on a detached context after the disk grew (5 lines, #346). A rerun of the same resize already converges without it; it is kept here because it matches whatvm startdoes.Evidence
Run on the branch head
8180c2ec:GOWORK=off make lint(linux and darwin)0 issues.twiceGOWORK=off make fmt-checkasl -forwarder=false ./..., both GOOSgo vet ./..., both GOOSgo mod tidy -diffgo test -race -count=1 ./..., darwingo test -race -count=1 ./..., linux/arm64 container with e2fsprogs, qemu-utils, erofs-utilsA flow re-read of the final diff, commit by commit against master along each entry point (order of side effects, crash windows, locks, contexts, errors, both backends, both engines): 43 commits, 40 behaviour-neutral, 3 with a note. The three notes are items 7 and 8 above and the
SyncParentDirclose error; none changes what a verb does.Equivalence checks made while applying, each with throwaway code that is not in the diff:
vm debug: byte-identical output from the old and the new code over 60 flag and image combinations.meta convert: same digest and row count on a 328-row source, on both engines.--helpof the detach subcommands, ofvm listand of the root command: identical.Hardware
One run on a bare-metal host (Cloud Hypervisor and Firecracker from the fork's 2026-11-30 backups, pinned by sha256), in a private kit: own root, network scope, cgroup slice and bridge, no route out. Two binaries built the same way, the candidate at
b1916932(all 42 cuts) and the control at masterb5f3170d, and every step run with both. The comparison was pre-registered: a line where the candidate differs from the control is a FAIL and stays one.8180c2ecWhat passed with both binaries, candidate equal to control:
--timeout 10: 10.1 to 10.2 s, the escalation line logged, exit 0, state stopped) on all four combinations. Windows: three graceful stops of one guest by control, candidate, control took 33.3 s (first boot), 6.0 s and 7.7 s.fsck.fat -nclean with 4 files on both.--cpu 4 --storage 20G, cold boot, restore, hibernate, wake.vm startconverges on both backends; under the daemon the record reads stopped within the wait.meta convertsqlite to json and back, three round trips:vm listandsnapshot listidentical between the binaries at every step and unchanged by the round trip.vm debugin three shapes and five help texts identical between the binaries.The 14 FAIL lines, all kept as FAIL in the record:
snapshot.jsonwith the export time as its mtime. The member-by-member comparison above replaces it.image listorder. Two reads of one store printed the two cloud images in swapped order, between the binaries and within master alone. With the fix, 20 calls print one order (table and JSON); master and the candidate without it print two.Timing sequence, trimmed mean in ms (control / candidate / control copy / candidate copy): clone 80.8 / 78.5 / 84.0 / 82.2; start 49.7 / 48.6 / 47.8 / 47.2; stop 90.5 / 92.1 / 93.6 / 89.6; cold start 89.4 / 96.0 / 87.4 / 84.6; rm 82.2 / 89.9 / 83.6 / 82.1; whole sequence 502.6 / 530.2 / 507.8 / 494.6. The two copies of the candidate differ by 35.6 ms on the whole sequence, more than candidate and control do, so no difference is claimed.
Store benchmark, median (control / candidate / control copy): sqlite update 60.1 / 58.1 / 56.7 us per durable update; json update 615 / 600 / 618 us; sqlite create 77.8 / 81.6 / 84.0 ms per 200 creates; json create 444.8 / 441.6 / 445.1 ms. The candidate's json update is 2.6 % under the control with a 0.5 % copy gap; everything else is inside the gap.
Not covered:
b1916932; the fix commit after it was run only in the last leg (image list, the convert comparison, the export comparison), not through the regression script or the timing sequence. It changes one loop inimages.listImages.