Skip to content

feat!: record scheduled-job runs and add a gauge instrument to the metrics seam - #26

Merged
AlexeyShalaev merged 1 commit into
masterfrom
feat/scheduler-job-metrics
Aug 30, 2026
Merged

AlexeyShalaev merged 1 commit into
masterfrom
feat/scheduler-job-metrics

Conversation

@AlexeyShalaev

Copy link
Copy Markdown
Member

Closes #25

Problem

SchedulerEntrypoint logs a run and opens a unit scope, and records nothing — no counter, no duration, no last success. A job that stopped firing, fails every time or slowed from two seconds to twenty is indistinguishable from a healthy one, and every consumer who fills the gap hits the same two traps: a last-success timestamp stamped on every run (a permanently failing job looks fresh), and an in-progress gauge leaked on the error path ("stuck" becomes permanently true).

Design

Two layers, one of them more general than the request:

Kernel: a gauge instrument. Half of the proposed metrics are gauges and MetricsSinkProtocol only minted counters and histograms. GaugeProtocol (set / inc / dec) joins core.contracts, gauge() joins MetricsSinkProtocol, NullMetricsSink (NullGauge), PrometheusMetricsSink (PrometheusGauge, cached per registry like the others) and the author-facing MetricsSink ABC — abstract, so a backend that predates gauges fails at construction with the usual abstract-method message instead of silently recording nothing. That is the one breaking change (feat!, 0.x → minor).

Adapters: the recorder, in the gRPC shape. SchedulerJobMetricsRecorder in adapters/apscheduler4/metrics.py and adapters/apscheduler3/metrics.py — the same code twice (the adapters share nothing; the conformance test now asserts the two modules are AST-identical), frozen names, buckets up to 1800 s. SchedulerEntrypoint(..., enable_metrics=True, metrics_prefix=...) and SchedulerPlugin likewise; the recorder is minted at bind from ctx.observability.metrics (an invalid prefix fails there, before the scheduler is entered). _dispatch wraps the unit of work in recorder.track(job_id): in-progress up on entry; on any exit — normal, error, cancellation — in-progress down and the run recorded from the exception, which is re-raised untouched.

scheduler_job_runs_total{job_id, outcome, error_kind}
scheduler_job_duration_seconds{job_id}                  histogram (ok and error runs; a cancelled run did not finish)
scheduler_job_last_success_timestamp_seconds{job_id}    gauge — set only on outcome="ok"
scheduler_job_in_progress{job_id}                       gauge — released in finally

Outcome vocabulary. outcome ∈ {ok, error, cancelled}; error_kind refines error with the library's own taxonomy — the ErrorKind of a ServiceError (validation, not_found, ...) or unexpected for any other exception ("" when the run did not fail). The reporter's domain/infra split becomes error_kind!="unexpected" with bounded cardinality and no application concept in the library. classify_outcome is public for recorders that want the same vocabulary.

Rejected: a generic "measure this entrypoint's unit of work" seam (a daemon's unit of work is its whole run; without an identity label the metric says nothing; per-adapter recorders are the pattern the library chose), documenting the pattern instead of shipping it, a counter-only approximation of last success, and a pluggable outcome classifier on the entrypoint (the existing error taxonomy covers the stated need; composing your own recorder from the instruments stays the escape hatch).

Docs: adapters/scheduler.md gains a Metrics section (names, semantics, the staleness and error-rate PromQL, the restart caveat), observability-backends.md documents the gauge in the ABC/protocols and the recorder, the worker blueprint enables metrics, ARCHITECTURE/checklist updated.

Verification

  • make check + make test: ruff, format, mypy, import-linter clean; 703 passed, 14 skipped, coverage 92.78 %.
  • make test-apscheduler3 (own venv, APScheduler 3.x): 21 passed, 1 skipped — including the four new APScheduler 3 metrics tests.
  • tests/unit/test_scheduler_metrics.py (13, over a real Prometheus registry): the two traps — a job failing every time never moves last_success; a raising body releases in_progress and re-raises — plus cancellation (counted, not timed, re-raised), ServiceError → error_kind, prefix, null sink.
  • Entrypoint wiring in both adapters (test_scheduler.py, test_scheduler_aps3.py), the Prometheus gauge, the ABC (a counter-only backend cannot be instantiated), conformance parity for metrics.py and SchedulerPlugin.__init__.
  • Negative control (new tests against master's package from a git archive tree): test_scheduler_metrics.py and the gauge tests fail at collection (SchedulerJobMetricsRecorder / PrometheusGauge do not exist); 7 of the 8 entrypoint metrics tests fail with TypeError: unexpected keyword argument 'enable_metrics' (the eighth — metrics disabled touches nothing — is trivially true on master).
  • Docs build: zensical build --clean — no issues; the recorder renders on the reference page.

…trics seam

SchedulerEntrypoint logged each run and recorded nothing, so a job that
stopped firing, failed every time or slowed down looked exactly like a
healthy one — and every consumer who filled the gap hit the same two traps:
a last-success timestamp stamped on every run, and an in-progress gauge
leaked on the error path.

Both scheduler adapters now take enable_metrics / metrics_prefix and record
every run through the app's metrics sink with SchedulerJobMetricsRecorder:
scheduler_job_runs_total{job_id,outcome,error_kind},
scheduler_job_duration_seconds, scheduler_job_last_success_timestamp_seconds
(moves only on ok) and scheduler_job_in_progress (released on every exit
path). Outcomes are ok / error / cancelled; error_kind carries the ErrorKind
of a ServiceError or "unexpected", so a job refused by a business rule and a
lost database connection are separate series.

Half of those are gauges, which the metrics seam did not have: GaugeProtocol
joins the contracts, gauge() joins MetricsSinkProtocol, the null sink, the
Prometheus sink and the author-facing MetricsSink ABC.

BREAKING CHANGE: MetricsSink.gauge() is abstract — a third-party metrics
backend must implement it (set / inc / dec) or fail at construction.

Closes #25
@AlexeyShalaev
AlexeyShalaev merged commit 92d45cf into master Aug 30, 2026
6 checks passed
@AlexeyShalaev
AlexeyShalaev deleted the feat/scheduler-job-metrics branch September 6, 2026 07:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature]: SchedulerEntrypoint records nothing, while the gRPC and FastAPI entrypoints measure their unit of work

1 participant