Use Datasette Lite to Catch Double-Counting in Agent-Written SQL

Use Datasette Lite to reproduce an inflated SQL report, count completed jobs at the right grain, and verify that every project appears, including zeroes.

Datasette Lite fixture with project lanes linking attempt IDs to distinct job IDs and showing zero jobs for C.Datasette Lite fixture with project lanes linking attempt IDs to distinct job IDs and showing zero jobs for C.
Illustrative task:join-check-01. Attempts 101 and 102 both belong to job-17, and project C stays visible with zero completed jobs. Based on the fixture and SQLite’s count semantics.

An agent writes a report that says project A completed two jobs. The query runs and the result looks plausible, but A completed one job that generated two attempts. Open a small synthetic fixture in Datasette Lite and you can point to the exact rows that inflated the report. You can also show how another common edit makes a project with zero jobs disappear, even when every count still on screen is correct.

This tutorial is for a developer reviewing SQL that should return one row per project. You need a modern browser with service workers enabled and an approved place to make a synthetic text file publicly readable, such as a public GitHub Gist. By the end, you’ll have a corrected query and a browser link a reviewer can open to check three expected rows, A=1, B=1 and C=0. Every result below is an illustrative expectation derived from the supplied fixture.

Simon Willison’s December 4 Datasette Advent demonstration introduces Datasette Lite, which runs the Datasette Python application in the browser using WebAssembly and Pyodide. The workflow here uses that browser runtime to reproduce a SQL result without deploying a Datasette server. Willison’s December 4 demonstration · Datasette getting-started documentation

Simon Willison’s weblog post introducing the Datasette Lite Advent demonstration.
Simon Willison’s Weblog, December 4, 2026. The post introduces the browser-based Datasette Lite demonstration. · Original source

Load the three-project fixture

  1. Copy the entire SQL block below into a file named join-check-01.sql in a public GitHub Gist. Use the raw file URL, preferably the URL for that specific revision. Open it directly and check that you see the SQL text you saved.
  2. Open Datasette Lite at lite.datasette.io in a normal browser window. Use Load SQL by URL at the bottom of the page and paste the raw URL. Keep the browser address once the file is loaded. It should contain the outer ?sql= parameter pointing to your fixture.
  3. Open the data database and confirm that it lists projects and job_attempts. Leave that database page available for the queries below.
-- task:join-check-01
CREATE TABLE projects (
  project_id TEXT NOT NULL PRIMARY KEY
);

CREATE TABLE job_attempts (
  attempt_id INTEGER PRIMARY KEY,
  project_id TEXT NOT NULL,
  job_id TEXT NOT NULL,
  job_status TEXT NOT NULL
);

INSERT INTO projects (project_id) VALUES ('A'), ('B'), ('C');

INSERT INTO job_attempts (attempt_id, project_id, job_id, job_status) VALUES
  (101, 'A', 'job-17', 'completed'),
  (102, 'A', 'job-17', 'completed'),
  (201, 'B', 'job-23', 'completed');

The file uses explicit column names in the inserts so you can check which value supplies the project, job and status in each tuple. projects.project_id identifies one project. job_attempts.attempt_id identifies one attempt. The two A rows have different attempt IDs, so each has a legitimate place in the table. The repeated job_id is the relationship the test needs. A uniqueness constraint on that column would prevent you from representing two attempts for the same job. SQLite CREATE TABLE · SQLite INSERT

For this fixture, job_status is the job’s status copied onto each of its attempts. Both rows for job-17 say completed because they describe the same completed job. In an attempt log where the status describes the individual attempt, a failed attempt followed by a successful attempt might have two different statuses. Confirm where the authoritative job status lives before applying this example to that schema. The SQL below implements the rule that a job qualifies when at least one of its rows carries the fixture’s completed job status.

Datasette Lite fetches the initialization script and uses it to initialize data.db. The database page editor is where you submit the SELECT statements in the rest of this guide. The loader takes a URL to a script. The editor takes SQL text and requires the execute-sql permission. The loader documents public raw GitHub and Gist files as an option with open cross-origin access. Use only synthetic values you intend to share, since the raw file is public and its URL travels with the reproduction. Datasette Lite README, Initializing with SQL and Special handling of GitHub URLs · Datasette custom SQL documentation

Verify both base tables before joining

  1. On the data database page, paste and run the first query. Check the three project IDs in their displayed order.
  2. Replace the SQL with the second query and run it. Check the three attempt IDs, which project owns each one, and which job ID repeats. Save this result or leave its query open if you expect to iterate on the report.
SELECT project_id
FROM projects
ORDER BY project_id
SELECT project_id, job_id, attempt_id, job_status
FROM job_attempts
ORDER BY project_id, job_id, attempt_id

Expect A, B and C in the first result. In the second, expect two rows for A with job-17 and attempt IDs 101 and 102, followed by one row for B with job-23 and attempt ID 201. All three rows carry the value completed. The absence of C in the second result is deliberate. The presence of C in the first result is your reference when evaluating the set of project IDs returned by the report.

Check the values as well as the number of rows. If A’s second attempt has the job ID job-18, the fixture would still have three attempts, but the query would legitimately count two jobs for A. If C is absent from projects, the example no longer tests whether a report keeps an unmatched project. If the SQL editor reports a missing table, reopen the clean fixture address and find the data database page before revising any query. A query opened against a different database tells you nothing about the report’s join.

The report’s grain is one output row per project_id. The counted entity within that row is one completed job, identified in this example by the pair (project_id, job_id). The base table’s grain is one row per attempt. Writing these three statements down gives you something precise to compare against the SQL. A query can group the output correctly by project_id while still counting the wrong thing inside each group. If you carry this check over to a report with human-readable labels, keep stable IDs visible while you diagnose the counts. Use Datasette Label Templates to Tell Same-Named Projects Apart

Follow job-17 through the join

  1. Run the ungrouped join below in the database editor. Read the four result rows from A through C.
  2. Run the grouped diagnostic immediately after it. For each project, compare joined_rows, matching_attempts and distinct_jobs before choosing a report expression.
SELECT p.project_id, a.job_id, a.attempt_id
FROM projects AS p
LEFT JOIN job_attempts AS a
  ON a.project_id = p.project_id
 AND a.job_status = 'completed'
ORDER BY p.project_id, a.job_id, a.attempt_id
Project Job ID Attempt ID
A job-17 101
A job-17 102
B job-23 201
C NULL NULL

These are expected SQL values. The browser may display the null cells without the literal text NULL. Read the A rows together. The LEFT JOIN matched A to each qualifying attempt, and each joined row carries the same job ID. That one-to-many expansion is join fan-out. There’s a single matching row for B, which is why B cannot expose the counting error by itself. C comes from the left side and keeps a row with null values on the right side. The PostgreSQL documentation illustrates the same outer-join semantics and the effect of moving conditions between ON and WHERE. The example queries here use SQLite. PostgreSQL table expressions, Joined Tables

SELECT
  p.project_id,
  COUNT(*) AS joined_rows,
  COUNT(a.attempt_id) AS matching_attempts,
  COUNT(DISTINCT a.job_id) AS distinct_jobs
FROM projects AS p
LEFT JOIN job_attempts AS a
  ON a.project_id = p.project_id
 AND a.job_status = 'completed'
GROUP BY p.project_id
ORDER BY p.project_id
Project joined_rows matching_attempts distinct_jobs
A 2 2 1
B 1 1 1
C 1 0 0

COUNT(*) counts all rows in the group, including the row that preserves C. COUNT(a.attempt_id) counts non-null attempt IDs, so that expression gives C zero. It still gives A two, because both A rows have an attempt ID. COUNT(a.job_id) would have the same problem on this fixture. The expression with DISTINCT counts distinct non-null job IDs within each project. Use the gap between matching attempts and distinct jobs to identify where the result depends on the choice of counted entity. SQLite built-in aggregate functions

Datasette Lite paired bars show matching attempts and distinct jobs as 2 and 1 for A, 1 and 1 for B, and 0 and 0 for C.Datasette Lite paired bars show matching attempts and distinct jobs as 2 and 1 for A, 1 and 1 for B, and 0 and 0 for C.
Illustrative task:join-check-01, December 4, 2026. Counting matching attempts overstates project A’s jobs by one. The series use SQLite COUNT and COUNT DISTINCT semantics.

If the original report gives A=2, bring both A rows into the review. They explain the discrepancy without requiring the author to infer how many duplicates were involved from a total. If the report gives C=1, inspect its count expression for COUNT(*) over the outer join. If C is absent entirely, check row selection before considering the arithmetic. An expression that ignores nulls can give zero for a group that exists. It has no group to count after the row has been removed. If a chart consumes the repaired query, check that the chart still includes project C. Verify Datasette Charts Against the SQL Behind Them

Keep project C while counting each job once

  1. Run the query with the deliberately misplaced filter below. Confirm that its two counts look right for A and B, then compare the returned project IDs against projects.
  2. Replace it with the corrected query. Read the inner result as one row per qualifying project and job pair, then check that the full query gives exactly one result row per project.
SELECT p.project_id, COUNT(DISTINCT a.job_id) AS completed_jobs
FROM projects AS p
LEFT JOIN job_attempts AS a ON a.project_id = p.project_id
WHERE a.job_status = 'completed'
GROUP BY p.project_id
ORDER BY p.project_id

As an illustrative result, A=1 and B=1. The WHERE predicate applies to the joined rows. For C, a.job_status is null and the comparison with completed does not evaluate to true. C disappears before grouping. The sum across the returned projects is still two, so an assertion that checks only the grand total would pass. Check the project IDs and the count attached to each ID as separate assertions. In a version that counts attempts and also puts the filter in WHERE, A would be inflated and C would disappear at the same time. PostgreSQL table expressions, The WHERE Clause

Datasette Lite SQL comparison showing the row for project C survive with an ON predicate and disappear with an outer WHERE predicate.Datasette Lite SQL comparison showing the row for project C survive with an ON predicate and disappear with an outer WHERE predicate.
Illustrative task:join-check-01. Keep the status test in the join or inside the right-hand subquery to preserve C. The paired clauses follow the outer-join semantics illustrated in PostgreSQL’s table expressions documentation.

SELECT p.project_id, COUNT(jobs.job_id) AS completed_jobs
FROM projects AS p
LEFT JOIN (
  SELECT project_id, job_id
  FROM job_attempts
  WHERE job_status = 'completed'
  GROUP BY project_id, job_id
) AS jobs ON jobs.project_id = p.project_id
GROUP BY p.project_id
ORDER BY p.project_id

The inner query can run on its own. Copy from its SELECT project_id, job_id through GROUP BY project_id, job_id and submit that selection as a standalone query. Expect the pairs (A, job-17) and (B, job-23) in either order. The filter selects eligible attempt rows, and grouping collapses all qualifying rows for each pair to one. Both columns belong in that grouping because the report attributes jobs to projects. A job ID reused by two projects would still produce a separate pair for each project. SQLite aggregate and SELECT syntax · PostgreSQL table expressions, GROUP BY and subqueries

In the full query, projects supplies the output population. The join can return several qualifying job rows for a project when that project actually has several jobs. It can also preserve a project with no qualifying jobs, as it does for C. The outer count uses jobs.job_id because a null from the join represents no matching job. The final grouping gives one row per project and the explicit ordering makes the output easy to compare with the expected rows.

Keep the status test inside the subquery when adapting this pattern to a report that includes every project. A project with attempts that all fail the eligibility test should also appear with zero completed jobs. The subquery returns no qualifying jobs for that project, so the outer join preserves the project in the same way it preserves C. A filter that defines which projects belong in the report answers a different question. Apply that filter to the project population and update the expected project IDs alongside it.

The diagnostic’s COUNT(DISTINCT a.job_id) with the filter in ON also gives the right counts here. The grouped subquery makes the counted entity inspectable on its own, which is useful when a reviewer needs to check which job IDs qualify. Carry that distinction forward if you add a metric to the same report. For example, counting one job while adding up the time spent on all its attempts calls for two different calculations. Resolve each metric at the level it describes before combining them. A job count that matches the answer key cannot verify an attempt-duration total.

Input Action Expected result
task:join-check-01 with A/job-17 on attempts 101 and 102, B/job-23 on attempt 201, and C without jobs Run the grouped diagnostic from Follow job-17 through the join on data. Compare matching_attempts and distinct_jobs for each project. Illustrative expectation. The two columns read 2 and 1 for A, 1 and 1 for B, and 0 and 0 for C. C has one raw joined row.
task:join-check-01 with the required project set A, B and C Run the misplaced-filter query, then run the corrected query with GROUP BY project_id, job_id inside the joined subquery. Illustrative expectation. The first result is A=1, B=1 with C absent. The corrected query returns A=1, B=1, C=0 in that order.

When reviewing a proposed patch, compare its output to the corrected result one row at a time. A must appear once with a count of one. Two rows for A, even with a count of one on each, would break the one-row-per-project contract and could inflate a later sum. Next, match B and C to their expected rows. B gives you a control case for a single matching attempt. C verifies the expected behavior when there are no attempts at all. These checks give the author specific regressions to preserve if they restructure the query again.

Share a query a reviewer can rerun

  1. Run the corrected query and copy the full address from the browser’s top-level address bar. Keep the fixture parameter before the # and the mirrored database query after it.
  2. Open that exact address in a second normal tab. Wait for the browser runtime to start, then check that it opens the query for data and gives the three expected rows. Repeat with the failing query if the reviewer needs both sides of the comparison.
  3. Put the corrected query link in the review with the fixture name and the expected rows. Keep the baseline fixture address handy so the reviewer can recover the base tables independently.

The outer URL tells Datasette Lite what to load. The # fragment reproduces the location within Datasette, including the SQL on the query page. Both parts can therefore contain sql parameters with different jobs. The outer parameter names the initialization file. The one inside the fragment holds the report query. Copying the address after running the query preserves its encoding and the database route generated by the running app. Willison describes the same URL structure when showing how to hand off browser reproductions across Datasette versions. Willison’s November 17 Datasette Lite walkthrough · Datasette custom SQL documentation

Use this note alongside the copied browser address. It specifies what the reviewer should compare, even if they open only the corrected link.

task:join-check-01 — illustrative expectations
Fixture: join-check-01.sql, three projects and three attempts.
Expected corrected rows (project_id, completed_jobs): (A, 1), (B, 1), (C, 0).
Diagnostic: A/job-17 has attempts 101 and 102. Count that job once.
Coverage check: require all three project IDs. A=1 and B=1 alone fails.

Prefer the raw URL of a fixed fixture revision so later changes to the example values don’t explain a reviewer’s different result. During review, the browser link carries enough context to rebuild the example and open the SQL. Keep it beside the specific report change being reviewed so a later reader can recover which query the fixture accompanied. The same distinction between a reproducible result and a description of what happened is useful for broader agent work. You Can’t Replay What You Can’t See

If the second tab loads the two tables and opens the database index without the report, compare its address with the one you copied after running the query. A missing fragment points to a handoff problem. Return to the original tab, run the corrected query, copy the top-level address again and check it in a fresh tab. In the review, put the SQL text beside the link if your review tool strips the fragment so the recipient can still reproduce the expected rows.

Recover the fixture before editing the report

Symptom Next action Expected observation
The raw URL opens a sign-in prompt, a rendered file page or a missing-file page Open the raw public Gist revision for join-check-01.sql, confirm the displayed SQL, then use Load SQL by URL with that address. The direct URL shows the fixture text. The data page should list both tables after successful initialization.
The SQL text opens directly, but Lite reports a fetch failure Check the origin’s cross-origin response headers or use the documented public Gist raw-file path. Reopen Lite with just that fixture. A successful fetch lets initialization proceed. Continue to the baseline SELECT checks to verify the actual contents.
The browser fails to start the runtime or requests a reload Open the original fixture address in a normal window with service worker support. A successful start opens a fresh session from the fixture URL.
The report errors but both tables appear Reopen the baseline address, run the two base queries in data, then paste the corrected SELECT into the database editor. The baseline IDs match and the corrected result is A=1, B=1, C=0.

Ordinary navigation to a raw file and a cross-origin fetch by Datasette Lite have different requirements. If you can open the file directly but the app cannot fetch it, check the host’s CORS behavior before changing the SQL. To isolate the app from your file, the README’s Initializing with SQL section supplies a public demo.sql link and a matching Lite URL. If that example loads and yours fails, compare the source URLs and file contents. If both fail during startup, check service worker support and retry in a normal browser window. Datasette Lite README

For a clean reset, reopen the saved fixture address in a new tab. If you saved it from a query page, remove the # and everything after it while retaining the outer fixture parameter. Each tab has its own session, and reopening the fixture reconstructs its tables from the file. You can close an experimental tab after saving any SQL you want to keep. If a setup change broke the fixture itself, return to the raw URL for the original revision, then rerun both base queries. The report’s SELECT statements require no reverse SQL. Datasette Lite README, How this works

Apply the result to the review at the scope you reproduced. Ask the report author to identify the key of the counted entity and where eligibility is determined. In this example, cite A’s attempts 101 and 102 for the counting issue and identify C explicitly for the coverage issue. If the original report has a richer schema, check that its job identity and status rules agree before transferring the repair. For investigations that start with loading a larger source file, verify ingestion before interpreting report discrepancies. If a follow-up needs the original schema’s constraints, use a synthetic fixture in a copy of that schema. Datasette CSV Import · Set Up a Neon Schema-Only Branch With Synthetic Test Data

Sources

Many assistants.
One place to remember.

Bring your AI sessions, context, and usage together with Automater.

Meet Automater