Skip to content

fix(service): keep the counts that the Service makes while it stops #4876

Done

Description

@dan-petty

Update 2026-11-26 (infra move): the monitoring network policy moved to dan-petty/homelab.

The design moves the scrape to port 8001, and the monitoring egress rule there admits only 8000 and 8080 to devops. Merge the homelab follow-up first. This issue keeps the server, the Deployment and k8s/devops/roadmap-service/networkpolicy.yaml (admit 8001). tests/server/routes/test_k8s_roadmap_service.py is deleted.

Follow-up: dan-petty/homelab#282.


Problem Description

A count that the roadmap Service makes while it stops is lost. On SIGTERM, uvicorn closes its listening socket ("Shutting down") and then drains the running rounds for up to 600 s ("Waiting for application shutdown"). In that time /metrics answers no scrape, so each counter increment of the drain never gets to Prometheus.

Seen on 2026-11-10: a Service pod logged "Shutting down" at 14:37:02Z. Its implement round reported runner Job devops-cli-runner-20261110-140833-a7fa at 14:37:25Z. The last sample of devops_cli_service_implement_jobs_total for that pod is at 14:36:15Z, and the pod logged "Application shutdown complete" at 14:39:02Z. So the jobs counter shows 7 reports for the 8 reports in Loki since 2026-11-09.

Reproduction Steps

  1. Start a rollout of the Service while a round of the status lane runs.
  2. Compare the reports of that round in Loki with sum by (pod) (devops_cli_service_implement_jobs_total) of the old pod.

Expected vs Actual Behavior

Expected: each count that the Service makes before it exits is in Prometheus.
Actual: the counts of the drain are lost, because the scrape cannot read the pod after uvicorn closes the socket.

Environment Diagnostics

The Service Deployment k8s/devops/roadmap-service/deployment.yaml, with terminationGracePeriodSeconds: 660 and no preStop hook (#4485). The pod is scraped through its prometheus.io/scrape annotation (k8s/monitoring/k8s-monitoring-values.yaml).

Logs, Traces, or Terminal Output

Loki, container service: "Shutting down" 14:37:02Z, "The implement row of dan-petty/devops-cli reported 1 Job(s)" 14:37:25Z, "Application shutdown complete" 14:39:02Z. Prometheus: max_over_time(timestamp(devops_cli_service_implement_jobs_total{pod=~"roadmap-service-6db9b9587b.*"})[2d:15s]) gives 14:36:15Z.

Possible fixes, each with an open tool: serve /metrics from prometheus_client.start_http_server on its own port, which stays up until the process exits, and wait one scrape interval after the drain; or push the Service counters through the OTLP exporter seam (#1319) and flush it at the end of the drain. Found while building #4703.

Source: #4703

Alternatives check of 2026-11-27: in-use.
The repository already uses this tool.
Tool: prometheus-client (https://pypi.org/project/prometheus-client), Apache-2.0 AND BSD-2-Clause, last activity 2026-07-24, maintained.
Reason: The package facts and searches confirm prometheus-client's start_http_server serves a chosen registry on a dedicated port from its own thread, which is exactly the fix the issue describes; the issue already uses it, so only the wait and manifest edits remain.

Covers:

  • start_http_server serves a registry on its own port from a background thread
  • Takes a registry argument, so GLOBAL_METRICS counters are served
  • Keeps the existing Prometheus scrape path and pod annotations

Lacks:

  • No wait for a final scrape after the drain
  • No Kubernetes annotation, container port or NetworkPolicy change
  • No OTLP push or exporter flush path

Proposed design

Problem statement

Serve /metrics from a prometheus-client HTTP server on port 8001. Wait one scrape interval after the drain. Point the Deployment and NetworkPolicy at port 8001. On SIGTERM, uvicorn closes its listening socket before the Service drains its rounds. The /metrics route on port 8000 then answers no scrape. The counter increments of the drain never reach Prometheus. The live scrape waits on dan-petty/homelab#282.

Acceptance criteria

Requirement: Standalone metrics server

The Service SHALL start a prometheus_client HTTP server on the port that metrics_port names when that argument is not None.

Scenario: Metrics server starts on the configured port

  • WHEN A test enters the lifespan of create_service_app(metrics_port=8001) with a fake start_metrics_server.
  • THEN The fake records port 8001 and no HTTP server binds a socket.

Requirement: Service registry served

The standalone metrics server SHALL serve the registry of GLOBAL_METRICS.

Scenario: Metrics server receives the Service registry

  • WHEN A test enters the lifespan of create_service_app(metrics_port=8001) with a fake start_metrics_server.
  • THEN The fake records the registry of GLOBAL_METRICS.

Requirement: No metrics server by default

The Service MUST NOT start the standalone metrics server when metrics_port is None.

Scenario: Default app starts no metrics server

  • WHEN A test enters the lifespan of create_service_app() with a fake start_metrics_server.
  • THEN The fake records no call.

Requirement: Service command passes the metrics port

The serve --service command SHALL pass CONST_SERVICE_METRICS_PORT to create_service_app.

Scenario: Serve command passes the metrics port

  • WHEN A test runs the serve command with a fake create_service_app.
  • THEN The fake receives metrics_port 8001.

Requirement: Metrics port constant

The Service SHALL define CONST_SERVICE_METRICS_PORT as 8001.

Scenario: Metrics port constant is 8001

  • WHEN A test imports CONST_SERVICE_METRICS_PORT.
  • THEN The value is 8001.

Requirement: Scrape wait constant

The Service SHALL define CONST_SERVICE_STOP_SCRAPE_WAIT_SECONDS as 60.

Scenario: Scrape wait constant is 60

  • WHEN A test imports CONST_SERVICE_STOP_SCRAPE_WAIT_SECONDS.
  • THEN The value is 60.

Requirement: Scrape wait after the drain

The Service SHALL sleep CONST_SERVICE_STOP_SCRAPE_WAIT_SECONDS after the drain completes and before the process exits.

Scenario: Stop waits one scrape interval

  • WHEN A test drives the Service stop path with a fake sleep and a drain that returns at once.
  • THEN The fake sleep records 60 seconds after the drain returns.

Requirement: Metrics server stays up through the wait

The Service SHALL leave the standalone metrics server running until the process exits, through the drain and the scrape wait.

Scenario: Metrics server is not stopped before the wait

  • WHEN A test drives the Service stop path with a fake metrics server and a fake sleep.
  • THEN The fake metrics server records no stop call before the fake sleep returns.

Requirement: Deployment scrape port

The Deployment SHALL set the pod annotation prometheus.io/port to the string 8001.

Scenario: Kubernetes check passes with the metrics port annotation

  • WHEN uv run devops ci --check --only k8s runs.
  • THEN The command exits 0.

Requirement: Metrics container port

The Service container SHALL declare a container port named metrics with containerPort 8001.

Scenario: Kubernetes check passes with the metrics container port

  • WHEN uv run devops ci --check --only k8s runs.
  • THEN The command exits 0.

Requirement: Monitoring network policy

The NetworkPolicy SHALL admit TCP port 8001 from the monitoring namespace to the Service pods and MUST NOT admit TCP port 8000 from that namespace.

Scenario: Kubernetes check passes with the metrics ingress rule

  • WHEN uv run devops ci --check --only k8s runs.
  • THEN The command exits 0.

Requirement: Grace period constant

The Service SHALL set CONST_SERVICE_STOP_GRACE_SECONDS to 720.

Scenario: Grace period constant covers the scrape wait

  • WHEN A test imports CONST_SERVICE_STOP_GRACE_SECONDS.
  • THEN The value is 720.

Requirement: Deployment grace period

The Deployment SHALL set terminationGracePeriodSeconds to 720.

Scenario: Kubernetes check passes with the raised grace period

  • WHEN uv run devops ci --check --only k8s runs.
  • THEN The command exits 0.

Existing Tool Considered

prometheus-client (https://pypi.org/project/prometheus-client) has the in-use verdict in the alternatives check of 2026-11-27 in the issue body. The check records what the tool covers and lacks. The proposal uses prometheus_client.start_http_server on port 8001 for GLOBAL_METRICS.registry. It adds the 60 s scrape wait and the Deployment annotation and container port. It also adds the NetworkPolicy ingress and the 720 s grace period that the check says the tool lacks.

Key questions

  • Which transport keeps the Service counters scrapeable during the drain?: Use prometheus_client.start_http_server on a dedicated port and keep the Prometheus scrape path. Do not add an OTLP push path for this fix. (best practice) [sources: src/devops_cli/telemetry/metrics.py, src/devops_cli/server/service.py]
  • Which port does the standalone metrics server use?: Use port 8001, held as CONST_SERVICE_METRICS_PORT. Port 8000 belongs to uvicorn, which closes it at SIGTERM. (best practice) [sources: k8s/devops/roadmap-service/deployment.yaml, k8s/devops/roadmap-service/networkpolicy.yaml]
    • Chosen: 8001. It is separate from the uvicorn port 8000 and is free in the Deployment.
    • Rejected: 8000. uvicorn owns port 8000 and closes it at SIGTERM.
    • Rejected: 9464. No exporter uses this port and it gives no benefit over 8001.
  • Which registry does the standalone server serve?: Serve GLOBAL_METRICS.registry, the singleton that holds the Service counters. (best practice) [sources: src/devops_cli/telemetry/metrics.py, src/devops_cli/server/service.py]
    • Chosen: GLOBAL_METRICS.registry. The Service counters increment in GLOBAL_METRICS, and the current /metrics route serves that registry.
    • Rejected: A new empty registry. It would omit every Service counter.
    • Rejected: The wrapper registry of routes/telemetry.py. It adds collectors that the Service app does not serve, and the issue needs the Service counters.
  • How long does the Service wait after the drain before the process exits?: Wait 60 seconds, one scrape interval, held as CONST_SERVICE_STOP_SCRAPE_WAIT_SECONDS. (best practice) [sources: src/devops_cli/config/constants.py, k8s/devops/roadmap-service/deployment.yaml]
    • Chosen: 60 seconds. One scrape interval covers a full scrape cycle, and the project holds each stop phase as a constant.
    • Rejected: 0 seconds. The final increment can miss the last scrape.
    • Rejected: 600 seconds. It repeats the drain wait and delays the rollout with no extra scrape.
    • Rejected: A configurable service setting. The stop phases are constants, and no evidence shows that the wait varies.
  • How does the Deployment grace period cover the new wait?: Raise CONST_SERVICE_STOP_GRACE_SECONDS to 720 and the Deployment's terminationGracePeriodSeconds with it. The current 660 covers the preStop sleep of 10 s and the drain of 600 s. It also covers the cut wait of 30 s, the Lease return of 5 s and the exit of 15 s. The 60 s scrape wait needs 60 more. (best practice) [sources: src/devops_cli/config/constants.py, k8s/devops/roadmap-service/deployment.yaml, docs/CLUSTER.md]
    • Chosen: 720 seconds. 10 + 600 + 30 + 5 + 15 + 60 = 720, and the constant and the manifest must match.
    • Rejected: Keep 660 seconds. The 60 s wait would exceed the grace period.
    • Rejected: Reduce the drain wait. It shortens the drain that the Service needs.
  • Where does the Service start the standalone metrics server?: Start it in the create_service_app lifespan from a metrics_port argument that defaults to None. The serve --service command passes CONST_SERVICE_METRICS_PORT. Start it through one start_metrics_server function that a test replaces with an in-memory fake. Do not stop it before the process exits. (best practice) [sources: src/devops_cli/server/service.py, src/devops_cli/commands/serve.py, docs/adr/0007-tests-double-only-process-edges.md]
    • Chosen: Lifespan with a metrics_port argument and a start seam. The server follows the app lifecycle, and the default None plus the seam keeps existing tests off a real socket, as ADR 0007 requires.
    • Rejected: Start in serve before uvicorn.run. The command tests would start a real server, and the app tests would not cover the wiring.
    • Rejected: Always start in create_service_app. The existing create_service_app() tests would bind the port and start a real process edge.
  • Which pods must admit the monitoring scrape on TCP 8001, and does the TCP 8000 rule stay?: The pods of the Deployment, which carry the label app.kubernetes.io/name: roadmap-service, as the homelab egress rule of dan-petty/homelab#282 requires. The NetworkPolicy admits TCP 8001 from the monitoring namespace. It drops the TCP 8000 rule, because no scrape uses port 8000 of the Service after the change. (best practice) [sources: k8s/devops/roadmap-service/deployment.yaml, k8s/devops/roadmap-service/networkpolicy.yaml]
    • Chosen: Admit 8001 from monitoring and drop the 8000 rule. The homelab rule admits only the labelled roadmap-service pods on 8001, and no scrape uses 8000 after the move.
    • Rejected: Keep both the 8000 and the 8001 rules. It keeps an ingress rule that no scrape uses.
    • Rejected: Admit the whole devops namespace on 8001. The homelab egress rule admits only the labelled roadmap-service pods, so a wider ingress rule gives no access.

Fit

Fits in one pull request.

Suspected block

dan-petty/homelab#282 must merge and sync before the monitoring egress rule admits TCP 8001 to the roadmap-service pods.

Dependencies

None.

Activity

  1. added
    source/agent
    on Nov 12, 2026
  2. added
    type/bug
    scope/service
    status/new
    value/medium
    effort/medium
    on Nov 12, 2026
  3. dan-petty commented on Nov 12, 2026

    @dan-petty
    OwnerAuthor

    Intake placed this item to the backlog: intake puts every new item in the backlog. A person plans the milestones.

    • Type: type/bug. The fix prefix of the title gives the type.
    • Scope: scope/service. The (service) scope of the title gives the scope.
    • Priority: P2-Medium. Metrics are silently lost on every rollout drain, which degrades operational visibility but does not break user-facing functionality.
    • Value: Medium. Operators lose a small number of counter increments per rollout, which reduces the accuracy of monitoring but does not block any workflow.
    • Effort: Medium. The fix needs a separate metrics port or an OTLP flush at drain end, plus a wait for one scrape interval, which is a bounded change to the shutdown path.
    • Related: fix(roadmap): a Service rollout stops stage rounds with no record #4485, which asks for a different change. Both deal with the Service shutdown window in the same Deployment, but #4485 fixes rounds that stop without a record while the candidate fixes metric counters lost because the scrape socket closes before the drain ends.
  4. added
    priority/p2-medium
    on Nov 12, 2026
  5. added
    priority/p2-medium
    and removed
    priority/p2-medium
    on Nov 12, 2026
  6. devops-cli-service commented on Nov 14, 2026

    @devops-cli-service
    Contributor

    Alternatives check: in-use

    Reason: The searches found prometheus-client, whose start_http_server serves /metrics from its own HTTP server thread on a separate port that keeps running independently of the uvicorn listener, so a scrape can still read the pod during the drain. It does not itself wait one scrape interval after the drain or flush the final increments, and the Deployment's scrape annotation and shutdown ordering must be changed in the Service, so it covers only part of the need.

    The repository already uses this tool.

    Tool: prometheus-client (https://pypi.org/project/prometheus-client)

    • License: Apache-2.0 AND BSD-2-Clause
    • Last activity: 2026-07-24
    • Maintained: yes

    Covers:

    • Serves /metrics from a standalone HTTP server on its own port, independent of uvicorn's listening socket
    • Keeps the metrics endpoint up until the process exits, so scrapes during the drain succeed

    Lacks:

    • No wait for one scrape interval after the drain; the Service must add that wait
    • No automatic flush of the last counter increments at shutdown
    • The Deployment's prometheus.io scrape annotation must be pointed at the new metrics port

    Tools considered:

    Searches run:

    • prometheus_client start_http_server metrics during graceful shutdown uvicorn, results: 5
    • Prometheus Pushgateway push counters before pod shutdown drain, results: 5
    • prometheus client python start_http_server separate thread continues serving until process exits, results: 5
    • pushgateway prometheus counters on shutdown Kubernetes, results: 5
    • prometheus pushgateway, results: 5
    • opentelemetry python force_flush metrics exporter shutdown, results: 5
    • prometheus pushgateway github, results: 5
    • prometheus/client_python start_http_server, results: 5
    • client_python prometheus metrics library README, results: 5
    • prometheus-client python package documentation, results: 5

    Sources:

    Checked on 2026-11-14. A person decides what this means for the item. The check changes no label and closes no issue.

  7. added
    status/ready
    and removed
    status/new
    on Nov 15, 2026
  8. devops-cli-service commented on Nov 15, 2026

    @devops-cli-service
    Contributor

    Status set to Ready at ca62d6a (see proposed design in issue body).

  9. 3 remaining items

  10. dan-petty commented on Nov 26, 2026

    @dan-petty
    OwnerAuthor

    The homelab half of the port move is in dan-petty/homelab#422 (draft, closes dan-petty/homelab#282). Facts for the builder of this item:

    • The new egress rule of monitoring-default-perimeter-egress admits TCP 8001 only to the pods of namespace devops with the label app.kubernetes.io/name: roadmap-service. It does not admit the namespace, because mcp-server also listens on TCP 8001. So the metrics server must run in a pod with that label, on TCP 8001.
    • Live state on 2026-11-26: roadmap-service-ingress admits namespace monitoring on TCP 8000 only (kubectl -n devops get networkpolicy roadmap-service-ingress -o yaml). The rule for TCP 8001 in k8s/devops/roadmap-service/networkpolicy.yaml stays in this item, as the body says. Without it the scrape fails after the homelab merge too.
    • A model test with temporary namespaces showed that kube-router keeps the port open for a pod that is Terminating (15 s and 40 s after the delete), with an egress rule of this form and an ingress rule that admits the scraper namespace. The table is in the evidence comment of dan-petty/homelab#422.
    • After this item, no scrape uses TCP 8000 of the Service. Rule 2 of roadmap-service-ingress (namespace monitoring on TCP 8000) can go in this item. TCP 8000 in the homelab rule for all pods of namespace devops then has no known user: I found no other client of devops port 8000 in k8s/monitoring of homelab, and did not check the dashboards of devops-cli.

    Order: dan-petty/homelab#422 merges and syncs first, then this item.

  11. devops-cli-service commented on Nov 27, 2026

    @devops-cli-service
    Contributor

    Owner question: See Suspected block in the section Proposed design of the body.

    Options

    1. Decide the question: The job refines the item with your answer.
    2. Leave it to the job: The job records the best-practice answer and goes on.

    Recommendation: Decide the question: only a person can answer it.

    Evidence

  12. devops-cli-service commented on Nov 29, 2026

    @devops-cli-service
    Contributor

    Owner question: See Suspected block in the section Proposed design of the body.

    Options

    1. Decide the question: The job refines the item with your answer.
    2. Leave it to the job: The job records the best-practice answer and goes on.

    Recommendation: Decide the question: only a person can answer it.

    Evidence

  13. added
    owner/agent
    status/in-progress
    status/in-review
    and removed
    status/new
    status/in-progress
    on Nov 30, 2026
  14. removed
    status/in-review
    owner/agent
    on Nov 30, 2026
  15. devops-cli-service commented on Nov 30, 2026

    @devops-cli-service
    Contributor

    Live since 2026-11-30 20:54 UTC

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

    effort/mediumpriority/p2-mediumscope/servicesource/agenttype/bugvalue/medium

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions