Skip to content

Idle suspension and wake

This page describes how the daemon suspends an idle sandbox and how the daemon wakes it. It is for a contributor who must change the rules for “idle”, the suspension, the wake, or the release of GPUs.

The code is in internal/sandbox/suspend.go. It uses the manager in internal/sandbox/manager.go and the snapshot code in internal/sandbox/snapshot.go. Read manager.md first. It explains the records, the lock m.mu, the lock opMu and the function boot.

A sandbox that does nothing holds the memory of its container and, more important, its GPUs. To suspend a sandbox, the daemon saves the files of the sandbox, removes the container and releases the GPUs. The sandbox keeps its ID and its record. The next call that needs the sandbox wakes it from the saved files.

The design has a cost:

  • A suspension keeps files only. It does not keep processes or memory. Thus the daemon suspends a sandbox only when no process runs in it.
  • The first call after a suspension waits for a full start of a container.
  • Each suspension adds one layer to the image below the container. An engine refuses an image with too many layers.
  • The saved files use disk space until the daemon removes the sandbox.

Suspension is off by default. A sandbox gets an idle time in one of two ways:

  • The client gives suspend_after_seconds in the create request (CreateRequest.SuspendAfter).
  • The daemon runs with --gpu-idle-suspend (Config.GPUIdleSuspend). This default applies only to a sandbox with GPUs.

A value of zero in the request means “never”, also on a host with a default. Create in manager.go makes these decisions.

Manager.idle gives the answer for one record. The caller holds m.mu. A sandbox is idle when all these conditions are true:

Condition Code Reason
The sandbox has an idle time. SuspendAfterSeconds > 0 Suspension is off unless something asked for it.
The image has no unsaved path. len(UnsavedPaths) == 0 A suspension does not save the volumes that the image makes for itself. The engine deletes them with the container.
The sandbox runs. State == StateRunning A paused sandbox has frozen processes that must not be lost.
A client owns the sandbox, and no kill is in progress. !hidden() A waiting sandbox and a copy of a fork in progress are not idle.
No command and no file operation is in progress. inUse == 0 See “The count of uses” in manager.md.
The last use was a full idle time before now. now - lastUsed >= SuspendAfterSeconds

idle does not ask the sandbox. Three more checks in suspend come after it:

  • No other operation holds opMu. A pause, a resume, a snapshot or a wake in progress is a use.
  • The record has fewer than MaxLayers layers.
  • The helper reports that no process runs.

A command can start a process and return. The process continues, and the daemon has no connection to it. inUse is then zero, but the sandbox does work. Thus the daemon asks the helper.

suspend calls m.ask(ctx, containerID, "procs", 30*time.Second). ask runs /.boxfork/guest procs in the container through Engine.Exec. The helper prints one number. The code is in internal/guest/procs.go.

countProcs counts the process directories in /proc. It does not count these processes:

  • process 1, which is the first process;
  • the procs process itself;
  • a process that ended and that its parent did not collect (state Z);
  • a helper that serves the kept connection, with the command line /.boxfork/guest serve.

The helper of the kept connection belongs to the daemon and does not make a sandbox busy. A command that this helper started is a normal process, and countProcs counts it. See kept-connection.md and helper.md.

suspend reads the answer in this way:

Answer What suspend does
0 It continues with the suspension.
A different number The sandbox stays. No log line.
No answer in 30 seconds, or an engine error The sandbox stays. The daemon writes a warning.
Text that is not a number The sandbox stays. The daemon writes a warning with the first 80 characters.

When the sandbox stays, the local function later sets lastUsed to the current time, if no use changed it. The daemon thus asks one time for each idle time, not on each pass of the loop.

The answer comes from code in the sandbox. A sandbox that keeps one process alive is never suspended and keeps its GPUs. That is the intended behavior: a job in the background keeps its sandbox for as long as the job runs.

Manager.Watch calls Manager.Reclaim one time each 2 seconds, in its own goroutine. Reclaim does nothing if snapshots do not work on the host (noSnapshots is not empty). If they work, it makes a list of the idle records under m.mu, sorts the list by ID, and calls suspend for each record.

sequenceDiagram
participant S as suspend
participant M as record (m.mu)
participant H as helper
participant E as engine
participant G as GPU allocator
S->>M: TryLock opMu, idle?
S->>H: guest procs
H-->>S: 0
S->>M: idle? lastUsed not changed? State = suspended
S->>E: Commit (temporary snapshot)
E-->>S: ok
S->>M: Disk = snapshot, ContainerID = empty, save
S->>E: Remove container
E-->>S: ok
S->>G: Release(sandbox ID)
S->>M: GPUs = nil, save
S->>M: release the snapshot of the suspension before

suspend does these steps. It returns true only if it suspended the sandbox.

  1. It tries opMu. If a different operation holds the lock, it stops.
  2. Under m.mu, it makes sure that the record is in boxes and that idle is true.
  3. It reads the container ID and lastUsed. It keeps lastUsed in the variable seen.
  4. If Layers is MaxLayers or more, it writes one warning, calls later and stops.
  5. It asks the helper the procs question. If the answer is not 0, it calls later and stops.
  6. Under m.mu, it makes sure that idle is true and that lastUsed equals seen.
  7. In the same hold of the lock, it sets State to suspended.
  8. It calls m.snapshot(ctx, id, nil, true, true): a temporary snapshot, with opMu held by the caller.
  9. Under m.mu, it sets Disk to the new snapshot and clears ContainerID. It calls save.
  10. It calls Engine.Remove for the container, with a limit of 1 minute.
  11. It calls Allocator.Release for the sandbox ID.
  12. Under m.mu, it clears GPUs and GPUVerified. It calls save.
  13. It calls unrefSnapshot for the snapshot that Disk held before.

Three points in this sequence are important.

Step 7 closes the door. From this step, use finds the state suspended and waits for opMu. No new command starts in the container. A command that comes now waits for the end of the suspension and then wakes the sandbox.

Step 9 comes before step 10. The daemon writes the record before it removes the container. If the daemon stops between the two steps, the state file knows the saved files. The next start removes the container as a container without a record. In the opposite sequence, a stop of the daemon loses the files.

Step 11 comes after step 10. The GPU allocator gets the GPUs back only when the container is gone. A GPU that a second sandbox gets while the first container runs is a GPU that two containers share.

Until step 9 succeeds, each failure puts the sandbox back. The local function back sets State to running and lastUsed to the current time. After step 9 there is no way back. The saved files are the sandbox, and the container is waste.

The context of the request does not cancel steps 8 and 10. The commit has a limit of 15 minutes, in snapshot.

What a suspension saves, keeps and releases

Section titled “What a suspension saves, keeps and releases”
Item What happens Where
The files of the container The engine commits them to the image boxfork-snapshot:<id>. A temporary snapshot record holds the image. snapshot, Engine.Commit
The files on mounted volumes They stay on the volumes. They are not in the snapshot. volumes.md
The files in volumes that the image makes for itself They are not saved. Thus a sandbox with unsaved paths is never idle. idle, unsaved
Processes and memory Lost. The daemon suspends only when procs answers 0. suspend
The container Removed. Engine.Remove
The GPUs Released to the GPU allocator. The record keeps the request in Want. Allocator.Release
The kept connection It ends with the container. kept-connection.md
The ID, the metadata, the limits of CPU and memory, the mounts They stay in the record. record
The timeout The clock continues. Sweep kills a suspended sandbox at its timeout. remove
The snapshot of the suspension before Released. The daemon deletes it if no other sandbox uses it. unrefSnapshot

The snapshot of a suspension is a temporary snapshot, as the snapshot of a fork is. ListSnapshots shows it with temporary set. MaxSnapshots does not count it. DeleteSnapshot refuses it with an InUseError while the sandbox exists, and SetPool refuses it as the source of a pool. See snapshots-and-forks.md.

A suspended sandbox counts for MaxSandboxes. Its record stays in boxes.

There is no “wake” call in the API. A call that needs the container wakes the sandbox.

Call Path in the code Wakes the sandbox
A command (Run, Exec) use Yes
A file operation (read, write, stat, list, mkdir, remove, rename) fsOp, use Yes
Resume setPaused, wakeLocked Yes. This is the way to wake a sandbox before you need it.
Pause setPaused, wakeLocked Yes, and then it pauses the sandbox.
Snapshot snapshot, wakeLocked Yes
Fork snapshot, wakeLocked Yes
Get, List No. They show the state suspended.
SetTimeout No. A client can extend the timeout of a suspended sandbox.
Kill remove No. There is no container to remove.

use runs a loop. When it finds the state suspended, it releases m.mu, calls wake, and examines the record again.

wake takes opMu. If a suspension is in progress, wake waits there for its end. Then wake examines the context of the request. If the client went away during the wait, wake returns the context error. A wake for no client takes the GPUs again for a full idle time, and nobody uses them.

wakeLocked does the work. Its caller holds opMu.

  1. Under m.mu, it makes sure that the record is in boxes and is not hidden.
  2. If the state is not suspended, it returns nil. A suspension that failed leaves the sandbox in the state running.
  3. If a container of this sandbox is in orphans, it returns an error. That container has the name and can hold the GPUs.
  4. It reads Disk and Want, and releases m.mu.
  5. It makes a context that the client cannot cancel, with a limit of 5 minutes.
  6. It calls boot with the image of Disk and with Want as the GPU request. It gives no environment.
  7. Under m.mu, it sets State to running and stores the new container ID, the GPUs, GPUVerified and Layers.
  8. It sets lastUsed to the current time and calls save.
  9. If save fails, it puts the record back to suspended, calls discard for the new container, and returns an error.
flowchart TD
A[use, setPaused or snapshot] --> B{State is suspended?}
B -- no --> Z[continue with the call]
B -- yes --> C[wait for opMu]
C --> D{client went away?}
D -- yes --> E0[context error, no wake]
D -- no --> F{orphan container?}
F -- yes --> E1[error: try again later]
F -- no --> G[boot from the image of Disk]
G -- fails --> E2[error, sandbox stays suspended]
G -- ok --> H[State = running, save]
H -- save fails --> I[discard the new container] --> E2
H -- ok --> Z

The client cannot cancel step 6, because a cancel in the middle leaves a container that no record knows.

boot is the same function that Create uses. See “The create path” in manager.md. At a wake:

  • The source is the local image of the snapshot. boot calls Engine.LocalImage and never pulls.
  • Allocator.Allocate gets Want: the same count, model and minimum memory as the create request. It can give a different device.
  • engineMounts makes sure that each volume of the record exists.
  • boot copies the helper of the current daemon into the new container.
  • NetworkReady, setDNS, giveVolumes and checkGPUs run again, as for a new sandbox.
  • The new container has the same name, boxfork-<sandbox ID>, and a new container ID.
Item After the wake
The files of the container Restored from the snapshot.
The mounted volumes Mounted again at the same paths, with the same read-only setting.
The ID, the metadata, the limits, the network setting The same.
The GPUs The same number and type, if the host has them free. The device can be a different one. gpu_verified comes from a new check.
The timeout Not changed. A wake does not extend the timeout.
Processes and memory Lost.
The environment variables of the create request The manager does not give them to boot at a wake. See “Not proven”.
The container ID New.
The kept connection The next command opens a new one.
The idle clock Starts again. lastUsed is the time of the wake.

MaxLayers is 100. suspend does not suspend a record whose Layers is MaxLayers or more.

Layers is the number of layers of the image below the container. boot reads it from the engine at a create and at each wake. Each suspension commits one more layer. The comment in the code says that an engine refuses an image at about 125 layers. The space between 100 and that number is for the snapshots and forks of the sandbox after its last suspension.

The count starts at the number of layers of the image. An image with 10 layers permits 90 suspensions.

When a sandbox is at the limit, the daemon writes one warning. The flag tooDeep prevents the same warning on each pass. From then on the sandbox runs while it is idle, and it keeps its GPUs. Commands, snapshots and forks continue to work. Layers is in the state file, thus the limit stays after a restart.

A suspended sandbox and the other parts of the daemon

Section titled “A suspended sandbox and the other parts of the daemon”
  • Kill. remove waits for opMu, sets dying and calls forget. forget releases Disk. The daemon deletes the image if no other sandbox uses the snapshot.
  • Timeout. Sweep tries opMu. If a suspension or a wake holds it, the next pass tries again.
  • Volumes. DeleteVolume refuses a volume that a suspended sandbox mounts. The sandbox needs it at the wake.
  • Fork. A copy gets the idle time of its original. wantsGPUs reads the GPU count from Want while the original is suspended. If the original has no GPU and no idle time, a copy with GPUs gets the default of the host.
  • Snapshot. A sandbox that a client creates from a snapshot does not inherit the idle time of the first sandbox.
  • Pools. A waiting sandbox has an idle time of zero. handOut sets the idle time of the request at the hand-out.
  • Reconcile. Reconcile ignores a record with no container.
  • Restart. See the next section.

New in manager.go handles the records of suspended sandboxes:

State file What New does
State suspended, no container ID, the snapshot in Disk exists It keeps the sandbox as suspended, clears GPUs, and counts Disk as used.
State suspended, no container ID, the snapshot in Disk is gone It drops the record and writes a warning.
State suspended, with a container ID, and the container runs It sets the state to running. The daemon stopped during steps 7 to 9.
The old container of a suspended sandbox still exists It removes the container as a container without a record.

New sets lastUsed of each record to the time of the start. The daemon suspends no sandbox immediately after a restart.

Race Guard
A pause, a resume or a snapshot is in progress when Reclaim looks. suspend uses opMu.TryLock and stops if it fails.
A command starts while the helper answers procs. Step 6 examines inUse again under m.mu.
A command starts and ends while the helper answers procs. done changes lastUsed. Step 6 compares it with seen.
A command comes after step 7. use finds suspended and waits for opMu in wake. Then it wakes the sandbox.
A command comes during a suspension that then fails. wakeLocked finds the state running and returns nil. use continues in the old container.
A kill comes during a suspension. remove waits for opMu. It then removes what exists: the container or only the record.
The record goes away during the commit. After the commit, suspend finds that the record is not in boxes and releases the new snapshot.
A timeout ends during a suspension. remove with onlyExpired uses TryLock. Sweep tries again one second later.
Reconcile has an old list of containers. reap uses TryLock, compares the container ID again, and inspects the container.
The commit takes longer than the idle time. snapshot sets lastUsed at its end. The time of the save does not count as idle time.
A sandbox wakes and Reclaim runs immediately. wakeLocked sets lastUsed. The sandbox has a full idle time.
The client goes away while it waits for a wake. wake examines the context after it gets opMu.
The client goes away during boot. wakeLocked uses context.WithoutCancel.
The daemon stops during the commit. The snapshot ID is in discarded before the commit. The record has a container, thus New sets it to running.
The daemon stops after the record is saved and before the container is gone. New keeps the suspended record and removes the container.
The engine removes the container but returns an error. suspend inspects the container. “Not found” means that it is gone.
The engine cannot remove the container. The container goes to orphans with the sandbox ID as owner. The GPUs stay held.
A wake starts while the old container exists. wakeLocked refuses the wake while hasOrphan is true.
A volume of the sandbox went away. engineMounts fails. The engine does not get the chance to make an empty volume.
Failure Result
The helper does not answer procs The sandbox stays as it is. The daemon asks again after one more idle time.
The engine cannot commit back sets the state to running. The daemon writes an error. The snapshot ID goes to the trash.
The container stops during the commit, but exists The commit completes and the suspension continues. reap cannot get opMu, thus Reconcile does not forget the sandbox.
The engine answers “not found” for the container during the commit snapshot calls engineErr, which forgets the sandbox. suspend writes no log line.
save fails in step 9 The record goes back to the old Disk and container ID. The sandbox continues in its container. The new snapshot is released.
The engine cannot remove the container, and the container exists The sandbox is suspended on its saved files. The container is an orphan and holds the GPUs and the name. retryOrphans removes it later.
save fails in step 12 The daemon writes an error. The record in memory is correct.
Failure Error that the client gets State after
No GPU of the requested type is free *gpu.ErrUnavailable: the sandbox “was suspended while it sat idle and cannot carry on until it has a GPU again”. HTTP 409 gpu_unavailable. Suspended, with its files
The image of Disk is not on the machine An error that wraps errFilesGone. HTTP 500 internal. Suspended. Each call fails until a kill or the timeout.
A volume of the sandbox is gone *StuckError. HTTP 409 sandbox_stuck. Suspended. Make a volume with that name, or kill the sandbox.
A container of the sandbox is in orphans An error: “cannot come back yet”. HTTP 500 internal. Suspended. Try again after retryOrphans removed the container.
A different step of boot fails An error: “is suspended and could not be brought back”. Suspended. discard removed the new container and released the GPUs.
boot fails and the engine cannot remove the new container The same error. Suspended. The container is an orphan, and the GPUs stay held.
save fails after boot An error: “recording that sandbox … is back”. Suspended. discard removed the new container.
The sandbox fails the GPU check The error of checkGPUs. Suspended. The allocator distrusts the GPU.

A StuckError exists because boot returns ErrVolumeNotFound, and the API changes that error to 404. A client that reads a file in the sandbox must not get “volume not found” for its call.

  1. The files of a sandbox are always in the container or in a snapshot that the record names.
  2. The daemon writes Disk to the state file before it removes the container.
  3. The daemon releases the GPUs only after the engine removed the container, or after an inspect answered “not found”.
  4. No command starts in a container after the state is suspended.
  5. The daemon suspends a sandbox only after the helper answered 0 to procs.
  6. suspend never waits for opMu. wake always waits for it.
  7. A failed suspension leaves the sandbox in the state running. A failed wake leaves it in the state suspended.
  8. A wake does not start for a client that went away.
  9. A sandbox with unsaved paths is never suspended, also when its record has an idle time.
  10. A sandbox has a maximum of one snapshot in Disk. The daemon releases the old one after each suspension.
  1. Put a condition that reads only the record in Manager.idle.
  2. Put a condition that needs the engine or the helper in suspend, between steps 3 and 6.
  3. If the condition stops the suspension, call later before you return false.
  4. Do not hold m.mu when you call the engine or the helper.
  5. Add a case to TestWhatKeepsASandboxFromBeingSuspended.
  1. If the operation runs a process in the sandbox, call m.use and call done at the end.
  2. If the operation gives a stream to its caller, connect done to the stream with released.
  3. If the operation changes the container itself, take opMu and call wakeLocked.
  4. Examine the record again under m.mu after wakeLocked returns.
  5. Add a subtest to TestOperationsOnASuspendedSandbox.
  1. Decide where the data lives while the sandbox has no container: in the snapshot or in the record.
  2. If the data goes in the record, add a saved field. See “Add a field to a sandbox record” in manager.md.
  3. Restore the data in wakeLocked, in the same hold of m.mu that sets the state to running.
  4. Put the old value back if save fails there.
  5. Do not put a secret in the state file.
  6. Add a test that restarts the manager between the suspension and the wake. Use TestSuspendedSandboxesSurviveARestart as the example.
  1. Keep these three rules: record before removal, removal before release of GPUs, state before commit.
  2. For each new step, decide what happens if the daemon stops immediately after it.
  3. Add a case to TestASuspensionThatFailsLeavesTheSandboxRunning for a step that can fail.
  4. Run TestSuspensionUnderLoad with -race many times.

The tests use the test engine and a clock that the test controls. A test moves the clock and calls Reclaim directly. The test engine answers guest procs itself. A test sets the field Procs of the test engine to give the answer.

File Content
internal/sandbox/suspend_test.go The main tests of suspension and wake
internal/sandbox/faults_test.go Engine failures and GPU failures during a suspension
internal/sandbox/kept_test.go TestASuspendedSandboxComesBackWithANewConnection
internal/sandbox/volume_test.go Suspended sandboxes and volumes
internal/sandbox/pool_test.go The idle time of a sandbox from a pool
internal/guest/procs_test.go countProcs on a prepared directory
internal/api/suspend_test.go The same behavior through the HTTP API, with the status codes
scripts/proof/conn.sh Step 9 of the proof script: a suspension and a wake on a real engine

The most important tests:

Test What it proves
TestAnIdleSandboxIsSuspendedAndComesBack The full cycle: not too early, the container is gone, the files are back, the old snapshot goes.
TestWhatKeepsASandboxFromBeingSuspended No idle time, a process that runs, no answer to procs, a command in progress, a pause.
TestACommandWhileTheSandboxIsBeingAsked The comparison of lastUsed with seen.
TestACommandDuringASuspension A command and a kill that come during the commit wait and then work.
TestSuspendingFreesTheGPU The release of the GPU, and the error when no GPU is free at the wake.
TestASandboxComesBackWithTheKindOfGPUItHad Want at the wake, and the GPU check at the wake.
TestASuspensionThatFailsLeavesTheSandboxRunning Failures of the commit, of save and of the removal.
TestComingBackThatFails Failures of boot, of save and of the snapshot image at a wake.
TestSuspendedSandboxesSurviveARestart, TestStateFilesFromTheMiddleOfASuspension The rules of New.
TestOperationsOnASuspendedSandbox Resume, pause, snapshot and fork of a suspended sandbox.
TestSuspendedSandboxesAndTheirTimeout The clock runs, and SetTimeout does not wake.
TestSuspendAfterIsChecked The checks of the idle time in Create.
TestSuspensionUnderLoad Commands, suspensions, the loops and kills at the same time. Each sandbox is whole at the end.
TestAContainerKilledButNotRemovedBySuspending The orphan container holds the GPU and blocks the wake.
TestARemovalThatReportsFailureButHappened The inspect after a failed removal.
TestASandboxSuspendedTooOftenKeepsRunning MaxLayers and the one warning.
TestAnImageThatKeepsFilesInAVolume Unsaved paths prevent a suspension.
TestNobodyIsBroughtBackForACallerWhoLeft wake examines the context.
TestSavingThatOutlastsTheIdleTimeIsNotIdleness lastUsed after a long commit.
  • Nobody ran a suspension or a wake on NVIDIA GPU hardware. The release and the new allocation of a GPU ran only with GPUs that are not real.
  • No test shows that a real GPU is free for a second container immediately after the engine removed the first container.
  • Nobody ran this code on x86_64, or on a real AWS or Google Cloud account.
  • The proof script ran a suspension and a wake on Docker with gVisor on arm64, in a nested virtual machine. That sandbox had no GPU and no volume.
  • The manager gives no environment variables to boot at a wake. If the variables of the create request stay depends on the commit of the engine. No unit test examines this.
  • The number of about 125 layers is from a comment in the code. No test finds the real limit of an engine.
  • No test measures the time of a suspension or of a wake. A wake does a full start of a container, and the first call waits for it.
  • procs reads /proc in the sandbox. In the unit tests, the test engine gives the answer. procs_test.go tests countProcs on a prepared directory. The real count in a sandbox ran only in the proof script.
  • The answer to procs comes from the sandbox. Code in the sandbox that controls the helper can give a wrong answer.