Skip to content
Open
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
2 changes: 2 additions & 0 deletions docs/src/api/sandboxes.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,8 @@ Each `Event[T]` carries:
- `Type`: one of `EventAdded`, `EventModified`, `EventDeleted`, or `EventError`
- `Object`: the `*Sandbox` at that point in time (`nil` for `EventError`)

The channel closes when the server ends the stream, when `StopOnTerminal` sees a terminal phase, when `ctx` is cancelled, or after `Stop`. Cancelling `ctx` or calling `Stop` closes it without an `EventError`, even if nothing is reading: `EventError` reports only a stream failure, such as the gateway becoming unavailable.

```go
watcher, err := client.Sandboxes().Watch(ctx, "default", "my-sandbox")
if err != nil {
Expand Down
26 changes: 13 additions & 13 deletions openshell/v1/sandbox_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,14 @@ func checkTerminalPhase(sb *Sandbox, name string, target SandboxPhase) (*Sandbox
}
}

// Watch streams status changes for one sandbox. The first event is

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: The new close/error contract for Watch is documented on the unexported sandboxClient.Watch method, so it never shows up in godoc. The exported SandboxInterface.Watch (openshell/v1/sandbox.go:120) that callers actually use still has no doc comment.

Why this matters: Someone reading go doc v1.SandboxInterface or pkg.go.dev to find out whether ctx cancellation produces an EventError won't see this comment, since sandboxClient is unexported. Sibling methods on the same interface (ListProviders, ListAllProviders at sandbox.go:113-116) carry their docs on the interface, so the new contract is only discoverable in docs/src/api/sandboxes.md or by reading the implementation, and the fake in openshell/v1/fake has nothing to conform to.

Suggested fix: Move (or copy) the comment onto Watch in SandboxInterface in openshell/v1/sandbox.go, following the ListProviders precedent, and drop or shorten the copy on the unexported method.

Source: architecture agent

// EventAdded, later ones EventModified, and EventDeleted once the sandbox is
// deleting.
//
// The channel closes when the server ends the stream, when StopOnTerminal
// sees a terminal phase, when ctx is cancelled, or after Stop. Cancelling ctx
// or calling Stop closes it without an EventError: EventError reports only a
// stream failure, such as the gateway becoming unavailable.
func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts ...WatchOptions) (WatchInterface[*Sandbox], error) {
if name == "" {
return nil, &StatusError{Code: ErrorInvalidArgument, Message: "sandbox name must not be empty"}
Expand Down Expand Up @@ -444,9 +452,7 @@ func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts
} else if sandbox.Status.Phase == SandboxDeleting {
eventType = EventDeleted
}
select {
case ch <- Event[*Sandbox]{Type: eventType, Object: sandbox}:
case <-w.done:
if !w.emit(streamCtx, Event[*Sandbox]{Type: eventType, Object: sandbox}) {
return
}
if watchOpts.StopOnTerminal && (sandbox.Status.Phase == SandboxReady || sandbox.Status.Phase == SandboxCompleted || sandbox.Status.Phase == SandboxStopped || sandbox.Status.Phase == SandboxError) {
Expand All @@ -457,16 +463,10 @@ func (s *sandboxClient) Watch(ctx context.Context, workspace, name string, opts
var recvErr error
ev, recvErr = stream.Recv()
if recvErr != nil {
if recvErr != io.EOF {
select {
case <-w.done:
return
default:
}
select {
case ch <- Event[*Sandbox]{Type: EventError, Err: converter.FromGRPCError(recvErr)}:
case <-w.done:
}
// A cancelled stream after Stop or ctx cancellation is the
// caller's own doing, not a failure to report.
if recvErr != io.EOF && !w.stopped() && streamCtx.Err() == nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: The newly documented guarantee that Stop closes the Watch channel without an EventError (even with an unread or full channel and a stream that is still open) has no Watch-level test. The only Stop test, TestSandboxWatch_StopCancelsStream, runs without watchKeepOpen, so the mock server hits EOF right after its single event.

Why this matters: That test passes whether or not Stop cancels the stream or suppresses the error, and the two new tests only exercise ctx cancellation. A regression where Stop no longer cancels streamCtx (for example newWatcher(ch, nil)), or where the Recv error branch emits EventError after Stop, would pass the whole suite.

Suggested fix: Add TestSandboxWatch_StopClosesWithoutError mirroring TestSandboxWatch_ContextCancelClosesWithoutError (set watchKeepOpen, read EventAdded, call w.Stop(), then assert.Empty(drainSandboxWatch(t, w))). A full-channel variant mirroring TestSandboxWatch_ContextCancelUnblocksFullChannel that calls w.Stop() instead of cancel() and asserts the channel closes with no EventError would cover the blocked-producer path too.

Source: test-quality agent

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: Watch now closes the channel silently when ctx's deadline expires. The guard recvErr != io.EOF && !w.stopped() && streamCtx.Err() == nil also suppresses context.DeadlineExceeded, which used to surface as an EventError.

Why this matters: A caller using context.WithTimeout can't tell a timeout apart from the server ending the stream unless it checks ctx.Err(), and neither the godoc (lines 402-405) nor docs/src/api/sandboxes.md:230 says to do that. For example, a for ev := range w.ResultChan() loop waiting for Ready under a 30s timeout just exits with no error if the sandbox never becomes Ready, which looks the same as a normal end of stream.

Suggested fix: Mention the deadline case and how to detect it in both places. For the godoc, something like // The same applies when ctx's deadline passes; after the channel closes, check ctx.Err() to tell a timeout or cancellation apart from the server ending the stream., plus a matching sentence in the docs paragraph.

Source: gator agent

w.emit(streamCtx, Event[*Sandbox]{Type: EventError, Err: converter.FromGRPCError(recvErr)})
}
return
}
Expand Down
91 changes: 91 additions & 0 deletions openshell/v1/sandbox_client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1163,6 +1163,97 @@ func TestSandboxWatch_StopCancelsStream(t *testing.T) {
}
}

// sandboxEvents returns n status snapshots for sb-1, so a test can fill the
// Watch channel.
func sandboxEvents(n int) []*pb.SandboxStreamEvent {
events := make([]*pb.SandboxStreamEvent, n)
for i := range events {
events[i] = &pb.SandboxStreamEvent{Payload: &pb.SandboxStreamEvent_Sandbox{Sandbox: &pb.Sandbox{
Metadata: &dm.ObjectMeta{Name: "sb-1", Id: "id-1"},
Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_PROVISIONING},
}}}
}
return events
}

// drainSandboxWatch collects events until the channel closes.
func drainSandboxWatch(t *testing.T, w WatchInterface[*Sandbox]) []Event[*Sandbox] {
t.Helper()
var events []Event[*Sandbox]
timeout := time.After(5 * time.Second)
for {
select {
case ev, ok := <-w.ResultChan():
if !ok {
return events
}
events = append(events, ev)
case <-timeout:
t.Fatal("timed out waiting for the Watch channel to close")
}
}
}

func TestSandboxWatch_ContextCancelUnblocksFullChannel(t *testing.T) {
// A consumer that cancels ctx without reading must not leave the producer
// blocked on a full channel: it has to stop sending and close.
const total = 100
mock := newMockSandboxServer()
mock.sandboxes["sb-1"] = &pb.Sandbox{
Metadata: &dm.ObjectMeta{Id: "id-1", Name: "sb-1"},
Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_PROVISIONING},
}
mock.watchEvents = sandboxEvents(total)
keepOpen := make(chan struct{})
defer close(keepOpen)
mock.watchKeepOpen = keepOpen
client, cleanup := setupSandboxTest(t, mock)
defer cleanup()

ctx, cancel := context.WithCancel(context.Background())
w, err := client.Watch(ctx, "default", "sb-1")
require.NoError(t, err)
defer w.Stop()

ch := w.ResultChan()
require.Eventually(t, func() bool { return len(ch) == cap(ch) }, 5*time.Second, 5*time.Millisecond,
"producer never filled the channel")
cancel()

events := drainSandboxWatch(t, w)
// The buffered events drain, plus at most one send that raced the
// cancellation. A producer that ignored ctx would deliver all of them.
assert.LessOrEqual(t, len(events), cap(ch)+1)
for _, ev := range events {
assert.NotEqual(t, EventError, ev.Type, "cancellation must not surface as an error: %v", ev.Err)
}
}

func TestSandboxWatch_ContextCancelClosesWithoutError(t *testing.T) {
mock := newMockSandboxServer()
mock.sandboxes["sb-1"] = &pb.Sandbox{
Metadata: &dm.ObjectMeta{Id: "id-1", Name: "sb-1"},
Status: &pb.SandboxStatus{Phase: pb.SandboxPhase_SANDBOX_PHASE_PROVISIONING},
}
mock.watchEvents = sandboxEvents(1)
keepOpen := make(chan struct{})
defer close(keepOpen)
mock.watchKeepOpen = keepOpen
client, cleanup := setupSandboxTest(t, mock)
defer cleanup()

ctx, cancel := context.WithCancel(context.Background())
w, err := client.Watch(ctx, "default", "sb-1")
require.NoError(t, err)
defer w.Stop()

ev := <-w.ResultChan()
assert.Equal(t, EventAdded, ev.Type)

cancel()
assert.Empty(t, drainSandboxWatch(t, w), "cancellation must close the channel without an error event")
}

func TestSandboxWatch_RPCError(t *testing.T) {
mock := newMockSandboxServer()
mock.sandboxes["watch-err"] = &pb.Sandbox{
Expand Down