Repository navigation
Conversation
A fork's metadata is saved before the fork is brought to its target state. If Hypeman was killed in between, the fork stayed behind as an ordinary standby or paused instance: nothing marked it as unfinished, and a restore that was cut short kept its VMM, its memory and its vGPU. The caller had been disconnected without an answer and could not know the instance existed. A fork is now marked pending until its request succeeds, and pending forks are deleted at startup before the vGPU reconciler runs.
The pending mark now names the API process that is making the fork, by PID, start time and boot ID. The startup pass deletes a marked fork only when that process no longer exists. Without this, a second API process started against the same data directory, by mistake or to check a binary, would have deleted the forks that the running one was still bringing up.
… parallel A running-source fork whose source did not come back failed its request but stayed up under the requested name until the next restart deleted it. Delete it when the request fails. Recovery deleted interrupted forks one at a time before the API listened, each waiting on guest shutdown. Delete up to 8 at once, and log instances whose metadata cannot be read instead of skipping them silently. Report a failure to clear the pending mark as itself rather than as a target state failure.
A standby compression job cleared its plan by loading and saving the instance metadata without the instance lock. For a fork brought to standby, a job ending as the fork completed could save a copy read before the pending mark was cleared, and the next start would delete a fork whose caller got a success. The job now takes the lock if it is free and otherwise leaves the plan to the holder or to recovery. It cannot wait: a delete or restore holds the lock while waiting for it. Recovery also logs instances whose metadata cannot be stat'd.
A source that could not be restored and one whose guest agent did not come back each deleted the fork separately, and only the first was tested. Both now return to one delete. Recovery logs how many interrupted forks it deleted, failed to delete and left to a running owner, and how long it took. Startup warns if the instance manager cannot run it. Cloning stored metadata copies the pending mark instead of sharing it. The compression job comment said a plan left behind is cleared by the lock holder. A reader blocks the clear too and clears nothing, so the plan can stay until the next start.
Startup restarted compression for every standby instance with a plan before it deleted interrupted forks, so a fork cut short just after it reached standby had its snapshot compressed and then deleted. A fork that is still marked is now skipped.
A guest directory is copied with its metadata file. A snapshot of a fork that was still pending kept the mark in its payload, and a fork or restore cut short after the copy, before it saved its own metadata, left that file in place. At the next start recovery then deleted by it: in a fork's directory it stopped the guest the metadata names, and on a restored instance it deleted the instance. Recovery now skips a directory whose metadata names another instance, and a snapshot payload's copy of the metadata no longer carries the mark.
The mark was cleared with a write and a rename, neither synced. A host crash soon after could bring the earlier, marked metadata back, and the new boot ID then had recovery delete a fork whose caller got a success. Clearing the mark now syncs the file and the instance directory, and the fork request fails if it cannot.
Recovery read the mark, then checked the owner, then deleted. With another API process on the same data directory, that process could clear the mark, answer its caller and exit between the read and the check, and recovery deleted the finished fork. It now reads the mark again after the owner is gone, when it can no longer change.
The cleared metadata is renamed into place before its directory is synced. When that sync failed the request failed with the mark already gone, so a fork whose delete then failed as well stayed behind unmarked and no later start removed it. The mark is now saved again before the request fails.
A restore killed while its source directory did not exist leaves a bare link with no backup, so startup recovery does not see it. Once startup deletes the fork it pointed at, the link dangles, and every later aliased restore for that source failed with "file exists". Also say what is wrong when startup finds an ordinary directory beside a parked source, instead of a bare readlink error.
A restore killed while it had renamed its source aside leaves a backup and a link to the fork. If an older binary runs next and the fork is deleted, the link dangles, and startup refused to run on that layout. The backup is still the source, so remove the link and put it back.
The durable save held the alias reader lock across both syncs. A restore waiting to alias a source directory takes that lock for writing, and while it waits no metadata on the host can be read. The file and directory are now opened under the lock and synced without it.
A fork request that fails because its caller went away runs its cleanup with a cancelled context. A delete that stops on it leaves the fork up and marked until the next start.
Recovery only logged what it did. A fork it could not delete, or left to an owner that looks alive, still holds its VMM and vGPU, and nothing reported that across hosts.
A TAP that could not be released, or whose short name another guest shares, kept the pending fork: its VMM was gone but it stayed listed under the requested name until the next start. The TAP reconciler already deletes a TAP that no live instance claims, so the fork is deleted and the TAP is left to it.
A delete that failed to unbind a device kept the instance as the device's owner and then removed the instance. Nothing retries the release once the owner is gone, and a device attached to a missing instance cannot be given to another one until the next start. Only a pending fork is kept for a retry, so any other delete now clears its own attachment.
Recovery waited up to 2 s for each running fork's guest to shut down while the API was not yet listening. Nobody was given these guests, so only one holding a passthrough device, whose driver has to unload, is shut down first.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Want higher recall? High effort reviews run extra passes and find more bugs. A team admin can switch effort levels in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 2063699. Configure here.
| // A source that cannot be put back is left as it is and never resolves | ||
| // to another guest, so the rest of the host starts without it. | ||
| if err := instances.RecoverParkedForkSources(paths.New(cfg.DataDir)); err != nil { | ||
| slog.Error("failed to recover parked fork sources; they are left as they are until repaired", "error", err) |
There was a problem hiding this comment.
Parked backups listed as unknown guests
Medium Severity
Startup now continues when RecoverParkedForkSources cannot put a source back, so *.fork-bak.* directories stay on disk while the API serves. walkMetadataFiles treats those backups as guests, and ListInstances reports each as Unknown because loadMetadata rejects the ID mismatch. Exact lookup maps that same mismatch to 404, so the ghosts appear in the list but cannot be fetched or deleted through the API.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 2063699. Configure here.


Summary
A fork that was still being brought up when Hypeman was killed stayed behind as an ordinary instance, holding its VMM, its memory and its vGPU. A fork is now marked pending until its request succeeds, and at startup Hypeman deletes the marked forks whose API process is gone.
A fork from a running instance is also deleted, even if it is already running, when its request fails because the source did not come back. It used to stay up under the requested name.
Why it happened
A fork is made in two steps: its metadata is saved, then it is brought to the state the caller asked for. If the process dies in between, the fork stays wherever it got to. Nothing on disk says it is unfinished, so after the restart it looks like any other standby or paused instance. The caller was disconnected without a response and has no ID to delete.
For a QEMU guest with a vGPU this is expensive: a restore that was cut short keeps its VMM, the guest memory it had pinned and its virtual function until someone deletes the instance by hand.
What changes
StoredMetadata.ForkPendingis set when a fork's metadata is first saved, for instance forks and snapshot forks, and cleared once the fork has reached its target state. It names the API process that is making the fork, by PID, start time and boot ID. If clearing it fails, the fork request fails and the fork is cleaned up like any other failed fork, so a fork whose caller got a success is never still marked.RecoverInterruptedForksruns once at startup, before the API listens and before the vGPU reconciler starts. It deletes a marked fork only when the process named in the mark no longer exists: its PID is gone, belongs to a process started at another time, or was recorded before a reboot. When it cannot tell, it leaves the fork alone and logs a warning. It reads the mark again after the owner check and goes by that: another API process can clear the mark, answer its caller and exit between the first read and the check, and once it is gone the mark can no longer change.metadata.json. The shared metadata loader rejects records naming another guest, so an older partial copy cannot supply that guest’s control socket to the TTL reaper or an exact-ID lookup. The listing that vGPU claims and reconciles read skips such a directory instead of failing on it. That listing fails on any guest it cannot read, and a kill during a fork copy on an older binary leaves exactly this directory, so without the skip one of them would fail every vendor VFIO claim on the host. A directory holding another guest's metadata cannot have a VMM of its own, so there is nothing in it to account for.flock) on the data directory before it reads or writes anything in it, and exits if another process holds the lock. Instance locks exist only inside one process, so a second API process on the same directory could save over the first one's metadata. Older binaries do not take the lock, so the old process has to be stopped before this one starts (DEVELOPMENT.md). The configuration is now loaded once, so the directory that is locked is the one the rest of startup uses.<id>.fork-bak.<time>and links the source path to the fork while the snapshot loads. A kill there left the source ID resolving to the fork.RecoverParkedForkSourcesruns under the lock, before instances are listed, and renames the backup back. It acts only when the link points at a Firecracker fork that records that source and has no running owner. For any other layout (two backups for one source, an ordinary directory at the source path, a link to something else) it leaves that source as it is, logs an error naming it and goes on to the others. The API still starts: the metadata loader never resolves a source's path to another guest, so a source left parked is missing and every other guest is unaffected. It stays that way until its directory is repaired.Forks that completed are not touched, and a graceful restart still lets in-flight forks finish.
The owner check was added before the data directory lock. With the lock, a second API process of this version cannot start against the same directory: the binary has no flags, so running it to look for a version used to start a second server, and now exits at the lock. The check stays as a second guard, because recovery is in
lib/instancesand cannot tell whether its caller holds the lock.Testing
For the follow-up fixes: eight regression tests passed locally in a non-root container with all capabilities dropped and no devices passed through. A separate Linux test with
/dev/net/tunandNET_ADMINin a private network namespace created real TAPs and verified that recovery removes a fork's TAP with the fork, and deletes the fork but leaves the TAP when another guest shares its short name. The VFIO tests used a fake binder, not a physical PCI device. The build, vet of the changed packages, targeted instance tests and thelib/devices,lib/networkandlib/forkvmpackage tests also passed. The full hypervisor suite was not rerun for this follow-up.TestForkIsPendingOnlyUntilItsRequestSucceedscovers the mark through an instance fork, a snapshot fork, a fork left half-made and a snapshot of that fork.TestRecoverInterruptedForksDeletesOnlyForksWhoseProcessIsGoneruns the startup pass over a fork whose process exited (deleted), one whose process is still running (kept) and a finished one (kept). Two more tests cover the owner check: an exited process, a reused PID, an earlier boot, and a live PID with nothing else recorded.TestRunningForkIsDeletedWhenItsSourceDoesNotComeBackfails the source restore after a fork and checks the fork is gone and the source is kept. A source whose guest agent does not come back returns through the same delete.TestRecoverInterruptedForksDeletesConcurrentlyholds three deletes open and checks all three are in flight together. Each fails when its change is reverted (no delete on a failed source restore; a concurrency limit of 1).TestCompressionJobLeavesLockedInstanceMetadataAloneends a compression job while the instance is locked and checks the job wrote nothing, then ends one unlocked and checks the plan is cleared and the mark kept. The recovery test now also covers an instance whose metadata fails stat and one whose metadata does not parse: both are kept and both are named in the log.TestRecoverPendingStandbyCompressionJobsSkipsPendingForkchecks that startup starts no compression job for a marked fork. Each of these fails when its change is reverted.TestRecoverInterruptedForksLeavesDirectoryHoldingAnotherInstancesMetadatacopies a pending fork's directory the way an interrupted fork does, lets the source finish, and checks that recovery deletes nothing and detaches none of the source's devices.TestRecoverInterruptedForksKeepsForkFinishedSinceItsMarkWasReadclears the mark between recovery's read and its owner check and checks the fork is kept.TestForkFailsWhenClearingItsMarkCannotBeSyncedfails the directory sync and checks the request fails and the fork is deleted, and that a fork left in place after the failed sync is still marked.TestForkIsPendingOnlyUntilItsRequestSucceedsnow also reads the metadata file in the payload of a snapshot of a pending fork. Each fails when its change is reverted.TestServerRefusesSecondWriterBeforeStartupstarts the server in a subprocess against a locked data directory, reached through a symlink, and checks it exits at the lock without creating anything.TestRecoveryRestoresParkedFirecrackerSourcecovers a parked source with its link and one with only the backup, and four layouts that must be refused and left untouched: a link to another fork, a fork whose owner is running, an ordinary directory at the source path, and two backups.TestWithSnapshotSourceDirAlias_ReplacesDanglingAliasruns an aliased restore over a dangling link, and fails with "file exists" when the removal is reverted.TestParkedSourceRecoveryGoesOnPastASourceItRefusesparks two sources behind one fork that records only one of them, and checks that one is put back, the other is left with its link and backup and resolves to no instance, and the error names only the refused one.TestReconcileListingSkipsDirectoryHoldingAnotherInstancesMetadataruns the vGPU listing over a copy of a source's directory, once with the source present and once with it deleted.TestAbandonedForkCannotBeStartedOrRestoredchecks that a finished fork and one whose owner is running pass, and that start and restore are refused for an exited owner and for the mark that names no process.TestForkItsRequestCannotDeleteIsAbandonedfails a fork's delete on a busy device and checks the mark is rewritten, the fork is refused, and the next recovery deletes it. Each fails when its change is reverted. These four ran locally without VMs; the tests inlib/instancesthat boot guests could not run there and were left to CI.TestRecoveryLeavesInheritedPCIDeviceWithOwnerdeletes an interrupted fork whose device list names a device attached to its source and checks the device record is unchanged.TestReleaseInstanceDeviceKeepsOwnerUntilUnboundchecks that an unbind failure retains the owner and that a retry can finish.TestDeleteFreesPCIDeviceWhenReleaseFailsdeletes an ordinary instance whose release fails and checks the device is left unattached, andTestDetachInstanceDeviceFreesOnlyItsOwnersDevicechecks that only the owner's attachment is cleared.TestRecoveryDeletesForkWhenTAPReleaseFailsfails the TAP release and checks the fork is deleted.TestRecoverInterruptedForksShutsDownOnlyGuestsWithPassthroughDevicesrecovers a running fork with and without a device and checks only the first is asked to shut down. Each fails when its change is reverted.TestRestoreSnapshotCannotReplacePendingForkandTestSnapshotPayloadNeverCopiesPendingMarkcover the two snapshot guards.The fork and snapshot tests in
lib/instances(102, among them the fork, warm fork chain and snapshot tests that boot cloud-hypervisor, Firecracker and QEMU guests) pass on a KVM host with the sync in place.A script doing the same write, sync, rename and directory sync as the durable save, on a host's XFS data disk, took 0.32 ms at the median against 0.07 ms unsynced, and 2.6 ms against 1.2 ms with 25 writers at once (p99 6.0 ms against 3.5 ms).
Nine mutants each fail at least one of them: the mark never cleared for either kind of fork, the mark kept in snapshots, the mark not naming the process, recovery ignoring the owner, recovery deleting nothing, and the owner check ignoring the PID, the start time or the boot ID.
On a host with two GPUs I killed Hypeman with SIGKILL while four vGPU snapshot forks were restoring, on a build of Add opt-in vGPU snapshots and forks on a managed QEMU runtime #552 plus this change:
No VMM, virtual function, TAP or guest directory was left in any case, and the next fork passed. Without the change the same kill at 1.0 s left two forks
Pausedand two inStandby, with two VMMs still holding two virtual functions (two runs).Not covered
Unknown, and the API cannot delete it, as for any guest whose metadata cannot be read.Note
High Risk
Changes core startup ordering, single-writer data-dir locking, fork lifecycle recovery, VFIO passthrough release, and network teardown—areas where mistakes can leak GPUs, TAPs, or delete usable instances.
Overview
This PR prevents half-finished forks from surviving API crashes by marking new forks with
fork_pending(owning API PID, start time, boot ID), durably clearing that mark only after the fork request succeeds, and runningRecoverInterruptedForksat startup (before serving requests / vGPU reconcile) to delete marked forks whose owner is gone—up to 8 at a time, with passthrough devices getting a longer guest shutdown window.Startup is hardened with an exclusive
flockon the data directory (second API exits immediately),RecoverParkedForkSourcesfor Firecracker snapshot alias backups, and refusal of start/restore on abandoned or in-flight forks. Failed running-fork flows delete the fork when the source cannot be restored; snapshot/instance copies omitmetadata.jsonand never propagate the pending mark.Passthrough and network cleanup is tightened: instance delete uses owner-aware
ReleaseInstanceDevice/DetachInstanceDevice, VFIO unbind is verified in sysfs before clearing attachments, orphan reconcile keeps ownership until unbind is confirmed, and interrupted forks can release TAPs by instance ID when allocation metadata is missing. Related fixes include stricter vz-shim discovery on Darwin, metadata ID mismatch handling for partial copy directories, and compression jobs that avoid clobbering fork metadata without the instance lock.Reviewed by Cursor Bugbot for commit cd62612. Bugbot is set up for automated code reviews on this repo. Configure here.