Skip to content

store: add TaskRow, TaskApplier, and StoredStatus runner seam - #591

Merged
siyuanfoundation merged 5 commits into
google:mainfrom
siyuanfoundation:common-ground
Nov 17, 2026
Merged

siyuanfoundation merged 5 commits into
google:mainfrom
siyuanfoundation:common-ground

Conversation

@siyuanfoundation

@siyuanfoundation siyuanfoundation commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

This PR establishes the minimal shared internal/store seam between the TaskApplier Store and Pull-Based Task Runner + ax-server workstreams on top of AX's existing synchronous Substrate lifecycle path (#515, #592): store.TaskKey, store.TaskRow, store.DeleteTaskRow, store.ApplyFunc / store.TaskApplier, and store.StoredStatus (extracted from server.storedStatus).

Runner wire protos (runner.proto), pure internal/lifecycle transition rules, :8081 / :8080 server handlers, ax-task-runner, and PostgreSQL/in-memory TaskApplier implementations land in their respective follow-up PRs. Merging this PR introduces zero runtime or database behavior changes.


Seam Overview

flowchart LR
    GRPC["ax-server gRPC (:8080, sync Substrate RPCs)"] -- "store.TaskApplier.Apply" --> TasksDB[("store.TaskRow (Task, Runnable, ActiveRunID, RunnerToken*)")]
    Runner["ax-server Runner HTTP (:8081, Claim / Events)"] -- "store.TaskApplier.Apply" --> TasksDB
Loading
Stream Unblocked By (in this PR) Independent Follow-Up Scope
1. Store (TaskApplier) store.TaskApplier (TaskKey, TaskRow, DeleteTaskRow, ApplyFunc, StoredStatus) Add PostgreSQL tasks runner columns (generation, actor_uid, runnable, active_run_id, run_seq, runner_token_hash, runner_token_confirmed, claim_nonce, last_acked_runner_seq); implement TaskApplier (Apply, GetTaskRow) in internal/store/{postgres,memory}.
2. Task Runner + ax-server store.TaskApplier, store.TaskRow, store.StoredStatus Add pkg/apis/runner/v1 wire protocol and internal/lifecycle state transitions operating on *store.TaskRow; wire :8081 runner HTTP server (ClaimAssignment, ReportEvents, and WorkspaceManager's SetupCoordinator), shared Profile ActorTemplate + warm Workspace Tag provisioning on :8080, and ax-task-runner.

Contract Rules

  • Reuse of store.StoredStatus & live actor state (#515). server.storedStatus is extracted into store.StoredStatus and reused by internal/server and Apply. Stored TaskStatus.state covers only AX-owned states (v1alpha1.IsAXTaskState: QUEUED during provisioning, plus terminal COMPLETED, FAILED, CANCELLED), while WORKING, SUSPENDED, SUSPENDING, status.actor, and status.actor_uid continue to be derived live from Agent Substrate on read. TaskRow.Runnable tracks whether execution is authorized so :8081 ClaimAssignment returns ASSIGNMENT_MODE_IDLE when a paused actor is woken externally (e.g. ax ssh).
  • store.ApplyFunc & store.DeleteTaskRow (internal/store/task_apply.go). Returning nil or current itself leaves storage unchanged; returning store.DeleteTaskRow (matched strictly by pointer identity) deletes the row; returning any other non-nil *TaskRow scrubs Task.Status via StoredStatus and inserts or updates at Generation + 1. Perform all Substrate RPCs and external reads outside Apply so the row lock is held only across pure in-memory transitions.
  • Runner fencing & idempotency (store.TaskRow). ActorUID binds :8081 Actor JWT claims to the active actor incarnation; RunSeq (r-1, r-2, ...) is a task-lifetime monotonic run ID allocator that never resets across retries or cold restores; RunnerTokenHash / RunnerTokenConfirmed / ClaimNonce authenticate PID 1 and make lost-response initial claim retries idempotent; and LastAckedRunnerSeq deduplicates runner events within the active run.

Known Limitations of the Synchronous Path (Deferred to Async Reconciler Phase)

Adapting the synchronous Substrate path keeps this phase small and aligned with #515, #468, and #592, with the following intentional trade-offs until background reconciliation lands:

  1. No automatic recovery from sandbox crashes or lost runners: In-place command retries (exit_code != 0 while PID 1 ax-task-runner remains alive) are handled via ReportEvents, and terminal actor parking (SuspendActor after COMPLETED / FAILED) retries transient Substrate errors. However, if the sandbox itself crashes (ACTOR_STATE_CRASHED / OOMKilled) or the runner hangs silently, there is no background loop to execute REVERT_ACTOR + ResumeActor (GetTask surfaces FAILED / SANDBOX_CRASHED from live actor state).
  2. No automatic re-parking after ax ssh: Waking a SUSPENDED, COMPLETED, or FAILED actor via ax ssh (atenet-router) safely receives ASSIGNMENT_MODE_IDLE on ClaimAssignment so the task command never re-runs, but without a background drift sweep AX does not automatically re-suspend the actor after the ax ssh session ends.
  3. No IDLE multi-turn parking or background timers yet: Agent-driven TASK_STATE_IDLE (POST /idle) and wall-clock budget timers are deferred to the next phase.

Key Changes

  • internal/store & internal/server: Extracted store.StoredStatus from server.storedStatus (internal/server/server.go) and added TaskApplier (TaskKey, TaskRow, DeleteTaskRow, ApplyFunc in task_apply.go + task_apply_test.go).
  • AGENTS.md: Synced internal/store/ summary and test package count (22).

Testing

  • make verify (buf format, buf lint, buf generate, go mod tidy, go fmt, golangci-lint — 0 issues)
  • go build ./cmd/ax ./cmd/ax-server ./cmd/ax-task-runner
  • go test -race -count=1 ./... (all 22 test packages pass)

@siyuanfoundation

Copy link
Copy Markdown
Collaborator Author

/cc @YoyinZyc @itssimrank

@siyuanfoundation
siyuanfoundation marked this pull request as draft November 15, 2026 15:19
@siyuanfoundation siyuanfoundation changed the title task, store, runner: add contracts for task queue, lifecycle, runner, and warm snapshots task, store, runner: add cross-workstream contracts for runner, lifecycle, queue, and substrate Nov 15, 2026
Comment thread pkg/apis/runner/v1/runner.proto Resolved
Comment thread pkg/apis/runner/v1/runner.proto Resolved
Comment thread internal/lifecycle/reconcile.go Resolved
@siyuanfoundation
siyuanfoundation force-pushed the common-ground branch 2 times, most recently from 135a549 to 328aa77 Compare November 15, 2026 19:18
@siyuanfoundation siyuanfoundation changed the title task, store, runner: add cross-workstream contracts for runner, lifecycle, queue, and substrate task, store, runner: add cross-workstream contracts for runner, lifecycle, store, and substrate Nov 15, 2026
@siyuanfoundation siyuanfoundation changed the title task, store, runner: add cross-workstream contracts for runner, lifecycle, store, and substrate store, lifecycle: add TaskRow, TaskApplier, and lifecycle state/action contracts Nov 15, 2026
@siyuanfoundation
siyuanfoundation force-pushed the common-ground branch 3 times, most recently from 6f70de5 to f22e770 Compare November 15, 2026 20:06
@siyuanfoundation
siyuanfoundation marked this pull request as ready for review November 15, 2026 20:08
@siyuanfoundation
siyuanfoundation force-pushed the common-ground branch 2 times, most recently from 70804a9 to d3fb2b4 Compare November 15, 2026 20:47
Comment thread internal/lifecycle/types.go Outdated
WaitWorkspaceTag bool
}

func (*CreateInput) isInput() {}

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.

nit: Consider adding a comment clarifying whether CreateTask supports starting directly in TASK_STATE_SUSPENDED or if CreateInput always initializes new tasks in TASK_STATE_QUEUED.

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.

Addressed in b2a7af6: documented on CreateInput that CreateTask does not support starting directly in TASK_STATE_SUSPENDED and always initializes new tasks in TASK_STATE_QUEUED.

Comment thread internal/store/task_apply.go Outdated
// SetLifecycleState writes s onto r and recomputes NextReconcileAt at now.
// Live Substrate actor identity fields (status.actor and status.actor_uid) are
// scrubbed so they are never persisted.
func (r *TaskRow) SetLifecycleState(s lifecycle.State, now time.Time) {

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.

nit: Guard if r == nil in SetLifecycleState (matching Clone and LifecycleState), and document in ApplyFunc that Apply initializes Task.Status if nil before mirroring Task.Status.Generation.

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.

Addressed in b2a7af6: added the if r == nil guard in SetLifecycleState (with test coverage) and documented in ApplyFunc that Apply initializes Task.Status if nil before mirroring Generation.

Comment thread internal/lifecycle/reconcile.go Outdated
// 2. Otherwise, if the task is in QUEUED (not deleting) with a ClaimDeadline,
// the row is due at that exact ClaimDeadline (no periodic polling).
// 3. Steady-state tasks (WORKING, IDLE, SUSPENDED, terminal) return nil.
func NextReconcileAt(state State, now time.Time) *time.Time {

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.

Guard state.ClaimDeadline != nil && !state.ClaimDeadline.IsZero() so a zero ClaimDeadline cannot schedule a QUEUED task as permanently overdue.

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.

Addressed in b2a7af6: guarded !state.ClaimDeadline.IsZero() in NextReconcileAt and added a zero-ClaimDeadline test case.

Comment thread internal/lifecycle/lifecycle_test.go Outdated
}
}

func TestNextReconcileAt(t *testing.T) {

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.

Consider adding TestNextReconcileAt cases for a past NotBefore and a terminal task with a queued SUSPEND_ACTOR_SYNC action, plus LastResumedAt and nil-field isolation checks in TestStateCloneAndIdentifiers.

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.

Addressed in b2a7af6: added TestNextReconcileAt coverage for past NotBefore and terminal COMPLETED with queued SUSPEND_ACTOR_SYNC, plus LastResumedAt and nil/empty-field isolation checks in TestStateCloneAndIdentifiers.

@mayawang

Copy link
Copy Markdown
Collaborator

Nice to have the seam spelled out before both streams build on it. Two things I'd like to settle here, since they're cheap to change now:

  1. The store doc makes stored TaskStatus.state authoritative for every state. Working/idle are ours, makes sense to store them, but suspended/suspending duplicate the actor's state on Substrate, which server, store: move to Postgres and read actor state from Substrate #515 moved away from. Could stored state cover only what AX owns, and keep reading actor state live?
  2. MaxQueueWaitDuration has AX retry on RESOURCE_EXHAUSTED and fail the task after 30 min. Per Retry and waiting policy for Substrate errors #468 AX shouldn't queue for capacity (Substrate will), and a capacity error should leave the task pending, not failed.

Smaller: I'd trim the stub-only parts (Transition, the lock/lease errors, NextReconcileAt) and land them with the PRs that implement them, and reuse storedStatus instead of a second scrubber.

@rakyll curious if you see 1 the same way

@siyuanfoundation

siyuanfoundation commented Nov 16, 2026 •

Copy link
Copy Markdown
Collaborator Author

Nice to have the seam spelled out before both streams build on it. Two things I'd like to settle here, since they're cheap to change now:

  1. The store doc makes stored TaskStatus.state authoritative for every state. Working/idle are ours, makes sense to store them, but suspended/suspending duplicate the actor's state on Substrate, which server, store: move to Postgres and read actor state from Substrate #515 moved away from. Could stored state cover only what AX owns, and keep reading actor state live?

TASK_STATE_SUSPENDED does not actually map to ACTOR_STATE_SUSPENDED in ax. A parked actor on Substrate can represent five different AX states (IDLE between turns, SUSPENDED via SuspendTask/budget, COMPLETED/FAILED kept parked for ax ssh, or QUEUED between CREATE_ACTOR and RESUME_ACTOR / during retry backoff).

TASK_STATE_SUSPENDING is different from ACTOR_STATE_SUSPENDING because ax actions are moving to async and the task state is purely on the ax side now.

  1. MaxQueueWaitDuration has AX retry on RESOURCE_EXHAUSTED and fail the task after 30 min. Per Retry and waiting policy for Substrate errors #468 AX shouldn't queue for capacity (Substrate will), and a capacity error should leave the task pending, not failed.

Good catch. I removed MaxQueueWaitDuration so RESOURCE_EXHAUSTED leaves the task in TASK_STATE_QUEUED rather than failing after 30m. Still keeping DefaultActionMaxBackoff before the substrate queueing lands. Will remove after.

Smaller: I'd trim the stub-only parts (Transition, the lock/lease errors, NextReconcileAt) and land them with the PRs that implement them, and reuse storedStatus instead of a second scrubber.

@rakyll curious if you see 1 the same way

Dropped Transition. storedStatus is kept for now to keep the synchronous path intact. I do plan to remove it after the async path lands. In the async path, the stored State would be the source of truth (a separate loop will sync the actor state into store), so storedStatus does not apply there, and the new scrub does not apply to the sync path either.

NextReconcileAt is already implemented and used in the PR.

@mayawang

Copy link
Copy Markdown
Collaborator

Thanks, that's a fair distinction, an AX suspended isn't the actor's suspended. Since the async path makes stored state the source of truth with a loop syncing actor state in, that's a deliberate change from #515, so I'd like @rakyll to sign off on that direction before both streams build on it. On capacity, works for me as a stopgap, could you add a TODO pointing at agent-substrate/substrate#2059 so the backoff goes when Substrate queues?

@mayawang mayawang 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.

Approving so you and Simran aren't blocked, Jaana can do the retrospective storage review when she's back. Let's keep one line from standup: storing AX's own task states is fine, but no Substrate actor attributes in the store (actor UID, actor state, worker), read those live like today. So: non-blocking, could the persisted ActorUID move out of stored State (or be documented as the one fencing exception for Jaana to review), and please add the TODO pointing at agent-substrate/substrate#2059 for the capacity backoff. Needs a rebase on main too.

@rakyll

rakyll commented Nov 17, 2026

Copy link
Copy Markdown
Member

I haven't been able to follow up on the earlier design conversation related to this but do we have a real reconciliation use case for tasks? I think we should remove ax apply, and switch to ax create. Tasks may need mutation only for input steering but they will rely on some input protocol for those use cases. We cannot easily use Substrate as the underlying layer with queueing and additional capabilities with mutations.

@siyuanfoundation siyuanfoundation changed the title store, lifecycle: add TaskRow, TaskApplier, and lifecycle state/action contracts store, lifecycle: add minimal TaskRow, TaskApplier, and runner lifecycle seam Nov 17, 2026
@siyuanfoundation siyuanfoundation changed the title store, lifecycle: add minimal TaskRow, TaskApplier, and runner lifecycle seam store: add TaskRow, TaskApplier, and StoredStatus runner seam Nov 17, 2026
…n 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.
- 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]>
- Drop MaxQueueWaitDuration so RESOURCE_EXHAUSTED backs off RESUME_ACTOR while keeping the task in TASK_STATE_QUEUED rather than failing after 30m (google#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]>
- 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]>
- 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]>
@mayawang

Copy link
Copy Markdown
Collaborator

Thanks for trimming, this fits v0.1 well, good to merge. Two things for the follow-up that implements the runner channel (the :8081 handler and the TaskApplier store):

  1. v0.1 risk: Add NetworkPolicies for ax-server and Postgres #582's NetworkPolicy blocks worker pods and the egress gateway from reaching ax-server, so the runner needs a deliberate path in. Completion (hero demo Steps 3/4) and prewarm (Step 2) both depend on it.
  2. Long-term: we have both a minted runner token and Actor JWT fencing. Worth deciding if we need both, since that becomes the runner security model.

Who's picking up that follow-up, and do we have an ETA? Steps 2–4 of the hero demo can't go live until it lands, so it tells us what we can show at the exit gate.

@siyuanfoundation
siyuanfoundation merged commit 0a541d3 into google:main Nov 17, 2026
10 checks passed
@siyuanfoundation

Copy link
Copy Markdown
Collaborator Author

Thanks for trimming, this fits v0.1 well, good to merge. Two things for the follow-up that implements the runner channel (the :8081 handler and the TaskApplier store):

  1. v0.1 risk: Add NetworkPolicies for ax-server and Postgres #582's NetworkPolicy blocks worker pods and the egress gateway from reaching ax-server, so the runner needs a deliberate path in. Completion (hero demo Steps 3/4) and prewarm (Step 2) both depend on it.

We will add a rule to allow ingress to the :8081 port of the ax-server from atenet-egress.

  1. Long-term: we have both a minted runner token and Actor JWT fencing. Worth deciding if we need both, since that becomes the runner security model.

They are both needed actually. the JWT token is to proves which actor the traffic is from through the egress gateway, the runner token is to prove the request is from the runner process instead of the agent running in the actor.

Who's picking up that follow-up, and do we have an ETA? Steps 2–4 of the hero demo can't go live until it lands, so it tells us what we can show at the exit gate.

I can add the port rule as the followup.

@mayawang

Copy link
Copy Markdown
Collaborator

Thanks, both makes sense. One follow-up on the token: the runner starts the launcher as the same uid, so how do we keep the runner token out of the agent's reach? And for the :8081 handler itself, is that you too, and any rough ETA?

@siyuanfoundation

Copy link
Copy Markdown
Collaborator Author

One follow-up on the token: the runner starts the launcher as the same uid, so how do we keep the runner token out of the agent's reach? And for the :8081 handler itself, is that you too, and any rough ETA?

The launcher will not be launched with the same uid. We will default to use 1000 first.
For the :8081 handler itself, it is part of the server-runner contract, Simran will work on it.

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.

4 participants