Skip to content

Commit 0bb1ea7

Browse files
authored
Persist Kubernetes sandbox uppers across pod recreation (#387)
* Persist Kubernetes sandbox uppers across eviction * Persist K8s sandbox uppers on pod termination
1 parent bdcb58d commit 0bb1ea7

9 files changed

Lines changed: 542 additions & 139 deletions

File tree

‎docs/architecture/chat-rendering-pipeline.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,8 @@ When the session is done streaming and has artifacts, the `embeddedArtifactPaths
258258

259259
PDF export uses `fetch()` + blob download (not `<a>.click()` navigation) because the backend PDF generation takes 5-15 seconds. The `<a>.click()` pattern causes the browser to show "Site wasn't available" for slow responses. The `fetch()` approach shows a loading spinner on the Download button during generation.
260260

261+
Artifact content lookup is best-effort across three sources: local host path, live sandbox backend `PullFile`, then persisted transcript `write_file` arguments. The transcript fallback is a recovery/cache path for historical artifacts; it does not prove that the file currently exists in a resumed sandbox. Direct K8s backends should read live files through the backend abstraction first so `/root/foo.md` refers to the composed sandbox rootfs, then fall back only if the live sandbox is unavailable.
262+
261263
## The Report Pipeline
262264

263265
Reports use a **two-step contract** combining `write_file` (which produces the file on disk and an `artifact` SSE event) with an explicit `astonish-report` fence emitted in the agent's reply text. Both signals are required: the file is the *content*, the fence is the *intent*.

‎docs/architecture/sandbox-backends.md‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -414,13 +414,16 @@ The entrypoint runs as PID 1 with the privilege path selected at chart-install t
414414
**Start / Stop** (decision Q1(b) — evict via tar stream to the uppers PVC):
415415

416416
- Sessions stay running while active. On idle timeout:
417-
- `StopSession` evicts: inside the pod, stream `/var/astonish/overlay/upper` to the uppers PVC via
418-
`tar --numeric-owner --xattrs --acls -I "zstd --adapt -T0" -C /var/astonish/overlay/upper -cf /mnt/astonish-uppers/<session-id>/upper.tar.zst .`
419-
then delete the pod.
420-
- Row in `sandbox_sessions` stays; status updated to `stopped`; `upper_persisted_at` is set.
421-
- On next user interaction, `StartSession` recreates the pod from the template; the entrypoint resume step (above) streams the persisted upper back into the local `emptyDir` before mounting the overlay. Resume latency: 1–5 s depending on upper-layer size.
422-
423-
This preserves Incus's "container exists but stopped, resume later" semantics.
417+
- Each session pod mounts only its own uppers PVC subdirectory (`subPath: <session-id>`) at `/mnt/astonish-uppers`. The full PVC root is not visible to the chrooted sandbox, so a session cannot enumerate or read another session's persisted upper directory through `/mnt/astonish-uppers`.
418+
- `StopSession` first marks the row `evicting`, then persists the live pod's writable layer by streaming `/var/astonish/overlay/upper` to that mounted session subdirectory via
419+
`tar --numeric-owner --xattrs --acls -I "zstd --adapt -T0" --exclude=/var/astonish/overlay/upper/mnt/astonish-uppers -C /var/astonish/overlay/upper -cf /mnt/astonish-uppers/upper.tar.zst.tmp . && mv .../upper.tar.zst.tmp .../upper.tar.zst`.
420+
Only after that capture succeeds does it delete the pod. If capture fails, the pod stays running so data is not lost.
421+
- The same persistence script is installed as a Kubernetes container `preStop` hook with a 90-second termination grace period. This covers manual `kubectl delete pod` and normal Kubernetes termination paths that bypass the backend's `StopSession` method.
422+
- Row in `sandbox_sessions` stays; status updates `evicting` → `evicted` and clears the pod binding after deletion. At eviction time, the original resolved layer chain is retained in the registry so resume does not silently fall back to plain `@base` for configured base/team-template sessions.
423+
- On next tool interaction, `StartSession` recreates the pod with the same `ASTONISH_SESSION_ID`; the entrypoint resume step (above) streams `/mnt/astonish-uppers/upper.tar.zst` back into the local `emptyDir` before mounting the overlay. Resume latency: 1–5 s depending on upper-layer size.
424+
- Isolation invariant: the persisted-upper path is derived only from the registry row's exact session ID. API callers never provide an upper path, unsafe session IDs are rejected before any pod/tar/cleanup script is built, and cleanup deletes only the validated session subdirectory.
425+
426+
This preserves Incus's "container exists but stopped, resume later" semantics while keeping each session's upper layer isolated under its own uppers-PVC directory.
424427

425428
**Destroy** (`DestroySession`) — the parity-critical operation:
426429

‎pkg/api/session_handlers.go‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ import (
1616
"strings"
1717
"time"
1818

19-
"github.com/gorilla/mux"
2019
"github.com/SAP/astonish/pkg/apps"
2120
"github.com/SAP/astonish/pkg/config"
2221
"github.com/SAP/astonish/pkg/credentials"
@@ -25,6 +24,7 @@ import (
2524
"github.com/SAP/astonish/pkg/sandbox"
2625
persistentsession "github.com/SAP/astonish/pkg/session"
2726
"github.com/SAP/astonish/pkg/store"
27+
"github.com/gorilla/mux"
2828
"google.golang.org/adk/session"
2929
)
3030

@@ -789,7 +789,7 @@ func StudioArtifactDownloadHandler(w http.ResponseWriter, r *http.Request) {
789789

790790
// Tier 2: Try reading from sandbox container
791791
if sessionID != "" {
792-
if content, ok := readFromSandboxContainer(sessionID, cleanPath); ok {
792+
if content, ok := readFromSandboxContainer(r, sessionID, cleanPath); ok {
793793
serveArtifactDownload(w, fileName, content)
794794
return
795795
}
@@ -870,7 +870,7 @@ func StudioArtifactContentHandler(w http.ResponseWriter, r *http.Request) {
870870

871871
// Tier 2: Try reading from sandbox container (if sandbox is enabled and session is provided)
872872
if sessionID != "" {
873-
if content, ok := readFromSandboxContainer(sessionID, cleanPath); ok {
873+
if content, ok := readFromSandboxContainer(r, sessionID, cleanPath); ok {
874874
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
875875
w.Write(content)
876876
return
@@ -904,16 +904,48 @@ func StudioArtifactContentHandler(w http.ResponseWriter, r *http.Request) {
904904
respondError(w, http.StatusNotFound, "file not found")
905905
}
906906

907-
// readFromSandboxContainer attempts to read a file from a sandbox container
908-
// using the Incus PullFile API. Returns the content and true on success.
909-
func readFromSandboxContainer(sessionID, filePath string) ([]byte, bool) {
910-
// Check if sandbox is enabled
907+
// readFromSandboxContainer attempts to read a file from the configured
908+
// sandbox backend. For direct K8s this uses Backend.PullFile, which targets the
909+
// session pod through the tenant-scoped registry. The legacy Incus path remains
910+
// as a compatibility fallback for deployments that still use the local Incus
911+
// client helpers.
912+
func readFromSandboxContainer(r *http.Request, sessionID, filePath string) ([]byte, bool) {
913+
if sessionID == "" || filePath == "" {
914+
return nil, false
915+
}
916+
917+
if backend, cleanup, err := sandboxBackendForRequest(r); err == nil && backend != nil {
918+
if cleanup != nil {
919+
defer cleanup()
920+
}
921+
state, stateErr := backend.SessionState(r.Context(), sessionID)
922+
if stateErr == nil && (state == sandbox.SessionStateRunning || state == sandbox.SessionStateCreating || state == sandbox.SessionStateResuming) {
923+
reader, pullErr := backend.PullFile(r.Context(), sessionID, filePath)
924+
if pullErr == nil {
925+
content, readErr := io.ReadAll(reader)
926+
closeErr := reader.Close()
927+
if readErr == nil && closeErr == nil {
928+
return content, true
929+
}
930+
if readErr != nil {
931+
slog.Debug("failed to read artifact content from sandbox backend", "session", sessionID, "path", filePath, "error", readErr)
932+
}
933+
if closeErr != nil {
934+
slog.Debug("failed to close artifact content stream from sandbox backend", "session", sessionID, "path", filePath, "error", closeErr)
935+
}
936+
} else {
937+
slog.Debug("failed to pull artifact from sandbox backend", "session", sessionID, "path", filePath, "error", pullErr)
938+
}
939+
}
940+
} else if err != nil {
941+
slog.Debug("sandbox backend unavailable for artifact read", "session", sessionID, "path", filePath, "error", err)
942+
}
943+
944+
// Legacy Incus fallback.
911945
appCfg, err := config.LoadAppConfig()
912946
if err != nil || appCfg == nil || !sandbox.IsSandboxEnabled(&appCfg.Sandbox) {
913947
return nil, false
914948
}
915-
916-
// Look up the container name for this session
917949
registry, err := sandbox.NewSessionRegistry()
918950
if err != nil {
919951
slog.Debug("failed to load sandbox session registry", "error", err)
@@ -923,28 +955,23 @@ func readFromSandboxContainer(sessionID, filePath string) ([]byte, bool) {
923955
if entry == nil || entry.ContainerName == "" {
924956
return nil, false
925957
}
926-
927-
// Connect to Incus and pull the file
928958
client, err := sandboxConnect()
929959
if err != nil {
930960
slog.Debug("failed to connect to sandbox for artifact read", "error", err)
931961
return nil, false
932962
}
933-
934963
reader, _, err := client.PullFile(entry.ContainerName, filePath)
935964
if err != nil {
936965
slog.Debug("failed to pull file from sandbox container",
937966
"container", entry.ContainerName, "path", filePath, "error", err)
938967
return nil, false
939968
}
940969
defer reader.Close()
941-
942970
content, err := io.ReadAll(reader)
943971
if err != nil {
944972
slog.Debug("failed to read file content from sandbox container", "error", err)
945973
return nil, false
946974
}
947-
948975
return content, true
949976
}
950977

@@ -977,7 +1004,7 @@ func StudioArtifactPDFHandler(w http.ResponseWriter, r *http.Request) {
9771004

9781005
// Tier 2: Try reading from sandbox container
9791006
if mdContent == nil && sessionID != "" {
980-
if content, ok := readFromSandboxContainer(sessionID, cleanPath); ok {
1007+
if content, ok := readFromSandboxContainer(r, sessionID, cleanPath); ok {
9811008
mdContent = content
9821009
}
9831010
}

‎pkg/sandbox/k8s/files.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,10 @@ import (
4141
"k8s.io/client-go/tools/remotecommand"
4242
)
4343

44+
func sandboxFileCommand(cmd []string) []string {
45+
return append([]string{"/usr/local/bin/astonish-shell"}, cmd...)
46+
}
47+
4448
// ---------------------------------------------------------------------------
4549
// PushFile
4650
// ---------------------------------------------------------------------------
@@ -97,7 +101,7 @@ func (b *K8sBackend) PushFile(ctx context.Context, sessionID, filePath string, c
97101
return fmt.Errorf("sandbox/k8s: PushFile(%s): build tar: %w", sessionID, err)
98102
}
99103

100-
command := []string{"tar", "-C", dir, "-xmpf", "-"}
104+
command := sandboxFileCommand([]string{"tar", "-C", dir, "-xmpf", "-"})
101105
method, u, err := b.buildExecURL(rec.PodName, command, false /*tty*/, true /*stdin*/, true /*stdout*/, true /*stderr*/)
102106
if err != nil {
103107
return fmt.Errorf("sandbox/k8s: PushFile(%s): build URL: %w", sessionID, err)
@@ -192,7 +196,7 @@ func (b *K8sBackend) PullFile(ctx context.Context, sessionID, filePath string) (
192196
}
193197

194198
// Keep PAX format so filenames up to 255 bytes work without truncation.
195-
command := []string{"tar", "-C", dir, "-cf", "-", name}
199+
command := sandboxFileCommand([]string{"tar", "-C", dir, "-cf", "-", name})
196200
method, u, err := b.buildExecURL(rec.PodName, command, false, false /*stdin*/, true /*stdout*/, true /*stderr*/)
197201
if err != nil {
198202
return nil, fmt.Errorf("sandbox/k8s: PullFile(%s): build URL: %w", sessionID, err)

‎pkg/sandbox/k8s/files_test.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,10 @@ func TestPushFile_EmitsSingleFileTarStream(t *testing.T) {
129129
t.Errorf("tar should have exactly one entry, got next err %v", err)
130130
}
131131

132-
// Validate exec'd command: tar -C /etc/astonish -xmpf -
132+
// Validate exec'd command: astonish-shell tar -C /etc/astonish -xmpf -
133133
q := se.url.Query()
134134
cmds := q["command"]
135-
want := []string{"tar", "-C", "/etc/astonish", "-xmpf", "-"}
135+
want := []string{"/usr/local/bin/astonish-shell", "tar", "-C", "/etc/astonish", "-xmpf", "-"}
136136
if len(cmds) != len(want) {
137137
t.Fatalf("command = %v, want %v", cmds, want)
138138
}
@@ -156,8 +156,8 @@ func TestPushFile_RootDirectoryPath(t *testing.T) {
156156
}
157157
q := se.url.Query()
158158
cmds := q["command"]
159-
if len(cmds) < 3 || cmds[2] != "/" {
160-
t.Errorf("root dir: command[2] = %v, want /", cmds)
159+
if len(cmds) < 4 || cmds[3] != "/" {
160+
t.Errorf("root dir: command[3] = %v, want /", cmds)
161161
}
162162
}
163163

@@ -255,7 +255,7 @@ func TestPullFile_StreamsFileContent(t *testing.T) {
255255
// Verify command shape.
256256
q := se.url.Query()
257257
cmds := q["command"]
258-
want := []string{"tar", "-C", "/etc/astonish", "-cf", "-", "hello.txt"}
258+
want := []string{"/usr/local/bin/astonish-shell", "tar", "-C", "/etc/astonish", "-cf", "-", "hello.txt"}
259259
if len(cmds) != len(want) {
260260
t.Fatalf("command = %v, want %v", cmds, want)
261261
}
@@ -398,5 +398,6 @@ func TestPushPullFile_RoundTrip(t *testing.T) {
398398

399399
// Sanity compile-time: pullFileReader satisfies io.ReadCloser.
400400
var _ io.ReadCloser = (*pullFileReader)(nil)
401+
401402
// Use sandbox package to silence if imports shift during refactors.
402403
var _ sandbox.BackendKind = sandbox.BackendKindK8s

‎pkg/sandbox/k8s/overlay_entrypoint.go‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,9 @@
33
// The sandbox container runs a single PID-1 entrypoint whose job is:
44
//
55
// 1. Streaming the persisted upper layer back onto the local emptyDir
6-
// when resuming a previously-evicted session
7-
// (/mnt/astonish-uppers/<session-id>/upper.tar.zst).
6+
// when resuming a previously-evicted session. Session pods mount only
7+
// their own uppers PVC subdirectory, so the live path is
8+
// /mnt/astonish-uppers/upper.tar.zst.
89
// 2. Composing the overlay chain encoded in $ASTONISH_LAYER_CHAIN as
910
// lowerdirs (top-most first, per overlayfs syntax), with the
1011
// emptyDir at /var/astonish/overlay/upper as upperdir and
@@ -306,10 +307,16 @@ fi
306307

307308
// Resume path.
308309
b.WriteString(`# --- 1. Resume from persisted upper (if present) -----------------------
309-
# When a previously-evicted session is restarted, Astonish persists its
310-
# upper layer to $UPPERS_DIR/<session>/upper.tar.zst. Stream it back
311-
# onto the local emptyDir before the overlay mount.
312-
RESUME_TAR="$UPPERS_DIR/$ASTONISH_SESSION_ID/upper.tar.zst"
310+
# When a previously-evicted session is restarted, Astonish mounts only that
311+
# session's uppers PVC subdirectory at $UPPERS_DIR. Stream the saved upper back
312+
# onto the local emptyDir before the overlay mount. Older pods mounted the PVC
313+
# root and used $UPPERS_DIR/<session>/upper.tar.zst; the fallback keeps those
314+
# sessions resumable during rolling upgrades without exposing other sessions to
315+
# the chrooted sandbox.
316+
RESUME_TAR="$UPPERS_DIR/upper.tar.zst"
317+
if [ ! -f "$RESUME_TAR" ] && [ -f "$UPPERS_DIR/$ASTONISH_SESSION_ID/upper.tar.zst" ]; then
318+
RESUME_TAR="$UPPERS_DIR/$ASTONISH_SESSION_ID/upper.tar.zst"
319+
fi
313320
if [ -f "$RESUME_TAR" ]; then
314321
echo "astonish-entrypoint: resuming upper from $RESUME_TAR" 1>&2
315322
mkdir -p "$UPPER_DIR"

‎pkg/sandbox/k8s/overlay_entrypoint_test.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ func TestEntrypointScript_Defaults(t *testing.T) {
3131
{"workdir default", "WORK_DIR='/var/astonish/overlay/work'"},
3232
{"mountpoint default", "MOUNT_POINT='/sandbox/rootfs'"},
3333
{"overlay-mode default", "OVERLAY_MODE='fuse'"},
34-
{"resume tarball path", `RESUME_TAR="$UPPERS_DIR/$ASTONISH_SESSION_ID/upper.tar.zst"`},
34+
{"resume tarball path", `RESUME_TAR="$UPPERS_DIR/upper.tar.zst"`},
35+
{"legacy resume fallback", `RESUME_TAR="$UPPERS_DIR/$ASTONISH_SESSION_ID/upper.tar.zst"`},
3536
{"resume guard", `if [ -f "$RESUME_TAR" ]; then`},
3637
{"resume tar cmd", `tar --numeric-owner --xattrs --acls -I zstd -xf "$RESUME_TAR" -C "$UPPER_DIR"`},
3738
{"awk reversal", `awk -F, -v dir="$LAYERS_DIR"`},

0 commit comments

Comments
 (0)