22.3 KiB · text History 78a7bd9

Roadmap

Vigil is a Sentry-compatible error tracker in the GlitchTip mould: the Sentry SDKs and sentry-cli talk to it unchanged. It is a Phoenix app with Oban for every background and periodic job, LiveView for every screen, UUIDv7 keys everywhere (Vigil.Schema), and Rust NIFs for format work, in the manner of gitgud’s native/ crates.

The plan is grouped into slices. Each slice ships something usable and ends with mix precommit green. Sizes are estimates.


References and licensing

The reference code lives in ~/Development/local/sentry_oss_2019/:

Repo License Used for
glitchtip-backend MIT The primary server reference: ingest, data model, alerts, uptime, maintenance
sentry (2019-11-06, before the switch to BSL) BSD-3-Clause Grouping strategies, event normalisation, culprit and title rules
sentry-python, sentry-elixir MIT What clients send and how they react to responses
sentry-cli BSD-3-Clause The release, chunk-upload and assemble API
sentry-docs, snuba, onpremise Apache-2.0 Protocol docs
  • Logic ported from any of these keeps its copyright notice in NOTICE.md.
  • Never consult Sentry server code from after 2019-11, which is BSL.

Wire contract

These rules are not negotiable. The conformance tests in slice 1 pin them down.

Endpoints and auth

  • POST /api/:project_id/envelope/ is the only endpoint current SDKs use. /store/ (legacy SDKs), /security/ (CSP report-uri) and /minidump/ are secondary. Routes work with and without the trailing slash.
  • The key is read from, in order:
    1. the sentry_key query parameter (also glitchtip_key);
    2. the X-Sentry-Auth header;
    3. the Authorization header;
    4. the envelope header dsn, which GlitchTip ignores but tunnels rely on.
  • sentry_version 5 (Elixir) and 7 (Python) are both accepted. sentry_timestamp and sentry_secret are optional.
  • The key, the project, the organisation, and whether each is active and not deleted are checked before the body is read.

Request bodies

  • Content-Type is ignored. Elixir sends none; Python sends application/x-sentry-envelope.
  • Content-Encoding may be gzip or deflate (zlib-wrapped, or raw deflate as a fallback), both via :zlib; zstd via OTP 28’s :zstd; or br via a NIF. br is Python’s default.
  • Bodies are capped twice: raw at 20 MiB, decompressed at 100 MiB per envelope and 1 MiB per event item. Decompression stops at the cap rather than inflating the whole body and checking afterwards.

Envelope parsing

  • An item is length-prefixed when its header has length; otherwise it runs to the next newline. Elixir’s log and trace_metric items have no length.
  • Unknown item types are skipped and parsing continues. GlitchTip stops at the first one; Vigil must not.
  • Payloads tolerate null anywhere. exception, breadcrumbs and threads may be bare arrays or {"values": […]}. message may be a string or an object. Timestamps may be ISO strings with or without Z, or unix ints or floats.

Responses

  • Always 200 with a JSON object: {"id": "<envelope event_id>"}, or {} when there is none.
    • sentry-elixir treats anything other than a 200 with a JSON object as a failure and retries it five times.
    • send_result: :sync returns that id to the caller.
  • 429 carries Retry-After: <int> and X-Sentry-Rate-Limits: <int>:<categories>:<scope>[:<reason>]. Use integers: Python silently drops float values.
  • 413 for oversize bodies; both SDKs drop the envelope and don’t retry.
  • 403 {"detail": …} for a bad key, with a short negative cache so that sentry-elixir’s retries don’t each hit the database.

CORS

  • * origins.
  • Allowed headers include x-sentry-auth, sentry-trace, baggage and content-type.
  • Exposed headers: Retry-After, X-Sentry-Rate-Limits, X-Sentry-Error.

Item types

Every item type the SDKs send gets a 200, whether it is stored or dropped:

Item type Handling
event Stored
transaction (Elixir) Stored
span v2 (Python 3.x) Stored
check_in Stored
log Stored
client_report Stored as outcome counts
session, sessions Stored
user_report, feedback Stored
attachment Stored
trace_metric, profile_chunk, replay_* Accepted and dropped until a slice takes them

Architecture

SDK ──► Vigil.Ingest.Plug   (in the Endpoint, ahead of Plug.Parsers and the
          │                   session; ingest never touches cookies)
          ├─ auth: ETS cache of project keys, invalidated over PubSub
          ├─ rate limit: ETS counters per key and org, with outcome headers
          ├─ decode: zlib / zstd / brotli NIF, with output caps
          ├─ frame: Vigil.Ingest.Envelope (pure Elixir; split items, skip unknown)
          └─ buffer: INSERT into ingest_items, then Oban.insert of a unique
             Drain job. Respond 200 {"id"}.
                   │
Oban queue :ingest ▼
  Vigil.Ingest.Drain: claims up to 100 rows (FOR UPDATE SKIP LOCKED) and
  dispatches each by item type to a processor:
    Events.Process   normalise ─► symbolicate ─► title/culprit ─► group
                     ─► upsert issue ─► insert event ─► tags/stats
                     ─► mark for alerts ─► PubSub
    Performance.Process, Crons.Process, Logs.Process, Sessions.Process,
    Outcomes.Process, Feedback.Process

Why a buffer table instead of payloads in Oban args. Envelope items can be megabytes. In oban_jobs.args they would bloat the jobs table and its pruner, and each event would cost its own job. A plain ingest_items table drained in batches behaves like GlitchTip’s 100-item, 2-second batches. Oban still owns scheduling, retries, concurrency and telemetry. A Drain job is unique per project within a 1-second window, so a burst of envelopes queues one drain, not one per item.

Oban queues:

  • ingest: the drains.
  • processing: symbolication and assemble.
  • notify: email and webhooks.
  • checks: uptime probes.
  • maintenance: partitions and retention.

Oban cron jobs:

Job Schedule
Alert evaluation every minute
Cron monitors: missed and timed-out check-ins every minute
Uptime reconciler: make sure each monitor has its next job scheduled every minute
Partition maintenance daily
Retention sweep daily
Stale-blob cleanup daily

Oban’s cron can’t run more often than once a minute, so uptime checks are self-rescheduling jobs: each check inserts its successor at now + interval, unique per monitor. GlitchTip ticks a Valkey counter every second instead.

Storage. Postgres only: no Valkey and no ClickHouse.

  • High-volume tables are range-partitioned by UUIDv7 id per day (issue_events, log_events, spans, monitor_checks, outcomes).
  • Stats tables are partitioned weekly by date.
  • Vigil.Partitions creates partitions ahead of time and drops whole partitions for retention. There are no DEFAULT partitions, so a missing partition fails loudly instead of silently filling one.

Live updates. Processors broadcast on PubSub topics (project:<id>:issues, issue:<id>, logs:<project>). Issue lists and the log tail update in place. libcluster is added when it runs on more than one pod, as cartosnap does.


NIF crates (native/, in gitgud’s style)

Each crate is a cdylib on rustler with a committed Cargo.lock and a thin use Rustler module. They are built from source with a pinned rustup toolchain in the Dockerfile and CI, and pass clippy -D warnings. Cargo.toml comments justify feature choices, and no crate may add system libraries to the images.

Crate What Slice
vigil_codec Brotli decode with an output cap, on the brotli crate. ex_brotli (MIT) was considered, but its decompress/1 reads to the end with no limit (a decompression bomb at the ingest edge) and fetches precompiled binaries by default, so the crate lives here 1
vigil_ua User-Agent to browser, OS and device contexts, on the uaparser crate with the uap-core regexes compiled in 2
vigil_sourcemap JS symbolication on the sourcemap crate (debug ids, index maps, sourcesContent context lines), plus zip and manifest reading for artifact bundles 5
vigil_symbolic Native, Proguard and minidump symbolication on symbolic and minidump. Optional; last 12

Slices

0. Foundations: orgs, projects, keys, tokens · medium

  • Add Oban (Postgres engine, Pruner, Lifeline, Cron) and a NOTICE.md.
  • Organizations: slug unique, reserved words blocked; accepting_events; scrub_ip.
  • Org members: user, org, role. Roles are member, admin, manager and owner, each with a scope set as in GlitchTip.
  • Org invites: addressed and hashed, as registration invites already are. For someone without an account an org invite doubles as a registration invite, so it reuses Vigil.Accounts.Invite’s flow and NEIAM link_pending.
  • Teams: members and projects. Teams control which projects a member can see; admins and owners see everything.
  • Projects: slug unique per org, platform, first_event_at, scrub_ip.
  • Project keys: public key UUID, active flag, rate limit {count, window} that is actually enforced, and the DSN builder.
  • API tokens: per user, labelled, scopes, stored as a SHA-256 hash and shown once. A Bearer plug computes effective scopes as token scopes ∩ the user’s role scopes in the target org (GlitchTip ignores the role).
  • LiveView: org switcher and create; org settings (members, invites, teams); project create (platform picker and a DSN snippet per SDK); project settings (keys); account → API tokens.
  • Vigil.Partitions and the maintenance cron job exist here, so later slices only declare their tables.
  • Exit: a user can create an org and project, copy a DSN, and mint a token.

1. Ingest edge · large

  • Vigil.Ingest.Plug covering everything under Wire contract: auth with a negative cache, decoders with caps, envelope framing, CORS, rate limits with outcome headers, the buffer and the Drain job.
  • /store/, /security/ and /minidump/ route into the same pipeline. /minidump/ stores the attachment for slice 12.
  • Items for later slices are kept in ingest_items with a deferred state, not discarded, so those slices can process the backlog when they land.
  • client_report becomes outcome counts (outcomes: org, project, category, reason, hour, quantity), shown later as “dropped by SDK”.
  • Conformance suite:
    • Fixture envelopes captured from real sentry-python 3.x and sentry-elixir 14.x runs.
    • Hand-written edge cases: no length, unknown types, nulls, bare arrays, binary attachments, br/gzip/zstd bodies, bombs, auth in each of the four places.
    • Tests on the status code, the body and the headers.
  • An optional CI job runs the real sentry-python and sentry-elixir against a test server.
  • Exit: both SDKs report success, and nothing is retried or lost.

2. Events into issues · large

  • Normalisation:
    • Tolerant per field, as GlitchTip: a bad interface becomes nil plus an entry in errors[], never a rejection.
    • Bare arrays and values are unified, and logentry is formatted.
    • Request headers become a sorted list, and cookies are scrubbed.
    • Client IPs are set and anonymised per project.
    • \u0000 is stripped.
  • Threads: an exception without a stacktrace borrows one from threads.
  • Contexts: browser, OS and device are filled from the User-Agent (vigil_ua).
  • Title, culprit and metadata: ported from 2019 Sentry and GlitchTip’s sentry/ subset. culprit is persisted, which GlitchTip forgets to do.
  • Grouping (a decision; see below). Recommended: port 2019 Sentry’s newstyle:2019-10-29 strategy (stacktrace components with in-app frames first, exception type, message fallback), with fingerprint and {{ default }}. Store (config, hash) on issue_hashes so a later strategy can add hashes without regrouping.
  • Issues:
    • Short id from a per-project counter upsert: PROJ-1A.
    • Status: unresolved, resolved, resolved-in-release, ignored.
    • Regression: a resolved issue reopens on a new event, or on an event from a different release when it was resolved in a release. Its alert dedupe resets.
    • Counts and first/last seen are updated in a single bulk statement per drain batch.
    • Releases and environments are created automatically.
  • Events: partitioned by day; the data JSON is trimmed to the interfaces; event_id is unique per project, which dedupes retries.
  • Tags and stats:
    • tag_keys and tag_values dictionaries.
    • issue_tags counts per day.
    • Hourly issue_counts and project_counts.
  • Search: a tsvector over title, culprit, transaction and frame filenames, plus a trigram index on title.
  • User feedback: user_report and feedback items are linked to the issue by event_id.
  • Exit: errors from both SDKs group sensibly and survive regression and resolve cycles.

3. Issue UI · large

  • Project issue list:
    • Stream-backed with live inserts.
    • Filters for status, level, environment, release, assignee and time range.
    • Free-text and key:value tag search.
    • A sort selector.
    • A sparkline per row from the hourly counts.
    • Bulk resolve, ignore, delete and assign.
  • Issue detail:
    • A header with counts, first and last seen, releases, and a tag facet sidebar from issue_tags.
    • An event pager (newest, oldest, prev, next).
    • Stacktrace with in-app collapsing, frame vars and source context, and a raw/symbolicated toggle.
    • Chained exceptions, breadcrumbs, request, contexts, user, extra, SDK, and a JSON view.
    • Comments, assignee, user feedback, and a public share toggle.
  • Org dashboard: projects, recent issues across them, and an events-per-hour chart.
  • Keyboard navigation (j/k, e/r/i).
  • Exit: daily triage is possible without leaving Vigil.

4. Alerts and notifications · medium

  • Rules: per project, “N events in M minutes”, “new issue” and “regression”. Recipients are email, a generic webhook (Slack-compatible), Discord, ntfy, Teams, Google Chat and Zulip, with GlitchTip’s payload shapes.
  • Evaluation:
    • Processors record touched issues in an alert_candidates table (instead of a Valkey set).
    • A minutely Oban cron job evaluates the rules.
    • Delivery is one Oban job per recipient. Unlike GlitchTip it retries with backoff, and failures are visible in the UI.
  • Dedupe: once per issue per rule, until a regression. A “snooze for X” option re-notifies after time passes, which GlitchTip can’t.
  • Who gets email: per-user project subscriptions with a subscribe-by-default setting; email goes through Swoosh.
  • Exit: new and regressed issues reach email and a webhook exactly once.

5. Releases, sentry-cli and sourcemaps · large

The /api/0 API:

  • GET /api/0/ returns user and token info.
  • Releases:
    • Create under both the org and project paths. It must be idempotent, which GlitchTip’s org path isn’t: it returns a 500.
    • Update, finalize and delete.
    • Get, returning 404 when missing.
    • List, with Link-header cursors.
    • version and shortVersion are both emitted.
    • dateReleased stays null until finalize; GlitchTip sets it on create.
  • Deploys and commits: deploys can be created and listed. The commits and refs sent in the release PUT are stored (GlitchTip drops them). GET /repos/ returns [], and previous-with-commits returns 404.
  • Chunk upload:
    • GET advertises artifact_bundles (and later artifact_bundles_v2).
    • POST takes multipart file_gzip parts. It verifies each SHA-1, which GlitchTip doesn’t, and stores blobs per org rather than globally.
  • Artifact-bundle assemble:
    • not_found returns the missing chunks.
    • Otherwise an Oban assemble job runs, with status tracked per (org, checksum).
    • It returns created, then assembling, then ok or error, so --wait works. GlitchTip never returns ok.
  • Bundles: extract the manifest and pair minified files with their maps by debug id or Sourcemap header, into artifact_bundle_files.
  • JS symbolication with vigil_sourcemap:
    • Match by debug id from debug_meta.images, falling back to release and filename.
    • raw_stacktrace is kept.
    • Handles webpack:, app: and ~/ prefixes, and sets in_app.
  • File storage behind a small behaviour, with local disk and S3 (Req’s aws_sigv4, as cartosnap does).
  • UI: releases list and detail (new, resolved and regressed issues, deploys, artifacts). Issues gain “resolve in next release”.
  • Exit: sentry-cli releases new/finalize/deploys, sourcemaps upload --wait and a minified-JS error together give a readable stacktrace.

6. Performance · large

  • Storage:
    • Elixir sends transaction items with spans[]; Python 3.x sends span v2 items (is_segment marks the root).
    • Both normalise into one spans table, partitioned daily, with trace id, span id, parent, segment, op, name, status, start, duration and attributes.
    • Segment spans roll up into transaction_groups keyed by (project, name, op, method).
    • Rollups keep count, error count, average duration and a 50-bucket histogram from which p50, p95 and p99 are computed, as in GlitchTip.
  • UI:
    • A transactions list with throughput, latency percentiles and error rate.
    • A transaction detail page with a duration histogram and sample traces.
    • A trace waterfall built from the spans.
    • Errors and spans linked through contexts.trace.trace_id.
  • Later: N+1 query detection (repeated db spans under one parent), as GlitchTip’s MCP tools offer.
  • Exit: a Phoenix app with sentry-elixir tracing shows endpoints and waterfalls.

7. Cron monitors · medium

This is new: GlitchTip throws check_in items away.

  • Monitors:
    • Upserted from monitor_config (crontab or interval schedule, timezone, check-in margin, max runtime, failure and recovery thresholds), or created in the UI.
    • Slugs are unique per project.
    • Crontab parsing uses crontab or Oban’s own cron expression parser.
  • Check-ins:
    • in_progress, then ok or error, matched by check_in_id; an unknown id is a new check-in.
    • Duration is taken from the payload or the pair.
    • sentry-elixir’s Oban and Quantum integrations work unchanged.
  • Minutely cron job: marks expected-but-missing check-ins missed, and in-progress ones past max_runtime timeout. Missed, error and timeout states cross the thresholds into monitor incidents, which alert through slice 4’s recipients.
  • UI: monitors list with a status timeline per monitor, and the next expected run.
  • GET /api/0/organizations/{o}/monitors/ returns the shape sentry-cli expects.
  • Exit: Vigil’s own Oban cron jobs, reported through sentry-elixir, show up and alert when they’re missed.

8. Uptime · medium

  • Monitors: HTTP GET, HTTP POST, ping, TCP, SSL expiry, and heartbeat (push to /api/0/organizations/{o}/heartbeat_check/{uuid}/).
  • Checks:
    • Self-rescheduling Oban jobs in the checks queue.
    • HTTP checks use Req, with expected status and body, a timeout, and an SSRF guard that blocks private addresses.
    • monitor_checks is partitioned daily; “up” heartbeats aren’t stored.
  • Alerts on up/down changes, through slice 4.
  • Status pages: public or private, slugged, live via PubSub.
  • Exit: monitors flip state within one interval and alert once per change.

9. Logs · medium

  • log items arrive from Python as version: 2 and from Elixir with no version.
  • Storage: flattened attributes (service, environment, host, severity) in a partitioned log_events table. Logs more than a day off server time are rejected.
  • UI:
    • A live tail over PubSub.
    • Filters for level, service, environment and attributes.
    • Search.
    • Jumps to the trace or issue by trace_id.
  • Exit: sentry-elixir’s logger handler streams into the tail.

10. Release health · small-medium

  • session and sessions items roll up into per-release, per-environment, per-hour crash-free counts.
  • Release pages show crash-free users and sessions and adoption.

11. Retention and operations · medium

  • Retention per type, settable per org: events and logs 90 days, releases 365 days. Old partitions are dropped. Orphaned issues, blobs and bundles are swept, and soft-deleted orgs and projects are removed by Oban jobs.
  • Health: /_health/ and /api/0/internal/health/; /metrics for Prometheus via telemetry.
  • Dogfooding: Vigil reports its own errors, crons and traces to itself through sentry-elixir. A loop guard drops events about the ingest path itself.
  • Packaging:
    • Dockerfile with a pinned rustup toolchain for the NIFs.
    • Forgejo CI: precommit, clippy, audit.
    • rel overlays for bin/invite, bin/migrate and bin/token.
    • Mail through the siblings’ setup (gen_smtp or mail-prism).
  • Optional:
    • An MCP endpoint with the same Bearer tokens, offering issue, event and log tools as GlitchTip’s MCP server does.
    • The sentry-wizard endpoints.
    • The DSN-keys API.

12. Native and mobile (optional) · large

  • Debug information file assemble (/projects/{o}/{p}/files/difs/assemble/), Proguard mappings, minidump processing, and native and JVM symbolication through vigil_symbolic.

Decisions to make

# Question Recommendation
1 Grouping: GlitchTip’s md5(title + culprit + type), or 2019 Sentry’s stacktrace grouping? 2019 Sentry newstyle (BSD), versioned per hash. Title-based grouping merges unrelated errors that share a message, and splits one error whose message carries ids. Changing strategy later means regrouping, so choose before data arrives
3 Where ingest payloads wait: a buffer table plus Drain jobs, or payloads in Oban args? The buffer table (see Architecture)
4 Org invites and registration invites: one table or two? Two tables, one flow. An org invite to an address without an account behaves as an addressed registration invite
5 Span volume: every span in Postgres? Yes, partitioned daily with short retention (7 to 14 days) and rollups kept longer. Revisit cold storage (Parquet) only if volume demands it
6 Multi-node: libcluster from the start? Not until slice 11. Ingest is stateless apart from the ETS caches, which PubSub keeps coherent once clustered