fix: enforce classified Git admission paths (#2150) (#2181)

This commit is contained in:
Carlos Florêncio
2026-08-03 11:04:34 +01:00
committed by GitHub
parent 069cc99e10
commit 431e5d40fe
71 changed files with 3130 additions and 357 deletions
@@ -0,0 +1,97 @@
# Class-Aware Git Subprocess Admission
- **Status:** Accepted
- **Date:** 2026-08-02
- **Scope:** Backend and agentctl Git subprocess scheduling
- **Related spec:** [Git Subprocess Admission](../specs/platform/git-subprocess-admission.md)
- **Related issue:** [#2150](https://github.com/kdlbs/kandev/issues/2150)
## Context
Kandev has a process-wide semaphore that caps Git subprocess concurrency. All Git
callers enter the same queue, while some API handlers also impose their own
fan-out limit. This bounds peak process creation but does not guarantee progress
for workspace polling or repository lifecycle work during sustained interactive
traffic. It also leaves callers to decide whether admission time consumes a
command timeout.
The admission policy is a cross-cutting platform contract: every backend and
agentctl Git call must use it, future call sites must select the correct behavior,
and operators need to identify which kind of work is creating contention.
## Decision
Kandev will retain one process-local hard cap and make Git admission class-aware.
1. Every production Git operation declares `interactive`, `lifecycle`, or
`background` work when it enters the shared controller.
2. Each class uses a FIFO queue. On each released slot, the controller selects the
next non-empty class by deterministic round robin in this order:
`interactive`, `lifecycle`, `background`.
3. The scheduler is work-conserving. A class may use the entire capacity when no
other class is waiting; there are no reserved slots or independent quotas.
4. The global cap remains the only authority on active Git subprocess count and
continues to use `KANDEV_GIT_MAX_CONCURRENT`.
5. Admission uses the caller lifetime context. Per-command execution timeouts are
created only after admission succeeds.
6. Public Git wrappers require a work class. Classless production helpers are
removed or made inaccessible so new call sites cannot silently join the wrong
queue.
7. Aggregate metrics are preserved and supplemented by per-class admission
metrics and a structured snapshot exposed through authenticated diagnostics.
8. Multi-repository status, log, and diff handlers derive their local worker bound
from the shared Git capacity. Local fan-out controls queued work; it does not
create a second concurrency policy.
## Why deterministic round robin
Round robin gives every continuously queued class a simple bounded-progress rule
without tuning weights that lack workload evidence. It also remains
work-conserving: interactive work keeps full throughput when lifecycle and
background queues are empty. FIFO within a class makes cancellation and ordering
testable and avoids priority inversions inside a class.
## Alternatives considered
### Raise the global limit
Rejected as the scheduling policy. A larger cap may move the saturation point but
does not prevent one workload from excluding another, and it increases peak
process pressure on Windows.
### Keep only local fan-out caps
Rejected because concurrent requests and non-HTTP Git callers still meet at the
global semaphore. Independent local constants cannot enforce system-wide
progress or the total active-process bound.
### Reserve slots per class
Rejected because idle reservations reduce throughput and require choosing
platform-wide quota sizes without sufficient workload evidence.
### Strict interactive priority
Rejected because sustained user traffic could indefinitely delay workspace
monitoring and instance setup, recreating the liveness failure.
### Weighted scheduling
Deferred. It adds policy knobs and more complex guarantees. Deterministic round
robin is sufficient for the observed liveness problem; telemetry can justify a
future weight decision if needed.
## Consequences
- Git call sites become explicit about user-visible, lifecycle, or background
intent, making incorrect classification visible in code review.
- Every continuously queued class makes bounded progress once running commands
release slots, but the scheduler cannot preempt commands that are already
running.
- Admission and execution latency can be measured separately, preventing queue
delay from masquerading as repository failure.
- The controller becomes more complex than a semaphore and needs focused race,
cancellation, fairness, and accounting tests.
- Scheduling state remains process-local. Independent backend and agentctl
processes each enforce their own configured cap; cross-host coordination is not
introduced.
+1
View File
@@ -106,4 +106,5 @@ Read individual ADRs for full context. Create new ones via `/record decision` or
| 2026-08-02-new-workspace-github-access-defaults | [Bootstrap New Workspaces From Host GitHub Access](2026-08-02-new-workspace-github-access-defaults.md) | accepted | backend, frontend, security | 2026-08-02 |
| 2026-08-02-single-owner-agent-task-titles | [Assign Agent Task Titles to One Session](2026-08-02-single-owner-agent-task-titles.md) | accepted | backend, frontend, protocol, workflow | 2026-08-02 |
| 2026-08-02-agent-terminal-diagnostics-over-stderr | [Capture Agent Terminal Diagnostics From Managed Stderr](2026-08-02-agent-terminal-diagnostics-over-stderr.md) | accepted | backend, frontend, protocol, security | 2026-08-02 |
| 2026-08-02-class-aware-git-subprocess-admission | [Class-Aware Git Subprocess Admission](2026-08-02-class-aware-git-subprocess-admission.md) | accepted | backend, agentctl, observability | 2026-08-02 |
| 2026-08-02-isolate-replaceable-session-stream-traffic | [Isolate Replaceable Session Stream Traffic](2026-08-02-isolate-replaceable-session-stream-traffic.md) | accepted | backend, frontend, protocol | 2026-08-02 |
+235
View File
@@ -0,0 +1,235 @@
---
spec: docs/specs/platform/git-subprocess-admission.md
created: 2026-08-02
status: implemented
---
# Implementation Plan: Git Subprocess Admission
## Overview
Replace the undifferentiated Git semaphore with one class-aware,
work-conserving admission controller, then migrate interactive, lifecycle, and
background call sites onto its typed API. Complete the repair by separating
workspace-poll admission from execution timeouts and exposing authenticated
contention diagnostics. Public Git response contracts and the existing process
cap remain unchanged.
Confirmed root cause: all Git work waits on one undifferentiated process-wide
pool, while multi-repository interactive fan-out can fill that pool. Workspace
polling creates its 10-second context before admission and treats the resulting
queue timeout like a Git failure, so repeated contention can stop an otherwise
healthy tracker. The merged fan-out limits reduce pressure but do not provide
cross-class progress or separate queue delay from execution failure.
---
## Backend
### Shared class-aware admission
- **Files:** `apps/backend/internal/common/subproc/throttle.go`,
`apps/backend/internal/common/subproc/shared.go`,
`apps/backend/internal/common/subproc/metrics.go`, and focused sibling tests.
- Add the following public contract (names may vary only to match established Go
naming in the package):
```go
type GitWorkClass string
const (
GitInteractive GitWorkClass = "interactive"
GitLifecycle GitWorkClass = "lifecycle"
GitBackground GitWorkClass = "background"
)
func AcquireGit(ctx context.Context, class GitWorkClass) (release func(), err error)
func GitCapacity() int
func AdmissionSnapshot() Snapshot
```
- Implement one mutex-protected FIFO per class and a round-robin cursor ordered
`interactive`, `lifecycle`, `background`. Skip empty queues and grant
immediately whenever unused capacity exists.
- Remove canceled waiters under the scheduler lock and make release idempotent.
Aggregate and per-class counters must be updated from the same synchronized
state.
- Require `GitWorkClass` on run/output/combined-output helpers and any
after-admission command builder. Keep generic `Throttle` for `gh`; retain old
Git entry points only during migration, then remove or privatize them after all
call sites are classified.
- Preserve `KANDEV_GIT_MAX_CONCURRENT` resolution. Add only a test-scoped capacity
seam; runtime resizing is not part of this repair.
### Interactive operations and repository fan-out
- **Files:** `apps/backend/internal/agentctl/server/api/git.go`,
`apps/backend/internal/agentctl/server/api/git_fanout_test.go`, and agentctl
process Git operators outside the polling path, including `git.go`,
`git_pr_providers.go`, `workspace_files.go`, `workspace_git_cmd.go`,
`workspace_git_commits.go`, and `workspace_git_diff.go`.
- Classify user-request status, log, diff, staging, branch, commit, fetch, pull,
push, file-history, and PR-support commands as `GitInteractive`.
- Replace the unbounded status goroutine burst and `maxGitFanout = 8` with one
helper that creates at most
`min(repository count, subproc.GitCapacity())` workers.
- Preserve indexed result ordering, response shapes, and partial-error behavior.
Admission remains authoritative for active subprocess count across overlapping
requests.
### Backend lifecycle operations
- **Files:** `apps/backend/internal/worktree/git_throttle.go`,
`apps/backend/internal/worktree/manager_git.go`,
`apps/backend/internal/repoclone/clone.go`, and
`apps/backend/internal/agent/runtime/lifecycle/env_preparer_local.go`.
- Classify cloning, fetching, branch preparation, worktree creation/removal,
cleanup, rescan, and local runtime preparation as `GitLifecycle`.
- Preserve arguments, credentials, error wrapping, rollback, and cleanup. Use
focused search in the owned backend packages as the migration completeness
check.
### Workspace tracker admission and timeout ownership
- **Files:** `apps/backend/internal/agentctl/server/process/workspace_monitor.go`,
`workspace_git_cmd.go`, `workspace_git_poll.go`, `workspace_tracker.go`, and
focused sibling tests.
- Classify initial index resolution, tracker setup, and explicit rescan as
`GitLifecycle`; classify repeating polls as `GitBackground`.
- Acquire with the tracker lifetime context. Only after admission succeeds,
create the existing 10-second execution context and construct/start Git.
- Return an internal admission-canceled result that does not increment
consecutive Git failures. Preserve the five-failure stop rule for genuine
post-admission failures and the existing missing-workspace behavior.
- After interactive, lifecycle, and poller migrations are complete, remove or
privatize the classless Git entry points and use a repository-wide production
search plus compilation as the final completeness check.
### Authenticated diagnostics
- **Files:** `apps/backend/internal/agentctl/server/api/control_server.go`,
`apps/backend/internal/agent/runtime/agentctl/control.go` with focused tests.
- Preserve aggregate expvar metrics and add class-keyed inflight, waiter,
acquisition, and cumulative admission-wait values plus an immutable snapshot.
- Add authenticated `GET /api/v1/debug/subprocess-admission` to the agentctl
control group and `ControlClient.SubprocessAdmission(ctx)` using its existing
bearer transport.
---
## Tests
The controller fairness test, mixed interactive/background tracker test, and
authenticated diagnostic integration test are written first and must fail on
current behavior for the missing class policy, timeout boundary, and endpoint
respectively before implementation turns them green.
- **What:** hard cap, same-class FIFO, deterministic class rotation,
work-conserving admission, cancellation, idempotent release, env capacity, and
metric/snapshot accounting.
**File:** `apps/backend/internal/common/subproc/*_test.go`.
**How:** table-driven tests with capacity 1–3 and channels controlling grants,
releases, and cancel-versus-release races; repeat concurrency cases under
`go test -race`.
- **What:** capacity-derived fan-out and unchanged status/log/diff order and
partial results.
**File:** `apps/backend/internal/agentctl/server/api/git_fanout_test.go` and
focused handler tests.
**How:** overlapping handler requests against temporary repositories through
the real Git operator; assert peak inflight and `interactive` attribution.
- **What:** backend lifecycle classification and cancellation cleanup.
**File:** focused tests in `internal/worktree`, `internal/repoclone`, and
`internal/agent/runtime/lifecycle`.
**How:** saturate admission, cancel preparation, and assert no command starts and
existing rollback remains intact.
- **What:** interactive saturation cannot turn a queued poll into a Git failure.
**File:** `apps/backend/internal/agentctl/server/process/workspace_*_test.go`.
**How:** use a cross-platform helper process, hold interactive work, enqueue a
poll, release slots, and assert bounded execution, unchanged failure count, and
zero leaked slots/waiters.
- **What:** authenticated diagnostic path.
**File:** control-server and `ControlClient` tests.
**How:** exercise route → bearer-authenticated client and assert authorized,
unauthorized, and snapshot response behavior.
- **What:** before/after Windows evidence required to close issue #2150.
**File:** attach results to the issue or implementation PR; no permanent host
fixture.
**How:** with cap 12, run the same multi-repository workload on current `main`
and the completed branch; record p50/p95/max latency, admission/execution
timeouts, tracker stops, and peak Git process count.
---
## Verification Results
Implementation checks are recorded in the task files. The focused admission,
diagnostics, poller race tests, production classless-call audit, and
`make -C apps/backend build` all pass. The Windows before/after workload
comparison required to close issue #2150 remains an external evidence step and
is not available in this Linux worktree.
The affected backend package sweep also passes: `go test ./internal/common/subproc
./internal/agentctl/server/process ./internal/agentctl/server/api
./internal/worktree ./internal/agent/runtime/lifecycle
./internal/agent/runtime/agentctl ./internal/repoclone ./internal/debug
./internal/backendapp -count=1` — 2,340 tests across 9 packages.
Review-blocker validation also passes: the raw-Git repository guard is green,
the deterministic cancel/release boundary test is green under `go test -race
./internal/common/subproc`, and the fresh-status regression records only
`GitInteractive` admissions for every subprocess in that observation. A
compile-only sweep (`go test -run '^$' ./...`) is green after the final audit.
The repository-wide `go test -tags fts5 ./...` reached 10,254 passing tests and
29 skips but stopped on the pre-existing websocket assertion
`TestTaskEventBroadcaster_NoDuplicateSubscriptions` (62 subscriptions versus
its expected 61); the same isolated test fails without any files in this
change's scope.
---
## Implementation Waves And Parallel Candidates
Wave 1:
- [x] [task-01-class-aware-admission](task-01-class-aware-admission.md) — done
Wave 2 (parallel candidates — user authorization required):
- [x] [task-02-interactive-git-fanout](task-02-interactive-git-fanout.md) — done
- [x] [task-03-lifecycle-git-classification](task-03-lifecycle-git-classification.md) — done
- [x] [task-05-admission-diagnostics](task-05-admission-diagnostics.md) — done
Wave 3:
- [x] [task-04-poller-admission-liveness](task-04-poller-admission-liveness.md) — done
Wave 4:
- [x] [task-06-review-blockers](task-06-review-blockers.md) — done
The default is sequential execution in the primary conversation. Wave 2 is
parallel-safe only because the tasks own disjoint call-site, backend lifecycle,
and diagnostics files; waves do not authorize subagents.
---
## Risks and mitigations
| Risk | Mitigation |
| --- | --- |
| Cancellation races grant work after its caller exits | Queue removal, grant, and counters share one lock; targeted race tests cover cancel-versus-release |
| A forgotten call site remains classless | Remove or privatize classless Git access, audit raw command construction/lookup/exec paths, and enforce the repository guard |
| Round robin reduces single-class throughput | Scheduler skips empty queues and lets the only active class use full capacity |
| Fan-out refactor changes result order or partial errors | Preserve indexed result slots and add handler-level regression tests for all three operations |
| Diagnostics expose process-local state across runtimes | Keep the authenticated agentctl snapshot endpoint process-local and do not aggregate or persist it |
| Fair admission cannot help a permanently hung command | Keep post-admission execution timeouts and release slots on every terminal path |
## Completion criteria
- All task files have recorded passing validation commands.
- Production Git call sites compile only through a declared work class.
- Race tests cover the scheduler and tracker contention paths.
- Documentation links and indexes resolve.
- The Windows before/after evidence required by the spec is attached before
closing issue #2150.
@@ -0,0 +1,79 @@
---
id: "01-class-aware-admission"
title: "Class-aware admission controller"
status: done
wave: 1
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on: []
---
# Task 01: Class-Aware Admission Controller
## Acceptance
- Active work never exceeds the configured capacity across mixed classes.
- A continuously queued class is selected within three successful releases while
all classes remain queued; FIFO, cancellation, and single-class full throughput
remain deterministic.
- Aggregate `git` metrics remain compatible, class snapshot values match scheduler
state, and the generic `gh` throttle is unchanged.
- The class-aware Git throttle rejects classless `Acquire` calls so production
callers cannot silently default to a scheduling class.
## Verification
```bash
# Direct Go commands are required because the backend Makefile has no focused or
# race-test targets.
cd apps/backend && go test ./internal/common/subproc -run 'Test(Class|GitAdmission|Throttle|Metrics)' -count=1
cd apps/backend && go test -race ./internal/common/subproc -run 'Test(Class|GitAdmission|Throttle|Metrics)' -count=1
```
## Files Likely Touched
- `apps/backend/internal/common/subproc/throttle.go`
- `apps/backend/internal/common/subproc/shared.go`
- `apps/backend/internal/common/subproc/metrics.go`
- `apps/backend/internal/common/subproc/admission.go`
- `apps/backend/internal/common/subproc/admission_test.go`
- Existing sibling throttle, shared, and metrics tests as needed
## Dependencies
None.
## Parallelism
Sequential. Every later task depends on this scheduler and typed API.
## Inputs
- Spec sections: one global hard cap, explicit work classes, fair
work-conserving admission, and diagnostics.
- Plan section: Shared class-aware admission.
- Existing `Throttle`, environment capacity resolver, and expvar compatibility in
`internal/common/subproc`.
- ADR: `docs/decisions/2026-08-02-class-aware-git-subprocess-admission.md`.
## Output Contract
Report red tests, scheduler/API shape, metric compatibility, files changed,
exact command outcomes, race-test evidence, residual risks, and synchronized
task/plan status.
## Results
- RED: `TestGitAdmissionPublishesClassMetrics` failed because the class-level
expvar maps did not exist.
- GREEN: added class-aware FIFO queues, deterministic round-robin admission,
cancellation removal, idempotent release, capacity test seam, typed Git
admission, snapshots, and additive per-class metrics.
- `cd apps/backend && go test ./internal/common/subproc -run 'Test(Class|GitAdmission|Throttle|Metrics)' -count=1` — 17 passed.
- `cd apps/backend && go test -race ./internal/common/subproc -run 'Test(Class|GitAdmission|Throttle|Metrics)' -count=1` — 17 passed.
- `cd apps/backend && go test ./internal/common/subproc -count=1` — 30 passed.
- `cd apps/backend && go test ./internal/common/subproc ./internal/worktree ./internal/agentctl/server/process ./internal/repoclone ./internal/agent/runtime/lifecycle -run '^$'` — all affected packages compiled.
- Classless Git run wrappers were removed after the Task 04 production
call-site audit, and class-aware `Throttle.Acquire` now returns
`ErrGitWorkClassRequired`; generic `Throttle`/`gh` compatibility behavior
remains unchanged.
@@ -0,0 +1,78 @@
---
id: "02-interactive-git-fanout"
title: "Interactive Git fan-out"
status: done
wave: 2
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on:
- "01-class-aware-admission"
---
# Task 02: Interactive Git Fan-Out
## Acceptance
- Status, log, and diff share one capacity-derived worker policy.
- Multiple simultaneous handler requests never exceed the process-wide Git cap.
- All user-request agentctl Git commands declare `interactive`, with no classless
or hardcoded secondary concurrency path.
- Existing per-repository order, response schemas, and partial results remain
unchanged.
## Verification
```bash
# Direct Go commands are required because the backend Makefile has no focused or
# race-test targets.
cd apps/backend && go test ./internal/agentctl/server/api ./internal/agentctl/server/process -run 'Test(FanOutRepos|Git.*Admission|MultiRepo.*Class)' -count=1
cd apps/backend && go test -race ./internal/agentctl/server/api ./internal/agentctl/server/process -run 'Test(FanOutRepos|Git.*Admission|MultiRepo.*Class)' -count=1
```
## Files Likely Touched
- `apps/backend/internal/agentctl/server/api/git.go`
- `apps/backend/internal/agentctl/server/api/git_fanout_test.go`
- `apps/backend/internal/agentctl/server/process/git.go`
- `apps/backend/internal/agentctl/server/process/git_pr_providers.go`
- `apps/backend/internal/agentctl/server/process/workspace_files.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_cmd.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_commits.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_diff.go`
- Focused sibling tests for migrated operators
## Dependencies
Task 01 (`01-class-aware-admission`).
## Parallelism
Parallel-safe with Tasks 03 and 05 after Task 01. This task owns agentctl Git API
and non-poller process files; Task 03 owns backend lifecycle packages and Task 05
owns control/debug files.
## Inputs
- Spec sections: explicit work classes and consistent multi-repository behavior.
- Plan section: Interactive operations and repository fan-out.
- Existing indexed fan-out behavior in `api/git.go` and typed admission API from
Task 01.
## Output Contract
Report red tests, classification audit, fan-out worker rule, preserved response
semantics, files changed, exact command outcomes, race-test evidence, residual
risks, and synchronized task/plan status.
## Results
- RED: `TestFanOutReposRespectsLimit` failed after deriving its expected bound
from the configured capacity; the old fixed fan-out admitted five workers with
capacity three.
- GREEN: status, log, and cumulative-diff fan-out now derive their worker limit
from `subproc.GitCapacity()` while preserving indexed result order.
- User-triggered Git operator, PR-provider, workspace file, and content-at-ref
operations use `GitInteractive`; tracker-owned background paths were completed
by Task 04 with `GitBackground` admission and post-admission timeouts.
- `cd apps/backend && go test ./internal/agentctl/server/api ./internal/agentctl/server/process -run 'Test(FanOutRepos|Git.*Admission|MultiRepo.*Class)' -count=1` — 3 passed.
- `cd apps/backend && go test -race ./internal/agentctl/server/api ./internal/agentctl/server/process -run 'Test(FanOutRepos|Git.*Admission|MultiRepo.*Class)' -count=1` — 3 passed.
@@ -0,0 +1,74 @@
---
id: "03-lifecycle-git-classification"
title: "Lifecycle Git classification"
status: done
wave: 2
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on:
- "01-class-aware-admission"
---
# Task 03: Lifecycle Git Classification
## Acceptance
- Every backend lifecycle Git subprocess passes through `GitLifecycle` admission.
- No owned backend lifecycle package uses the old classless shared helper; the
GitHub CLI throttle remains unchanged.
- Lifecycle cancellation starts no subprocess and preserves arguments,
credentials, rollback, error wrapping, and cleanup guarantees.
## Verification
```bash
# Direct Go commands are required because the backend Makefile has no focused
# package target.
cd apps/backend && go test ./internal/worktree ./internal/agent/runtime/lifecycle ./internal/repoclone ./internal/task/service -run 'Test.*Git.*(Admission|Class|Cancel)' -count=1
cd apps/backend && go test ./internal/common/subproc ./internal/worktree ./internal/agent/runtime/lifecycle ./internal/repoclone ./internal/task/service -count=1
cd apps/backend && ! rg -n 'subproc\.Git\(\)' internal/worktree internal/repoclone internal/agent/runtime/lifecycle --glob '*.go' --glob '!*_test.go'
```
Compilation verifies the new required class argument on run helpers; the final
search verifies the owned packages no longer use the classless throttle accessor.
## Files Likely Touched
- `apps/backend/internal/worktree/git_throttle.go`
- `apps/backend/internal/worktree/manager_git.go`
- `apps/backend/internal/repoclone/clone.go`
- `apps/backend/internal/agent/runtime/lifecycle/env_preparer_local.go`
- Focused sibling tests for cancellation and classification
## Dependencies
Task 01 (`01-class-aware-admission`).
## Parallelism
Parallel-safe with Tasks 02 and 05 after Task 01. This task owns backend
lifecycle packages; the other tasks own agentctl API/process and diagnostics.
## Inputs
- Spec section: explicit work classes.
- Plan section: Backend lifecycle operations.
- Task 01 typed helpers and the lifecycle-package call-site search recorded in
the design investigation.
## Output Contract
Report the lifecycle call-site classification, red tests, files changed, exact
command outcomes, cleanup evidence, residual risks, and synchronized task/plan
status.
## Results
- Migrated worktree, repository-clone, and local runtime preparation Git calls to
`GitLifecycle`, including explicit acquire-before-execution-timeout paths.
- Moved the worktree capacity seam into its test file so production lifecycle
packages have no classless `subproc.Git()` usage.
- `cd apps/backend && go test ./internal/worktree ./internal/agent/runtime/lifecycle ./internal/repoclone ./internal/task/service -run 'Test.*Git.*(Admission|Class|Cancel)' -count=1` — 1 passed.
- `cd apps/backend && go test ./internal/common/subproc ./internal/worktree ./internal/agent/runtime/lifecycle ./internal/repoclone ./internal/task/service -count=1` — passed.
- `cd apps/backend && ! rg -n 'subproc\.Git\(\)' internal/worktree internal/repoclone internal/agent/runtime/lifecycle --glob '*.go' --glob '!*_test.go'` — no production matches.
- `cd apps/backend && go test -race ./internal/worktree ./internal/agent/runtime/lifecycle ./internal/repoclone ./internal/task/service -run 'Test.*Git.*(Admission|Class|Cancel)' -count=1` — 1 passed.
@@ -0,0 +1,87 @@
---
id: "04-poller-admission-liveness"
title: "Poller admission liveness"
status: done
wave: 3
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on:
- "01-class-aware-admission"
- "02-interactive-git-fanout"
- "03-lifecycle-git-classification"
---
# Task 04: Poller Admission Liveness
## Acceptance
- Admission wait does not consume the Git execution timeout.
- Admission cancellation does not increment the tracker failure counter or stop a
healthy tracker; genuine post-admission failures retain the five-failure rule.
- Tracker setup uses `lifecycle`, repeating polls use `background`, and a queued
poll progresses within the bounded class rotation after slots release.
- No production package can access the classless Git throttle or run helpers once
all migrations finish.
## Verification
```bash
# Direct Go commands are required because the backend Makefile has no focused or
# race-test targets.
cd apps/backend && go test ./internal/agentctl/server/process -run 'TestWorkspace.*(Admission|Timeout|Monitor)|TestRunPollingGit' -count=1
cd apps/backend && go test -race ./internal/agentctl/server/process -run 'TestWorkspace.*(Admission|Timeout|Monitor)|TestRunPollingGit' -count=1
cd apps/backend && ! rg -n 'subproc\.Git\(\)' internal --glob '*.go' --glob '!*_test.go'
make -C apps/backend build
```
## Files Likely Touched
- `apps/backend/internal/agentctl/server/process/workspace_monitor.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_cmd.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_poll.go`
- `apps/backend/internal/agentctl/server/process/workspace_tracker.go`
- `apps/backend/internal/common/subproc/shared.go`
- Focused `workspace_*_test.go` files and cross-platform helper-process fixture
## Dependencies
Tasks 01 (`01-class-aware-admission`), 02 (`02-interactive-git-fanout`), and 03
(`03-lifecycle-git-classification`).
## Parallelism
Sequential after Wave 2. This completes the agentctl process migration and its
mixed interactive/background tests overlap Task 02's package ownership.
## Inputs
- Spec sections: admission and execution are different phases; interactive load
cannot disable workspace tracking.
- Plan section: Workspace tracker admission and timeout ownership.
- Existing 10-second polling context, five-consecutive-failure behavior, and the
completed production call-site migrations from Tasks 02 and 03.
## Output Contract
Report red contention evidence, admission-versus-execution result semantics,
classless-API removal/search evidence, files changed, exact command outcomes,
race-test and cleanup evidence, preserved failure behavior, residual risks, and
synchronized task/plan status.
## Results
- RED: `TestWorkspaceGitAdmissionWaitDoesNotConsumeTimeout` observed the
queued command inheriting the already-expired 100 ms context and returning
`context deadline exceeded` before the admission/timeout split.
- GREEN: polling and tracker setup now use explicit `background`/`lifecycle`
classes, execution timers start only after admission, and admission
cancellation resets rather than advances the tracker failure counter.
Classless Git run wrappers were removed after the production call-site audit;
the class-aware throttle also rejects classless `Acquire` calls.
- `cd apps/backend && go test ./internal/agentctl/server/process -run 'TestWorkspace.*(Admission|Timeout|Monitor)|TestRunPollingGit' -count=1` — 2 passed.
- `cd apps/backend && go test -race ./internal/agentctl/server/process -run 'TestWorkspace.*(Admission|Timeout|Monitor)|TestRunPollingGit' -count=1` — 2 passed.
- `cd apps/backend && ! rg -n 'subproc\.Git\(\)' internal --glob '*.go' --glob '!*_test.go'` — no production matches.
- `make -C apps/backend build` — passed for agentctl, backend, and companion
binaries (the environment reported only the existing codesign-tool warning).
- Admission helper tests additionally cover timeout freshness and wrapped
cancellation: `cd apps/backend && go test -race ./internal/common/subproc -run 'TestRunGitOutputAfterAcquire|TestClassAdmission' -count=1` — 8 passed.
@@ -0,0 +1,69 @@
---
id: "05-admission-diagnostics"
title: "Admission diagnostics"
status: done
wave: 2
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on:
- "01-class-aware-admission"
---
# Task 05: Admission Diagnostics
## Acceptance
- The agentctl snapshot is inaccessible without its existing bearer credential.
- The authenticated agentctl endpoint reports the process-local admission
snapshot without exposing or changing the bearer credential.
- Metrics distinguish inflight work, waiters, acquisitions, and wait time per
class while preserving aggregate Git keys and adding no mutable settings or UI.
## Verification
```bash
# Direct Go commands are required because the backend Makefile has no focused or
# race-test targets.
cd apps/backend && go test ./internal/agentctl/server/api ./internal/agent/runtime/agentctl -run 'Test.*SubprocessAdmission' -count=1
cd apps/backend && go test -race ./internal/agentctl/server/api ./internal/agent/runtime/agentctl -run 'Test.*SubprocessAdmission' -count=1
```
## Files Likely Touched
- `apps/backend/internal/agentctl/server/api/control_server.go`
- Focused agentctl control-server tests
- `apps/backend/internal/agent/runtime/agentctl/control.go`
- Focused `ControlClient` tests
## Dependencies
Task 01 (`01-class-aware-admission`).
## Parallelism
Parallel-safe with Tasks 02 and 03 after Task 01. This task owns control-server,
control-client, debug, and backend wiring files, not Git call sites.
## Inputs
- Spec sections: diagnostics, API and permissions, persistence guarantees.
- Plan section: Authenticated diagnostics.
- Existing agentctl bearer middleware and `ControlClient` auth transport.
## Output Contract
Report red authorization tests, response shape, files changed, exact command
outcomes, race-test evidence, security boundary, residual risks, and synchronized
task/plan status.
## Results
- RED: the authenticated control-server test returned 404 for the new
admission route and the client test failed before the route/client contract
existed.
- GREEN: added the bearer-protected agentctl admission snapshot route, the
authenticated `ControlClient` probe, and standalone/lifecycle provider wiring.
- `cd apps/backend && go test ./internal/agentctl/server/api ./internal/agent/runtime/agentctl -run 'Test.*SubprocessAdmission' -count=1` — passed.
- `cd apps/backend && go test -race ./internal/agentctl/server/api ./internal/agent/runtime/agentctl -run 'Test.*SubprocessAdmission' -count=1` — passed.
- The endpoint uses the existing control-server bearer middleware and returns
only the owning agentctl process's in-memory snapshot.
@@ -0,0 +1,90 @@
---
id: "06-review-blockers"
title: "Close admission review blockers"
status: done
wave: 4
plan: "plan.md"
spec: "../../specs/platform/git-subprocess-admission.md"
depends_on:
- "01-class-aware-admission"
- "02-interactive-git-fanout"
- "03-lifecycle-git-classification"
- "04-poller-admission-liveness"
---
# Task 06: Close Admission Review Blockers
## Root Cause
The first migration audited the old `subproc.Git()` accessor but not every raw
`exec.Command*(..., "git", ...)` invocation. The scheduler also treated a
cancel-versus-release interleaving as a successful grant, and fresh status used
the background-only polling helper for its final porcelain command.
## Acceptance
- Every production Git command starts through an explicitly classified shared
helper; a repository guard rejects raw Git execution outside tests and the
approved command-construction seam.
- A waiter canceled at the grant boundary returns `ErrAdmissionCanceled` (and
the context error), starts no command, and leaves the round-robin cursor and
slot accounting correct.
- Every subprocess in a fresh interactive status observation is admitted as
`GitInteractive`; polling commands remain `GitBackground` and retain
`GIT_OPTIONAL_LOCKS=0`.
## Verification
```bash
cd apps/backend && go test ./internal/common/subproc -run 'Test(ClassAdmission|GitAdmission|Throttle|RawGit|FreshStatus)' -count=1
cd apps/backend && go test -race ./internal/common/subproc -run 'Test(ClassAdmission|GitAdmission|Throttle|RawGit|FreshStatus)' -count=1
cd apps/backend && go test ./internal/agentctl/server/process -run 'Test(.*FreshStatus|.*Admission|.*Poll)' -count=1
cd apps/backend && go test -race ./internal/agentctl/server/process -run 'Test(.*FreshStatus|.*Admission|.*Poll)' -count=1
cd apps/backend && go test ./internal/agent/runtime/lifecycle ./internal/backendapp ./internal/agentctl/server/api -run 'Test.*(Git|Admission|Materialize|Worktree)' -count=1
cd apps/backend && rg -n 'exec\.(Command|CommandContext)\([^\n]*"git"|exec\.LookPath\("git"\)|\b(unix|syscall)\.Exec\(' . --glob '*.go' --glob '!*_test.go'
```
## Files
- `apps/backend/internal/common/subproc/admission.go`
- `apps/backend/internal/common/subproc/admission_test.go`
- `apps/backend/internal/common/subproc/raw_git_audit_test.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_cmd.go`
- `apps/backend/internal/agentctl/server/process/workspace_git_status.go`
- `apps/backend/cmd/agentctl/github_cli_shim.go`
- `apps/backend/cmd/mock-agent/scenarios.go`
- direct Git call sites identified by the repository audit
- this task's sibling tests and the shared command helpers
## Results
- Migrated remaining production Git construction paths (task services, local
repository initialization, worktree helpers, agentctl materialization, and
lifecycle helpers) to the shared command seam and classified runners.
- Added a repository AST guard that rejects raw Git command construction,
executable lookup, and direct `unix/syscall.Exec` outside the `subproc` seam.
- Made cancellation win both queue-head dispatch and the post-grant select
boundary; canceled grants release their slot before returning the context
error.
- Split lock suppression from scheduling class so fresh status remains
`GitInteractive` while background polling remains `GitBackground`.
- Added deterministic cancellation/release and fresh-status class-attribution
regression tests.
Validation:
```text
go test ./internal/common/subproc ./internal/task/gitinit ./internal/task/service -run 'TestProductionGitCommandsUseTheAdmissionSeam|TestClassAdmissionCancellationWinsReleaseBoundary|TestClassAdmissionCancellationDoesNotAdvanceQueue|TestPerformFreshBranch|TestInitializeLocalRepository' -count=1 # pass
go test -race ./internal/common/subproc -count=1 # 32 tests pass
go test ./internal/agentctl/server/process ./internal/common/subproc ./internal/task/service ./internal/task/gitinit ./internal/backendapp ./internal/agent/runtime/lifecycle ./internal/agentctl/server/api ./internal/worktree ./internal/repoclone ./internal/office/configloader ./internal/office/skills ./internal/office/testharness ./internal/orchestrator/executor -count=1 # pass
go test ./cmd/agentctl ./cmd/mock-agent -count=1 # 259 tests pass
go test -run '^$' ./... # compile pass
make -C apps/backend build # pass
```
The repository-wide `go test -tags fts5 ./...` reached 10,254 passing tests,
29 skips, and one pre-existing failure in
`TestTaskEventBroadcaster_NoDuplicateSubscriptions` (62 subscriptions versus
61). The isolated websocket test reproduces the same failure outside this
change's scope (`go test -tags fts5 ./internal/gateway/websocket -run
TestTaskEventBroadcaster_NoDuplicateSubscriptions -count=1`).
+1
View File
@@ -44,6 +44,7 @@ Product-wide capabilities that are not tied to a single feature area.
| [plugins — marketplace](plugins/marketplace.md) | building |
| [semantic-notifications](platform/notifications.md) | shipped |
| [workspace-git-status](platform/workspace-git-status.md) | shipped |
| [git-subprocess-admission](platform/git-subprocess-admission.md) | building |
| [bounded-task-status-delivery](platform/bounded-task-status-delivery.md) | approved |
| [diagnostic-logging](platform/diagnostic-logging.md) | approved |
@@ -0,0 +1,210 @@
---
title: Git Subprocess Admission
status: building
created: 2026-08-02
owner: kandev
---
# Git Subprocess Admission
Related issue: [#2150](https://github.com/kdlbs/kandev/issues/2150)
## Why
Kandev limits concurrent Git subprocesses, but every caller currently competes in
one undifferentiated pool. A burst of interactive multi-repository log, diff, or
status work can occupy the pool long enough for workspace monitoring and
instance setup to wait behind it. Workspace polling also starts its execution
timeout before admission, so queue delay can be reported as a Git failure and
eventually stop a healthy tracker.
The existing fan-out caps reduce the frequency of saturation, but they do not
define which work may progress under contention or distinguish admission delay
from command failure. The platform needs one enforceable concurrency boundary
with deterministic progress for every kind of Git work.
## What
### One global hard cap
- All Git subprocesses in a Kandev process MUST pass through one process-wide
admission controller.
- Active Git subprocesses MUST never exceed `KANDEV_GIT_MAX_CONCURRENT`.
- The existing default and environment override remain unchanged by this work.
- A caller that is the only queued work MAY use all available capacity. Separate
per-class pools that can exceed the global cap are not permitted.
### Explicit work classes
Every production Git operation MUST declare one of these classes:
| Class | Work included |
| --- | --- |
| `interactive` | User-observed Git requests, including status, log, diff, staging, commits, and pushes |
| `lifecycle` | Repository, worktree, runtime, tracker setup, cleanup, rescans, and instance construction |
| `background` | Periodic workspace polling and detached refresh work |
Classless production helpers are not part of the supported API. Tests MAY use a
dedicated capacity seam without weakening production classification.
### Fair, work-conserving admission
- Each class has a FIFO wait queue.
- Released slots are assigned in deterministic round-robin order across non-empty
classes: `interactive`, then `lifecycle`, then `background`, then repeat.
- Empty classes are skipped, so available capacity is never reserved for work
that does not exist.
- When all three classes remain queued and admitted commands complete, each class
receives a slot within at most three successful slot releases.
- Already-running commands are not preempted.
- A canceled waiter is removed promptly and MUST NOT consume a slot or start a
subprocess.
### Admission and execution are different phases
- Admission waits under the lifetime context supplied by the caller.
- A command-specific execution timeout starts only after admission succeeds and
before the subprocess starts.
- Admission cancellation or queue delay MUST NOT be counted as a Git command
failure and MUST NOT advance the workspace tracker's permanent-failure counter.
- A Git failure or timeout after admission still follows the caller's existing
error policy, releases its slot, and may advance the tracker failure counter.
- Missing or removed workspaces retain their existing stop behavior.
### Consistent multi-repository behavior
- Multi-repository status, log, and diff requests use one shared fan-out policy.
- Fan-out worker counts are derived from the configured Git capacity rather than
a separate hardcoded concurrency constant.
- The admission controller remains authoritative for active subprocess count;
local fan-out only bounds goroutine and queued-work creation.
- Existing HTTP and WebSocket response shapes, ordering guarantees, and partial
result behavior remain unchanged.
### Diagnostics
- Existing aggregate Git subprocess metrics remain available for compatibility.
- Admission metrics additionally expose, per class: active work, waiters,
admission attempts, and cumulative admission wait time.
- The agentctl control server exposes its process-wide admission snapshot through
an authenticated debug endpoint.
- Admission state is in-memory and resets when its owning process restarts.
## API and permissions
- Existing user-facing Git APIs are unchanged.
- Agentctl adds `GET /api/v1/debug/subprocess-admission` on its control server.
The route requires the same bearer token as instance-management routes and is
not added to the health or handshake authentication exemptions.
- The endpoint permits no changing of capacity, queues, work classes, or running
commands.
## Persistence guarantees
The controller, queues, counters, and structured snapshots are process-local
runtime state. They are not written to SQLite or restored after restart. The
configured capacity continues to come from the existing environment/default
resolution at process startup.
## Failure modes
- If a waiting request is canceled, it returns the context error without starting
Git and without disturbing the round-robin cursor.
- If Git cannot start after admission, the slot is released and the start error is
reported as an execution failure.
- If a running command exceeds its execution timeout, it is canceled, the slot is
released, and the normal post-admission failure policy applies.
- If the agentctl debug endpoint is unavailable, the caller receives the existing
control-client error; no admission state is persisted or inferred remotely.
## Scenarios
### Interactive load cannot disable workspace tracking
1. Interactive multi-repository requests keep their queue continuously populated.
2. A workspace poll enters the `background` queue.
3. The poll receives admission within the bounded round-robin window.
4. Its execution timeout begins after admission.
5. Queueing alone does not increase the tracker failure count or stop monitoring.
### Background work cannot starve instance setup
1. Background polling occupies and replenishes the available capacity.
2. Repository or tracker setup enters the `lifecycle` queue.
3. Lifecycle work receives a slot within the bounded round-robin window.
4. Other classes continue to use remaining slots without exceeding the global cap.
### Single-class throughput remains available
1. Only interactive work is queued.
2. Interactive work consumes every available slot.
3. No capacity remains idle solely to preserve a class reservation.
### Cancellation while queued is safe
1. A request waits while the global cap is full.
2. Its context is canceled before admission.
3. It leaves the queue promptly, starts no subprocess, and does not block the next
eligible waiter.
### Cancellation wins a simultaneous grant race
1. A queued request is canceled at the same scheduling boundary that releases a
slot.
2. The scheduler removes the canceled waiter before advancing the round-robin
cursor, or returns an admission-canceled result if cancellation wins after a
grant notification.
3. The canceled request starts no Git subprocess and does not consume a slot or
count as a post-admission failure.
### Fresh status keeps interactive classification
1. A user requests fresh status while the tracker is also capable of polling.
2. Every Git subprocess spawned for that fresh observation is admitted as
`interactive`, while periodic polling remains `background`.
3. Lock-suppression environment settings may differ by caller, but command
scheduling and per-class metrics reflect the user-visible request.
### Raw Git execution cannot bypass admission
1. A production code path constructs a Git command for lifecycle, interactive,
or background work.
2. It invokes a classified shared helper that acquires the process-wide Git
controller before starting the command.
3. A repository guard fails when production code directly runs a raw Git command
or uses an unclassified execution path.
## Out of scope
- Raising the default Git concurrency cap or introducing platform-specific defaults.
- Removing the process-wide cap or replacing Git subprocesses with a native library.
- Serializing all instance creation independently of Git admission.
- Changing public status, log, or diff payloads.
- Aggregating admission snapshots across Docker or remote agentctl processes.
- Guaranteeing wall-clock completion when Git itself hangs; execution timeouts
continue to bound commands after admission.
## Success criteria
- Deterministic tests prove the hard global cap, same-class FIFO order,
work-conserving behavior, cancellation safety, and bounded progress across all
three classes.
- A saturated interactive workload cannot stop a healthy workspace tracker due
only to admission delay.
- Saturated background work cannot starve interactive or lifecycle operations.
- Status, log, and diff fan-out share the same capacity-derived policy.
- Aggregate and per-class diagnostics attribute contention to admission wait versus
command execution.
- Before closing GitHub issue #2150, current `main` and the completed change are
measured on Windows with the same workload. Record p50, p95, and maximum
latency; timeout and tracker-stop counts; and peak Git process count with the
cap left at 12. Host-dependent values are evidence for closure, not fixed CI
thresholds.
## Decisions
- [Class-aware Git subprocess admission](../../decisions/2026-08-02-class-aware-git-subprocess-admission.md)
## Implementation plan
- [Git subprocess admission plan](../../plans/git-subprocess-admission/plan.md)