Skip to content

workspace: add WorkspaceManager snapshot pre-warming and status lifecycle - #592

Merged
YoyinZyc merged 5 commits into
google:mainfrom
YoyinZyc:feat/ws5-workspace-reconciler
Nov 16, 2026
Merged

YoyinZyc merged 5 commits into
google:mainfrom
YoyinZyc:feat/ws5-workspace-reconciler

Conversation

@YoyinZyc

@YoyinZyc YoyinZyc commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #584

Summary

Adds the control-plane WorkspaceManager, store status persistence, synchronous actor snapshotting, and gRPC server / CLI wiring for Workspace snapshot pre-warming and lazy snapshot Tag caching, gated on SetupCoordinator until the pull-based runner channel is wired into ax-server.

Key Changes

  • pkg/apis/v1alpha1: Add WorkspacePhase (Preparing, Ready, Failed), WorkspaceCondition (SetupComplete, SnapshotReady), and WorkspaceReason constants.
  • internal/substrate:
    • Add SuspendActorAndWaitForSnapshot (DURABILITY_MODE_SYNCHRONOUS) so CreateTag runs only after the setup actor's durable snapshot is recorded.
    • Retry codes.Aborted in EnsureActorEgressPolicy and include codes.Aborted in IsTransientError.
    • Populate completed TagStatus.Snapshot in substratetest.CreateTag.
  • internal/store: Add UpdateWorkspaceStatus across Store, MemoryStore, and PostgresStore.
  • internal/controller:
    • Add WorkspaceManager (Prepare, EnsureSnapshotTag with per-tag distributed lock coalescing, incomplete-tag recovery, and fresh-actor bounded retries, plus Delete prefix cleanup for default + lazy tags and stranded setup actors).
    • Add NeedsPrewarmSnapshot (skipping setup actors for empty or pure-MCP workspaces) and the SetupCoordinator interface.
  • internal/server & cmd:
    • Wire WorkspaceManager into Server (CreateWorkspace / DeleteWorkspace) and cmd/ax-server, preserving codes.Unimplemented on spec.profile and spec.setup.gateway while SetupCoordinator is nil.
    • Reject CreateTask with codes.FailedPrecondition when the bound Workspace is in Preparing or Failed.
    • Add PHASE column to ax get workspaces and report configured when re-applying a Preparing Workspace.

No breaking runtime behavior change in this PR: SetupCoordinator is not yet wired in cmd/ax-server/main.go (PrewarmEnabled() == false), so CreateWorkspace continues to reject spec.profile and spec.setup.gateway with codes.Unimplemented and skips setup actor provisioning for existing Workspaces.

Next pr will wire production SetupCoordinator over the pull-based runner channel and wire TaskReconciler to resolve (Workspace, EffectiveProfile) via WorkspaceManager.EnsureSnapshotTag and boot Task actors from the snapshot Tag once the channel and task reconciler changes are ready.

Known gap (fix it follow up pr):

DeleteWorkspace and EnsureSnapshotTag are not mutually exclusively as they are holding different mutex locks.
#592 (comment)

…ycle

Part of google#563

- pkg/apis/v1alpha1: add WorkspacePhase, WorkspaceCondition, and WorkspaceReason constants.
- internal/substrate: add SuspendActorAndWaitForSnapshot (DURABILITY_MODE_SYNCHRONOUS), retry codes.Aborted in EnsureActorEgressPolicy, include codes.Aborted in IsTransientError, and populate completed TagStatus.Snapshot in substratetest.
- internal/store: add UpdateWorkspaceStatus across Store, MemoryStore, and PostgresStore.
- internal/controller: add WorkspaceManager (Prepare, EnsureSnapshotTag with per-tag lock coalescing and fresh setup actor retries, Delete prefix cleanup), NeedsPrewarmSnapshot, and SetupCoordinator interface.
- internal/server, cmd: wire WorkspaceManager into Server and ax-server, guard CreateTask against Preparing/Failed Workspaces, and surface PHASE in ax get workspaces.
@YoyinZyc
YoyinZyc marked this pull request as ready for review November 14, 2026 20:36
@YoyinZyc
YoyinZyc requested review from siyuanfoundation and yongruilin and removed request for rakyll November 14, 2026 20:36
@siyuanfoundation

Copy link
Copy Markdown
Collaborator

This has some conflicts with #591. Can we work together on #591 first because it unlocks 3 sub-workstreams?

@YoyinZyc

YoyinZyc commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

This has some conflicts with #591. Can we work together on #591 first because it unlocks 3 sub-workstreams?

I quickly compared the two prs, the good thing is that I don't think we have too many conflicts and I can easily have a follow up pr to connect #591.

  1. internal/substrate: basically identical for both prs to create the some helper specifically for warm snapshot
  2. Runner interface: I have a SetupCoordinator interface on workspace end, while there is another unimplemented SetupRunnerHandler interface in store: add TaskRow, TaskApplier, and StoredStatus runner seam #591. It is not a conflict, but it is something we could connect in next pr.
  3. WorkspaceSnapshotStore: I don't think we should persist the snapshot which is substrate resource. It may be useful for snapshot refresh. But let's keep it in next iteration. And it also does not have any reference in store: add TaskRow, TaskApplier, and StoredStatus runner seam #591 yet.

And #591 can be too big to review, as I already extracted the workspace specific part out, can I focus on this one to remove some noise from #591?

…s-setup- prefix

- Align SetupActorPrefix to "ax-ws-setup-" so the runner control plane can route temporary setup actor claims and events distinctly from Task actors.
- Split SetupCoordinator into RegisterSetup (invoked after EnsureActor with actorUID and before ResumeActor to eliminate the boot race), AwaitSetup, and DeleteSetup (for multi-replica store-backed coordination).
- Populate default actor Metadata.Uid in substratetest.CreateActor and verify pre-resume registration and cleanup in controller tests.
@YoyinZyc
YoyinZyc requested a review from rakyll November 15, 2026 05:45
@siyuanfoundation

Copy link
Copy Markdown
Collaborator

yes, WorkspaceSnapshotStore is used for ws refresh. It is ok to come back to it.

And #591 can be too big to review, as I already extracted the workspace specific part out, can I focus on this one to remove some noise from #591?

sounds good

Comment thread internal/controller/workspace.go Resolved
Comment thread internal/controller/workspace.go Resolved
Comment thread internal/server/workspace.go Resolved

// Step 3: Cold miss (or incomplete stranded Tag) — acquire a per-Tag
// distributed lock so concurrent requests coalesce onto one setup actor.
unlock, err := m.locker.Lock(ctx, "workspace-tag", atespace, tagName)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

this holds lock only for the ws tag, while DeleteWorkspace holds lock for the ws. They are not mutually exclusive. DeleteWorkspace could delete the tag while some lazy task is holding the tag lock.

@YoyinZyc YoyinZyc Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Good catch, if both holds the "workspace" lock, we will prevent the task with customized profile to start in parallel. So I think a better and most correct way is to have the RLock to allow parallel code start. I will fix it in the follow up pr.

Also added the todo in the code and documented it as a known gap.

- Wire --default-task-image / AX_DEFAULT_TASK_IMAGE through
  WorkspaceManagerOptions into ResolveProfileTemplate so omitted
  profile.image falls back to the server default task image.
- Move SetupActorPrefix to internal/apivalidation and reject Task names
  starting with ax-ws-setup- in ValidateTask.
- Persist WorkspaceStatus in prepareWorkspace with an independent
  context.WithoutCancel(ctx) timeout and map context.Canceled to
  codes.Canceled.
- Assign Metadata.Uid in defaultMetadata and key snapshot Tag and setup
  actor names by 16-hex SHA-256(uid), eliminating name truncation and
  cross-generation collisions on delete-and-recreate.
Comment thread internal/controller/workspace.go Resolved
Comment thread internal/controller/workspace.go Resolved
Comment thread internal/server/workspace.go Resolved
YoyinZyc added a commit to YoyinZyc/ax that referenced this pull request Nov 16, 2026
- Unexport needsPrewarmSnapshot and test it through WorkspaceManager.Prepare.
- Move ensureProfileTemplate to internal/controller/profile.go for sharing
  with TaskReconciler.
- Check existing Workspace in saveOrLoadWorkspace before resolving
  spec.setup.gateway so idempotent re-applies of Ready Workspaces succeed
  even if the setup gateway was deleted.
- Unexport needsPrewarmSnapshot and test it through WorkspaceManager.Prepare.
- Move ensureProfileTemplate to internal/controller/profile.go for sharing
  with TaskReconciler.
- Check existing Workspace in saveOrLoadWorkspace before resolving
  spec.setup.gateway so idempotent re-applies of Ready Workspaces succeed
  even if the setup gateway was deleted.
@YoyinZyc
YoyinZyc force-pushed the feat/ws5-workspace-reconciler branch from 2b8d5bf to 557784a Compare November 16, 2026 17:20

@yongruilin yongruilin left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

2 findings I feel critical.

Comment thread internal/server/workspace.go Resolved
Comment thread internal/controller/workspace.go Resolved
@siyuanfoundation

Copy link
Copy Markdown
Collaborator

/lgtm

@YoyinZyc
YoyinZyc merged commit 84ab0c7 into google:main Nov 16, 2026
10 checks passed
mayawang added a commit that referenced this pull request Nov 16, 2026
… is on (#607)

ax-server rejects spec.profile on a Workspace as not supported yet until
workspace pre-warming is enabled (#592), so Step 2 of the hero demo failed
at ax apply in live mode. Leave a TODO to add the profile back.

Verification:
  ./hack/hero-demo/run.sh   # prints the scoreboard, exit 0
workspace.yaml, task-starter.yaml and task-custom.yaml decode with the
strict v1alpha1 YAML decoder and pass ValidateWorkspace/ValidateTask and
ax-server's unimplemented-field checks; main's workspace.yaml fails the
latter with spec.profile.
siyuanfoundation added a commit to siyuanfoundation/ax that referenced this pull request Nov 17, 2026
- Drop queue, lease, sweep, and timer types (Action, ActionKind, SuspendReason, NextReconcileAt, ErrLockTimeout, reconciler/sweep inputs) so this phase reuses AX's synchronous Substrate lifecycle path (google#515, google#468, google#592).
- Extract server.storedStatus into store.StoredStatus and use it in TaskRow.SetLifecycleState so stored TaskStatus.state covers only AX-owned states while live actor state continues to be read from Substrate.
- Track Runnable, ClaimNonce, RunnerToken*, ActiveRunID, RunSeq, and LastAckedRunnerSeq on lifecycle.State for pull-based runner assignment and event fencing.

Signed-off-by: siyuanfoundation <[email protected]>
siyuanfoundation added a commit to siyuanfoundation/ax that referenced this pull request Nov 17, 2026
- Drop queue, lease, sweep, and timer types (Action, ActionKind, SuspendReason, NextReconcileAt, ErrLockTimeout, reconciler/sweep inputs) so this phase reuses AX's synchronous Substrate lifecycle path (google#515, google#468, google#592).
- Extract server.storedStatus into store.StoredStatus and use it in TaskRow.SetLifecycleState so stored TaskStatus.state covers only AX-owned states while live actor state continues to be read from Substrate.
- Track Runnable, ClaimNonce, RunnerToken*, ActiveRunID, RunSeq, and LastAckedRunnerSeq on lifecycle.State for pull-based runner assignment and event fencing.

Signed-off-by: siyuanfoundation <[email protected]>
siyuanfoundation added a commit that referenced this pull request Nov 17, 2026
* store, lifecycle: add TaskRow, TaskApplier, and lifecycle state/action contracts

Establish the minimal shared seam between the Task Reconciliation Loop
and the Task Runner + ax-server workstreams:

- Add transactional TaskApplier (TaskKey, TaskRow, DeleteTaskRow sentinel,
  ApplyFunc, LifecycleState / SetLifecycleState, ScrubStoredTask) and
  ErrLockTimeout in internal/store.
- Add pure Task lifecycle contract types (ActionKind, SuspendReason,
  Action, State, sealed Input variants, Output, TransitionFunc,
  IsTerminal), Transition contract stub, and NextReconcileAt in
  internal/lifecycle.
- Sync AGENTS.md and skills/substrate/SKILL.md.

* store, lifecycle: address review comments on contracts and tests

- Clarify on CreateInput that CreateTask always initializes new tasks in TASK_STATE_QUEUED (starting directly in TASK_STATE_SUSPENDED is unsupported).
- Guard nil receiver in (*TaskRow).SetLifecycleState and document Task.Status initialization in ApplyFunc.
- Guard non-zero ClaimDeadline in NextReconcileAt so a zero time cannot schedule a QUEUED task as permanently overdue.
- Expand lifecycle and store unit tests for past NotBefore, zero ClaimDeadline, terminal SUSPEND_ACTOR_SYNC, LastResumedAt, and nil-field/nil-receiver isolation.

Signed-off-by: siyuanfoundation <[email protected]>

* lifecycle: remove MaxQueueWaitDuration and Transition stub

- Drop MaxQueueWaitDuration so RESOURCE_EXHAUSTED backs off RESUME_ACTOR while keeping the task in TASK_STATE_QUEUED rather than failing after 30m (#468).
- Remove the ErrUnimplemented Transition stub (transition.go) so the state-machine PR adds Transition alongside its real implementation; preserve pure-transition contract invariants on TransitionFunc.

Signed-off-by: siyuanfoundation <[email protected]>

* store, lifecycle: trim seam to minimal sync-path runner contract

- Drop queue, lease, sweep, and timer types (Action, ActionKind, SuspendReason, NextReconcileAt, ErrLockTimeout, reconciler/sweep inputs) so this phase reuses AX's synchronous Substrate lifecycle path (#515, #468, #592).
- Extract server.storedStatus into store.StoredStatus and use it in TaskRow.SetLifecycleState so stored TaskStatus.state covers only AX-owned states while live actor state continues to be read from Substrate.
- Track Runnable, ClaimNonce, RunnerToken*, ActiveRunID, RunSeq, and LastAckedRunnerSeq on lifecycle.State for pull-based runner assignment and event fencing.

Signed-off-by: siyuanfoundation <[email protected]>

* store: consolidate runner seam onto TaskRow and defer internal/lifecycle

- Move runner control fields directly onto store.TaskRow and remove internal/lifecycle from this seam so the runner + ax-server PR introduces internal/lifecycle alongside its real Transition implementation and tests.

Signed-off-by: siyuanfoundation <[email protected]>

---------

Signed-off-by: siyuanfoundation <[email protected]>
itssimrank added a commit that referenced this pull request Nov 17, 2026
* store, lifecycle: add TaskRow, TaskApplier, and lifecycle state/action contracts

Establish the minimal shared seam between the Task Reconciliation Loop
and the Task Runner + ax-server workstreams:

- Add transactional TaskApplier (TaskKey, TaskRow, DeleteTaskRow sentinel,
  ApplyFunc, LifecycleState / SetLifecycleState, ScrubStoredTask) and
  ErrLockTimeout in internal/store.
- Add pure Task lifecycle contract types (ActionKind, SuspendReason,
  Action, State, sealed Input variants, Output, TransitionFunc,
  IsTerminal), Transition contract stub, and NextReconcileAt in
  internal/lifecycle.
- Sync AGENTS.md and skills/substrate/SKILL.md.

* store, lifecycle: address review comments on contracts and tests

- Clarify on CreateInput that CreateTask always initializes new tasks in TASK_STATE_QUEUED (starting directly in TASK_STATE_SUSPENDED is unsupported).
- Guard nil receiver in (*TaskRow).SetLifecycleState and document Task.Status initialization in ApplyFunc.
- Guard non-zero ClaimDeadline in NextReconcileAt so a zero time cannot schedule a QUEUED task as permanently overdue.
- Expand lifecycle and store unit tests for past NotBefore, zero ClaimDeadline, terminal SUSPEND_ACTOR_SYNC, LastResumedAt, and nil-field/nil-receiver isolation.

Signed-off-by: siyuanfoundation <[email protected]>

* lifecycle: remove MaxQueueWaitDuration and Transition stub

- Drop MaxQueueWaitDuration so RESOURCE_EXHAUSTED backs off RESUME_ACTOR while keeping the task in TASK_STATE_QUEUED rather than failing after 30m (#468).
- Remove the ErrUnimplemented Transition stub (transition.go) so the state-machine PR adds Transition alongside its real implementation; preserve pure-transition contract invariants on TransitionFunc.

Signed-off-by: siyuanfoundation <[email protected]>

* store, lifecycle: trim seam to minimal sync-path runner contract

- Drop queue, lease, sweep, and timer types (Action, ActionKind, SuspendReason, NextReconcileAt, ErrLockTimeout, reconciler/sweep inputs) so this phase reuses AX's synchronous Substrate lifecycle path (#515, #468, #592).
- Extract server.storedStatus into store.StoredStatus and use it in TaskRow.SetLifecycleState so stored TaskStatus.state covers only AX-owned states while live actor state continues to be read from Substrate.
- Track Runnable, ClaimNonce, RunnerToken*, ActiveRunID, RunSeq, and LastAckedRunnerSeq on lifecycle.State for pull-based runner assignment and event fencing.

Signed-off-by: siyuanfoundation <[email protected]>

* store: consolidate runner seam onto TaskRow and defer internal/lifecycle

- Move runner control fields directly onto store.TaskRow and remove internal/lifecycle from this seam so the runner + ax-server PR introduces internal/lifecycle alongside its real Transition implementation and tests.

Signed-off-by: siyuanfoundation <[email protected]>

* runner, lifecycle: add runner.v1 wire protocol and pure task/runner transitions

---------

Signed-off-by: siyuanfoundation <[email protected]>
Co-authored-by: siyuanfoundation <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants