Skip to content

feat(cli): service mode for devops serve with github webhooks, a polling tick and per-repo job queues #752

Closed

Description

@dan-petty

Problem Statement

The roadmap jobs run when they are due. Deciding what is due is devops roadmap run (#981, split from #741; the service's Deployment is #1083, on #741's in-cluster runtime). GitHub sends no webhook when a board owned by a personal account changes (projects_v2_item is organization-only), and it does not redeliver failed deliveries. So polling is how the service sees changes, and a webhook only makes a job due sooner (ADR 0003, docs/adr/0003-polling-is-how-the-roadmap-sees-changes.md). GitHub expects a 2XX answer within 10 seconds, caps payloads at 25 MB, and keeps the same X-GitHub-Delivery on a manual redelivery.

What exists at HEAD (9c879ae, branch release/v0.2.25):

  • The server. devops serve is a Typer callback (commands/serve.py:32-133) that builds create_app (server/app.py:29-124). It mounts:

    • /, which lists the other routes (app.py:103-115);
    • /health and /healthz, one handler that always answers ok (server/routes/health.py:27-37);
    • /metrics (server/routes/telemetry.py:60-91), and /api/v1/telemetry, which pings the OTLP collector (telemetry.py:38-57);
    • /api/v1/status (server/routes/status.py:16, :36), /api/v1/workspaces (absolute paths on disk, server/routes/workspace.py:48, :81), /api/v1/config (workspace.py:128) and a simulated reasoning stream under /v1 (server/routes/stream.py:20, :60);
    • Swagger and ReDoc by default (serve.py:65-69, :102-104), and CORS for localhost (app.py:48-65).

    There is no webhook route and no readiness probe. serve prints a Rich banner before it starts uvicorn (serve.py:75-99, strings in ServeMessages, lang/en/messages.py:846), and binds 127.0.0.1 by default (DEFAULT_REST_HOST, config/defaults.py:458; DEFAULT_SERVER_WORKERS = 1, :316).

  • One process. serve passes an app object to uvicorn.run (serve.py:127-133); --reload passes an import string instead (:116-124). uvicorn 0.53.0 (pyproject.toml:35) exits at startup when it gets an app object with reload or workers > 1 (uvicorn/main.py:614-618). So the server runs as one process today, which in-memory queues need. uvicorn.run accepts a log_config dict (uvicorn/main.py:528).

  • Unused webhook code.

    • CONST_GH_WEBHOOK_SIGNATURE_HEADER (config/constants.py:682) is defined and never read.
    • verify_webhook_signature (github/graphql.py:278-292) computes HMAC-SHA256 and compares with hmac.compare_digest. Only tests call it (tests/test_github_graphql.py:212-228).
    • WebhookEventDispatcher (graphql.py:295-353) and WebhookEvent (:115) are also called only by tests (tests/test_github_graphql.py:230-281, :607-619). The dispatcher skips verification when no secret is passed (:316). Without a raw body it verifies a re-serialized payload (:317-321), which never matches GitHub's signature.
    • GitHubWebhookVerificationError (exceptions/git.py:142-157, exported at exceptions/__init__.py:59, :148, listed in docs/ERRORS.md:60) is raised only by the dispatcher (graphql.py:323).
    • github/__init__.py:37-40, :184-185, :241 export all four names.
    • refactor(github): one github session per identity owning token, quota and transport #767 (v0.2.26, lands before this item) removes GitHubGraphQLClient (graphql.py:657), GraphQLTokenBucket (:225) and RFC7234ETagCache (:135) from the same module and their exports from github/__init__.py, and deletes tests/test_github_graphql.py with the client; it does not name the webhook code. Its transport half, refactor(github): the github session owns transport, ledger, error classes and link pagination #983 (v0.2.28), lands after this item and leaves the webhook code to this item (its Out of Scope names verify_webhook_signature and WebhookEventDispatcher as feat(cli): service mode for devops serve with github webhooks, a polling tick and per-repo job queues #752's).
  • Metrics. The registry InMemoryMetricsRegistry (telemetry/metrics.py:41) has counters and gauges with labels (increment_counter :61, set_gauge :77, reset :143, export_prometheus_text :164), capped at 1,000 names and 5,000 label sets per name (:25-26). Its histograms keep the last 10,000 samples (:24, :53) and export _count and _sum from those samples with no buckets (:178-185). In a long-running service _count stops at 10,000 and _sum can fall, so neither behaves as a counter. The /metrics handler get_metrics (telemetry.py:60-91) reads GLOBAL_METRICS (metrics.py:191) and adds AI spend and uptime.

  • Logs. Nothing in src/ formats logs as JSON (git grep -iE "jsonformatter|class .*Formatter" -- src prints nothing). telemetry/logging_bridge.py is an OTLP correlation bridge, not a formatter.

  • Config and credentials. Settings read DEVOPS_CLI_ variables, with __ for nesting (config/settings.py:597-598). There is no ServiceConfig and no Settings.service. Credentials resolve through one chain: keyring, then Vault, then environment, then config (security/secrets.py:408-456, settings.py:958-965). cloudflare.api_token is the precedent for a managed credential with no Settings field: config/options.py:93, in SECRET_CONFIG_OPTIONS (:220-234) and KEYRING_KEYS (:236-248), config/env.py:84, :169, registry entry secrets.py:439-444; CloudflareConfig (settings.py:325) has no token field. devops config show prints such options as set (****) (commands/config.py:102-116, :314-338).

  • GitHub calls. run_gh times out after 30 s by default (github/rate_limiter.py:1874-1883), so a job can't hang forever on one GitHub call.

  • Tests. tests/test_server.py already uses TestClient (:9) and patches uvicorn.run under CliRunner (:225-232). The network guard (fix(test): the test network guard refuses loopback connects to services the test did not start #837, shipped in v0.2.24, e6ce3db) refuses non-loopback connects and loopback connects to ports the test process did not open (tests/conftest.py:66-160); TestClient runs in process and opens no socket.

Proposed Solution

A service mode, devops serve --service, added to the existing callback in commands/serve.py.

  • Webhook route. POST /webhooks/github checks the request, verifies X-Hub-Signature-256 over the raw body and queues a trigger for the repo. It never runs a job inside the request. Its answers:

    • 202: verified and queued, or merged into the repo's pending batch;
    • 200: verified but not queued: a ping, a repeated X-GitHub-Delivery, or an event sent by the machine account (ADR 0002);
    • 400: X-GitHub-Event or X-GitHub-Delivery is missing, or the body is not a JSON object;
    • 401: the signature is missing or wrong, or the repo is not managed;
    • 413: the body is over 25 MiB. This is decided from Content-Length when it is present, and otherwise while the body streams in, so no more than the limit is ever read;
    • 415: the content type is not application/json;
    • 503: the service is shutting down.
  • Polling tick. At startup, and then every service.poll_interval_seconds (default 300, minimum 60), it queues a poll trigger for every managed repo. The tick reads nothing from GitHub. The job function reads what changed through the roadmap store (refactor(github): roadmap store that reads and writes items, releases and board fields behind one interface #768, delivered in bf746de: roadmap/store.py, roadmap/github_store.py).

  • Per-repo queues.

    • One queue per repo in service.repos. Each runs one job at a time, on its own thread, and calls the job function with the repo and the triggers queued since its last run.
    • Job threads are started with daemon=True, not on asyncio's default executor, so a job cut off at the drain timeout does not keep the process alive.
    • Triggers that arrive while a job runs merge into one pending batch, counted by source, event and action. A burst makes one more run, not many.
    • Different repos run at the same time.
    • A job that raises is logged and counted, and its queue goes on.
  • Job function. create_service_app(job=...) takes it as a parameter. Its contract is Callable[[str, TriggerBatch], None]: the repo as owner/name, and a frozen TriggerBatch model exported from server/service.py holding repo, counts: dict[tuple[str, str, str], int] keyed by (source, event, action) (source is webhook or poll; event and action are empty strings for poll), first_at and last_at. The function runs synchronously on the repo's thread. Until feat(roadmap): run the roadmap jobs when they are due (devops roadmap run) #981 lands, devops serve --service passes one that logs the batch and changes nothing. feat(roadmap): run the roadmap jobs when they are due (devops roadmap run) #981 replaces it with devops roadmap run's service_job adapter; feat(k8s): the roadmap service runs in the cluster's devops namespace, reachable from outside only on /webhooks/github #1083's deployment is proven on the cluster against the log-only function first.

  • Probes.

    • /healthz answers 503 once the tick task or any repo's queue task has exited, so the kubelet restarts the pod. The service app defines its own handler; it does not include health_router, whose one handler always answers ok (health.py:27-29).
    • /readyz answers 503 until startup completes and while draining.
  • Graceful shutdown. On SIGTERM:

    • /readyz and the webhook route answer 503;
    • the tick stops;
    • pending batches are dropped, and the startup tick finds the work again;
    • shutdown waits at most service.drain_timeout_seconds (default 120) in total for running jobs to finish, then exits.
  • Logs. In service mode every line the process writes, uvicorn's included, is one JSON object. serve prints no Rich banner; the startup details are logged instead. A line has time, level, logger and message, plus repo, source, event, action, delivery, outcome, duration_s and result where they apply. Bodies, signatures, secrets and tokens are never logged.

  • Metrics on /metrics, counters and gauges only, registered on GLOBAL_METRICS:

    • devops_cli_service_webhook_deliveries_total{outcome};
    • devops_cli_service_triggers_total{repo,source};
    • devops_cli_service_pending_triggers{repo};
    • devops_cli_service_jobs_total{repo,result};
    • devops_cli_service_job_seconds_total{repo};
    • devops_cli_service_job_start_timestamp_seconds{repo}, 0 when idle;
    • devops_cli_service_last_tick_timestamp_seconds.

    The service app mounts the existing get_metrics handler (telemetry.py:65) on its own router, not telemetry_router, which also carries /api/v1/telemetry.

  • Routes. The service app mounts only POST /webhooks/github, GET /healthz, GET /readyz and GET /metrics. It has no docs, no CORS, no /, and none of the /api/v1 or /v1 routes.

  • Config.

    • ServiceConfig under Settings.service: repos (a list of owner/name), machine_account (a login), poll_interval_seconds (at least 60) and drain_timeout_seconds (above 0). Values outside these rules fail validation.
    • Webhook secrets are one managed credential, service.webhook_secrets: a JSON object from repo to secret. It is declared in build_secret_registry (secrets.py:408) with the environment variable DEVOPS_CLI_SERVICE_WEBHOOK_SECRETS, listed in SECRET_CONFIG_OPTIONS and KEYRING_KEYS (options.py:220, :236) and in config/env.py, and is not a Settings field. It follows the cloudflare.api_token pattern.
  • CLI checks.

    • --service with --reload, or with --workers above 1, exits 2.
    • An empty service.repos or an unset service.machine_account exits 1, with a message naming the setting.
    • A service.webhook_secrets value that is not a JSON object from repo to string exits 1, with a message naming the credential and never its value.
    • A repo with no secret logs a warning at startup. Its deliveries get 401, and polling still covers it.
  • Cleanup.

    • verify_webhook_signature moves from github/graphql.py:278-292 into server/routes/webhooks.py; its test (tests/test_github_graphql.py:212-228) moves into tests/test_server_service.py.
    • The route reads CONST_GH_WEBHOOK_SIGNATURE_HEADER (constants.py:682), plus new constants for X-GitHub-Event and X-GitHub-Delivery.
    • WebhookEventDispatcher, WebhookEvent, their exports in github/__init__.py (:37-38, :184-185) and their tests (tests/test_github_graphql.py:230-281, :607-619) are deleted.
    • GitHubWebhookVerificationError (exceptions/git.py:142-157) and its exports in exceptions/__init__.py (:59, :148) are deleted, because the route answers 401 and raises nothing. docs/ERRORS.md is regenerated with uv run devops docs generate (commands/docs.py:54; generator.py:797, :1046), and uv run devops docs check (docs.py:157) passes.
    • refactor(github): one github session per identity owning token, quota and transport #767 merges first. Its removals leave graphql.py and github/__init__.py without the GraphQL client, and tests/test_github_graphql.py already deleted; this item's rebase then drops the hunks that are already gone, and the cleanup criterion below holds either way.
  • Where the code goes.

    • server/service.py: queues, TriggerBatch, tick, lifespan and probes;
    • server/routes/webhooks.py: the route and the verifier;
    • server/json_logs.py: the formatter and the log_config (not logging.py, which would shadow the standard library module);
    • create_service_app in server/app.py, exported from server/__init__.py beside create_app (:5-7);
    • ServiceConfig in config/settings.py;
    • the credential in config/options.py, config/env.py and security/secrets.py;
    • messages in lang/en/messages.py (ServeMessages, :846) and help in lang/en/help.py (ServeCommandHelp, :629);
    • the changelog fragment changelog.d/752.md; the task file docs/agent/tasks/task-752-serve-service-mode.md.

Scope

One pull request. It adds the service mode (route, tick, queues, probes, shutdown, JSON logs, metrics, config, credential, CLI checks) and removes the dead webhook code it replaces. No new dependency: FastAPI 0.141.1 (pyproject.toml:34) and pydantic-settings 2.15.0 (:27) are pinned, and httpx 0.28.1, which TestClient needs, is already in the lock (tests/test_server.py:9 imports TestClient today).

Key Questions

All answered.

Acceptance Criteria

Unless a criterion says otherwise, it is verified by an in-process test in tests/test_server_service.py. The tests use FastAPI's TestClient, a fake job function, and an injected clock and sleep. Assertions use structural tuple equality (AGENTS.md:15-17).

  • With repo A idle, a delivery signed with A's secret gets 202 while the job it started is still blocked on an unset threading.Event. The fake job function records that it ran on a thread other than the request's and received a TriggerBatch with counts == {("webhook", "issues", "opened"): 1}. A second delivery then gets 202 and lands in A's pending batch. This shows no job runs inside a request. (tests/test_server_service.py)

  • Each of these gets 401 and queues nothing: no signature; a wrong signature; a body signed with another managed repo's secret; a repo not in service.repos; a managed repo with no secret, which also logs one warning at startup. (tests/test_server_service.py)

  • The same X-GitHub-Delivery sent twice gets 202 and then 200, and queues one trigger. (tests/test_server_service.py)

  • A ping, and an event whose sender.login is the machine account in any letter case, each get 200 and queue nothing. (tests/test_server_service.py)

  • With the size limit patched to 1 KiB: a 1 KiB + 1 byte body gets 413; the same body sent in chunks with no Content-Length (a generator body) also gets 413. (tests/test_server_service.py)

  • A form-encoded body gets 415. A request without X-GitHub-Event gets 400, and a signed body that is a JSON array gets 400. (tests/test_server_service.py)

  • Ten triggers for repo A while A's job runs produce exactly one more run of A, whose batch counts all ten. A job for repo B runs while A's job runs. A per-repo concurrency counter kept by the fake job function never exceeds 1. (tests/test_server_service.py)

  • The test drives the running tick loop through the injected clock and sleep, not by calling a tick method. Startup queues one poll trigger per repo, and advancing past one interval queues exactly one more per repo. A poll_interval_seconds below 60 and a drain_timeout_seconds of 0 each fail ServiceConfig validation. (tests/test_server_service.py)

  • A job function that raises adds 1 to jobs_total{result="error"} and logs the exception, and the repo's next trigger still runs. (tests/test_server_service.py)

  • /readyz gives 503 before startup completes and during drain, and 200 in between. /healthz gives 503 after a queue task is cancelled from outside, and in a separate case after the tick task is. (tests/test_server_service.py)

  • Leaving the TestClient context while a job runs waits for that job to finish. With the drain timeout patched to 0.05 s, a job blocked until the test releases it does not hold the context exit past 0.3 s, and its thread has daemon set. The test then releases the job. During drain the webhook route answers 503. (tests/test_server_service.py)

  • The service app's routes are exactly the four listed, asserted over app.routes. GET /, GET /docs and GET /api/v1/config return 404. (tests/test_server_service.py)

  • With GLOBAL_METRICS.reset() first, one delivery and one job leave each metric above on GET /metrics, with the expected labels and values. (tests/test_server_service.py)

  • Every captured log line parses with json.loads. The delivery and job lines carry the fields above. No line contains the secret, the signature or the body. (tests/test_server_service.py)

  • In tests/test_server.py, with CliRunner and uvicorn.run patched: --service --workers 2 and --service --reload exit 2; an empty service.repos, or no service.machine_account, exits 1; a DEVOPS_CLI_SERVICE_WEBHOOK_SECRETS that is not a JSON object exits 1, and the output names the credential but not the value; a valid config calls uvicorn.run once, with workers=1 and the JSON log_config, and every line the command prints parses with json.loads. (tests/test_server.py)

  • With DEVOPS_CLI_SERVICE_WEBHOOK_SECRETS set through monkeypatch, the service resolves both repos' secrets, and devops config show prints neither value. (tests/test_server_service.py, tests/test_server.py)

  • git grep -n -E "WebhookEventDispatcher|WebhookEvent\b|GitHubWebhookVerificationError" -- src tests docs/ERRORS.md prints nothing. git grep -n "def verify_webhook_signature" -- src prints one line, in server/routes/webhooks.py. git grep -n CONST_GH_WEBHOOK_SIGNATURE_HEADER -- src shows the route reading it. uv run devops docs check passes. (commands, recorded in the task file)

  • The new tests open no sockets and pass under the network guard (tests/conftest.py:66-160). uv run pytest tests/test_server_service.py --durations=0 totals under 1 s, and uv run devops ci passes. (commands)

  • changelog.d/752.md exists; CHANGELOG.md and docs/ROADMAP.md are untouched. (devops pr check-readiness)

  • Pending a person: the local smoke check below, run once. It needs no cluster and is not part of the gate.

    export DEVOPS_CLI_SERVICE__REPOS='["dan-petty/devops-cli"]'
    export DEVOPS_CLI_SERVICE__MACHINE_ACCOUNT=example-machine-account
    export DEVOPS_CLI_SERVICE_WEBHOOK_SECRETS='{"dan-petty/devops-cli":"local-test-secret"}'
    uv run devops serve --service --port 8787 &
    body='{"action":"opened","repository":{"full_name":"dan-petty/devops-cli"},"sender":{"login":"someone"}}'
    sig=$(printf '%s' "$body" | openssl dgst -sha256 -hmac local-test-secret -r | cut -d' ' -f1)
    id=$(python3 -c 'import uuid; print(uuid.uuid4())')
    for i in 1 2; do curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8787/webhooks/github -H 'Content-Type: application/json' -H 'X-GitHub-Event: issues' -H "X-GitHub-Delivery: $id" -H "X-Hub-Signature-256: sha256=$sig" --data "$body"; done
    curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8787/readyz
    curl -s http://127.0.0.1:8787/metrics | grep devops_cli_service_
    kill -TERM %1; wait

    Expected: 202, then 200, then 200; the service metrics are listed; every line the service printed is JSON; and the process exits 0 within the drain timeout.

Out of Scope

Dependencies

Depends on: none. The tick reads nothing from GitHub, the tests use a fake job function, and nothing here reads session.login, so this item does not wait on #767 (the cross-check corrects #767's claim that it does). #768, which the job function reads through, is delivered (bf746de). #837's network guard shipped in v0.2.24 (e6ce3db, tests/conftest.py:66-160).

Order in v0.2.26 (owner, 2026-10-03): #753, then #741, then #420, with #742 starting in parallel on day one; on the service side #767, then this item, then #1083, then #981 last.

Activity

  1. added this to the v0.2.26 milestone on Sep 30, 2026
  2. added
    type/feature
    scope/cli
    priority/p1-high
    on Sep 30, 2026
  3. added a commit that references this issue on Oct 1, 2026
  4. dan-petty commented on Oct 3, 2026

    @dan-petty
    OwnerAuthor

    References to #741's Deployment now point at #1083 (split 2026-10-03). The webhook secrets reach the pod through #741's devops-cli Secret, as a push-secrets row #1083 adds.

  5. dan-petty commented on Oct 4, 2026

    @dan-petty
    OwnerAuthor

    What changed

    #1171, merged into release/v0.2.26 as aeb4119.

    Closes #752

    27 file(s) changed.

    How it was verified

    Check runs at f7a2691:

    • Prune PR DevContainer Images: pass
    • CodeQL: pass
    • DevContainer Image: skipping
    • Static Analysis: pass
    • Analyze (actions): pass
    • Tests & Coverage: pass
    • Analyze (python): pass
    • Service Image: skipping
    • Dependency Freshness: skipping

    Acceptance Criteria of docs/agent/tasks/task-752-serve-service-mode.md:

    • In-process delivery test in tests/test_server_service.py proves a delivery signed with a repo's secret receives 202 while the job is blocked on an unset event, executing on a separate daemon thread with a coalesced TriggerBatch (counts == {("webhook", "issues", "opened"): 1}). A second delivery receives 202 and coalesces into the pending batch.
    • Delivery authentication rejects missing signatures, wrong signatures, signatures from other managed repos, unmanaged repos, and managed repos with no secret with 401. Managed repos lacking secrets log a startup warning.
    • Duplicate deliveries identified by X-GitHub-Delivery within the 10,000 in-memory LRU window receive 202 on initial delivery and 200 on duplicate replay, queueing exactly one trigger.
    • ping events and deliveries where sender.login matches service.machine_account (case-insensitive) receive 200 and queue nothing.
    • Payload size limits enforce 25 MiB: requests exceeding the limit via Content-Length or streaming chunked transfer receive 413.
    • Unsupported Content-Type headers receive 415. Missing X-GitHub-Event or bodies that are not JSON objects receive 400.
    • Ten concurrent triggers for a repo while a job is running merge into exactly one subsequent run whose TriggerBatch counts all ten. Different repositories execute concurrently without cross-blocking. Per-repo concurrency never exceeds 1.
    • Polling tick loop advances time through injected clock/sleep fixtures, scheduling one poll trigger per repo at startup and after each poll_interval_seconds interval. ServiceConfig enforces poll_interval_seconds >= 60 and drain_timeout_seconds > 0.
    • Job function exceptions increment jobs_total{result="error"} and log details while allowing subsequent triggers to run.
    • /readyz returns 503 prior to startup completion and during shutdown drain, and 200 while ready. /healthz returns 503 if any queue worker or the tick task fails or is cancelled.
    • Graceful shutdown waits up to drain_timeout_seconds for active jobs to complete while rejecting new webhook requests with 503. Job threads use daemon=True to allow clean termination.
    • The service app serves exactly four routes: POST /webhooks/github, GET /readyz, GET /healthz, and GET /metrics. Unmounted routes (/, /docs, /api/v1/config) return 404.
    • Prometheus metrics on GET /metrics record webhook_deliveries_total, triggers_total, jobs_total, job_seconds_total, job_start_timestamp_seconds, and queue_depth.
    • JSON log formatter formats all logs as single-line JSON containing time, level, logger, message, and contextual fields, with zero credential/secret/signature leakage.
    • CLI flags: devops serve --service rejects --workers > 1 and --reload with exit code 2. Requires non-empty service.repos, present service.machine_account, and valid JSON object for service.webhook_secrets (failing with exit code 1 naming the credential).
    • Cleaned up dead webhook symbols: git grep -n -E "WebhookEventDispatcher|WebhookEvent\b|GitHubWebhookVerificationError" -- src tests docs/ERRORS.md returns 0 lines. Canonical verify_webhook_signature resides in src/devops_cli/server/routes/webhooks.py and reads CONST_GH_WEBHOOK_SIGNATURE_HEADER.
    • Fast in-gate tests in tests/test_server_service.py total under 1 s and open no network sockets. uv run devops ci passes.
    • changelog.d/752.md created; CHANGELOG.md and docs/ROADMAP.md remain untouched.
    • Pending a person: local smoke test running devops serve --service --port 8787, verifying delivery flow, ready probe, and metrics emission.
  6. added a commit that references this issue on Oct 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority/p1-highscope/clitype/feature

    Type

    No type

    Projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions