Repository navigation
Support scoped repository work and typed decisions on Agents Runs - #1083
Conversation
5217383 to
5be5637
Compare
412f0bf to
494fe1b
Compare
|
@mjudeikis-bot review |
mjudeikis
left a comment
There was a problem hiding this comment.
Requested review of the 494fe1b head. No Critical findings. Three Warnings: two are marked Unverified because I traced the code but could not reproduce the interleaving. One more Warning is a missing test. The three Notes are inline. The PR is stacked and in draft; the PR body says runner tests, lint, hosted CI and the private integration are tracked separately.
Not anchored
store/store.go(RunArtifact.validate, ~324) bounds nothing on size or media type. The 32 KiB and 16 KiB limits live only intools/result.go, so any other caller ofSaveRunArtifactcan store an unbounded blob. This is a Note.- The 3-child fan-out cap (
delegation_budget.go:23,Limit: 3) is check-then-create, so concurrent delegate calls from one parent can exceed it. This is a Note. codex/mcp.goemitsdefault_tools_approval_modeandenabled_tools. Its test only checks the string is emitted, so nothing confirms the pinned Codex version accepts the key. This is a Note.harness_mcp.go:129-137: when the dispatcher is not acapabilityReader,ApprovedToolsis sent anyway, and an older runner rejects the unknown field. This is a Note.Postgres-only SQL (SaveRunOwned,RecordRunUsageOwned, the conflictWHEREclauses) is exercised only whenAGENTS_TEST_POSTGRES_DSNis set, andMemoryStore.saveRunLockedis more permissive than Postgres on unownedSaveRun. Memory-store tests can therefore pass on paths that fail on Postgres. This is a Note.
Checked
Read beyond the diff: api/resume.go, api/run_lease.go, api/run_lineage.go, api/recover.go, api/background.go (RecoverRun), api/runprojection.go, api/harness.go, api/harness_mcp.go, api/delegation_*.go, controller/run/controller.go (stranded, claimAndDispatch), controller/connection/controller.go, store/postgres.go and store/memory.go (claim, lease, usage, recovery paths), internal/githubapp/token.go, backend/model/model.go, tools/result.go, pkg/runner/{cleanup,git_result,environment,runner}.go, pkg/runner/harness/{environment.go,systemd_linux.go,codex/*}, pkg/runner/dispatch/events.go, the code provider's manifest and APIExport.
Hunt categories:
- Correctness: the findings above (
ClaimRecovery, the final-message ordering, the usage CAS,Doneon MCP errors). Lineage walks are bounded byvisited,maxRunLineageRowsand a repeated-cursor check. - Concurrency: the recovery/resume race and the fan-out cap above. I found no lock-order or goroutine-lifetime problems; the lease heartbeat is bounded by its deadline and context.
- Tenancy and kcp: every new store method filters
org_uuidandworkspace_uuid.githubapp.Mintpinsrepository_ids, read-onlycontentsandmetadata, a fixed API base, and refuses redirects.harness.go:716-731pins repositoryID, auth mode and secret name. No cross-tenant path found.permissionclaimpolicy.yaml, the APIExport copy and the chartfiles/apiexport.yamlare byte-identical, and the claim iscode.railgrid.aipullrequestsget andpullrequests/operate. No serviceaccount or clusterrole claims. - Provider contract:
manifest.yamland chartcatalogentry.yamlhave matchingrequires: code.dataplane_contract_test.go:372pins the text. No new routes or bearer verbs. - API, codegen and storage: no
apis/change. The new run columns and artifact tables are additive; I found no stored-format break. - Security: no credential in logs, errors or status. The checkout token is readable by the agent (see the harness.go Note). The
cleanup.gohook log refuses tracked paths andO_EXCL-reopens. - Portal: not applicable, since no portal files are in the diff.
- Tests: new lease, lineage and approval tests discriminate against the change except where listed above.
ConformanceTestand the verbs-match-manifest test are unchanged and pass.
Commands:
cd providers/agents && go build ./... && go vet ./... && go test -count=1 ./...: all pass. The embed needed a placeholderportal/distto build, which I added untracked.go build ./pkg/runner/... && go vet ./pkg/runner/... && go test -count=1 ./pkg/runner/...: pass, exceptpkg/runner/harnessTestResolveBinary*(two tests). These fail because/usr/local/bin/claudeexists on this host.resolve_test.gois not in the PR.make verify-provider-contract: passes (21/21 node tests; permission claim policy: 0 violations).- Not run:
make lint,make verify-codegen,make verify-boilerplate, Postgres-backed store tests (no DSN here), and e2e. Noapis/or portal files changed, and the e2e suites for providers need a kcp stack that I did not bring up here.
| string(RunPhaseRunning), now.UTC(), observed.UTC()) | ||
| AND updated_at=$6 | ||
| AND cancel_requested=FALSE | ||
| AND (execution_lease_at IS NULL OR execution_lease_at <= $5::timestamptz - interval '2 minutes') |
There was a problem hiding this comment.
Warning: Unverified: recovery sweep can claim an approval-resume run between ClaimRun and startRunLease
ClaimRun (postgres.go:1436) moves a parked run to Running with execution_owner='' and execution_lease_at=NULL. The run takes its lease only later, in startRunLease (api/run_lease.go:64), after resumeRun has done projection, agent lookup and attachment loading. In that window ClaimRecovery accepts the row because of execution_lease_at IS NULL. The Run controller's stranded() (controller/run/controller.go:~395) judges age from Status.StartedAt/ClaimedAt, not updated_at, so an approval that waited more than ClaimGrace already looks stale, and the projection write from resumeRun re-queues the reconcile. If recovery wins, attempt is bumped and the real resume fails in AcquireRunLease with ErrRunLeaseLost. For a caller-identity run recoverRun then fails it with "caller identity cannot be safely restored". I traced this by reading the code and did not reproduce the interleaving; no test runs a recovery claim between the two steps (execution_lease_test.go runs them in sequence). The memory store has the same rule (memory.go:1317 only guards a non-zero lease).
AND ((execution_lease_at IS NULL AND updated_at <= $5::timestamptz - interval '2 minutes')
OR execution_lease_at <= $5::timestamptz - interval '2 minutes')Apply the same rule in MemoryStore.ClaimRecovery, or have ClaimRun take the lease atomically.
| // The final transcript row is a terminal side effect. Write it only after | ||
| // this executor wins the owned terminal CAS so a stale lease cannot append | ||
| // an answer after a newer owner has taken over the run. | ||
| if werr := s.appendTurnFinal(persistCtx, scope, run, sessionID, startedAt, end, tracker, finalContent); werr != nil { |
There was a problem hiding this comment.
Warning: Run is reported Succeeded even when its final assistant message cannot be written
finishRunOwned commits Succeeded first, then appendTurnFinal runs and its error is only logged. The PR removed the previous guard (the removed block in the diff) that failed the run when the reply could not be persisted. If appendTurnFinal fails (transient DB error, persistCtx timeout) or the process dies between the two writes, the run is terminal Succeeded and the chat transcript has no answer. The final row also carries the tracker.continuation metadata, so the session loses its continuation. Terminal runs are not revisited by recovery. The ordering comment explains the lease fencing, but the failure mode is not handled.
// Write the final row inside the same owned terminal transaction, or retry it
// idempotently (fixed message ID) and fail the run when it still cannot be written:
if werr := s.appendTurnFinal(persistCtx, scope, run, sessionID, startedAt, end, tracker, finalContent); werr != nil {
log.Printf("run %s: persisting final assistant message after success: %v", runID, werr)
s.finishRunOwned(persistCtx, scope, runID, runOutcome{Phase: store.RunPhaseFailed, Message: "persist final assistant message: " + werr.Error()}, end, run.ExecutionOwner, run.Attempt)
}| var usageErr error | ||
| if run.ExecutionOwner != "" { | ||
| var recorded bool | ||
| window, recorded, usageErr = s.store.RecordRunUsageOwned(usageCtx, scope, runID, run.ExecutionOwner, run.Attempt, |
There was a problem hiding this comment.
Warning: Unverified: usage is dropped when a run is cancelled from another replica
RecordRunUsageOwned only updates a row with phase='Running' and the same owner and attempt (postgres.go ~2473). If replica B cancels a run executing on replica A, closeRunNow writes Aborted. When A's turn ends, recorded is false, line 1214 turns that into ErrRunLeaseLost, and line 1222 returns without calling AddUsage. The tokens and cost of a cancelled turn are never charged to the agent's budget window. I traced the SQL and this branch but did not run it against two replicas.
if usageErr == nil && !recorded {
// The row was settled (e.g. Aborted) under us; still charge the spend.
window, usageErr = s.store.AddUsage(usageCtx, scope, agent.Name,
out.Usage.Billed.InputTokens, out.Usage.Billed.OutputTokens, out.Usage.Billed.CostMicros, end, budgetWindow(agent.Spec.Budget))
}|
|
||
| // Reuse the native repository attempt: the runner performs private checkout and | ||
| // exports the canonical snapshot, rather than asking the model to clone/commit. | ||
| func (s *Server) delegatedRepository(ctx context.Context, d tools.Deps, child *agentsv1alpha1.Agent) (*repositoryAttempt, error) { |
There was a problem hiding this comment.
Warning: delegatedRepository has no test
This function decides which repository, commit and credential a delegated child run gets, and it holds the mismatch branches (repositoryID, repository name, task-mode UID). grep -rn delegatedRepository providers/agents finds only the caller in delegation_wait.go:66. TestRepositoryDispatchRequiresPinnedAppCheckoutAuthority covers rejections for the parent path only, and nothing asserts that the minted token lands in run.Repository.Source. Add table tests for a matching connection, a renamed repository, a swapped repositoryID and a task UID mismatch.
| return nil, fmt.Errorf("GitHub App connection %q: %w", connName, err) | ||
| } | ||
| if repositoryID != "" && run.Repository != nil { | ||
| run.Repository.Source = &runner.RepositorySource{RemoteURL: repositoryURL, Username: "x-access-token", Token: token} |
There was a problem hiding this comment.
Note: comments now contradict the checkout token handling
The token is stored in run.Repository.Source, and it is also exported as GH_TOKEN and GITHUB_TOKEN a few lines below. The comment at api/background.go (~1034, "never has its clone source") and the repository.go text about the token being included only for the turn describe the old behaviour. A prompt-injected agent can read the repository-scoped read-only token from the environment. Update the comments, and say in the docs that the token is readable by the agent.
| for head := 0; head < len(queue); head++ { | ||
| cursor := "" | ||
| for { | ||
| page, err := s.store.QueryRuns(ctx, scope, store.RunQuery{ParentRunID: queue[head], Limit: runDescendantPage, Cursor: cursor}) |
There was a problem hiding this comment.
Note: child-run lookups have no supporting index
QueryRuns with ParentRunID filters parent_run_id (store/postgres.go:1711). The only runs indexes are agents_runs_scope_idx (org_uuid, workspace_uuid, created_at DESC) and (phase, updated_at). The Run controller calls ReconcileDescendants on every reconcile of every terminal Run (controller/run/controller.go:252), so a run with no children scans the workspace's run history up to the whole table each time.
`CREATE INDEX IF NOT EXISTS agents_runs_parent_idx ON agents_runs (org_uuid, workspace_uuid, parent_run_id) WHERE parent_run_id <> ''`| Result: firstNonBlank(rec.Item.AggregatedOutput, rec.Item.Output, rec.Item.Result), | ||
| Args: firstNonBlank(rec.Item.Command, arguments), | ||
| Result: firstNonBlank(rec.Item.AggregatedOutput, rec.Item.Output, resultText), | ||
| Failed: mcpResult.IsError, |
There was a problem hiding this comment.
Note: a failed MCP tool item with no status is not marked Done
Failed: mcpResult.IsError sets Failed only. An item with an id, no status field and result.isError=true skips the Done switch below, so ToolEnd (line 447 requires item.Done) is never emitted and the tool stays in flight.
if mcpResult.IsError {
item.Done = true
}|
@mjudeikis-bot review again |
mjudeikis
left a comment
There was a problem hiding this comment.
Re-review of 7e13ac7 (one new commit since my review of 494fe1b). No new Critical or Warning findings. Two Notes inline.
Earlier findings
- Resolved:
ClaimRecoverycan claim an approval-resume run beforestartRunLease.ClaimRunnow takes the owner and setsexecution_lease_atin the same UPDATE (postgres.go:1531, memory.go ClaimRun), andresumeRunstarts the lease right after the claim. Theexecution_lease_at IS NULLwindow no longer exists whenProcessIDis set, and a claimed run can only be recovered after the 2 minute lease lapses. - Resolved: Succeeded reported when the final assistant message cannot be written.
CompleteRuncommits the Succeeded transition and the final message in one transaction (postgres.gosaveRunningRun, memory.gosaveRunningRun). A write failure now goes tofinishFailedTurn. - Resolved: usage dropped when a run is cancelled from another replica.
RecordRunUsageOwnedacceptsAbortedwithcancel_requestedfor the same owner and attempt (postgres.go, memory.go), andrunTurnchecksleaseWasLost(ctx)after billing. - Resolved:
delegatedRepositoryhad no test.TestDelegatedRepositoryChecksAdmittedCheckoutcovers the matching, renamed, swapped-ID and task-UID cases and asserts the minted token lands inrun.Repository.Source. - Resolved: the comments that contradicted the checkout token handling (background.go, repository.go, harness.go, README) now say the token is readable by the agent. The
agents_runs_parent_idxindex covers the child lookup. The failed MCP item with no status now setsDone. Artifact size and media type are bounded inRunArtifact.validate. The fan-out cap is now admitted underpg_advisory_xact_lockincheckDelegationAdmission. The review MCP is refused when the dispatcher cannot report capabilities. - No reply from the author declined any item.
Hunt, new commit
- Correctness: the
ClaimRunplaceholders shift correctly ($8owner,$9inbox ID).AcquireRunLeaseaccepts a row whose owner already equals the caller with a fresh lease. WithProcessIDempty the owner is"", the lease stays NULL, andCompleteRunwith an empty owner matches only an unleased row. The memory and Postgres rules agree. - Concurrency: the delegation advisory lock is keyed by org, workspace and parent and held until commit.
existinglets an idempotent re-save through. No lock-order change found. - Tenancy: the new queries filter
org_uuidandworkspace_uuid.SaveRunandsaveRunningRunnow also pinagent_name.delegatedRepositorystill checksrepositoryID, the repository name and the task UIDs. - Provider contract, API and codegen, portal: not applicable. The commit adds no route, verb, manifest, CRD or portal change.
- Security: the checkout token reaches the harness environment, which is now documented. No token in logs, errors or stored rows.
- Tests: new tests cover delegatedRepository, the lease claim ordering and the Codex config parse.
Not anchored
- Note: the Postgres paths added here (
ClaimRun ... RETURNING,CompleteRun/saveRunningRun,checkDelegationAdmission, the cancelled-usage branch) run only whenAGENTS_TEST_POSTGRES_DSNis set (store/postgres_test.go:25). I had no database (docker is denied in this runner), so the SQL is checked by reading only.
Checked
Read beyond the diff: api/run_lease.go (startRunLease, leaseWasLost, newExecutionOwner), store/postgres.go (AcquireRunLease, ReleaseRunLease, ClaimRecovery, SaveRun conflict handling), store/store.go (validateRunCompletion), api/run_progress.go (turnFinalMessage), api/delegation_repository.go, api/delegation_budget.go, api/resume.go, and every caller of ClaimRun and ClaimRecovery.
Commands:
cd providers/agents && go vet ./api/... ./store/... ./tools/...: clean. The module root does not build here becauseassets.goembedsportal/dist, which is not built in this checkout, so I scoped to the changed packages.go test -count=1 ./api/... ./store/... ./tools/... ./controller/...inproviders/agents: all pass. Postgres store tests skipped (no DSN).go test -count=1 ./pkg/runner/...at the root:pkg/runner,client,dispatch,harness/claude,harness/codexandrunnerclipass.pkg/runner/harnessfailsTestResolveBinaryLeavesExplicitPathsAndUnknownNamesAloneandTestResolveBinarySkipsNonExecutablesbecause this host has/usr/local/bin/claude. The commit does not touch that package, so this is environmental.- Not run:
make lint,make verify-*(noapis/, manifest, chart or portalkit change in this commit), and the e2e suites (they need the stack, and the PR notes that private integration is tracked separately).
| UPDATE agents_runs SET phase=$4, | ||
| updated_at=GREATEST($5::timestamptz, updated_at + interval '1 microsecond'), | ||
| started_at=COALESCE(started_at, GREATEST($5::timestamptz, updated_at + interval '1 microsecond')), | ||
| execution_owner=$8, |
There was a problem hiding this comment.
Note: the new claim-with-lease transition is only tested on the memory store
ClaimRun now sets execution_owner and execution_lease_at in this UPDATE, and resumeRun relies on it to close the recovery window. The memory-store tests pass, but the Postgres version (CASE expression, RETURNING, the $8/$9 placeholder order) runs only when AGENTS_TEST_POSTGRES_DSN is set. Add a Postgres case to execution_lease_test.go that claims a parked run and then asserts ClaimRecovery is rejected while the fresh lease is live.
// after ClaimRun(owner) on a PendingApproval run:
if _, err := st.ClaimRecovery(ctx, scope, id, claimed.UpdatedAt, "other/owner", claimed.UpdatedAt.Add(time.Second)); err == nil {
t.Fatal("recovery claimed a freshly leased resume")
}| // Point RAILGRID_TEST_CODEX_BINARY at the binary used by the runner's | ||
| // version pin to check its actual app-server configuration parser. | ||
| func TestApprovedMCPToolsLoadInCodexAppServer(t *testing.T) { | ||
| binary := os.Getenv("RAILGRID_TEST_CODEX_BINARY") |
There was a problem hiding this comment.
Note: the real Codex config check never runs in CI
TestApprovedMCPToolsLoadInCodexAppServer skips unless RAILGRID_TEST_CODEX_BINARY is set, and it was skipped when I ran the package. The default_tools_approval_mode and enabled_tools keys are therefore still unconfirmed against the pinned Codex version unless someone runs it by hand. Record the version you ran it against in the PR, or wire the variable into the runner image job.
Summary
Reuse existing Agents Runs for Factory orchestration. Pin private repository checkout to the admitted commit, use repository-scoped App checkout credentials, export verified runner snapshots, and record typed decisions as bounded result artifacts. Persist invocation ownership and delegated-run lineage for recovery.
Stacked on #1081. Factory admission and lifecycle are reviewed separately in the Providers repository.
Validation
Agents provider Go tests passed locally. Runner tests, lint, hosted CI, and private integration validation are tracked separately while this PR is in draft.
Review verification for
7e13ac77cTestPostgresRunExecutionLeaseContractpassed withAGENTS_TEST_POSTGRES_DSNset. The PostgreSQL test entry point runs the parked approval regression. It asserts thatClaimRungrants a fresh lease,ClaimRecoveryrejects a different owner during that lease, and the original owner can proceed. The same PostgreSQL run passed the atomic completion, concurrent delegation admission, and cancellation usage cases.TestApprovedMCPToolsLoadInCodexAppServerpassed locally withRAILGRID_TEST_CODEX_BINARYpointing to that binary. Its real app server returneddefault_tools_approval_mode = "approve"andenabled_tools = ["code_pull_request"]throughconfig/read.