Code protections
SQL is parsed as one SELECT-only Snowflake statement, checked against a table allowlist, given a LIMIT, and run with a statement timeout. User text is never interpolated into SQL.
Ask about US population, income, or housing from the 2020 ACS 5-year estimates.
One chat turn, from the message you type to the answer and its saved evidence.
Its instructions, the conversation, three tool definitions, and this turn's tool results.
No census variable ids in the prompt. No database connection.
Post one message, read a stream of events
app.py::chat Replay earlier turns from local SQLite
sessions.py::get_session In scope or not. Allows the turn on its own errors
guardrail.py::classify_input Pick a tool, read the result, repeat, then write the answer
agent.py::agent_turn Search local variable labels
tools.py::search_census_variables Rank local geography records
tools.py::resolve_geography The only request-time path to Snowflake
tools.py::run_census_sql Labels and place ids, no answer values
snapshot.py::build_snapshot One SELECT, approved tables only, LIMIT added
sqlgate.py::validate_sql 2020 ACS tables, run with a statement timeout
snowflake_conn.py::connect Stream the reply, then offer checked follow-up questions
follow_ups.py::questions Save the turn's steps for the Evidence tab
tracing.py::record_turn_trace The model chooses tools and writes SQL. Code decides whether that SQL runs: every query crosses the SQL gate, and nothing else reaches Snowflake while a question is being answered. All files are under src/, and both models are pinned in model_config.py.
| File | Role | Responsibility |
|---|---|---|
app.py | HTTP and streaming layer | chat accepts one message for a session and returns a stream of events. _stream_turn forwards each event from the agent and guarantees the stream ends in done or error, even if the agent raises. |
sessions.py | Conversation memory | get_session replays the session's full history from local SQLite, and append_message adds each user and assistant message to it. |
guardrail.py | Scope classifier, a soft layer | classify_input sends the message and the two most recent messages to the guardrail model and returns allow or refuse. On a timeout or any error of its own it allows the turn. |
agent.py | The tool loop | agent_turn runs one turn: history, a check that the census data is available, guardrail, then the agent model calling tools until it can answer. It stops with an honest failure after two failed or empty queries, ends tool use at the 50 second watchdog or after eight tool rounds, and records the trace. |
tools.py | The three tools | search_census_variables and resolve_geography read only the local snapshot. run_census_sql passes the SQL through the gate, runs the sanitized query, and normalizes directly selected census values as described under Verified normalization. |
snapshot.py | Local discovery data | build_snapshot builds the SQLite file of variable labels and geography records from Snowflake metadata on first start, then reuses it. |
sqlgate.py | The trust boundary | validate_sql parses the SQL as Snowflake dialect and accepts only a single SELECT over allowlisted tables, with a row LIMIT added when one is missing and lowered when it is above the cap. Anything else is rejected before it reaches Snowflake. |
health.py | Startup health | check_snowflake_reachability probes Snowflake once at startup. is_degraded reads that result on each turn, so an app that started without its data says so instead of guessing. |
snowflake_conn.py | Database connection | connect opens the key-pair connection that the query tool and the snapshot build use. |
follow_ups.py | Suggested next questions | questions returns up to three follow-up questions derived in code from what the finished turn queried. It makes no model call. |
tracing.py | Turn record | record_turn_trace saves the turn's guardrail, model and tool steps to SQLite, and get_traces reads them back for the Evidence tab. |
model_config.py | Model pins | AGENT_MODEL and CLASSIFIER_MODEL are the only place a model id is named. |
Two support files are left out: contracts.py holds the shared types and limits, and us_states.py maps state names to abbreviations.
One chat turn in the order the code runs it. Each step names the functions involved, so you can follow it in the table above and in the Evidence tab.
The Chat tab posts your message and your session id to /api/chat, where chat in app.py receives it. The reply is not one block of JSON but a stream of small events, which is how the page can show progress such as "Request check" and the tool steps, and then the answer as it is being written. _stream_turn sits between the browser and the agent: it forwards every event and guarantees the stream ends with a done or an error event, even if something inside the agent raises, so the page is never left waiting on a reply that will not come.
agent_turn in agent.py runs the rest of the turn. It first calls get_session, which reads every earlier message in this session from a local SQLite file, and gives that history to the model, so a follow-up such as "What about households?" is understood as a question about the place you asked about before. Your new message is stored with append_message before anything else happens, which means it stays in the history even if the turn later fails.
Before spending a model call, is_degraded from health.py decides whether the app can answer at all. It reports a problem only when the local snapshot file is missing and Snowflake could not be reached when the app started. The first fact is a file check and the second was recorded at startup by check_snowflake_reachability, so this step makes no network call. If the data is unavailable, the turn ends here with a fixed message that says so, rather than an answer the app cannot back up.
classify_input sends your message, together with the two most recent messages for context, to the guardrail model with a fixed classification prompt. The model returns a verdict such as on topic, off topic, adversarial or inappropriate, and an off-topic or unsafe verdict ends the turn with a short, polite refusal. This check is deliberately a soft layer: if the guardrail model takes longer than 1.5 seconds or fails, the question is allowed through, because blocking a legitimate question is worse than relying on the SQL gate further down to stop anything harmful.
The agent model receives its instructions, the whole conversation, and the definitions of exactly three tools. Each call to the model is one round, in which it either asks for one or more tools or finishes with the answer, and any text it writes in any round streams to your screen as it arrives and becomes part of the reply. The loop allows at most eight rounds and checks the 50 second watchdog before starting each one. The model has no database connection and no list of census variables in its prompt, so everything it learns about the data comes back from the tools in the next steps.
To turn a phrase such as "median household income" into a census variable, the model calls search_census_variables. It runs a full-text search over the variable labels, universes and field descriptions in the local snapshot, ranked by relevance, first requiring every word to match and only if that finds nothing accepting any of the words. Each hit carries the variable id, its label, and the exact Snowflake table that holds it, so the model never has to guess a table name. This step reads only the local SQLite file and opens no Snowflake connection.
resolve_geography looks up a place name such as "Travis County, Texas" in the local geography index and returns every matching state or county with its identifier. When a name matches more than one place, as "Washington County" does, the result is marked ambiguous. If the model then tries to run a query anyway, the loop blocks it and ends the turn with a clarifying question that lists the candidates, because quietly picking one would produce a confident answer about the wrong place.
With a variable, its table and a place, the model writes a SQL query and calls run_census_sql. Before anything reaches Snowflake, validate_sql parses the text as Snowflake SQL and accepts it only if it is a single SELECT statement that reads allowlisted tables and uses none of the banned constructs, such as writes or session commands. It adds a row LIMIT when one is missing and lowers any limit above the cap of 200 rows. A rejected query never runs, and the reason goes back to the model as a tool error. This is the trust boundary: the earlier steps guide the model, while this one decides what may run.
Only the sanitized SQL that came out of the gate is executed. run_census_sql opens a connection through connect in snowflake_conn.py, which signs in with a key pair, and sets a 25 second statement timeout on the session so that Snowflake itself cancels a runaway query. The returned rows are cleaned before the model sees them: a missing value in a directly selected census column becomes "not reported", and a known top code becomes a bounded value such as "$250,000 or more", as described under Verified normalization below.
The query result, or the error, goes back to the model as the tool's answer, and the next round begins. A query that was rejected, failed in Snowflake or returned zero rows counts as a recovery attempt, and the model gets a chance to search again or rewrite its SQL. After two failed or empty queries the loop stops, and the turn ends with a message explaining what was tried instead of a number. The watchdog works the same way: once 50 seconds have passed, no new round starts, and the turn ends with a partial answer built by code from the rows already collected. If the model is still asking for tools after eight rounds, the reply ends with a note that the turn reached its tool-call limit.
When the model stops asking for tools, the turn's reply is everything it wrote across the rounds, and it has already streamed to your screen. The model is instructed to take every number from the rows returned in this turn, but no code checks the final answer against those rows. The Evidence tab helps you spot-check it: for each query it keeps the start of the SQL, the row count, the column names and the first row, though not every row. The answer is then saved to the conversation with append_message. If the model finishes without writing any text, the turn ends with an error rather than a blank reply.
If the turn finished normally and no place was left ambiguous, questions in follow_ups.py looks at what this turn actually queried and may offer up to three next questions. Today it only does so in one narrow case, a clean comparison of exactly two counties, where it can suggest questions such as comparing renter share, so most answers come with no suggestions. These are chosen by code from the turn's own results, not by a model, and they appear as buttons that fill the input box without sending, so you can edit a question before asking it. If this step fails for any reason, the answer you already have is unaffected.
Along the way the turn recorded spans with their timing: the data check, the guardrail verdict, each model call with its token counts, and each tool call with a summary of its result. record_turn_trace writes those spans to a SQLite trace store, and get_traces reads them back for the Evidence tab, which is why you can inspect an earlier turn even after the app restarts. The stream then ends with a done event, carrying any follow-up questions, and that event is what tells the page the turn is over.
SQL is parsed as one SELECT-only Snowflake statement, checked against a table allowlist, given a LIMIT, and run with a statement timeout. User text is never interpolated into SQL.
The model is instructed to ground answer numbers in this turn's query results. The serving path does not independently validate every final answer number.
Six stable scenarios are regression and eight broader scenarios are capability. Each result is pass, fail, or inconclusive.
| Query value | Answer-facing value |
|---|---|
| SQL NULL in a directly selected or simply aliased demographic variable | not reported |
| A directly selected or simply aliased known top code | A bounded value, such as “$250,000 or more.” |
| Derived or aggregate projection | Returned unchanged. Derived and aggregate projections are not normalized. |
No numeric suppression codes were observed or transformed.
The allowed Snowflake tables come from SafeGraph's Open Census Data share and repackage US Census Bureau data. This app is pinned to the 2020 vintage, the ACS 2016-2020 5-year estimates, at census-block-group grain. State and county counts are computed by aggregating block groups. The local discovery snapshot contains labels and geography identifiers, not answer values.
Inspected 2026-10-15. The file and function names above, and the limits the steps quote, are checked against the code by tests/test_system_flow.py; the descriptions were checked by reading the code on that date. Opening this tab makes no model call and no database query.
Each stored turn is replayed in order from guardrail and model spans through tool calls and terminal timing. Expand Raw trace JSON only when the curated steps are not enough.
No turns recorded for this session yet.
Loading…
Why Census Chat works this way: the problem behind each decision, an example to remember it by, and what we gained or gave up. These are lessons from this build, not rules that every app must follow. Select a title to open it.
In your app: agent_turn (src/agent.py) asks the model for tool calls. The model sends SQL to run_census_sql (src/tools.py), which calls validate_sql (src/sqlgate.py) before executing the accepted query in Snowflake.
The problem: Snowflake needs precise SQL instructions. The model can understand a question about employment and still write a query with the wrong quotation marks or an invented table name.
| Design | Strength | Cost |
|---|---|---|
| LLM writes SQL, code validates it | The model writes the whole query, so it can combine data in ways we did not build a specific template for. | Code must check its work. A query can be rejected and need another attempt before the user gets an answer. |
| LLM selects options, code builds SQL | The model picks a metric, location, and supported calculation. Tested code assembles the query with the correct syntax and verified table names. | We must build each supported calculation. A request outside that menu needs more implementation. |
Example: for an employment total in Texas, the model could write the entire SQL statement, or select “employment count + Texas + total” and let code write it. The second path removes syntax choices, but the model could still select the wrong employment measure.
Remember: writing freely gives flexibility; choosing from a tested menu gives predictability. Today the model writes SQL and code validates it. The menu approach is an option to evaluate, not a shipped feature.
In your app: validate_sql checks query structure and ALLOWED_TABLES. Separately, agent_turn blocks SQL when resolve_geography reports unresolved ambiguity. Multiple matches for “Washington County” trigger clarification instead of a silent choice.
The problem: a prompt saying “only read approved tables” is an instruction the model can get wrong. We need the app to stop a forbidden query even when the model tries it.
Our choice: code checks SQL before Snowflake sees it and rejects queries that violate the rules. For example, an instruction to delete records is blocked even if the model generated it. Code also controls retry limits and time budgets.
Remember: the prompt explains the rules; code controls what can happen. The cost is writing and maintaining those checks, and sometimes rejecting a query the checker cannot safely understand.
Decision record: D-007, D-010, D-013, D-014. The gate checks query structure; passing it does not prove the answer is statistically correct. Row limits, explicit columns, and execution timeouts bound different resources.
In your app: search_census_variables answers “which measure?”; resolve_geography answers “which place?” Both live in src/tools.py and read the local SQLite snapshot prepared by build_snapshot (src/snapshot.py). For rented homes in Travis County, the first finds the renter measure and the second finds the county’s geographic code. Neither retrieves the final count: that is run_census_sql’s job.
The problem: Census has thousands of measures. Putting a handful of familiar ones in the prompt would make population demos easy, but could miss a less expected question about housing or commuting.
Our choice: the model searches a local copy of the catalog when a question arrives. For “How many homes are rented?”, it looks up available measures before choosing what to query.
Remember: give the model a searchable catalog, not just a cheat sheet. This expands discovery, but introduces search errors and a local catalog that must be kept current.
Architecture §2-4: local SQLite lookups keep discovery fast and avoid warehouse calls. The trade-off is maintaining a snapshot that must be rebuilt when the catalog changes.
In your app: agent_turn (src/agent.py) returns tool errors to the model and tracks recovery_attempts and recovery_log. The Evidence tab exposes failed and successful tool calls so you can inspect the repair sequence.
What happened: the model generated incorrectly quoted column names, received a database error, and sometimes fixed the query on retry. The user got an answer, making the system look healthier than its first attempt really was.
The trade-off: recovery saves a conversation, but costs extra time and model calls. If we only count final success, we can miss the same avoidable mistake happening repeatedly.
Remember: “worked immediately,” “worked after repair,” and “failed” are different outcomes. Track them separately so recovery does not become an excuse to leave the original bug unfixed.
Source: Reflection §4, the quoted-identifier incident. This is a measurement lesson, not a claim that every metric is already implemented.
In your app: tests/test_sqlgate.py checks validate_sql offline; tests/test_agent.py checks loop controls with simulated responses. evals/scenarios.py defines live cases, and evals/run_evals.py runs and scores them through the real agent_turn.
Offline example: give the SQL validator a saved DELETE statement or a query against a disallowed table. Check that it rejects the query before contacting Snowflake. This is fast, repeatable, and needs no paid model call.
Live example: ask the original employment question again using the real model and Snowflake. Check whether it picks the right data and returns the expected answer. Its newly generated query can differ on each run.
Remember: offline tests check predictable code behavior; live evals check whether the full app delivers. Live runs cost more and can vary, while offline tests cannot prove that the real model and database work together.
Reflection §4: calibrate graders against known-correct and deliberately wrong answers. A failing score can reveal a broken grader; a passing score only supports what the checks actually measure.
In your app: ALLOWED_TABLES (src/contracts.py) enforces the permitted vintage through validate_sql. In src/tools.py, resolve_geography searches available places and _geo_levels_for marks median measures as valid only at block-group level. That metadata informs the model; it is not itself a SQL-level ban on averaging medians.
Example: a user asks about Austin, but our source does not include city boundaries. Returning Travis County's population as Austin's population would sound convincing and still answer the wrong question.
Our choice: explain missing coverage and make any substitute explicit. We also restrict queries to the 2020 ACS release. For income, averaging neighborhood medians does not produce the county median, so that shortcut is not a valid substitute.
Remember: fewer supported questions is an accepted cost of being honest about the data. Expanding coverage requires the right data and calculations, not just a more confident prompt.
Decision record: D-002, D-003, D-005, D-009. A county substitute or a mean instead of a median must be explained. The single-vintage restriction avoids boundary and overlapping-window complications; it is not a claim that every comparison across years is invalid.
In your app: search_census_variables uses SQLite FTS5 keyword search and BM25 ranking. Its helper _fts_match_query builds the strict AND search, then an OR search if no rows match. _should_index_variable (src/snapshot.py) excludes margin-of-error and allocation fields when building the index.
What happened: searches like “number of households” returned nothing because all words had to appear together in a Census label. The household data existed, but the wording did not match.
Our choice: try the strict search first. If it finds nothing, try matching any of the words. Local keyword search keeps the setup simple, without a separate service for matching by meaning.
Remember: broader search finds more possibilities but also more distractions. “Number of households” can surface “number of rooms,” so the model must still check what a result means. We also exclude margins of error from normal search to reduce misleading matches.
Decision record: D-008, D-020. Search relevance still needs evaluation; finding a variable does not establish that it is the right one.
In your app: classify_input (src/guardrail.py) calls the classifier and allows requests on errors or timeouts. _ALLOW_VERDICTS includes unknown_subject. Later, run_census_sql raises SqlRejected if validate_sql rejects the query, before opening a Snowflake connection.
The problem: a small model first checks whether a question belongs in Census Chat. If that check times out while someone asks a legitimate population question, refusing everything would make a helper component take down the experience.
Our choice: let the question continue when the topic check fails. The SQL gate still runs and blocks queries that fail validation. A question about an unknown place also gets a chance to reach data discovery.
Remember: losing the topic checker may waste an extra model call; losing SQL validation must stop execution. The two checks have different consequences, so their failure behavior is different.
Reflection §1; decision record D-019. The classifier helps route requests efficiently; it is not the SQL security boundary.
In your app: agent_turn counts failed or empty SQL results against MAX_RECOVERY_RETRIES, limits rounds with _MAX_TOOL_LOOP_ITERATIONS, and checks elapsed time before further work. Separately, run_census_sql sets Snowflake’s STATEMENT_TIMEOUT_IN_SECONDS to limit query execution.
Example: the model cannot find household data, searches again, rewrites the query, and searches again. Without limits, one question can keep consuming time and paid calls without making progress.
Our choice: cap recovery attempts and tool rounds, and stop further tool use when the time budget is exhausted. Explain the failure instead of endlessly retrying.
Remember: more attempts can rescue difficult questions, but also make failures slower and more expensive. Fix why the agent is stuck before simply giving it a larger budget.
Decision record: D-013, D-020. Successful recovery is useful evidence, but should remain distinguishable from first-attempt success.
In your app: TraceSpan records each step and TurnTrace groups a turn (src/tracing.py). record_turn_trace saves it to SQLite; get_traces retrieves it. /api/traces feeds the history displayed by the Evidence tab.
The need: when an answer fails, we need to see which searches and queries ran, what failed, and how long each step took. The in-app trace view provides that record.
Our choice: defer Langfuse, a separate monitoring service, to fit the build budget. Store traces locally in SQLite so deploying a new version does not erase the old evidence.
Remember: this helps explain one conversation, but does not provide shared monitoring across several servers or automatic alerts. It is simpler to operate today; a larger service would need more monitoring and a policy for deleting old history.
Decision record: D-021, superseded for persistence by D-023. Earlier reflection text describing memory-only traces is historical.
In your app: lifespan (src/app.py) calls check_snowflake_reachability at startup. In src/health.py, health_report and is_degraded read the cached result. The browser’s /api/health request does not perform a new Snowflake connection test.
Our choice: test the Snowflake connection when the app starts and remember the result. Reading that saved status is cheaper than opening another database connection on every health check.
Example: if Snowflake becomes unavailable an hour later, the saved status may still say healthy. The next real query will expose the problem, but the saved check cannot warn us first.
Remember: this was enough for checking a fresh deployment. Continuous outage detection would need refreshed checks, with the extra work and connections that brings.
Decision record: D-015; implemented in the health module.
In your app: src/app.py serves static/index.html directly. Its activateTab function switches visible panels. deploy.sh starts the app container, and docker-compose.override.yml publishes it on 127.0.0.1:8000 for the host’s Caddy server.
Our choice: keep the frontend in one HTML file, with no separate build process. Reuse Caddy, the server already handling HTTPS and login protection, instead of starting a competing copy that would disrupt another site.
Example: adding this learning tab only needs an HTML edit. But moving the whole app to another machine also requires recreating the existing server configuration; the container alone does not describe everything.
Remember: fewer moving parts helped us ship. The cost is a growing frontend file, manually maintained explanation pages, and some setup tied to this host.
Decision record: D-016, D-017. Simplicity was chosen for this deployment and build budget, not as a universal architecture rule.
In your app: evals/scenarios.py holds the active scenarios. evals/run_evals.py writes results into evals/results/. The /api/evals endpoint (src/app.py) supplies recorded results to the Evals tab; opening the tab does not run evaluations.
What happened: the evaluation page mixed executed scenarios with a much larger backlog of scenarios that had never run. Readers had to work too hard to understand what was actually verified.
Our choice: reduce the active set, preserve historical results, and label the captured but unrun regression as pending. The report is easier to read, but omitted coverage still needs work.
Remember: a written test idea is not evidence. A smaller executed set is easier to assess, but cannot justify claims about cases it never tested. Keep gaps visible and preserve failures.
Decision record: D-022. Never erase failed results to improve the reported score.
In your app: The form in static/index.html posts to /api/chat. agent_turn coordinates search_census_variables, resolve_geography, and run_census_sql, then streams events back to the browser. Exercising that whole path checks how the parts work together.
What helped: inspecting the real data before coding uncovered missing city boundaries and invalid ways to combine medians. That prevented us from planning features the dataset could not support.
What hurt: the browser interface came late. Offline tests passed, but typing real questions exposed database naming problems that simulated database responses could not catch.
Remember: investigate the data, then get one question working from browser to database to answer. Planning reduces bad assumptions; using the complete app reveals the assumptions you still missed.
Reflection §1, §2, §4. Planning and isolated tests cannot substitute for exercising the complete user journey.
Summaries reflect this checkout's implementation. Rationale and incident evidence are recorded in docs/decisions.md, docs/01-architecture.md, and docs/reflection.md. Proposed alternatives are not shipped guarantees.