Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions kubernetes/internal/controller/allocator.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ func NewAnnoAllocationSyncer(client client.Client) AllocationSyncer {
}

func (syncer *annoAllocationSyncer) SetAllocation(ctx context.Context, sandbox *sandboxv1alpha1.BatchSandbox, allocation *SandboxAllocation) error {
allocation.PoolRef = sandbox.Spec.PoolRef
allocation.Generation = sandbox.Generation
js, err := json.Marshal(allocation)
if err != nil {
return err
Expand Down
8 changes: 7 additions & 1 deletion kubernetes/internal/controller/allocator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -350,14 +350,20 @@ func newTestSyncer(sandbox *sandboxv1alpha1.BatchSandbox) (*annoAllocationSyncer

func TestSetAllocation_AddsFinalizer(t *testing.T) {
sandbox := &sandboxv1alpha1.BatchSandbox{
ObjectMeta: metav1.ObjectMeta{Name: "sbx1", Namespace: "default"},
ObjectMeta: metav1.ObjectMeta{Name: "sbx1", Namespace: "default", Generation: 7},
Spec: sandboxv1alpha1.BatchSandboxSpec{PoolRef: "pool1"},
}
syncer, sbx := newTestSyncer(sandbox)

err := syncer.SetAllocation(context.Background(), sbx, &SandboxAllocation{Pods: []string{"pod1"}})
assert.NoError(t, err)
assert.Contains(t, sbx.Finalizers, FinalizerPoolAllocation)

allocation, err := syncer.GetAllocation(context.Background(), sbx)
assert.NoError(t, err)
assert.Equal(t, []string{"pod1"}, allocation.Pods)
assert.Equal(t, "pool1", allocation.PoolRef)
assert.Equal(t, int64(7), allocation.Generation)
}

func TestSetReleased_FinalizerBehavior(t *testing.T) {
Expand Down
4 changes: 3 additions & 1 deletion kubernetes/internal/controller/apis.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ const (
var AnnotationSandboxEndpoints = pkgutils.AnnotationEndpoints

type SandboxAllocation struct {
Pods []string `json:"pods"`
Pods []string `json:"pods"`
PoolRef string `json:"poolRef"`
Generation int64 `json:"generation"`
}

type AllocationRelease struct {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,14 @@ private static SandboxInfo ParseSandboxInfo(JsonElement element)
Platform = element.TryGetProperty("platform", out var platform) && platform.ValueKind == JsonValueKind.Object
? JsonSerializer.Deserialize<PlatformSpec>(platform.GetRawText(), JsonOptions)
: null,
Allocation = element.TryGetProperty("allocation", out var allocation) && allocation.ValueKind == JsonValueKind.Object
? new AllocationSummary
{
Mode = allocation.GetProperty("mode").GetString() ?? throw new SandboxApiException("Missing allocation.mode in response"),
PoolRef = allocation.GetProperty("poolRef").GetString() ?? throw new SandboxApiException("Missing allocation.poolRef in response"),
State = allocation.GetProperty("state").GetString() ?? throw new SandboxApiException("Missing allocation.state in response")
}
: null,
Entrypoint = element.GetProperty("entrypoint").EnumerateArray().Select(e => e.GetString() ?? string.Empty).ToList(),
Metadata = ParseStringMap(element, "metadata"),
Extensions = ParseStringMap(element, "extensions"),
Expand Down
30 changes: 30 additions & 0 deletions sdks/sandbox/csharp/src/OpenSandbox/Models/Sandboxes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,30 @@ public class SandboxStatus
public string? Message { get; set; }
}

/// <summary>
/// Runtime-confirmed Pool allocation for a sandbox.
/// </summary>
public class AllocationSummary
{
/// <summary>
/// Gets or sets the confirmed allocation mode. Currently, this is "pool".
/// </summary>
[JsonPropertyName("mode")]
public required string Mode { get; set; }

/// <summary>
/// Gets or sets the concrete Pool reference allocated to the sandbox.
/// </summary>
[JsonPropertyName("poolRef")]
public required string PoolRef { get; set; }

/// <summary>
/// Gets or sets the confirmed allocation state. Currently, this is "allocated".
/// </summary>
[JsonPropertyName("state")]
public required string State { get; set; }
}

/// <summary>
/// Information about a sandbox.
/// </summary>
Expand Down Expand Up @@ -765,6 +789,12 @@ public class SandboxInfo
[JsonPropertyName("platform")]
public PlatformSpec? Platform { get; set; }

/// <summary>
/// Gets or sets the current runtime-confirmed Pool allocation, when available.
/// </summary>
[JsonPropertyName("allocation")]
public AllocationSummary? Allocation { get; set; }

/// <summary>
/// Gets or sets the sandbox creation time.
/// </summary>
Expand Down
15 changes: 15 additions & 0 deletions sdks/sandbox/csharp/tests/OpenSandbox.Tests/ModelsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,21 @@ public void SandboxInfo_ShouldStoreProperties()
info.Metadata.Should().ContainKey("key");
}

[Fact]
public void AllocationSummary_ShouldStorePoolAllocation()
{
var allocation = new AllocationSummary
{
Mode = "pool",
PoolRef = "default/python",
State = "allocated"
};

allocation.Mode.Should().Be("pool");
allocation.PoolRef.Should().Be("default/python");
allocation.State.Should().Be("allocated");
}

[Fact]
public void SandboxStatus_ShouldStoreProperties()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,12 +79,74 @@ public async Task GetSandboxAsync_ShouldTreatMissingExpiresAtAsNull()
SandboxInfo sandbox = await adapter.GetSandboxAsync("sbx-1");

sandbox.ExpiresAt.Should().BeNull();
sandbox.Allocation.Should().BeNull();
sandbox.Platform.Should().NotBeNull();
sandbox.Platform!.Arch.Should().Be("amd64");
sandbox.Extensions.Should().ContainKey("opensandbox.extensions.custom-label")
.WhoseValue.Should().Be("中文数据");
}

[Fact]
public async Task GetSandboxAsync_ShouldParseAllocation()
{
const string payload = """
{
"id": "sbx-pool",
"status": { "state": "Running" },
"entrypoint": ["/bin/sh"],
"createdAt": "2026-03-14T12:00:00Z",
"allocation": {
"mode": "pool",
"poolRef": "default/python",
"state": "allocated"
}
}
""";
var adapter = CreateAdapterWithJsonResponse(payload);

SandboxInfo sandbox = await adapter.GetSandboxAsync("sbx-pool");

sandbox.Allocation.Should().NotBeNull();
sandbox.Allocation!.Mode.Should().Be("pool");
sandbox.Allocation.PoolRef.Should().Be("default/python");
sandbox.Allocation.State.Should().Be("allocated");
}

[Fact]
public async Task ListSandboxesAsync_ShouldParseAllocation()
{
const string payload = """
{
"items": [
{
"id": "sbx-pool",
"status": { "state": "Running" },
"entrypoint": ["/bin/sh"],
"createdAt": "2026-03-14T12:00:00Z",
"allocation": {
"mode": "pool",
"poolRef": "default/python",
"state": "allocated"
}
},
{
"id": "sbx-legacy",
"status": { "state": "Running" },
"entrypoint": ["/bin/sh"],
"createdAt": "2026-03-14T12:00:00Z"
}
]
}
""";
var adapter = CreateAdapterWithJsonResponse(payload);

ListSandboxesResponse response = await adapter.ListSandboxesAsync();

response.Items[0].Allocation.Should().NotBeNull();
response.Items[0].Allocation!.PoolRef.Should().Be("default/python");
response.Items[1].Allocation.Should().BeNull();
}

[Fact]
public async Task CreateSandboxAsync_ShouldTreatMissingExpiresAtAsNull()
{
Expand Down
100 changes: 100 additions & 0 deletions sdks/sandbox/go/allocation_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2026 Alibaba Group Holding Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package opensandbox

import (
"context"
"encoding/json"
"net/http"
"testing"
"time"
)

func TestSandboxInfoAllocationJSON(t *testing.T) {
var info SandboxInfo
err := json.Unmarshal([]byte(`{
"id":"sbx-pooled",
"status":{"state":"Running"},
"createdAt":"2026-07-10T00:00:00Z",
"allocation":{"mode":"pool","poolRef":"pool-runc","state":"allocated"}
}`), &info)
require.NoErrorf(t, err, "unmarshal sandbox allocation")
require.NotNil(t, info.Allocation, "allocation should be present")
require.Equal(t, AllocationModePool, info.Allocation.Mode, "allocation mode")
require.Equal(t, "pool-runc", info.Allocation.PoolRef, "allocation pool ref")
require.Equal(t, AllocationStateAllocated, info.Allocation.State, "allocation state")
}

func TestSandboxInfoAllocationAbsentIsOmitted(t *testing.T) {
info := SandboxInfo{
ID: "sbx-unpooled",
Status: SandboxStatus{State: StateRunning},
CreatedAt: mustParseTime(t, "2026-07-10T00:00:00Z"),
}

body, err := json.Marshal(info)
require.NoErrorf(t, err, "marshal sandbox without allocation")
var fields map[string]json.RawMessage
require.NoErrorf(t, json.Unmarshal(body, &fields), "unmarshal sandbox JSON")
_, present := fields["allocation"]
if present {
t.Fatal("absent allocation should remain omitted")
}
}

func TestLifecycleClientAllocationInGetAndListResponses(t *testing.T) {
_, client := newLifecycleServer(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.URL.Path {
case "/sandboxes/sbx-pooled":
_, _ = w.Write([]byte(`{
"id":"sbx-pooled",
"status":{"state":"Running"},
"createdAt":"2026-07-10T00:00:00Z",
"allocation":{"mode":"pool","poolRef":"pool-runc","state":"allocated"}
}`))
case "/sandboxes":
_, _ = w.Write([]byte(`{
"items":[{
"id":"sbx-pooled",
"status":{"state":"Running"},
"createdAt":"2026-07-10T00:00:00Z",
"allocation":{"mode":"pool","poolRef":"pool-runc","state":"allocated"}
}],
"pagination":{"page":1,"pageSize":20,"totalItems":1,"totalPages":1,"hasNextPage":false}
}`))
default:
http.NotFound(w, r)
}
})

info, err := client.GetSandbox(context.Background(), "sbx-pooled")
require.NoErrorf(t, err, "get sandbox")
require.NotNil(t, info.Allocation, "get allocation")
require.Equal(t, "pool-runc", info.Allocation.PoolRef, "get allocation pool ref")

list, err := client.ListSandboxes(context.Background(), ListOptions{})
require.NoErrorf(t, err, "list sandboxes")
require.Len(t, list.Items, 1)
require.NotNil(t, list.Items[0].Allocation, "list allocation")
require.Equal(t, AllocationModePool, list.Items[0].Allocation.Mode, "list allocation mode")
}

func mustParseTime(t *testing.T, value string) time.Time {
t.Helper()
parsed, err := time.Parse(time.RFC3339, value)
require.NoErrorf(t, err, "parse time")
return parsed
}
46 changes: 36 additions & 10 deletions sdks/sandbox/go/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -165,19 +165,45 @@ type CreateSandboxRequest struct {
Platform *PlatformSpec `json:"platform,omitempty"`
}

// AllocationMode identifies how the runtime allocated a sandbox.
type AllocationMode string

const (
// AllocationModePool indicates that the sandbox was allocated from a pool.
AllocationModePool AllocationMode = "pool"
)

// AllocationState describes the confirmed allocation state of a sandbox.
type AllocationState string

const (
// AllocationStateAllocated indicates that the pool allocation is active.
AllocationStateAllocated AllocationState = "allocated"
)

// AllocationSummary is the public summary of a confirmed active pool
// allocation. It is present only when the runtime confirms an active pool
// allocation.
type AllocationSummary struct {
Mode AllocationMode `json:"mode"`
PoolRef string `json:"poolRef"`
State AllocationState `json:"state"`
}

// SandboxInfo represents a runtime execution environment provisioned from a
// container image, as returned by the lifecycle API.
type SandboxInfo struct {
ID string `json:"id"`
Image *ImageSpec `json:"image,omitempty"`
SnapshotID string `json:"snapshotId,omitempty"`
Status SandboxStatus `json:"status"`
Metadata map[string]string `json:"metadata,omitempty"`
Extensions map[string]string `json:"extensions,omitempty"`
Entrypoint []string `json:"entrypoint"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
Platform *PlatformSpec `json:"platform,omitempty"`
ID string `json:"id"`
Image *ImageSpec `json:"image,omitempty"`
SnapshotID string `json:"snapshotId,omitempty"`
Status SandboxStatus `json:"status"`
Metadata map[string]string `json:"metadata,omitempty"`
Extensions map[string]string `json:"extensions,omitempty"`
Entrypoint []string `json:"entrypoint"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
Platform *PlatformSpec `json:"platform,omitempty"`
Allocation *AllocationSummary `json:"allocation,omitempty"`
}

type SnapshotState string
Expand Down
9 changes: 8 additions & 1 deletion sdks/sandbox/javascript/src/adapters/sandboxesAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type {
CreateSnapshotRequest,
CreateSandboxRequest,
CreateSandboxResponse,
AllocationSummary,
Endpoint,
ListSnapshotsParams,
ListSnapshotsResponse,
Expand Down Expand Up @@ -65,6 +66,10 @@ type ApiListSnapshotsOk =
type ApiEndpointOk =
LifecyclePaths["/sandboxes/{sandboxId}/endpoints/{port}"]["get"]["responses"][200]["content"]["application/json"];

type ApiSandboxWithAllocation = ApiGetSandboxOk & {
allocation?: AllocationSummary;
};

function encodeMetadataFilter(metadata: Record<string, string>): string {
// The Lifecycle API expects a single `metadata` query parameter whose value is `k=v&k2=v2`.
// The query serializer will URL-encode the value (e.g. `=` -> %3D and `&` -> %26).
Expand Down Expand Up @@ -122,8 +127,10 @@ export class SandboxesAdapter implements Sandboxes {
}

private mapSandboxInfo(raw: ApiGetSandboxOk): SandboxInfo {
const { allocation, ...sandbox } = raw as ApiSandboxWithAllocation;
return {
...(raw ?? {}),
...sandbox,
...(allocation == null ? {} : { allocation }),
createdAt: this.parseIsoDate("createdAt", raw?.createdAt),
expiresAt: this.parseOptionalIsoDate("expiresAt", raw?.expiresAt),
} as SandboxInfo;
Expand Down
Loading
Loading