The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
fix(runner,api): stop stale state sync from regressing STARTED boxes to CREATING (#3254)
Lhfcwse5424a0fdbc0
diff --git a/apps/api/README.md b/apps/api/README.mdindex 4d276c6bd..1f3d9ada7 100644--- a/apps/api/README.md+++ b/apps/api/README.md@@ -595,6 +595,17 @@ Image-preparation timeouts retain `progress` and `Retry-After`. The ID remainsavailable even if the best-effort progress lookup fails. HTTP status, message,and synchronous SDK behavior are unchanged; a timeout is not a running Box.+## Runner state reports++Runners push their local view to `PUT /box/{boxId}/state`, and `BoxService.updateState`+is the entry point. A report matching the stored state is a no-op, and a stale+`creating` report for a `started` Box is acknowledged without writing: writing it+would move the Box backwards, leave `desiredState` at `started`, and the pending+invariant would then block destroy with "state change in progress". Real runtime+exits (`stopped`, `error`) still write. A `started` report for a Box still shown+as starting completes its stalled startup job once that job has stopped making+progress on its own.+## Registry credential rotation`PUT /api/images/registries/{id}` replaces a stored username and password/token with `write:registries` permission.diff --git a/apps/api/src/box/services/box.service.spec.ts b/apps/api/src/box/services/box.service.spec.tsindex cb4b61b9d..5741c389d 100644--- a/apps/api/src/box/services/box.service.spec.ts+++ b/apps/api/src/box/services/box.service.spec.ts@@ -390,6 +390,93 @@ describe('BoxService image reporting', () => {})})+describe('BoxService stale runner state reports', () => {+ function makeLifecycleService(box: { id: string; state: BoxState; desiredState: BoxDesiredState; pending: boolean }) {+ const service = Object.create(BoxService.prototype) as BoxService+ const updateWhere = jest.fn()+ Object.assign(service as any, {+ boxRepository: { findOne: jest.fn().mockResolvedValue(box), updateWhere },+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },+ imageRegistrarService: { onBoxStarted: jest.fn().mockResolvedValue(undefined) },+ imagePullFailureService: passThroughPullFailures(),+ })+ return { service, updateWhere, box }+ }++ /**+ * A stale runner snapshot can say a box that is already up is still creating+ * (a configured-but-never-booted local record folds into Creating). Writing+ * it would walk STARTED back to CREATING, leave desiredState at STARTED, and+ * the pending invariant would then block destroy with "state change in+ * progress". The report is stale, not the box: it is acknowledged without a+ * write, so an older runner gains nothing from retrying.+ */+ it('ignores a stale creating report for a started box without writing', async () => {+ const { service, updateWhere, box } = makeLifecycleService({+ id: 'box-1',+ state: BoxState.STARTED,+ desiredState: BoxDesiredState.STARTED,+ pending: false,+ })++ await expect(service.updateState('box-1', BoxState.CREATING)).resolves.toBeUndefined()++ expect(updateWhere).not.toHaveBeenCalled()+ expect(box.state).toBe(BoxState.STARTED)+ expect(box.desiredState).toBe(BoxDesiredState.STARTED)+ expect(box.pending).toBe(false)+ })++ /**+ * Only the stale regression is filtered. A real runtime exit reported by the+ * runner is news the control plane must record.+ */+ it('still records a stopped report for a started box', async () => {+ const { service, updateWhere } = makeLifecycleService({+ id: 'box-1',+ state: BoxState.STARTED,+ desiredState: BoxDesiredState.STARTED,+ pending: false,+ })++ await service.updateState('box-1', BoxState.STOPPED)++ expect(updateWhere).toHaveBeenCalledWith(+ 'box-1',+ expect.objectContaining({+ updateData: expect.objectContaining({ state: BoxState.STOPPED, desiredState: BoxDesiredState.STOPPED }),+ }),+ )+ })++ /**+ * An error report from a runner names a real failure and may mark the box+ * recoverable; filtering it would leave the control plane believing a dead+ * box is up.+ */+ it('still records an error report for a started box', async () => {+ const { service, updateWhere } = makeLifecycleService({+ id: 'box-1',+ state: BoxState.STARTED,+ desiredState: BoxDesiredState.STARTED,+ pending: false,+ })++ await service.updateState('box-1', BoxState.ERROR, true, 'runtime failed')++ expect(updateWhere).toHaveBeenCalledWith(+ 'box-1',+ expect.objectContaining({+ updateData: expect.objectContaining({+ state: BoxState.ERROR,+ recoverable: true,+ errorReason: 'runtime failed',+ }),+ }),+ )+ })+})+describe('BoxService inbound defaults', () => {function makeCreateService(overrides: Record<string, unknown> = {}) {const boxRepository = {diff --git a/apps/api/src/box/services/box.service.ts b/apps/api/src/box/services/box.service.tsindex a9bb1d176..001d80368 100644--- a/apps/api/src/box/services/box.service.ts+++ b/apps/api/src/box/services/box.service.ts@@ -1629,6 +1629,18 @@ export class BoxService {return}+ // A stale runner snapshot can say a box that is already up is still+ // creating: a configured-but-never-booted local record folds into+ // Creating. Believing it walks STARTED back to CREATING, leaves+ // desiredState at STARTED, and the pending invariant then blocks destroy+ // with "state change in progress". The report is stale, not the box —+ // acknowledge it without writing, so an older runner gains nothing from+ // retrying. Real runtime exits (STOPPED, ERROR) are unaffected below.+ if (box.state === BoxState.STARTED && newState === BoxState.CREATING) {+ this.logger.debug(`Ignoring stale creating report for started box ${boxId}`)+ return+ }+// only allow updating the state of started | stopped boxesif (![BoxState.STARTED, BoxState.STOPPED].includes(box.state)) {// One exception: a runner reporting STARTED for a box we still show asdiff --git a/apps/runner/README.md b/apps/runner/README.mdindex 5042eaa63..9055edd81 100644--- a/apps/runner/README.md+++ b/apps/runner/README.md@@ -176,7 +176,12 @@ the in-process TTL caches under `pkg/cache/`.- `BoxSyncService.StartSyncProcess` — every 10 s, list localboxes, ask the API for boxes still marked STARTED upstream,and push any state mismatch to the API. One-way: **local state is- authoritative**, the API is the replica being corrected.+ authoritative**, the API is the replica being corrected. One+ exception: a box the API already shows STARTED is never told+ `creating` — a configured-but-never-booted local record folds+ into Creating, and reporting it stale would walk the box+ backwards and raise a false pending that blocks destroy. Real+ runtime exits (stopped, error) still push through.- `metrics.Collector.Start` — periodic CPU and allocation samplingfor the `/info` and `/metrics` endpoints (see _Metrics_).- `healthcheck.Service.Start` and `poller.Service.Start` — only ifdiff --git a/apps/runner/pkg/services/box_sync.go b/apps/runner/pkg/services/box_sync.goindex a1feff837..e84ab5633 100644--- a/apps/runner/pkg/services/box_sync.go+++ b/apps/runner/pkg/services/box_sync.go@@ -250,12 +250,20 @@ func (s *BoxSyncService) PerformSync(ctx context.Context) error {// local snapshot while keeping state and timestamp tied to the same lifecycle.// Every fact comes from one `BoxInfo`, so they cannot describe two lifecycles.//+// A control plane that already shows the box STARTED is never told Creating:+// a configured-but-never-booted record in a stale snapshot folds into+// Creating, and reporting it would walk the box backwards and raise a false+// pending that blocks destroy. A real runtime exit still reports through —+// Stopped, Stopping, Error carry news even against a remote STARTED.+//// Every other remote state keeps the long-standing behaviour: the local view// wins unconditionally.func (s *BoxSyncService) canReport(local localContainerState, remoteState apiclient.BoxState) bool {switch remoteState {case apiclient.BOXSTATE_CREATING, apiclient.BOXSTATE_STARTING:return local.state == enums.BoxStateStarted && local.startedAt != nil+ case apiclient.BOXSTATE_STARTED:+ return local.state != enums.BoxStateCreatingdefault:return true}diff --git a/apps/runner/pkg/services/box_sync_test.go b/apps/runner/pkg/services/box_sync_test.goindex 288bc9fb4..1a487d701 100644--- a/apps/runner/pkg/services/box_sync_test.go+++ b/apps/runner/pkg/services/box_sync_test.go@@ -324,6 +324,34 @@ func TestPerformSyncStaysQuietWhenStatesAgreeAndNothingIsOwed(t *testing.T) {}}+// A configured-but-never-booted local record folds into Creating. When that+// snapshot is stale — the box has since booted and the control plane already+// says STARTED — reporting it would walk the box back to CREATING, leave+// desiredState at STARTED, and the pending invariant would then block destroy.+// A box that is up now was never creating; a real runtime exit (STOPPED,+// ERROR) must still be reported, so only Creating is held back.+func TestPerformSyncDoesNotRegressStartedBoxToCreating(t *testing.T) {+ api := &runnerAPIStub{+ startedBoxes: []map[string]any{remoteBox("box-1", apiclient.BOXSTATE_STARTED)},+ transitionalBoxes: []map[string]any{},+ }+ server := httptest.NewServer(api.handler(t))+ defer server.Close()++ reader := &stubBoxReader{+ infos: []sdkboxlite.BoxInfo{{ID: "box-1", State: sdkboxlite.StateConfigured}},+ }++ service := newSyncServiceForTest(server, reader)+ if err := service.PerformSync(context.Background()); err != nil {+ t.Fatalf("PerformSync: %v", err)+ }++ if state := api.updates["/box/box-1/state"]; state != "" {+ t.Fatalf("stale configured snapshot regressed started box to %q", state)+ }+}+func TestPerformSyncStillReconcilesStartedBoxesWhenTransitionalQueryIsRejected(t *testing.T) {api := &runnerAPIStub{rejectTransitional: true,