A support queue chart can look right while counting the wrong tickets. Build a Datasette chart type plugin with four tickets whose counts you can predict, then check the rows returned by the server and the bars drawn by the browser. The open query should draw billing at 2 followed by shipping at 1. Changing the query parameter to closed should leave one shipping bar at 1. The second case catches a compiler that always counts open tickets, even if the first chart looks right.
You’ll write an installable Python package, a JavaScript renderer, a seed file, a chart spec and an HTTP test. Work in a disposable Python environment with a compatible Datasette checkout installed and a browser on the same machine. The example pins Datasette Charts 0.4a0, whose package metadata requires Python 3.11 or later and Datasette 1.0a44 or later. Simon Willison published the prerelease on November 27, 2026, with the chart type authoring reference and shared renderer helpers. The reference describes the extension interface as unstable. Keep the pin for the exercise and use the same fixture to check the extension when you change versions. 0.4a0 release · Tagged package metadata · Chart type authoring reference
Seed four tickets with different filter outcomes
- Create an empty working directory and save the following SQL as
seed.sqlat its root. - Run the fixture creation command from that directory. Keep the filename
queue.dbbecause the browser URLs and endpoint tests usequeueas the database name. - Use this database for the browser exercise. The test will load the same seed into a fresh temporary file for each case.
CREATE TABLE tickets (
id INTEGER PRIMARY KEY,
queue TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('open', 'closed'))
);
INSERT INTO tickets (id, queue, status) VALUES
(101, 'billing', 'open'),
(102, 'billing', 'open'),
(103, 'shipping', 'open'),
(104, 'shipping', 'closed');
python -c "import sqlite3; from pathlib import Path; db = sqlite3.connect('queue.db'); db.executescript(Path('seed.sql').read_text(encoding='utf-8')); db.commit(); db.close()"
There is one row per ticket. Billing has two separate open tickets, so the exercise can distinguish counting rows from counting distinct queue names. Shipping has one ticket in each status. A compiler that reads all four tickets would show shipping at 2, and a compiler that always reads the open tickets would show shipping at 1 alongside billing in the closed case. Those bugs leave different numerical signatures. The entire fixture is small enough to check by reading the inserts, even if the chart endpoint is unavailable.
Use the following source query for both cases. It projects queue, the category you want to group. The status column selects the tickets that count. In Datasette’s custom SQL editor, :ticket_status creates a parameter field that accepts the fixture’s text values. Use a local instance where the browser actor has execute-sql for this database. A chart on the tickets table page can work with view-table, while the custom SQL chart requires execute-sql. Datasette named SQL parameters · Tagged Charts HTTP API and permissions
SELECT queue FROM tickets WHERE status = :ticket_status
With open, the raw query should return two billing rows and one shipping row. With closed, it should return one shipping row. The raw query has no ORDER BY, so check membership and multiplicity here. The compiler will set the order of the grouped result. If the seed command reports that tickets already exists, move aside the disposable file you created or start in a fresh directory and rerun the command. When a browser result looks surprising, open /queue/tickets without filters and confirm the four IDs. That check tells you whether you loaded the intended database before you inspect the chart code.
Package the Python chart type
- Save
pyproject.tomlbesideseed.sqland createdatasette_queue_counts/__init__.pywith the chart class below. - Create
datasette_queue_counts/static/for the renderer. The directory belongs inside the Python package so the distribution can include the JavaScript file. - Use
datasette-queue-countsto identify the installed distribution,datasette_queue_countsfor the Python module andqueue_countsas the chart type in a spec. The entry point key and the chart type share a spelling in this example. They serve separate registration interfaces.
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "datasette-queue-counts"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["datasette-charts==0.4a0"]
[project.entry-points.datasette]
queue_counts = "datasette_queue_counts"
[tool.setuptools.packages.find]
include = ["datasette_queue_counts*"]
[tool.setuptools.package-data]
datasette_queue_counts = ["static/queue-counts.js"]
The datasette entry point tells Datasette which module to load. The setuptools package-data entry puts the JavaScript alongside that module’s Python files in the installed package. Keep the filename in the package-data entry, the static directory and js_url aligned. A regular install exercises the installed distribution and can reveal a missing static asset that still exists in your working tree. Tagged packaging example · Datasette plugin packaging and static assets
from datasette import hookimpl
from datasette_charts import SOURCE_CTE, Channel, ChartType, CompiledQuery
LIMIT = 20
def quote_identifier(name):
return '"' + name.replace('"', '""') + '"'
class QueueCounts(ChartType):
name = "queue_counts"
label = "Queue counts"
description = "Ticket counts for the categories present in the selected source"
js_url = "/-/static-plugins/datasette-queue-counts/queue-counts.js"
channels = [
Channel(name="x", label="Queue", roles=("category",)),
]
max_rows = LIMIT
def compile(self, spec, source, profile):
queue = quote_identifier(spec["encoding"]["x"]["column"])
return CompiledQuery(
sql=f"""
{source.with_clause()}
SELECT {queue} AS key, count(*) AS value
FROM {SOURCE_CTE}
WHERE {queue} IS NOT NULL
GROUP BY 1
ORDER BY 2 DESC, 1 ASC
LIMIT :chart_queue_limit
""",
params={**(source.params or {}), "chart_queue_limit": LIMIT},
max_rows=LIMIT,
meta={"y": "Tickets"},
)
def title(self, spec):
return "Tickets by " + spec["encoding"]["x"]["column"]
@hookimpl
def register_chart_types(datasette):
return [QueueCounts]
The hook returns the chart class. Queue counts is the label in the builder. The single required channel selects the group column, and the fixed count(*) aggregate removes the need for a measure control. The channel’s category role affects where choices appear in the builder. A small input, especially the closed query with just one row, can make queue look constant to the profiler. Look under Other columns if it is absent from the preferred group. The class inherits the default propose() behaviour, which leaves automatic suggestions to other chart types. Choose this type explicitly through Build a chart. ChartType and Channel reference
source.with_clause() defines the rows requested by the page or API, and SOURCE_CTE names that result. Reading it lets the same compiler receive a different set of tickets when ticket_status changes. Keep the status predicate in the source query and preserve source.params so SQLite receives the binding for :ticket_status. The chart adds chart_queue_limit for its own limit. If you adapt the source query, give its parameters distinct names so they survive the merge into CompiledQuery.params.
Quote the validated column name as a SQLite identifier. The helper wraps it in double quotes and doubles embedded double quotes. SQLite receives the status and limit as named values, while the validated column name becomes part of the statement. The output aliases key and value give the renderer the same field names whichever category column you select. Filtering null keys keeps missing categories out of the chart. In this fixture queue already requires a value, so that predicate leaves both expected results intact. Rules for chart SQL
Grouping by the first result column makes one row per queue. Sorting by the second column descending puts larger counts first, and sorting by the key ascending settles ties. For the open case, billing leads because two exceeds one. On the unfiltered table both counts would be two and billing would lead by the tie rule. The SQL limit and max_rows both use 20. If you reuse this pattern with more than 20 categories, the heading and surrounding prose should tell readers they are seeing a ranking limited to 20 groups. The limit bounds the result sent to the renderer. SQLite can still need to read many source rows to compute the counts within Datasette’s query time limits. Chart SQL limits

Draw the returned rows and install the package
- Save the renderer as
datasette_queue_counts/static/queue-counts.js. - Save the JSON below as
spec.jsonat the project root. The test will use this file for every request. - Install the package in the active environment and run
datasette plugins. Look for bothdatasette-queue-countsanddatasette-charts. This verifies that the process can discover the packages. The registry and browser checks establish whether the type and static module are usable.
export function render(el, ctx) {
const { Plot, helpers, theme, data } = ctx;
const { basePlot, isThumbnail, mount, fmt, TIP } = helpers;
const thumbnail = isThumbnail(ctx);
const plot = Plot.plot(basePlot(ctx, {
...(thumbnail ? {} : { marginLeft: 68 }),
x: { domain: data.map((row) => row.key), label: null },
y: { label: ctx.meta.y, grid: !thumbnail, nice: true },
marks: [Plot.barY(data, {
x: "key",
y: "value",
fill: theme.series[0],
...(thumbnail ? {} : {
title: (row) => `${row.key}\n${fmt(row.value)}`,
tip: TIP,
}),
})],
}));
mount(el, ctx, plot);
}
{
"v": 1,
"type": "queue_counts",
"encoding": {"x": {"column": "queue"}}
}
python -m pip install . pytest pytest-asyncio
datasette plugins
ctx.data gives the renderer objects keyed by the returned column names. The open case starts with an object whose key is billing and whose value is 2. The domain takes keys in response order so the vertical bars read left to right in the order returned by SQL. Plot.barY takes each height from value. The Tickets label comes from CompiledQuery.meta. This is the interface between the two files. If you rename a SQL alias, update the renderer’s mapping and the expected endpoint columns together. Renderer reference
basePlot supplies the initial size and styling. The theme’s first series colour fills both bars, and mount places the plot into the supplied element. The thumbnail configuration uses the helper’s compact margins and omits tooltips. The full-size configuration uses fmt in each tooltip and takes tooltip options from TIP. These helpers are available directly on ctx.helpers. The renderer receives its data from Charts and performs no separate fetch or count. That makes the HTTP response a useful checkpoint when the drawing disagrees with the fixture. Shared helper implementation · Chart type authoring reference
Test both filters at data.json
- Save the following as
test_queue_counts.pybesidespec.jsonandseed.sql. - Run the pytest command from the project root in the environment that received the package.
- If an assertion fails, read the failed case’s status parameter and response before editing the compiler or renderer.
import json
import sqlite3
from contextlib import closing
from pathlib import Path
from urllib.parse import urlencode
import pytest
from datasette.app import Datasette
ROOT = Path(__file__).resolve().parent
SPEC = json.loads((ROOT / "spec.json").read_text(encoding="utf-8"))
SOURCE_SQL = "SELECT queue FROM tickets WHERE status = :ticket_status"
@pytest.fixture
def datasette(tmp_path):
path = tmp_path / "queue.db"
with closing(sqlite3.connect(path)) as db:
db.executescript((ROOT / "seed.sql").read_text(encoding="utf-8"))
db.commit()
return Datasette([str(path)])
@pytest.mark.asyncio
async def test_package_is_loaded(datasette):
response = await datasette.client.get("/-/plugins.json")
assert response.status_code == 200, response.text
assert "datasette-queue-counts" in {p["name"] for p in response.json()}
@pytest.mark.asyncio
@pytest.mark.parametrize(
"status, expected_rows",
[
("open", [["billing", 2], ["shipping", 1]]),
("closed", [["shipping", 1]]),
],
)
async def test_chart_rows(datasette, status, expected_rows):
source = {
"kind": "query",
"sql": SOURCE_SQL,
"params": {"ticket_status": status},
}
params = urlencode({"source": json.dumps(source), "spec": json.dumps(SPEC)})
response = await datasette.client.get(f"/queue/-/charts/data.json?{params}")
assert response.status_code == 200, response.text
payload = response.json()
assert payload["ok"], payload
assert payload["columns"] == ["key", "value"], payload
assert payload["rows"] == expected_rows, payload
python -m pytest -q test_queue_counts.py
Each request sends the same spec and SQL. The only input that changes between the data requests is params.ticket_status. Encode both JSON arguments in the query string so the route receives a source and a spec separately. The tagged README documents this query source shape. The authoring guide demonstrates using the Datasette test client against the same data endpoint used by the chart panel. Tagged HTTP API · Authoring guide’s endpoint test
The following are illustrative expected observations for task:queue-chart-01, calculated from the seed. A successful pytest run should report three passing cases, including package discovery and both endpoint requests. The response text on an HTTP failure and the parsed payload on a chart assertion failure help you distinguish a request error from a successful request with incorrect results.
| Input | Action | Expected result |
|---|---|---|
task:queue-chart-01 with ticket_status=open, chart type queue_counts, and category column queue |
Run python -m pytest -q test_queue_counts.py and check the parameterized open case against /queue/-/charts/data.json. |
Columns are key, value. Ordered rows are [["billing", 2], ["shipping", 1]]. |
task:queue-chart-01 with ticket_status=closed and the identical chart specification |
Run python -m pytest -q test_queue_counts.py and check the parameterized closed case. |
The only row is [["shipping", 1]]. Billing is absent because there are no closed billing tickets. |
task:queue-chart-01 with the browser’s custom SQL query set to ticket_status=open |
Submit the query, select Build a chart, choose Queue counts, set Queue to queue and hover over the bars. |
Billing appears first with a tooltip count of 2, followed by shipping with a count of 1. |
task:queue-chart-01 with the same browser chart spec and ticket_status=closed |
Submit the query with closed, select the same chart type and column if needed, and hover over the remaining bar. |
Only shipping appears. Its tooltip says 1. |
Comparing the ordered array catches a sort regression even when both totals are correct. Checking every row catches a change that leaves billing at 2 and adds the closed shipping ticket to the open result. Checking the column names catches changes that leave the array intact but change the object keys the JavaScript receives. For a chart someone else already configured, use an independent query to calculate the expected values. In this exercise the four inserts supply the expected values directly. Verify Datasette Charts Against the SQL Behind Them
Match the browser bars to the tested rows
- Start Datasette with the command below, open
http://127.0.0.1:8001/queueand run the source query from the seed section. Submitopenin theticket_statusfield. - In the query’s chart panel, select Build a chart, choose Queue counts and set Queue to
queue. Look under Other columns if necessary. - Hover over the full-size bars. Expect billing on the left at 2 and shipping on the right at 1. In the browser’s Network panel, inspect the chart’s
data.jsonresponse forkey,valueand the two ordered rows. - Change
ticket_statustoclosed, submit the source query and select the same chart type and column if needed. Expect a single shipping bar with a tooltip value of 1. Read the tooltip because the numeric axis can rescale when the largest value changes.
datasette queue.db
Start with the raw query results before examining the chart network response. If the open SQL page shows two shipping rows, inspect the submitted SQL and parameter. If the page shows one shipping row but the chart response says shipping has a count of two, inspect the source passed to the chart. A response captured from the unfiltered table page can be internally correct and still answer a different question. Keep the browser on the SQL query page for both filter checks. SQL editor and named parameters · Chart builder and query page support
The HTTP test reaches the server and ends with its response. The browser check adds the installed JavaScript file, dynamic import and visual mapping. If you’re handing a plugin change to a coding assistant, give it both expected arrays and ask it to record the command result and the browser observations with their filter values. An image of two bars can corroborate the open case. The closed case and its corresponding endpoint response establish that changing the filter changed what the chart counted. Proof for a task’s finish line · Spec-driven development
When a teammate runs the example from another workspace, have them record which environment ran pytest and which process served the browser page. They can compare the installed plugin listings first if their HTTP tests pass but the browser lacks Queue counts. A result from one process gives you a starting point for diagnosing the other. AgentOps · Python environment and pytest setup
Diagnose the first failing boundary
| Observation | Check next | Recovery |
|---|---|---|
datasette-queue-counts is absent from /-/plugins.json. |
Inspect the active environment and the datasette entry point. |
Install the package alongside Datasette and restart the server. |
The package is listed but queue_counts is absent from /-/charts/types.json. |
Check that the hook returns QueueCounts and that the chart type name is unique. |
Correct registration, reinstall and inspect the registry again after restart. |
| Both statuses return billing 2 and shipping 2. | Read the request’s source and inspect the compiler’s FROM. |
Restore source.with_clause() and FROM {SOURCE_CTE} if the compiler reads the full fixture table. |
| The closed case returns the same two rows as the open case. | Confirm ticket_status=closed in the request and look for a fixed open predicate. |
Pass source parameters through and let the supplied query determine the status. |
| Both JSON responses match their expected rows, while the browser shows wrong marks or goes blank. | Inspect the renderer request and the first browser console error. | For load errors, correct the packaged path or module export. For mapping errors, compare Plot.barY with the actual key and value fields. |
In the diagram, Rows match means each case matches its own expected rows. The open and closed responses should differ. Start at the chart registry when the type is missing from the builder. The plugin list establishes that Datasette loaded the distribution, while /-/charts/types.json establishes that Charts registered the type. If the package is missing and you inherited an environment from another project, check whether DATASETTE_LOAD_PLUGINS restricts loading. Plugin discovery and loading controls · Chart type registry
If the query request fails, confirm the database, execute-sql permission, queue projection and status spelling in the editor first. If the source shows shipping but the chart route reports a missing binding, inspect the compiled parameter dictionary for ticket_status. A query for an unmatched status legitimately returns zero rows. The closed case in this fixture should return shipping because ticket 104 meets the predicate. That gives you a specific row to trace through the source before you change the group or count. Named parameters · Source parameters
If the endpoint returns the expected rows, open the module path advertised by the registered chart type. Expect JavaScript beginning with export function render. An error page at that path points to the static URL, the packaged files or the environment used by the running server. If the file loads but the console reports a missing helper, check the installed Charts version and the member name in the reference. After editing the regular install, reinstall with python -m pip install .. Restart for Python changes and reload the browser to request the JavaScript. Verify the original failing case first and then switch the filter to confirm the repair works for both inputs. Static assets · Renderer loading
Uninstall the example and draw a built-in chart
- Stop the local Datasette process. Run the uninstall command in the example environment and confirm removal of
datasette-queue-countsat the prompt. - Restart Datasette with
queue.dband reload/-/charts/types.json. Expect the customqueue_countsentry to disappear and the built-inbarentry to remain. - Open
http://127.0.0.1:8001/queue/ticketswithout filters or an old chart fragment. Select the built-in Bar chart, choosequeueas the category and count rows. Expect billing and shipping at 2 each, since this page includes both shipping tickets.
datasette uninstall datasette-queue-counts
datasette queue.db
The uninstall command runs in Datasette’s Python environment. Removing the custom distribution leaves its Charts dependency available for the final comparison. Keep the same database to hold the data constant while changing the installed plugin set. If the built-in chart disappears, run datasette plugins from the shell that started the new process and check that datasette-charts is still loaded. A fresh table URL also avoids a fragment that asks Charts to load the removed type. If you want to reproduce the exercise, keep the seed, package files, spec and test together. Reinstall the package, restart, and use the original open and closed expectations. Datasette plugin uninstall · Tagged built-in chart and URL behaviour
Sources
- Datasette Charts 0.4a0 release
- Writing chart type plugins
- Datasette Charts 0.4a0 package metadata
- Datasette Charts 0.4a0 README
- Datasette plugin packaging and static assets
- Datasette plugin installation and loading
- Datasette SQL editor and parameters
- Datasette Charts shared renderer helper implementation

