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.
The idea
Section titled “The idea”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_secondsin 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.
When a sandbox is idle
Section titled “When a sandbox is idle”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
MaxLayerslayers. - The helper reports that no process runs.
The procs question
Section titled “The procs question”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
procsprocess 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.
How the daemon suspends a sandbox
Section titled “How the daemon suspends a sandbox”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 beforesuspend does these steps. It returns true only if it suspended the sandbox.
- It tries
opMu. If a different operation holds the lock, it stops. - Under
m.mu, it makes sure that the record is inboxesand thatidleis true. - It reads the container ID and
lastUsed. It keepslastUsedin the variableseen. - If
LayersisMaxLayersor more, it writes one warning, callslaterand stops. - It asks the helper the
procsquestion. If the answer is not0, it callslaterand stops. - Under
m.mu, it makes sure thatidleis true and thatlastUsedequalsseen. - In the same hold of the lock, it sets
Statetosuspended. - It calls
m.snapshot(ctx, id, nil, true, true): a temporary snapshot, withopMuheld by the caller. - Under
m.mu, it setsDiskto the new snapshot and clearsContainerID. It callssave. - It calls
Engine.Removefor the container, with a limit of 1 minute. - It calls
Allocator.Releasefor the sandbox ID. - Under
m.mu, it clearsGPUsandGPUVerified. It callssave. - It calls
unrefSnapshotfor the snapshot thatDiskheld 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.
How a sandbox wakes
Section titled “How a sandbox wakes”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.
- Under
m.mu, it makes sure that the record is inboxesand is not hidden. - If the state is not
suspended, it returns nil. A suspension that failed leaves the sandbox in the staterunning. - If a container of this sandbox is in
orphans, it returns an error. That container has the name and can hold the GPUs. - It reads
DiskandWant, and releasesm.mu. - It makes a context that the client cannot cancel, with a limit of 5 minutes.
- It calls
bootwith the image ofDiskand withWantas the GPU request. It gives no environment. - Under
m.mu, it setsStatetorunningand stores the new container ID, the GPUs,GPUVerifiedandLayers. - It sets
lastUsedto the current time and callssave. - If
savefails, it puts the record back tosuspended, callsdiscardfor 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 --> ZThe client cannot cancel step 6, because a cancel in the middle leaves a container that no record knows.
What boot does at a wake
Section titled “What boot does at a wake”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.
bootcallsEngine.LocalImageand never pulls. Allocator.AllocategetsWant: the same count, model and minimum memory as the create request. It can give a different device.engineMountsmakes sure that each volume of the record exists.bootcopies the helper of the current daemon into the new container.NetworkReady,setDNS,giveVolumesandcheckGPUsrun again, as for a new sandbox.- The new container has the same name,
boxfork-<sandbox ID>, and a new container ID.
What a wake restores and what is lost
Section titled “What a wake restores and what is lost”| 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. |
The limit of layers
Section titled “The limit of layers”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.
removewaits foropMu, setsdyingand callsforget.forgetreleasesDisk. The daemon deletes the image if no other sandbox uses the snapshot. - Timeout.
SweeptriesopMu. If a suspension or a wake holds it, the next pass tries again. - Volumes.
DeleteVolumerefuses a volume that a suspended sandbox mounts. The sandbox needs it at the wake. - Fork. A copy gets the idle time of its original.
wantsGPUsreads the GPU count fromWantwhile 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.
handOutsets the idle time of the request at the hand-out. - Reconcile.
Reconcileignores a record with no container. - Restart. See the next section.
After a restart of the daemon
Section titled “After a restart of the daemon”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.
Races that the code guards against
Section titled “Races that the code guards against”| 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 cases
Section titled “Failure cases”During a suspension
Section titled “During a suspension”| 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. |
During a wake
Section titled “During a wake”| 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.
Invariants that a change must keep
Section titled “Invariants that a change must keep”- The files of a sandbox are always in the container or in a snapshot that the record names.
- The daemon writes
Diskto the state file before it removes the container. - The daemon releases the GPUs only after the engine removed the container, or after an inspect answered “not found”.
- No command starts in a container after the state is
suspended. - The daemon suspends a sandbox only after the helper answered
0toprocs. suspendnever waits foropMu.wakealways waits for it.- A failed suspension leaves the sandbox in the state
running. A failed wake leaves it in the statesuspended. - A wake does not start for a client that went away.
- A sandbox with unsaved paths is never suspended, also when its record has an idle time.
- A sandbox has a maximum of one snapshot in
Disk. The daemon releases the old one after each suspension.
How to change it
Section titled “How to change it”Change the conditions for “idle”
Section titled “Change the conditions for “idle””- Put a condition that reads only the record in
Manager.idle. - Put a condition that needs the engine or the helper in
suspend, between steps 3 and 6. - If the condition stops the suspension, call
laterbefore you return false. - Do not hold
m.muwhen you call the engine or the helper. - Add a case to
TestWhatKeepsASandboxFromBeingSuspended.
Add an operation that needs the container
Section titled “Add an operation that needs the container”- If the operation runs a process in the sandbox, call
m.useand calldoneat the end. - If the operation gives a stream to its caller, connect
doneto the stream withreleased. - If the operation changes the container itself, take
opMuand callwakeLocked. - Examine the record again under
m.muafterwakeLockedreturns. - Add a subtest to
TestOperationsOnASuspendedSandbox.
Change what a suspension saves
Section titled “Change what a suspension saves”- Decide where the data lives while the sandbox has no container: in the snapshot or in the record.
- If the data goes in the record, add a saved field. See “Add a field to a sandbox record” in manager.md.
- Restore the data in
wakeLocked, in the same hold ofm.muthat sets the state torunning. - Put the old value back if
savefails there. - Do not put a secret in the state file.
- Add a test that restarts the manager between the suspension and the wake. Use
TestSuspendedSandboxesSurviveARestartas the example.
Change the sequence of steps in suspend
Section titled “Change the sequence of steps in suspend”- Keep these three rules: record before removal, removal before release of GPUs, state before commit.
- For each new step, decide what happens if the daemon stops immediately after it.
- Add a case to
TestASuspensionThatFailsLeavesTheSandboxRunningfor a step that can fail. - Run
TestSuspensionUnderLoadwith-racemany times.
Where the tests are
Section titled “Where the tests are”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. |
Not proven
Section titled “Not proven”- 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
bootat 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.
procsreads/procin the sandbox. In the unit tests, the test engine gives the answer.procs_test.gotestscountProcson a prepared directory. The real count in a sandbox ran only in the proof script.- The answer to
procscomes from the sandbox. Code in the sandbox that controls the helper can give a wrong answer.