Browse the OpenTelemetry traces and metrics a Datasette instance emits, from
inside that instance: a self-recording span and metric store plus the
/-/otel viewer (/traces, /metrics). Nothing else can write into the
store over HTTP. Product notes, privacy posture and config reference live in
NOTES.md; this file is the map for working on the code.
- Backend: Python, Datasette (>=1.0a41, which ships OpenTelemetry support), datasette-plugin-router, Pydantic, opentelemetry-sdk/proto
- Frontend: Svelte 5 (runes), TypeScript, Vite, openapi-fetch, SveltePlot (metric charts only), served through datasette-vite
- Store:
otel.db(traces+spans,metrics+metric_points,store.py), no migration framework —SCHEMA_SQLisIF NOT EXISTSand reruns on every startup - Build: Just (Justfile), uv (Python), npm (frontend)
| Command | What it does |
|---|---|
just dev |
Datasette on :8012 against demo.db with datasette-debug-gotham; only clark (and --root) holds datasette-otel-viewer; serves the built bundle |
just dev-with-hmr |
dev + Vite HMR via datasette-vite dev_paths; restarts on .py/.html changes |
just frontend-dev |
Vite dev server on :5186 (pair with dev-with-hmr) |
just frontend |
Production build → datasette_otel_viewer/static/gen/ + manifest.json |
just types |
Regenerate frontend/api.d.ts + frontend/src/page_data/*.types.ts from Python |
just types-watch |
Watch .py files, auto-regenerate types |
just format / just format-check |
ruff (backend) + prettier (frontend) |
just check |
ruff check + ty check + svelte-check/tsc |
just test |
pytest (page routes run in Vite dev mode, no build needed) |
just test-frontend |
vitest over frontend/src/lib/*.test.ts |
just shots |
Regenerate docs/screenshots/*.png via Playwright (not in CI; re-run and check git status) |
just demo |
The NOTES.md self-mode demo on :8003 |
CI: .github/workflows/test.yml builds the bundle before pytest, and
type-checks/tests/builds the frontend in a second job.
datasette_otel_viewer/
├── __init__.py # Hooks: startup, register_routes, extra_template_vars, menu_links
├── config.py # OtelViewerConfig: the plugin's config block, validated (get_config)
├── router.py # Shared Router + check_viewer() decorator
├── page_data.py # Pydantic models: page data + API request/response
├── queries.py # Read-side SQL shared by pages and API
├── routes/pages.py # GET /-/otel (index), /traces, /traces/{trace_id}, /http, /sql, /spans, /spans/list, /metrics, /metrics/{name} (HTML)
├── routes/api.py # POST .../traces/list, http/endpoints, sql/queries, spans/groups, metrics/*; GET .../traces/{trace_id}
├── selfsource.py # TracerProvider ownership + suppression sampler
├── selfmetrics.py # MeterProvider ownership/attach + SDK metrics → rows
├── store.py # Schema, batch insert, retention
├── permissions.py # datasette-otel-viewer action; raw tables private by default
├── templates/otel_viewer_base.html # The single template (overrides Datasette's `crumbs` block)
├── static/gen/, manifest.json # Built by Vite (gitignored)
frontend/src/
├── pages/index/ # /-/otel landing page (IndexPage.svelte): counts + links
├── pages/traces_list/ # List page (TracesListPage.svelte)
├── pages/trace_detail/ # Waterfall + inspector (TraceDetailPage, WaterfallRow)
├── pages/http_summary/ # /-/otel/http endpoints (HttpSummaryPage.svelte)
├── pages/sql_summary/ # /-/otel/sql statements (SqlSummaryPage.svelte)
├── pages/spans_summary/ # /-/otel/spans catalogue (SpansSummaryPage.svelte)
├── pages/spans_list/ # /-/otel/spans/list drill-through (SpansListPage.svelte)
├── pages/metrics_list/ # Metrics table
├── pages/metric_detail/ # SveltePlot charts (SeriesChart, HistogramHeatmap, PercentileChart)
├── lib/traceTree.ts # Span forest assembly (unit-tested), time.ts, sort.ts
├── lib/metricsMath.ts # TS twin of metrics_math.py (shared test vectors), metricsSeries.ts
├── components/SortHeader.svelte, Breadcrumbs.svelte, Icon.svelte
├── components/Shortcuts.svelte # Binds a page's keyboard shortcuts (TanStack Hotkeys) and draws the ? help panel
├── lib/shortcuts.ts # Shortcut groups: global, section jumps, table cursor (unit-tested)
├── lib/rowCursor.svelte.ts # The j/k row cursor the table pages share
├── lib/icons.ts # bootstrap-icons path data by meaning; Icon.svelte renders it
├── page_data/load.ts # loadPageData<T>()
├── api.ts # openapi-fetch client over api.d.ts
└── app.css
frontend/scripts/screenshots.mjs # `just shots` harness
scripts/typegen-pagedata.py # Pydantic → JSON Schema
- A route in
routes/pages.pybuilds a Pydantic model fromqueries.py - Passes
page_data.model_dump()(a dict) tootel_viewer_base.html - The template embeds it as
<script id="pageData">{{ page_data | tojson }}</script>and the Vite entrypoint viadatasette_otel_viewer_vite_entry(entrypoint) - The Svelte page calls
loadPageData<TracesListPageData>() - Types come from
just types-pagedata(models listed inpage_data.__exports__)
routes/api.pydeclaresoutput=Modelandbody: Annotated[Model, Body()]just types-routes→router.openapi_document_json()→ openapi-typescript →frontend/api.d.ts- The frontend calls
client.POST("/-/otel/api/traces/list", { body })viasrc/api.ts
The list fetch is a POST with a body (not GET + query string) because the
router only types path params and bodies. Do not add
from __future__ import annotations to route modules: the router inspects
the real Annotated[..., Body()] objects at decoration time.
datasette-otel-viewer(global action, same name as the plugin) gates the viewer pages, the JSON API and the rawoteltables.public_viewer: trueopens pages + API only; the raw tables stay gated (permissions.pyemits a database-scoped deny row).check_viewer()inrouter.pyreturns a plain-text 403, preserving the message the tests assert on.- There is no write path over HTTP: the store is only written by this instance's own span and metric readers.
- Breadcrumbs are built twice from one definition of the trail:
routes/pages.SECTIONS/_crumbs()feeds Datasette's header (thecrumbsblock inotel_viewer_base.html, which calls core'scrumb_items()for the "home" link), andcomponents/Breadcrumbs.svelterenders the same trail above each page's<h1>. A new page needs both. - Svelte 5 runes only (
$state,$derived,$props); noexport let. - Generated files are gitignored:
api.d.ts,*_schema.json,*.types.ts,static/gen/,manifest.json. Runjust typesafter touching Pydantic models or route signatures;just frontendbeforejust dev. make_ds()builds instances withself_traces: falseunless a test passesself_traces=True. The first request launches the store's writer tasks, which then write on their own timer, so an instance that records itself can drop spans into the store mid-test, which every row count then races -- that was a ~1-in-4 suite failure. Tests that want self-recorded spans opt in anddrain(), which calls the exporter'sflush()directly;make_dsshuts each instance down so those tasks end with the test.- Tests configure
plugins.datasette-vite.dev_pathsso page routes render without a build;test_built_manifest_serves_hashed_assetsis the one test that needsjust frontendfirst (CI does it). scripts/shots_plugins/seed.pyis loaded only byjust shots(--plugins-dir); it builds row dicts againststore.COLUMNS/METRIC_POINT_COLUMNSby hand — update it when those change./-/otel/sqldecides "was this a write?" with a correlatedexistsoverspans(parent_span_id, name)(queries._IS_WRITE_CHILD,store.idx_spans_parent_name). The index is not optional: as a joined subquery, or as thisexistswithout the index, that test is a scan per span and the page takes over a minute atmax_spans.- Every route is wrapped by
check_viewer(), which turns aQueryInterruptedinto a plain-text 503. The summary pages scan the whole store, so a big store on a slow box can outrunsql_time_limit_ms; that has to be an answer, not a 500.prepare_connectiongives the otel database a 32MB page cache for the same reason. - Store writes run inside
store.suppress()so spans about storing spans are never recorded; seeselfsource.pybefore touching the write path. The exporters only buffer (they run on OTel's worker threads); the write happens instore.write_periodically, one background task per exporter registered fromstartupviadatasette.add_background_task.selfmetrics.pydrops metric points whosedb.namespaceis the otel database for the same reason. - The traces list sorts and pages in SQL, under Datasette's own querystring
names (
?_sort/?_sort_desc/?_size/?_nexton the page, the same fields onTracesQueryfor the API). The sortable-column allowlist ispage_data.TRACE_SORT_COLUMNS; the SQL behind each name isqueries.TRACE_ORDER_BY, and a module-level assert keeps the two in sync.lib/sort.ts'ssortRowsis now the metrics catalogue's only (it fits in one response); the traces page usesnextSortfor header state alone. page_data.TraceFiltersis the filter surface both trace views share (service,path,route,method,status,min_duration_ms);queries._where()turns one into SQL for the trace list, the root facet and the HTTP endpoint summary alike, so/-/otel/httpcan drill through to/-/otel/tracesby handing over its own querystring. All three summaries share one shape, and it is load-bearing at the defaultmax_spans: a materializedgroupedCTE aggregates first, then_percentile_ctes()joins one row per group onto it.groupedalso handspctthe group size (n_timed), which is what letsrankedget away with a single window and a single sort, and letspctdiscard every row but the two percentile boundaries and the last. Do not reintroduce acount(*) overwindow for the size, and do not joinpctto the rows and aggregate afterwards -- each costs a full extra pass over every span. The slowest span's ids ride along onpct(rn = n_timed, ties broken byspan_id desc) rather than a second window pass.sql_queriesaggregates spans rather than traces (its ownSqlFilters/_sql_where, since path/status/method mean nothing there) and keys rows oncoalesce(db_query_text, datasette.callback)so callback work is counted, not dropped.span_groupsis the general case of both: any span, keyed on name +scope_name(the plugin that emitted it), withsplit_bybreaking a row down by an attribute -- that key reaches a JSON path, so it is bound as?1and pattern-checked inpage_data.SpanFilters. A summary row is a group, so opening one drills intospan_list()(the spans behind it, paged like the trace list), never into a single span -- the slowest-span jump stays on the Max cell.SpanListQuery.highlightis one span_id to pin: the trace inspector's "All spans like this" link intospan_list(). With no cursor of its own,span_list()ranks that span with one window over the matching spans under the query's own ordering and writes the page offset back ontoquery.next, so the frontend, the URL and Previous all see an ordinary offset. An explicit_nextwins, which is what stops paging away from the pinned page snapping back to it; SpansListPage marks the row and says so on the chip when the pin is not on the page in front of you.- The scatter above that list (
DurationScatter.svelte, fed bySpanListResponse.chart) is the whole matching set, not the page: the page is a sorted slice, which is exactly the wrong sample to judge one span's duration by.queries._span_chartsamples it withrowid % stride(stridefromtotalandpage_data.SPAN_CHART_POINTS) rather than alimit-- which would draw the first slice of the time range as if it were the whole cloud -- or a window, which would sort every matching span a third time after the count and the page. Rowid order is insertion order, roughly start order, the same assumptionspan_attribute_keyssamples on. The pinned span is unioned in so it is drawn even when the sample misses it. - A traces list row has two destinations: the row (and its trace id cell)
opens the trace, while the root span label opens
span_list()for that label'sname_exact+scope+nesting=root-- a label names a kind of work, not an event. That link is whyTraceRow.scopeexists (the root span'sscope_name, already selected asroot_scopeby_MATCHING_SQL): without it the link would not key the same row/-/otel/spansdoes. - The traces list's
?root=filter buckets traces by root span --queries.root_kindsderives the buckets from the store (HTTP roots collapsed, everything else by span name and instrumentation scope), so nothing here enumerates Datasette's or a plugin's span names._where()builds the filter for both the list and the facet; keep the HTTP test (url.pathon the root span) in step withhttp_label. - The trace waterfall folds runs of consecutive siblings with the same name
and
scope_nameinto one group row (traceTree.groupSiblings, rows for the whole trace precomputed bybuildRows): at leastGROUP_MIN_RUNsiblings, none an ERROR, none longer thanGROUP_MAX_FRACTIONof the trace -- proportional so a 15s agent trace folds every query away and a 30ms request keeps its 1ms ones. Only consecutive siblings fold, so the order of work survives (Sentry's autogrouping, adapted: members may have children, since everydb.querydoes). Groups start closed; the header toggle disables grouping, andreveal()opens the group around a#span-deep link the same way it expands collapsed ancestors. The "Slowest" strip ranks byselfTimeNs(duration minus children), not duration, or every wrapper around the slow call would fill it. - Keyboard shortcuts: every page mounts one
<Shortcuts groups page>(components/Shortcuts.svelte), and thatgroupslist is the single source for both the bindings and the?help panel, so a key cannot be bound without being documented or vice versa. Groups come fromlib/shortcuts.ts(globalShortcuts,sectionShortcuts,tableShortcutsover aRowCursor); the trace page builds its own "Waterfall" group overtraceTree.visibleRows, which must mirror whatWaterfallRowdraws. Bindings go through@tanstack/svelte-hotkeys: a shifted letter is spelledShift+H,?isShift+/, a chord is an array. Escape is bound once, inShortcuts.svelte(help panel, then blur a field, then the page's own Escape entries); pages never bind it themselves. Datasette core owns/for its navigation search. The table pages mark the cursor row withclass:cursor+data-cursor(styled inapp.css); the trace page's cursor iscursorId, a span or group id, and the inspector follows it. metrics_math.pyandfrontend/src/lib/metricsMath.tsmust stay in sync; both test files assert the same vectors.- The metrics planning package (research, decision log, tickets) is in
plans/metrics/, untracked.