Skip to content

Add native exception and message capture with Error App DSNs - #47

Open
aflanagan wants to merge 22 commits into
masterfrom
claude/sentry-exception-ingestion-8v0m74
Open

aflanagan wants to merge 22 commits into
masterfrom
claude/sentry-exception-ingestion-8v0m74

Conversation

@aflanagan

@aflanagan aflanagan commented Oct 29, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds native error tracking to cronitor-python 4.10.0. There are no new dependencies.

  • Config: set cronitor.ingest_key to an Error App's ingest key. cronitor.ingest_url is optional and defaults to https://cronitor.link (CRONITOR_INGEST_URL). Events go to POST {ingest_url}/e as gzipped Sentry envelopes, authenticated by the ingest key in X-Sentry-Auth. A Sentry-style DSN in cronitor.dsn is still accepted but no longer documented.
  • Capture API:
    • cronitor.capture_exception(exc=None, *, monitor=None, series=None, level='error', tags=None, extra=None, fingerprint=None)
    • cronitor.capture_message(message, level='info', ...)
    • Monitor.capture_exception and Monitor.capture_message, bound to the monitor and its environment.
      Each returns the event id, or None when nothing was sent.
  • Events: each event carries the exception chain, stack frames with five lines of source context, the hostname, cronitor.release (CRONITOR_RELEASE) and the environment. Local variables are never sent. fingerprint accepts a string or a list.
  • Transport: a background thread with a bounded queue. Events are trimmed to 1 MB, requests time out after 5 seconds, and 429 responses are honoured. The transport is fork-safe, and cronitor.flush(timeout=2.0) also runs at exit. It never raises into application code.
  • @cronitor.job auto-capture: on by default (cronitor.capture_exceptions). It can be turned off per job with capture_exceptions=False. It sends a fail ping, then an unhandled-exception event bound to the same monitor and run series.
  • REST clients:
    • cronitor.ErrorApp: create, list, data, update, delete, and rotate_key, which refreshes ingest_key.
    • cronitor.ErrorGroup: list with filters and pagination, data, update, events, and event.
  • type=errors monitors work in cronitor.yaml (errors:), apply_config and Monitor.put.

Testing

  • python3 -m pytest: green on 3.11 to 3.15 in CI.

claude and others added 20 commits October 29, 2026 20:56
cronitor/ingest.py builds Sentry-format envelopes and sends them to
{ingest_url}/api/envelope from one daemon thread with a bounded queue.
Events go out one envelope each; log records batch to 100 or 5 seconds.
Bodies are gzipped, sends time out after 5 seconds with one retry, a 429
pauses sending for Retry-After (capped at 60 seconds), and failures are
logged, never raised. The worker starts lazily, restarts after fork, and
queued items are flushed at exit with a 2 second cap.

cronitor.ingest_url (env CRONITOR_INGEST_URL, default https://cronitor.link)
now also sets the ping URL base, so a dev stack can receive everything.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
cronitor/capture.py builds exception and message events and structured
log records. Exceptions follow __cause__ then __context__, oldest first,
with frames oldest first, five lines of source context from linecache,
and in_app false for site-packages, dist-packages and the stdlib. Local
variables are never sent. Values, messages and log bodies are truncated
to 4000/4000/8000 characters and tags and attributes to 50 entries.

cronitor.logger mirrors sentry_sdk.logger: the body is formatted with
str.format when attributes and braces are present, and the template and
parameters are recorded as sentry.message.* attributes. It replaces the
stdlib logger that was exported under that name; its configuration
methods still delegate to logging.getLogger('cronitor').

Monitor.capture_exception and Monitor.capture_message bind the monitor
key, environment and API key. New settings: cronitor.release (env
CRONITOR_RELEASE) and cronitor.capture_exceptions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
The decorator binds the monitor key, series and environment in a context
variable while the function runs, so capture_exception, capture_message
and cronitor.logger calls inside it are tagged with cronitor.monitor and
cronitor.series. When the function raises, the decorator sends the fail
ping as before and then an exception event bound to the same series,
with mechanism cronitor.job and handled false. Set
cronitor.capture_exceptions = False to send only the ping.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
LogHandler ships logging records as structured log items through the
same batching transport. Levels map DEBUG->debug, INFO->info,
WARNING->warn, ERROR->error, CRITICAL->fatal, and anything below DEBUG
to trace. Records carry logger.name, code.file.path, code.line.number
and code.function.name, the %-style template and its arguments, and the
cronitor.monitor/cronitor.series binding inside a job. A record with
exc_info gets its formatted traceback in exception.stacktrace; no
second event is sent. Records from the transport itself are ignored so
a failing send cannot feed itself.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Covers the requests session, gzip body and headers on the wire, a real
429 with Retry-After, and a ping routed through the same ingest_url.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Adds an "Exceptions and Logs" README section: configuration,
capture_exception, capture_message, cronitor.logger, LogHandler, flush,
the @job behavior, and the Sentry SDK DSN alternative. Documents
CRONITOR_INGEST_URL and CRONITOR_RELEASE.

5.0.0 because @cronitor.job now sends an exception event on failure by
default and cronitor.logger is now the log shipper. A test keeps the SDK
version reported on the wire equal to setup.py.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Envelope payloads are now strict JSON: NaN and Infinity in extra or log
attributes become strings, circular extra data is cut instead of losing
the event, unencodable dict keys are skipped, and lone surrogates are
replaced. A missing API key is logged once per transport instead of on
every record, which matters with LogHandler on a busy logger. The test
envelope parser now rejects NaN like a strict backend would.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
cronitor.app (or CRONITOR_APP) names the app monitor that exception
events and log records belong to. A cronitor.app tag or attribute on a
single call overrides it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
The monitor type that owns exceptions and logs is called service. The
SDK setting is cronitor.service (CRONITOR_SERVICE) and the tag and log
attribute are cronitor.service.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
A telemetry outage used to raise the ping's ConnectionError into the
decorated function before it ran. Pings are now best effort and logged.
The README points Sentry SDK users at a service monitor's dsn instead
of an API key id, and restores apply_config() in two examples.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
A child that inherited the transport reused the parent's keep-alive
session, so both processes wrote to the same TLS socket, and a pool
lock held by a parent thread at fork time could deadlock the child.
When the pid changes the session and the rate limit window are reset
along with the queue and the worker thread.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Before 5.0 cronitor.logger was logging.getLogger('cronitor'), so code
like cronitor.logger.info('x %s', 1) now raised TypeError. The logger
takes %-style arguments (falling back to the raw body when they do not
format), and adds warn, critical, exception (an error log carrying the
handled exception's type, message and stack trace) and log(level, ...)
for stdlib level numbers and names. Configuration calls still pass
through to the stdlib logger.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
The server drops event items over 1 MB, and a deep exception chain with
source context or a large extra could exceed it. An event over 900 KB
now loses every frame's source context, then extra, then all but the
last 20 frames of each exception, stopping as soon as it fits, and
extra['_trimmed'] records what was dropped.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Attribute keys are cut to 64 characters and values to 400, except the
exception stack trace and message and the message template, which keep
8,000 like the body; a record keeps at most 50 attributes. LogHandler
now defaults to INFO, so a root logger at DEBUG no longer ships every
library's debug lines; LogHandler(level=logging.DEBUG) opts in.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
After a 429 the sender thread slept until the limit lifted, so every
item queued behind it waited too and was lost when the 2 second exit
flush gave up. Envelopes sent during the limit window are now dropped,
counted in Transport.dropped and logged once per window.
X-Sentry-Rate-Limits is read before Retry-After, as Sentry's SDKs do.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01B4Z4DjN96ccpNoVRZuoCxo
@aflanagan aflanagan changed the title 5.0: native exception and log capture Add native exception and message capture with Error App DSNs Nov 27, 2026

@aflanagan aflanagan left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Opus 5.5 Medium review

I reviewed git diff origin/master...HEAD at 045f0eb against the frozen Error Tracking contract (cronitorio/cronitor #810–#821). I checked the REST shapes against the errors-api.md docs and cronitor/domain/errors.py in #816, and the errors-monitor validation against #821. Local test run: 116 passed, 7 skipped (the skips are the integration tests that need CRONITOR_TEST_API_KEY).

Contract alignment (verified)

  • Ingest: the DSN is parsed as https://<ingest_key>@host/<project_id> (the default /1 is a placeholder). The client POSTs a gzipped envelope to {scheme}://{netloc}{prefix}/api/{project_id}/envelope/ and sends both X-Sentry-Auth: Sentry sentry_key=<ingest_key>, sentry_version=7, ... and the envelope header dsn. cronitor.api_key is never used as the ingest key: test_capture sets a REST key and still requires a DSN.
  • Capture: capture_exception and capture_message (module-level and on Monitor) take level, fingerprint (always sent as a list of strings), extra, and tags. Messages go out as {"formatted": ...}. Exceptions carry the __cause__/__context__ chain and frames with 5 lines of source context. No locals are sent. Every capture path is wrapped and returns None on failure. The transport runs on a daemon thread with a bounded queue, handles fork safety, and backs off on 429.
  • Logger and version: cronitor.logger is still logging.getLogger('cronitor'), and there is no LogHandler. Version is 4.10.0 in both setup.py and _version.py.
  • REST: ErrorApp (create/list/get/update/delete/rotate_key → /api/error-apps[/:key[/rotate-key]]) and ErrorGroup (list with every documented filter/update(status, env)/events(env, app, cursor, limit)/event → /api/errors...) use basic auth api_key:. List parsing handles the server's {"data": [...]} envelope. HTTP 4xx/5xx map to AuthenticationError, APIValidationError, ErrorAppNotFound/ErrorGroupNotFound, or APIError. Only opaque keys are used.
  • @cronitor.job: auto-captures by default (mechanism=cronitor.job, handled=False), and cronitor.capture_exceptions and the decorator's capture_exceptions= override it correctly. Run/fail/complete pings go through _safe_ping, so a ping failure no longer raises into the job. The ContextVar binding is always reset in finally.
  • Errors monitors: apply_config counts the errors: key, and Monitor.put passes type: errors through unchanged. No numeric DB primary keys appear anywhere.

Issue to fix

  1. The README errors: YAML example fails backend validation. README.md (the billing-error-spikes example) uses window: 5 minutes. In #821, parse_spike_window only accepts an integer or a string matching ^(\d+)\s*m?$ after strip/lower, and the API serializes the value back as "5m". "5 minutes" fails that match, so the server raises window: must be whole minutes between 1m and 60m. A user who copies this example into cronitor.yaml gets a validation error from apply_config(), and the whole config sync fails. Change it to window: 5m (or window: 5). The other fields in that example (trigger: spike, apps: [app_...], threshold, per: fingerprint, notify) match #821.

Non-blocking

  • ErrorApp.list and ErrorGroup.list with auto_paginate=True stop when len(result) < pageSize. The server clamps pageSize to 200, so passing pageSize=500 returns only the first page. Monitor.list behaves the same way. You could clamp pageSize client-side or paginate on page_count.
  • The REST helpers call resp.json() without a guard, and network failures surface as requests exceptions rather than package exceptions. This matches the existing Monitor code, but you could wrap a non-JSON 2xx body (for example a proxy error page) in APIError.
  • cronitor.ingest_url only changes the ping host; the envelope host comes from the DSN. The README states this correctly, but the name suggests it also controls error ingest. Consider a short note in the docstring or the env-var docs.
  • ErrorGroup.event() raises ErrorGroupNotFound for a missing event. That's acceptable because both share the 404, but the exception name may surprise users.

I found no comments that narrate old behavior.

Verdict: REQUEST CHANGES

@aflanagan

Copy link
Copy Markdown
Collaborator Author

Interrogate + Review R1 (Gemini 4 Neon Medium)

HEAD: 045f0eb

Intent

Adds native Cronitor Error Tracking support for cronitor-python 4.10.0 aligned to the Error App DSN and Errors API contract:

  • Error App DSN (cronitor.dsn / CRONITOR_DSN) parsing and gzipped Sentry envelope transport (POST /api/{project_id}/envelope/ with X-Sentry-Auth and envelope dsn, never falling back to cronitor.api_key), with bounded queue, 900 KB event trimming, 429 rate-limit dropping, fork safety, and atexit/explicit flush.
  • First-class capture_exception / capture_message (module-level and Monitor-bound) supporting level, fingerprint, tags, extra, exception chaining, source context, and ContextVar job binding.
  • @cronitor.job best-effort pings and default-on unhandled exception capture (cronitor.capture_exceptions = True, per-job kwarg override).
  • REST clients cronitor.ErrorApp (/api/error-apps) and cronitor.ErrorGroup (/api/errors) using string keys only, plus type=errors monitor support in apply_config and README.
  • Retains stdlib cronitor.logger and version 4.10.0 (no structured log shipping, no 5.0 breaking change).

Verification Run

  • uv run --with pyyaml --with requests --with pytest pytest -v: 116 passed, 7 skipped (live integration tests).
  • Verified all added comments against the diff-narration rule (git diff origin/master...HEAD -- '*.py' | grep -E '^\+.*#'): all comments describe current behavior only.
  • Verified contract alignment across cronitor/__init__.py, cronitor/ingest.py, cronitor/capture.py, cronitor/errors.py, cronitor/monitor.py, cronitor/_version.py, setup.py, and README.md.

Findings

NO VERIFIED FINDINGS

Dropped

  • _json_safe with non-finite float dict keys (extra={float('nan'): 'x'}): _json_safe sanitizes non-finite float values but not dict keys, causing json_bytes to raise ValueError and drop the event when a caller passes float('nan')/float('inf') as a dict key in extra. Dropped as too contrived/pathological to block the PR (normal non-finite float values, cycles, and non-JSON-primitive keys are handled and tested).
  • _retry_after header casing on plain dicts: headers.get('X-Sentry-Rate-Limits') / headers.get('Retry-After') is case-sensitive on a plain Python dict, but real HTTP responses from requests.Session use CaseInsensitiveDict, so this does not affect production traffic.
  • ErrorApp / ErrorGroup empty key in _api_url: Passing an empty key hits the collection URL (same existing pattern as Monitor._monitor_api_url), where the API returns an error; not a real defect.

Verdict: APPROVE

The backend accepts window as an integer or a string like 5m, not
"5 minutes", so a copied README example would fail apply_config.
@aflanagan

Copy link
Copy Markdown
Collaborator Author

Follow-up on the Claude Opus 5.5 Medium review at 045f0eb:

Fixed in 9d073b6:

  • README errors: example now uses window: 5m, which the backend accepts.
  • Package-config docs (and a short ingest_url comment) now say that setting is the ping host only; error envelopes use the DSN host.

Skipped, with reasons:

  • Auto-pagination stopping early when pageSize is above the server clamp of 200: same behavior as existing Monitor.list.
  • Unwrapped resp.json() / raw requests network errors: same as existing Monitor helpers.
  • ErrorGroup.event() raising ErrorGroupNotFound on a missing event: both are 404s from the same resource tree; a second exception class would not help callers.

@aflanagan aflanagan left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Opus 5.5 Medium (delta review)

Range reviewed: 045f0eb..9d073b6 (README.md, cronitor/init.py; 3 lines changed)

Previous blocking finding: fixed

  • The README errors: YAML example now says window: 5m (README.md:309) instead of window: 5 minutes. 5m matches the backend's parse_spike_window pattern (^(\d+)\s*m?$) and is the same form the backend writes back out, so apply_config won't reject it anymore.

Clarifications: done

  • The package-config docs now say cronitor.ingest_url is the host for telemetry pings only, and that error envelopes use the host in cronitor.dsn. That matches how the transport works: envelopes go to the DSN's host and never fall back to ingest_url.
  • There's a short inline comment on ingest_url in cronitor/__init__.py that says the same thing. It describes current behavior.

Non-blocking notes I raised before

The PR comment says these were skipped because they work the same way as the existing Monitor helpers (pagination clamp, unwrapped resp.json() and network errors, ErrorGroupNotFound for a missing event). That's a reasonable call for this PR, and I don't need any changes for them.

Verification

  • uv run --with pyyaml --with requests --with pytest pytest -q: 116 passed, 7 skipped (the skipped ones are the live integration tests) at 9d073b6.

New findings

None. The delta only touches docs and a comment, so runtime behavior is unchanged.

Verdict: APPROVE

@aflanagan

Copy link
Copy Markdown
Collaborator Author

Interrogate R2 regression-only (Gemini 4 Neon Medium)

HEAD: 9d073b6
Previous: 045f0eb

Scope Checked

  • git diff 045f0eb845b3cf1d3cf31d49800ec4f1e7d7b87f..9d073b633b26a91dd39ae799436f6c4319c1be05:
    • README.md: Updated the errors: YAML example from window: 5 minutes to window: 5m (resolving the previously flagged invalid duration format) and clarified that cronitor.ingest_url / CRONITOR_INGEST_URL applies to telemetry pings only while error envelopes use the host in cronitor.dsn.
    • cronitor/__init__.py: Added a matching inline comment on ingest_url; no functional code changes.
  • Verification:
    • git grep -n "window:\|ingest_url\|minutes" confirms no remaining invalid window: examples.
    • uv run --with pyyaml --with requests --with pytest pytest -q: 116 passed, 7 skipped.

NO VERIFIED FINDINGS

Verdict: APPROVE

Cronitor SDKs now take ingest_key and optional ingest_url, and post
to /e. DSN config still works but is no longer the documented path.
@aflanagan

Copy link
Copy Markdown
Collaborator Author

Posts envelopes to /e. Preferred config is cronitor.ingest_key plus optional cronitor.ingest_url. DSN still works but is no longer documented. Tests: 53 ingest/ErrorApp unit tests passed.

@aflanagan

Copy link
Copy Markdown
Collaborator Author

Interrogate R3 regression-only (final allowed round) (local fallback, Grok 4.7 pending: cloud seats paused) on 3c5ec1b (adversary: Gemini 4 Neon Medium via agy on the mini)

Intent

Switch native error capture to post gzipped Sentry envelopes to {ingest_url}/e authenticated by cronitor.ingest_key (with optional cronitor.ingest_url defaulting to https://cronitor.link), update ErrorApp docs/tests to ingest_key/ingest_url, and retain undocumented cronitor.dsn compatibility.

Prior findings

Findings

None.

Verification run:

  • python -m pytest -q (isolated venv with pip install -e . pytest): 117 passed, 7 skipped (live integration tests).
  • Exercised cronitor.ingest_key with default and custom cronitor.ingest_url, precedence over cronitor.dsn, fallback to cronitor.dsn posting to /e, and missing/invalid config returning None without falling back to cronitor.api_key.
  • git diff 9d073b633..HEAD -- '*.py' | grep -E '^\+.*(#|import |getenv|environ)': no diff-narrating comments, no inline imports, and no new environment variables.
  • git grep -n "envelope/": no stale /api/.../envelope/ references remain.

Dropped

  • Passing a non-string cronitor.ingest_url to credentials_from_key() raises AttributeError on .strip() (still caught by the public capture_exception/capture_message wrappers); dropped as contrived input.
  • CaptureTestCase.setUp (cronitor/tests/test_capture.py) and LocalCollectorTests.setUp (cronitor/tests/test_ingest.py) do not save/reset cronitor.ingest_key; defaults to None and every test that sets it restores it, so no failure occurs.

NO VERIFIED FINDINGS

@aflanagan aflanagan left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gemini 4 Neon Medium (agy on the mini), review of 3c5ec1b

Verdict: APPROVE

No findings.

Checked git diff 9d073b633..HEAD (README.md, cronitor/__init__.py, cronitor/errors.py, cronitor/ingest.py, cronitor/tests/test_errors.py, cronitor/tests/test_ingest.py). Verified credentials_from_key, parse_dsn, and Transport._resolve_dsn route envelopes to {ingest_url}/e with X-Sentry-Auth sentry_key, keep cronitor.dsn working as a fallback, and add no new environment variables. Ran uv run --with pyyaml --with requests --with pytest pytest -q: 117 passed, 7 skipped.

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.

2 participants