Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,7 @@ stream completion.
| File transfer API (transport capability-gated) | `FileInterface` | [Files](https://ai-openshell.github.io/sdk-go/api/files.html) |
| Policy management (draft review, approve, reject, merge, global policy) | `PolicyInterface` | [Policy](https://ai-openshell.github.io/sdk-go/api/policy.html) |
| Sandbox logs (streaming retrieval) | `SandboxInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) |
| Resumable log and platform event watch (loss-aware reconnect) | `SandboxLogsWatchInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) |
| Workspace management (create, get, list, delete, members) | `WorkspaceInterface` | [Workspaces](https://ai-openshell.github.io/sdk-go/api/workspaces.html) |
| Sandbox provider attachment (attach, detach, list) | `SandboxInterface` | [Sandboxes](https://ai-openshell.github.io/sdk-go/api/sandboxes.html) |
| Gateway info and current user identity | `HealthInterface` | [Health](https://ai-openshell.github.io/sdk-go/api/health.html) |
Expand Down
77 changes: 77 additions & 0 deletions docs/src/api/sandboxes.md
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,83 @@ for event := range watcher.ResultChan() {
// Channel closes after Ready or Error
```

## WatchLogs

Streams a sandbox's log lines and platform events with loss-aware resume. Returns a `WatchInterface[*WatchLogEvent]`.

`WatchLogs` lives on the optional `SandboxLogsWatchInterface`, reached through `client.SandboxLogsWatch()`, so `SandboxInterface` stays unchanged for existing mocks and wrappers.

Each delivered item carries an opaque `Cursor`. The watcher tracks the highest cursor it has seen, reconnects transparently when the stream drops, and asks the gateway to replay only what follows that cursor, so a reconnect neither loses nor duplicates events. The gateway delivers live log and platform events in cursor order across both sources, which is what makes the highest cursor a safe resume point.

Only gRPC `Unavailable` (a dropped connection or gateway restart) is retried, with exponential backoff from 100ms capped at 2s, and it is retried indefinitely. Nothing is emitted while the watcher reconnects, so a gateway that stays down looks the same as a quiet sandbox. Bound the watch with a context deadline, or call `Stop`, when that matters. This differs from `Watch`, which reports `Unavailable` as an `EventError` immediately. Every other error ends the stream with an `EventError`.
Comment thread
Gkrumbach07 marked this conversation as resolved.
Resolved

Every `Event[*WatchLogEvent]` has `Type` `EventAdded`, except a terminal failure, which arrives as `EventError` with `Err` set and no `Object`. The `Object.Kind` field selects the populated payload:

| Kind | Payload | Meaning |
|------|---------|---------|
| `WatchLogKindLog` | `Log *LogLine` | A log line |
| `WatchLogKindEvent` | `Event *PlatformEvent` | A runtime event from the compute backend |
| `WatchLogKindWarning` | `Warning string` | Recoverable loss — the server skipped ahead after a lag and the stream continues |

**Available options** (`WatchLogsOptions`):

| Field | Description |
|-------|-------------|
| `FollowLogs bool` | Stream log lines. Defaults to true when neither follow flag is set |
| `FollowEvents bool` | Stream platform events |
| `LogSources []string` | Filter log lines by source (e.g. `"gateway"`, `"sandbox"`) |
| `LogMinLevel string` | Minimum log level (e.g. `"WARN"`) |
| `ResumeAfterCursor string` | Replay only what follows a cursor from an earlier watch |
| `LogTailLines uint32` | Bound the initial log backfill. Ignored when resuming from a cursor |
| `EventTail uint32` | Bound the initial event backfill. Ignored when resuming from a cursor |

```go
watcher, err := client.SandboxLogsWatch().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{
FollowLogs: true,
FollowEvents: true,
LogTailLines: 100,
})
if err != nil {
log.Fatal(err)
}
defer watcher.Stop()

var cursor string
for event := range watcher.ResultChan() {
if event.Type == v1.EventError {
if v1.IsOutOfRange(event.Err) {
// Unrecoverable gap: events after the resume point are gone.
fmt.Println("log history was trimmed; some events were lost")
}
break
}
switch item := event.Object; item.Kind {
case v1.WatchLogKindLog:
fmt.Printf("[%s] %s\n", item.Log.Level, item.Log.Message)
case v1.WatchLogKindEvent:
fmt.Printf("event %s: %s\n", item.Event.Reason, item.Event.Message)
case v1.WatchLogKindWarning:
fmt.Printf("warning: %s\n", item.Warning)
}
if item := event.Object; item.Cursor > cursor {
cursor = item.Cursor
}
}
```

Loss is never silent. A recoverable gap arrives as a `WatchLogKindWarning` item and the stream continues. An unrecoverable gap ends the stream with an `EventError` carrying `ErrorOutOfRange`: the resume point is gone, so the events after it cannot be replayed. The SDK does not retry that error, because restarting from the tail would hide the loss. To continue anyway, start a new watch with an empty `ResumeAfterCursor`; retrying the same cursor fails identically.

Persist the highest cursor to resume across process restarts:

```go
watcher, err := client.SandboxLogsWatch().WatchLogs(ctx, "default", "my-sandbox", v1.WatchLogsOptions{
FollowLogs: true,
ResumeAfterCursor: savedCursor,
})
```

Cursors are opaque. Do not parse or construct one. The only supported operation is comparing two cursors observed on the same stream and keeping the greater one.

## GetLogs

Retrieves log entries from a sandbox. The sandbox is looked up by name (the SDK resolves the name to an internal ID automatically). Use functional options to filter results.
Expand Down
3 changes: 3 additions & 0 deletions docs/src/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ Use these top-level functions to check error types. They work with wrapped error
| `v1.IsInvalidArgument` | `ErrorInvalidArgument` | Invalid request parameters |
| `v1.IsDeadlineExceeded` | `ErrorDeadlineExceeded` | Operation timed out |
| `v1.IsCancelled` | `ErrorCancelled` | Operation was cancelled (context cancellation) |
| `v1.IsOutOfRange` | `ErrorOutOfRange` | Operation attempted past a valid range (gRPC `OUT_OF_RANGE`). On `WatchLogs`, the resume cursor is gone and the events after it are unrecoverable |

gRPC `OUT_OF_RANGE` maps to `ErrorOutOfRange` on every RPC. Earlier releases mapped it to `ErrorInvalidArgument`, so code that matched `IsInvalidArgument` for an out-of-range result should match `IsOutOfRange` instead.

For `ErrorInternal` (server-side errors), no convenience predicate exists. Match it directly via the `Code` field:

Expand Down
6 changes: 6 additions & 0 deletions openshell/v1/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ type ClientInterface interface {
SandboxTemplates() SandboxTemplateInterface
CreateSandboxFromTemplate(ctx context.Context, workspace, name, templateName string, spec *SandboxSpec, opts ...CreateOption) (*Sandbox, error)
SandboxSuspendResume() SandboxSuspendResumeInterface
SandboxLogsWatch() SandboxLogsWatchInterface
Comment thread
Gkrumbach07 marked this conversation as resolved.
Resolved
Providers() ProviderInterface
Services() ServiceInterface
Exec() ExecInterface
Expand Down Expand Up @@ -55,6 +56,7 @@ type Client struct {
sandboxes SandboxInterface
templateCreate SandboxTemplateCreateInterface
suspendResume SandboxSuspendResumeInterface
logsWatch SandboxLogsWatchInterface
templates SandboxTemplateInterface
providers ProviderInterface
services ServiceInterface
Expand Down Expand Up @@ -102,6 +104,7 @@ func NewClient(cfg Config) (*Client, error) {
c.sandboxes = sandboxes
c.templateCreate = sandboxes
c.suspendResume = sandboxes
c.logsWatch = sandboxes
c.templates = newSandboxTemplateClient(conn)
c.providers = newProviderClient(conn)
c.services = newServiceClient(conn)
Expand Down Expand Up @@ -132,6 +135,9 @@ func (c *Client) CreateSandboxFromTemplate(ctx context.Context, workspace, name,
// SandboxSuspendResume returns the sandbox suspend and resume sub-client.
func (c *Client) SandboxSuspendResume() SandboxSuspendResumeInterface { return c.suspendResume }

// SandboxLogsWatch returns the resumable sandbox log and event watch sub-client.
func (c *Client) SandboxLogsWatch() SandboxLogsWatchInterface { return c.logsWatch }

// Providers returns the provider sub-client.
func (c *Client) Providers() ProviderInterface { return c.providers }

Expand Down
5 changes: 5 additions & 0 deletions openshell/v1/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const (
ErrorUnimplemented = types.ErrorUnimplemented
ErrorConflict = types.ErrorConflict
ErrorUnauthenticated = types.ErrorUnauthenticated
ErrorOutOfRange = types.ErrorOutOfRange
)

// StatusError is the typed error returned by all SDK operations.
Expand Down Expand Up @@ -64,3 +65,7 @@ func IsConflict(err error) bool { return types.IsConflict(err) }

// IsUnauthenticated returns true if the error indicates invalid or missing credentials.
func IsUnauthenticated(err error) bool { return types.IsUnauthenticated(err) }

// IsOutOfRange returns true if the error indicates a resume cursor is no longer
// available and the events after it are unrecoverable.
func IsOutOfRange(err error) bool { return types.IsOutOfRange(err) }
2 changes: 2 additions & 0 deletions openshell/v1/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,8 @@ func TestErrorCode_String(t *testing.T) {
{ErrorInternal, "Internal"},
{ErrorUnimplemented, "Unimplemented"},
{ErrorConflict, "Conflict"},
{ErrorUnauthenticated, "Unauthenticated"},
{ErrorOutOfRange, "OutOfRange"},
}
for _, tt := range tests {
assert.Equal(t, tt.want, tt.code.String())
Expand Down
7 changes: 7 additions & 0 deletions openshell/v1/fake/fake.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Client struct {
sandboxes v1.SandboxInterface
templateCreate v1.SandboxTemplateCreateInterface
suspendResume v1.SandboxSuspendResumeInterface
logsWatch v1.SandboxLogsWatchInterface
templates v1.SandboxTemplateInterface
providers v1.ProviderInterface
services v1.ServiceInterface
Expand Down Expand Up @@ -86,6 +87,7 @@ func NewClient(opts ...ClientOption) *Client {
fc.sandboxes = sandboxes
fc.templateCreate = sandboxes
fc.suspendResume = sandboxes
fc.logsWatch = sandboxes
fc.templates = newFakeSandboxTemplateClient(fc.templateStore, fc.isClosed)
fc.providers = newFakeProviderClient(fc.providerStore, fc.isClosed)
fc.services = newFakeServiceClient(fc.isClosed)
Expand Down Expand Up @@ -128,6 +130,11 @@ func (fc *Client) SandboxSuspendResume() v1.SandboxSuspendResumeInterface {
return fc.suspendResume
}

// SandboxLogsWatch returns the resumable sandbox log and event watch sub-client.
func (fc *Client) SandboxLogsWatch() v1.SandboxLogsWatchInterface {
return fc.logsWatch
}

// Providers returns the provider sub-client.
func (fc *Client) Providers() v1.ProviderInterface { return fc.providers }

Expand Down
1 change: 1 addition & 0 deletions openshell/v1/fake/fake_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ func TestFakeClient_SubClients(t *testing.T) {
fc := NewClient()

assert.NotNil(t, fc.Sandboxes())
assert.NotNil(t, fc.SandboxLogsWatch())
assert.NotNil(t, fc.Providers())
assert.NotNil(t, fc.Exec())
assert.NotNil(t, fc.Files())
Expand Down
10 changes: 10 additions & 0 deletions openshell/v1/fake/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,7 @@ type fakeSandboxClient struct {
var _ v1.SandboxInterface = (*fakeSandboxClient)(nil)
var _ v1.SandboxTemplateCreateInterface = (*fakeSandboxClient)(nil)
var _ v1.SandboxSuspendResumeInterface = (*fakeSandboxClient)(nil)
var _ v1.SandboxLogsWatchInterface = (*fakeSandboxClient)(nil)

// newFakeSandboxClient creates a new fakeSandboxClient.
func newFakeSandboxClient(
Expand Down Expand Up @@ -899,6 +900,15 @@ func (c *fakeSandboxClient) GetLogs(_ context.Context, _, _ string, _ ...v1.LogO
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "GetLogs not implemented in fake client"}
}

// WatchLogs returns Unimplemented — the fake client has no log or platform
// event stream to replay, so it cannot honor the cursor resume contract.
func (c *fakeSandboxClient) WatchLogs(_ context.Context, _, _ string, _ ...v1.WatchLogsOptions) (types.WatchInterface[*types.WatchLogEvent], error) {
Comment thread
rhuss marked this conversation as resolved.
Resolved
if c.closedFunc() {
return nil, &types.StatusError{Code: types.ErrorUnavailable, Message: "client is closed"}
}
return nil, &types.StatusError{Code: types.ErrorUnimplemented, Message: "WatchLogs not implemented in fake client"}
}

// ListProviders returns a pager over stub Provider objects attached to the
// sandbox. The returned providers contain only the Name field, since the fake
// client does not maintain a full provider registry per sandbox.
Expand Down
19 changes: 19 additions & 0 deletions openshell/v1/fake/sandbox_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1008,6 +1008,25 @@ func TestSandbox_GetLogs_ClosedReturnsUnavailable(t *testing.T) {
assert.True(t, types.IsUnavailable(err))
}

func TestSandbox_WatchLogs_ReturnsUnimplemented(t *testing.T) {
sc := newTestSandboxClient()
w, err := sc.WatchLogs(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.Nil(t, w)
assert.True(t, types.IsUnimplemented(err))
}

func TestSandbox_WatchLogs_ClosedReturnsUnavailable(t *testing.T) {
store := newobjectStore(sandboxName, copySandbox)
templateStore := newobjectStore(sandboxWorkloadTemplate, copySandboxWorkloadTemplate)
broadcaster := newWatchBroadcaster[*types.Sandbox]()
sc := newFakeSandboxClient(store, templateStore, broadcaster, func() bool { return true })
w, err := sc.WatchLogs(context.Background(), "default", "sb-1")
require.Error(t, err)
assert.Nil(t, w)
assert.True(t, types.IsUnavailable(err))
}

func TestSandbox_SuspendAndResume(t *testing.T) {
sc := newTestSandboxClient()
ctx := context.Background()
Expand Down
2 changes: 1 addition & 1 deletion openshell/v1/internal/converter/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ var grpcToSDK = map[codes.Code]types.ErrorCode{
codes.Unauthenticated: types.ErrorUnauthenticated,
codes.FailedPrecondition: types.ErrorConflict,
codes.ResourceExhausted: types.ErrorUnavailable,
codes.OutOfRange: types.ErrorInvalidArgument,
codes.OutOfRange: types.ErrorOutOfRange,
}

// FromGRPCError converts a gRPC error to a typed StatusError.
Expand Down
16 changes: 16 additions & 0 deletions openshell/v1/internal/converter/errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ func TestFromGRPCError_Aborted(t *testing.T) {
assert.Equal(t, "version conflict", se.Message)
}

func TestFromGRPCError_OutOfRange(t *testing.T) {
// A trimmed resume cursor is unrecoverable loss, not a malformed request,
// so it must stay distinguishable from InvalidArgument.
grpcErr := status.Error(codes.OutOfRange, "resume cursor was trimmed")
err := FromGRPCError(grpcErr)
require.Error(t, err)
assert.True(t, v1.IsOutOfRange(err))
assert.False(t, v1.IsInvalidArgument(err))

var se *v1.StatusError
require.ErrorAs(t, err, &se)
assert.Equal(t, v1.ErrorOutOfRange, se.Code)
assert.Equal(t, "resume cursor was trimmed", se.Message)
assert.Equal(t, int32(codes.OutOfRange), se.GRPCCode)
}

func TestFromGRPCError_UnmappedCode(t *testing.T) {
grpcErr := status.Error(codes.DataLoss, "data loss")
err := FromGRPCError(grpcErr)
Expand Down
60 changes: 60 additions & 0 deletions openshell/v1/internal/converter/watch_log.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

package converter

import (
"github.com/ai-openshell/sdk-go/openshell/v1/types"
pb "github.com/ai-openshell/sdk-go/proto/openshellv1"
)

// --- PlatformEvent ---

// PlatformEventFromProto converts a proto PlatformEvent to an SDK PlatformEvent.
func PlatformEventFromProto(e *pb.PlatformEvent) *types.PlatformEvent {
if e == nil {
return nil
}
return &types.PlatformEvent{
Timestamp: TimeFromProto(e.GetEventTime()),
Source: e.GetSource(),
Type: e.GetType(),
Reason: e.GetReason(),
Message: e.GetMessage(),
Metadata: CopyStringMap(e.GetMetadata()),
}
}

// --- WatchLogEvent ---

// WatchLogEventFromProto converts a watch stream event into a WatchLogEvent.
//
// Returns nil for payloads that are not part of the log and platform event
// stream (status snapshots, draft policy updates), which callers skip.
func WatchLogEventFromProto(ev *pb.SandboxStreamEvent) *types.WatchLogEvent {
if ev == nil {
return nil
}
switch payload := ev.GetPayload().(type) {
case *pb.SandboxStreamEvent_Log:
line := LogLineFromProto(payload.Log)
if line == nil {
return nil
}
return &types.WatchLogEvent{Kind: types.WatchLogKindLog, Log: line, Cursor: ev.GetCursor()}
case *pb.SandboxStreamEvent_Event:
event := PlatformEventFromProto(payload.Event)
if event == nil {
return nil
}
return &types.WatchLogEvent{Kind: types.WatchLogKindEvent, Event: event, Cursor: ev.GetCursor()}
case *pb.SandboxStreamEvent_Warning:
if payload.Warning == nil {
return nil
}
// Warnings are not resumable and carry no cursor.
return &types.WatchLogEvent{Kind: types.WatchLogKindWarning, Warning: payload.Warning.GetMessage()}
default:
return nil
}
}
Loading
Loading