Skip to content

Commit 1f122e7

Browse files
pelikhanCopilotgithub-actions[bot]
authored
feat(cli): include work-queue diagnostics in health reports (#70965)
* feat(cli): include work-queue diagnostics in health reports Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> * docs(adr): add draft ADR-70965 for work-queue diagnostics in health * fix(health): preserve Actions evidence and validate queue host safely Sanitize optional queue warnings, retain actionable transport guidance, reuse complete lock blobs, and keep detection warnings separate from ledger status. Validate enterprise resource references during read, replay, and checkpoint recovery. Finalize the design record and cover offline command tests and compiler marker contracts. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
1 parent 1bbf084 commit 1f122e7

27 files changed

Lines changed: 1263 additions & 38 deletions
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# ADR-70965: Include Work-Queue Ledger Diagnostics in `gh aw health`
2+
3+
**Date**: 2026-10-21
4+
**Status**: Proposed
5+
**Deciders**: Repository maintainers through PR #70965 review
6+
7+
---
8+
9+
### Context
10+
11+
`gh aw health` reports workflow health using GitHub Actions run outcomes: success rates, trends, durations, and failure inventories. Workflows that use the work queue can fail in ways that never appear in run outcomes. Examples include a growing backlog, pools that cannot schedule work, paused admission or grants, and failed deliveries. Some of these workflows may have no recent runs at all, so a run-based report can show them as quiet or healthy when they are actually stalled. The work-queue ledger (the `work-queue` branch) already holds this state, and `pkg/workqueue` can already read, replay, and summarize it (`workQueueStatsAt`). Health must stay read-only, stay within its shared API budget, avoid downloading artifacts, and avoid modifying the user's checkout.
12+
13+
### Decision
14+
15+
Extend `gh aw health` to detect work-queue usage and report current ledger diagnostics **after** collecting primary Actions evidence. A workflow counts as using the work queue when its **published default-branch lock file** sets `GH_AW_WORK_QUEUE_ENABLED: "true"` at the workflow, job, or step `env` level. This deliberately uses compiler-emitted environment entries, not examples or JSON embedded in scripts. Detection shares the remaining health API budget and reuses committed Git objects and downloaded lock content; exhausting that remaining budget must not displace already collected Actions evidence.
16+
17+
When at least one selected workflow uses the work queue, health reads the repository's queue ledger **once** through the existing authenticated, isolated `workqueue.Branch` Git transport. The selected GitHub host applies both to transport and to resource-reference validation during read and replay. Cross-host resource references remain invalid. Health checks that a policy is installed and that the ledger's repository matches the health target, then computes metadata-only diagnostics at the current time.
18+
19+
The result appears as `collection.work_queue` in JSON and as `[health_work_queue]` in text. Status is `attention_required` only when admission or grants are paused or any delivery failed, `unavailable` when ledger evidence cannot be read, and `observed` otherwise. Detection warnings remain separate from ledger status: an unreadable unrelated workflow cannot degrade an otherwise observed ledger. Public warnings use payload-free categories and recovery guidance instead of raw API responses or transport diagnostics. `observed` describes a ledger snapshot, not live worker health. Queue diagnostics do not depend on `--days` or the date window, and do not alter Actions success rates or fleet counts.
20+
21+
### Alternatives Considered
22+
23+
#### Alternative 1: Keep work-queue diagnostics in the dedicated work-queue CLI only
24+
25+
Users could keep using the existing work-queue stats commands while health stays based only on Actions runs. This needs no new code in health. It was rejected because health is the main fleet-status command, and the PR's stated problem is that success rates hide queue backlog, blockers, pauses, and failed deliveries. If a user has to run a second command, stalled workflows with no recent runs stay invisible in health.
26+
27+
#### Alternative 2: Infer work-queue health from Actions runs or artifacts
28+
29+
Health could infer queue state from worker or dispatcher run outcomes, or from downloaded run artifacts. This was rejected for three reasons. Health intentionally avoids downloading artifacts. Run outcomes cannot show scheduling blockers, pauses, or delivery verification state. And workflows with no runs in the window would produce no evidence at all. The ledger is the authoritative source of queue state.
30+
31+
#### Alternative 3: Detect work-queue usage from local workflow sources or the checkout's current branch
32+
33+
Detection could parse local `.md` sources or lock files in the working tree. This alternative is rejected in this decision because health targets the published default-branch configuration, possibly in another repository (`--repo`), and the local checkout may be stale, dirty, on another branch, or a different repository altogether. Committed local Git objects may accelerate reading the published revision, but working-tree contents are not authoritative.
34+
35+
#### Alternative 4: Inspect queue configuration before collecting Actions evidence
36+
37+
This ordering could reuse detection reads during subsequent run analysis. It is rejected because repositories with many workflows can exhaust the shared API budget before the failure inventory or run samples are collected. Queue evidence is optional enrichment and must use only the budget left after primary collection.
38+
39+
### Consequences
40+
41+
#### Positive
42+
- Health surfaces backlog, pool blockers, oldest available work, pauses, native reservations, and delivery state, including for workflows with no recent runs.
43+
- Missing or invalid definitions, policy, ledger, credentials, or a repository mismatch appear as explicit warnings instead of looking healthy.
44+
- `workqueue.Branch` gains an explicit `Host`, so ledger reads (and REST clients) work against non-default GitHub hosts.
45+
- The JSON change is additive (`work_queue` field plus a new `work_queue` capability).
46+
- Public warnings omit raw response bodies, stored payloads, and credential diagnostics while retaining actionable access and timeout guidance.
47+
48+
#### Negative
49+
- Health makes extra API calls (repository metadata plus one lock-file blob per selected workflow) and performs a Git ledger read with a 30-second timeout, which makes it slower and adds new failure modes.
50+
- Detection depends on the compiler emitting at least one plain `GH_AW_WORK_QUEUE_ENABLED` environment marker. Compiler contract regression coverage must preserve this invariant; JSON text in a script alone is not a detection signal.
51+
- Queue detection may be incomplete when primary Actions collection consumes the shared budget; explicit warnings are preferable to sacrificing the failure-first report.
52+
- The report mixes two kinds of evidence, windowed run samples and a current ledger snapshot, which users have to tell apart.
53+
- An `observed` status can be misread as "workers are healthy", even though it only means the ledger snapshot could be read.
54+
55+
#### Neutral
56+
- Queue diagnostics are computed once per repository even when several selected workflows share the queue.
57+
- Text rendering reuses existing work-queue formatters (`workQueueStatsText`, `workQueuePoolDiagnosticsText`), so health output and work-queue CLI output stay the same.
58+
- Actions success rates, fleet workflow counts, and `healthy_workflows` membership do not change.
59+
60+
---
61+
62+
This record is complete for review. Acceptance remains part of the maintainers' pull request decision.

‎docs/src/content/docs/setup/cli.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -980,6 +980,8 @@ Revision reads prefer committed Git objects in the current checkout when its ori
980980

981981
Shows success/failure rates, trend indicators (↑ improving, → stable, ↓ degrading), execution duration, token usage, costs, and warnings when success rate drops below threshold.
982982

983+
When a selected workflow's published default-branch lock file enables work-queue, health also reads and validates the repository's current `work-queue` ledger once. This includes workflows without recent runs. Text `[health_work_queue]` and JSON `collection.work_queue` report backlog, eligible and blocked work by pool, oldest available work, pauses, native reservations, and pending, verified, or failed delivery. Pauses and failed deliveries produce `attention_required`; an otherwise readable snapshot is `observed`, not proof of live worker health. Detection warnings do not change the status of a successfully read ledger. Missing or invalid definitions, policy, ledger, or credentials remain explicit, privacy-safe warnings rather than healthy results. Queue diagnostics are current ledger evidence independent of `--days` or date bounds, do not download artifacts, and do not mutate the queue or launch workers. Optional workflow detection runs after primary Actions collection, uses its remaining API budget, and reuses downloaded lock content. The ledger uses the authenticated, isolated Git transport without fetching into the checkout, and validates resource references against the selected GitHub host. Actions rates and fleet workflow counts remain unchanged.
984+
983985
Health also reads matching `run_summary.json` files from `--logs-dir` (default: `.github/aw/logs`) for failed sub-agent invocations, including workflows whose Actions conclusion is `success`. An affected current revision has status `subagent_failures_observed` and is excluded from `healthy_workflows`; its Actions success/failure counts and success rate remain unchanged. JSON reports include `subagent_failure_count` (invocations), `subagent_failure_runs` (distinct runs), and per-workflow `subagent_failures` with run URLs, agent names, and requested models. Fleet JSON also includes `degraded_workflows`.
984986

985987
This check does not download artifacts. Populate the cache with `gh aw logs --artifacts usage` or `gh aw audit <run-id>` before checking health. `collection.cache_evidence` reports per-run `compatible`, `missing`, `unreadable`, `invalid`, `stale`, or `version_mismatch_raw_jobs_only` status, with the cached producer version when readable. A producer-version mismatch permits reuse of raw Jobs API observations only, after checking run identity, repository URL, attempt, head SHA, workflow, status, conclusion, and update time. Derived usage, classification, and sub-agent metrics still require the current CLI version; cached producer metadata is never rewritten. Missing or rejected derived evidence does not establish failure-free delegation. Historical-revision failures do not degrade the current revision.

‎pkg/cli/health_collection.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ type HealthCollection struct {
2020
ReportSchemaVersion int `json:"report_schema_version,omitempty"`
2121
ObservedAt time.Time `json:"observed_at,omitzero"`
2222
Capabilities []string `json:"capabilities,omitempty"`
23+
WorkQueue *HealthWorkQueue `json:"work_queue,omitempty"`
2324
CacheEvidence map[int64]HealthCacheEvidence `json:"cache_evidence,omitempty"`
2425
JobEvidence map[int64]HealthJobEvidence `json:"job_evidence,omitempty"`
2526
JobRequests int `json:"job_requests"`
@@ -145,6 +146,9 @@ func renderHealthCollection(w io.Writer, collection *HealthCollection) error {
145146
if err := renderHealthCacheEvidence(w, collection.CacheEvidence); err != nil {
146147
return err
147148
}
149+
if err := renderHealthWorkQueue(w, collection.WorkQueue); err != nil {
150+
return err
151+
}
148152
for _, id := range slices.Sorted(maps.Keys(collection.PRLifecycleEvidence)) {
149153
evidence := collection.PRLifecycleEvidence[id]
150154
if _, err := fmt.Fprintf(w, "[health_pr_lifecycle] run=%d status=%s reason=%q pr=%d event_at=%s\n",

‎pkg/cli/health_command.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ Shows health metrics for workflows including:
4444
- Trend indicators (↑ improving, → stable, ↓ degrading)
4545
- Average execution duration
4646
- Warnings when success rate drops below threshold
47+
- Work-queue diagnostics when a selected published workflow uses work-queue
4748
4849
Inventories failure signals from run-list payloads, verifies one representative
4950
per branch/event, then samples successful and pending runs. Reuses local Git
@@ -149,7 +150,7 @@ func RunHealth(config HealthConfig) error {
149150
ProducerVersion: GetVersion(),
150151
ReportSchemaVersion: 1,
151152
ObservedAt: time.Now().UTC(),
152-
Capabilities: []string{"failure_inventory", "source_revisions", "typed_job_steps", "cache_diagnostics", "cross_version_raw_jobs", "pr_lifecycle_filtering"},
153+
Capabilities: []string{"failure_inventory", "source_revisions", "typed_job_steps", "cache_diagnostics", "cross_version_raw_jobs", "pr_lifecycle_filtering", "work_queue"},
153154
Host: normalizedGitHubAPIHost(logsRateLimitHost(config.RepoOverride)),
154155
StartDate: config.StartDate,
155156
EndDate: config.EndDate,
@@ -162,6 +163,7 @@ func RunHealth(config HealthConfig) error {
162163
if err != nil {
163164
return fmt.Errorf("failed to fetch workflow runs: %w", err)
164165
}
166+
collectHealthWorkQueue(config.collection)
165167

166168
if len(runs) == 0 && len(config.collection.workflows) == 0 && !config.collection.Partial {
167169
if config.WorkflowName != "" {

‎pkg/cli/health_file_snapshots.go‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,11 @@ type healthFileSnapshot struct {
2121
type healthLockSnapshot struct {
2222
metadata *workflow.LockMetadata
2323
err error
24+
content []byte
2425
}
2526

2627
func useHealthFileSnapshots(collection *HealthCollection) bool {
27-
return collection.localGit != nil || len(collection.workflows) > 1
28+
return collection.localGit != nil || len(collection.workflows) > 1 || len(collection.fileSnapshots) > 0
2829
}
2930

3031
// A directory response supplies source and lock blob identities for every workflow.
@@ -135,23 +136,33 @@ func readHealthLockMetadata(run WorkflowRun, ref string, collection *HealthColle
135136
endpoint = path.Join(healthRepositoryEndpoint(collection.repoOverride), "git/blobs", blobSHA)
136137
}
137138
out, err := readHealthLockContent(endpoint, blobSHA, collection)
138-
var metadata *workflow.LockMetadata
139-
if err == nil {
140-
metadata, _, err = workflow.ExtractMetadataFromLockFile(string(out))
141-
if err == nil && (metadata == nil || metadata.FrontmatterHash == "" || metadata.BodyHash == "") {
142-
err = errors.New("workflow revision hashes unavailable; recompile workflows to include gh-aw-metadata body_hash")
139+
if err != nil {
140+
if blobSHA != "" {
141+
cacheHealthLockSnapshot(blobSHA, nil, err, collection)
142+
}
143+
return nil, err
144+
}
145+
snapshot := cacheHealthLockSnapshot(blobSHA, out, nil, collection)
146+
return snapshot.metadata, snapshot.err
147+
}
148+
149+
func cacheHealthLockSnapshot(blobSHA string, content []byte, readErr error, collection *HealthCollection) healthLockSnapshot {
150+
snapshot := healthLockSnapshot{content: content, err: readErr}
151+
if readErr == nil {
152+
// Metadata belongs to the header, never to a matching string in a job's script.
153+
header, _, _ := strings.Cut(string(content), "\n")
154+
snapshot.metadata, _, snapshot.err = workflow.ExtractMetadataFromLockFile(header)
155+
if snapshot.err == nil && (snapshot.metadata == nil || snapshot.metadata.FrontmatterHash == "" || snapshot.metadata.BodyHash == "") {
156+
snapshot.err = errors.New("workflow revision hashes unavailable; recompile workflows to include gh-aw-metadata body_hash")
143157
}
144158
}
145159
if blobSHA != "" {
146160
if collection.lockSnapshots == nil {
147161
collection.lockSnapshots = make(map[string]healthLockSnapshot)
148162
}
149-
collection.lockSnapshots[blobSHA] = healthLockSnapshot{metadata: metadata, err: err}
163+
collection.lockSnapshots[blobSHA] = snapshot
150164
}
151-
if err != nil {
152-
return nil, err
153-
}
154-
return metadata, nil
165+
return snapshot
155166
}
156167

157168
func readHealthLockContent(endpoint, blobSHA string, collection *HealthCollection) ([]byte, error) {
@@ -163,7 +174,11 @@ func readHealthLockContent(endpoint, blobSHA string, collection *HealthCollectio
163174
}
164175
healthLog.Printf("Local lock blob unavailable: %v; using GitHub API", err)
165176
}
166-
out, err := healthAPI(collection, endpoint, "--jq", `.content | @base64d | split("\n") | .[0]`)
177+
filter := `.content | @base64d | split("\n") | .[0]`
178+
if blobSHA != "" {
179+
filter = ".content | @base64d"
180+
}
181+
out, err := healthAPI(collection, endpoint, "--jq", filter)
167182
collection.RevisionLookups++
168183
return out, err
169184
}

‎pkg/cli/health_no_jobs_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,12 @@ func TestHealthOnlyNoJobFailuresRemainInsufficient(t *testing.T) {
246246
}
247247
healthRunGH = func(_ context.Context, _ string, args ...string) ([]byte, error) {
248248
switch {
249+
case args[3] == "repos/org/repo":
250+
return []byte(`{"full_name":"org/repo","default_branch":"main"}`), nil
251+
case strings.Contains(args[3], "/contents/.github/workflows?"):
252+
return []byte(`[{"path":".github/workflows/example.lock.yml","sha":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","type":"file"}]`), nil
253+
case strings.Contains(args[3], "/git/blobs/"):
254+
return []byte("jobs: {}"), nil
249255
case strings.Contains(args[3], "/actions/workflows?"):
250256
return []byte(`{"workflows":[{"id":1,"name":"Example","path":".github/workflows/example.lock.yml","state":"active"}]}`), nil
251257
case strings.Contains(args[3], "/actions/runs?status=failure"):

‎pkg/cli/health_sampling_test.go‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -290,13 +290,22 @@ func TestHealthCurrentSnapshotFromGitHubMetadata(t *testing.T) {
290290
for i := range slices.Backward(responses) {
291291
newestFirst = append(newestFirst, responses[i])
292292
}
293-
requests := 0
293+
requests, queueRequests := 0, 0
294294
healthRunGH = func(ctx context.Context, message string, args ...string) ([]byte, error) {
295295
requests++
296296
require.GreaterOrEqual(t, len(args), 4)
297297
assert.Equal(t, "api", args[0])
298298
endpoint := args[3]
299299
switch {
300+
case endpoint == "repos/org/repo":
301+
queueRequests++
302+
return []byte(`{"full_name":"org/repo","default_branch":"main"}`), nil
303+
case strings.Contains(endpoint, "/contents/.github/workflows?"):
304+
queueRequests++
305+
return []byte(`[{"path":".github/workflows/example.lock.yml","sha":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee","type":"file"}]`), nil
306+
case strings.Contains(endpoint, "/git/blobs/"):
307+
queueRequests++
308+
return []byte("jobs: {}"), nil
300309
case strings.Contains(endpoint, "/actions/workflows?"):
301310
return []byte(`{"workflows":[{"id":11,"name":"Example","path":".github/workflows/example.lock.yml","state":"active"}]}`), nil
302311
case strings.Contains(endpoint, "/actions/runs?status=failure"):
@@ -358,7 +367,7 @@ func TestHealthCurrentSnapshotFromGitHubMetadata(t *testing.T) {
358367
}
359368
assert.Empty(t, report.FailureClusters)
360369
assert.False(t, report.Collection.Partial)
361-
assert.LessOrEqual(t, requests, 14, "superseded sources do not need lock metadata lookups")
370+
assert.LessOrEqual(t, requests-queueRequests, 14, "superseded sources do not need lock metadata lookups")
362371
})
363372
}
364373
}

‎pkg/cli/health_time_window_test.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ func TestHealthCommandTimeWindowFlags(t *testing.T) {
9494

9595
func TestHealthTimeWindowReachesSamplingAndJSON(t *testing.T) {
9696
stubHealthFailureCandidates(t)
97+
stubHealthTimeWindowAPI(t)
9798
originalDiscover, originalList := healthDiscoverWorkflows, healthListWorkflowRuns
9899
t.Cleanup(func() { healthDiscoverWorkflows, healthListWorkflowRuns = originalDiscover, originalList })
99100
healthDiscoverWorkflows = func(*HealthCollection) ([]GitHubWorkflow, error) {
@@ -167,6 +168,7 @@ func TestHealthRunListingPreservesTimeWindowAcrossPages(t *testing.T) {
167168

168169
func TestHealthDaysOnlyPeriodThroughCommand(t *testing.T) {
169170
stubHealthFailureCandidates(t)
171+
stubHealthTimeWindowAPI(t)
170172
originalDiscover, originalList := healthDiscoverWorkflows, healthListWorkflowRuns
171173
t.Cleanup(func() { healthDiscoverWorkflows, healthListWorkflowRuns = originalDiscover, originalList })
172174
healthDiscoverWorkflows = func(*HealthCollection) ([]GitHubWorkflow, error) {
@@ -188,6 +190,26 @@ func TestHealthDaysOnlyPeriodThroughCommand(t *testing.T) {
188190
assert.Equal(t, "Current status (up to 7 days)", report.Period)
189191
}
190192

193+
func stubHealthTimeWindowAPI(t *testing.T) {
194+
t.Helper()
195+
originalRate, originalGH := fetchRateLimitForHostFunc, healthRunGH
196+
t.Cleanup(func() { fetchRateLimitForHostFunc, healthRunGH = originalRate, originalGH })
197+
fetchRateLimitForHostFunc = func(context.Context, string) (rateLimitResource, error) {
198+
return rateLimitResource{Limit: 5000, Remaining: 4000}, nil
199+
}
200+
healthRunGH = func(_ context.Context, _ string, args ...string) ([]byte, error) {
201+
switch args[3] {
202+
case "repos/org/repo":
203+
return []byte(`{"full_name":"org/repo","default_branch":"main"}`), nil
204+
case "repos/org/repo/contents/.github/workflows?ref=main":
205+
return []byte(`[]`), nil
206+
default:
207+
t.Fatalf("unexpected health API request: %v", args)
208+
return nil, nil
209+
}
210+
}
211+
}
212+
191213
func TestHealthTimeWindowTextOutput(t *testing.T) {
192214
config := HealthConfig{
193215
StartDate: "2026-10-14T04:49:11Z", EndDate: "2026-10-15T13:20:00Z",

0 commit comments

Comments
 (0)