From 53bdb0c8b5550cf048c9bb3f8259458291311141 Mon Sep 17 00:00:00 2001 From: Malav Shah Date: Tue, 6 Oct 2026 10:58:35 -0700 Subject: [PATCH 1/5] shortened explanation pages and sized the quiz to the change Part of #4. --- README.md | 8 +- skills/explain-diff-html/SKILL.md | 175 ++++++++++--- skills/explain-diff-html/html-template.html | 67 ++++- .../explain-diff-html/references/diagrams.md | 3 + .../references/quiz-design.md | 28 ++- .../references/validation.md | 49 +++- .../scripts/validate-output.sh | 230 +++++++++++++++++- 7 files changed, 502 insertions(+), 58 deletions(-) diff --git a/README.md b/README.md index b0e5250..3ae0c07 100644 --- a/README.md +++ b/README.md @@ -115,9 +115,11 @@ the code around it, and writes a single page with four sections: - Intuition, on the core idea, with toy data and diagrams rather than full detail. - Code walkthrough, ordered by the path a request or an action takes through the - system, not by filename. -- Quiz, five interactive multiple-choice questions that test whether the reader - understood why the change is shaped the way it is. + system, not by filename. The edits that carry the change get a step each. + Every other changed file gets one line in an "Also changed" table at the end. +- Quiz, three or five interactive multiple-choice questions that test whether + the reader understood why the change is shaped the way it is. A small change + gets three, or fewer when it carries fewer testable decisions. The output is one HTML file with the CSS and JavaScript inline. It opens with a double click, reads on a phone, and follows the reader's light or dark system diff --git a/skills/explain-diff-html/SKILL.md b/skills/explain-diff-html/SKILL.md index fbd1a1a..04b5fc8 100644 --- a/skills/explain-diff-html/SKILL.md +++ b/skills/explain-diff-html/SKILL.md @@ -115,6 +115,11 @@ therefore no Node. The hand-built families cover it. - One long page with section headers and a table of contents. Do not use tabs for the top-level structure. - Responsive enough to read on a phone. +- A lead under the title, in the `p.lead` paragraph: the change's purpose in one + sentence, derived from what the diff does. The pull request body may shape + that sentence, but the diff, not the body, decides which files the page treats + as core. When no record supports the purpose, mark the sentence as your + inference. - A provenance line under the lead, in the `.provenance` paragraph that `html-template.html`, the scaffold every page starts from, already carries: the source, the exact ref, and the date the page was written, as in `owner/repo PR 1234 at abc1234, explained 2026-09-01`. Use the short form of @@ -233,7 +238,15 @@ blank page, not an error. Evidence: uPortal PR 2983 gives 0 files that way and because it was squashed. `gh pr diff ` returns the same diff and needs no fetch, so use it when `gh` -is available and keep the git form for when it is not. +is available and keep the git form for when it is not. Create `` first +either way, and save the diff to the same file, so every target leaves a +`/diff.txt` for the later steps: + +```bash +work="$(mktemp -d)" +echo "$work" # write this path out in later steps +gh pr diff > "$work/diff.txt" +``` Fetching a bare sha is not always allowed. The server decides whether to serve an object that no ref advertises. GitHub.com serves one that is reachable, and a @@ -346,10 +359,25 @@ is still running. Write in the order below. Aim for concrete, engaging, classic prose, with smooth transitions so the page reads as one piece rather than four. -Three rules bind all four sections. They are authoring rules, not review +Before you write any section, do three things in this order: + +1. Write the `p.lead` sentence, as the output contract describes. +2. Sort every path in the diff into core, brief, or table, as the Code section + below defines them. Save the list to `/triage.txt`, one path and its + group per line. The walkthrough and the "Also changed" table follow that + list. +3. List the names the Code and Quiz sections will use. The naming rule below + checks them. + +Four rules bind all four sections. They are authoring rules, not review notes: the humanize pass in step 6 catches violations, but by then the prose is already built around them. +Match the length to what the change needs. A one-file fix gets a short page. Add +no filler, no summary that restates a section, and no boilerplate. Cut +repetition, never explanation: a passage that is long because the mechanism is +hard stays long. + Mark every inference as yours. Explaining why code is shaped a certain way is most of the value of a page like this, and the record almost never states the reason. So when you have worked out a reason the record does not give, write it @@ -376,23 +404,89 @@ one argument makes a warning point at the caller, without saying the argument is them the number and they verify it themselves; withhold it and they take the whole section on faith. +When you shorten any passage, keep every name, number, condition, and edge case +exactly as it is. Shorten a caveat when you must, but never delete it. + Background: explain the existing system relevant to this change. Include a deep -background for a beginner, marked so a familiar reader can skip it, then a -narrow background covering exactly the code the change touches. +background for a beginner, marked so a familiar reader can skip it. Then give a +narrow background on the code the change touches. Scope both to what the core +paths in the triage list need. The narrow background gives the change's reason, +its names and data shapes, and the entry point the Code flow map starts from. +It describes the code before the change at that level. What each changed line +does belongs to the Code section. The narrow background walks an unchanged +helper only when a core edit changes how the code calls it. Any other name the +walkthrough uses gets a one-line definition in Background or Intuition. The deep +background covers only the concepts the narrow background, Intuition, and the +walkthrough use. Background, counting the collapsed part, runs no longer than +the Code walkthrough. The `words:` line of the step 7 script counts both. When +Background must run longer, the step 8 report says by how much and why. Report +the excess, and never cut explanation to meet the limit. Intuition: explain the core idea of the change. Focus on the essence, not the -full detail. Use concrete examples with toy data. Use figures and diagrams -liberally. - -Code: a high-level walkthrough of the changes, ordered by logical flow, never -by filename, directory, or the order hunks appear in the diff. Open with a -one-line flow map that names the path end to end, so the reader sees the whole -path before the steps. Then follow that path: start where the change is entered -(a request, a user action, an event, a command, a scheduled job, a schema -migration that runs first), move through each layer it flows into, and end -where the effect lands. Group the edits under that flow so each step builds on -the one before it. When a single logical change touches several files, present -them together as one step rather than scattering them alphabetically. +full detail. Use concrete examples with toy data. + +Code: a walkthrough of the changes, ordered by logical flow, never by filename, +directory, or the order hunks appear in the diff. Open with a one-line flow map +that names the path end to end, so the reader sees the whole path before the +steps. Then follow that path: start where the change is entered (a request, a +user action, an event, a command, a scheduled job, a schema migration that runs +first), move through each layer it flows into, and end where the effect lands. + +The triage list from the start of this step decides how much each path gets: + +- Core: the edits that carry the change's purpose. Walk each one in depth, in + flow order, under its own `h3.core-step` heading. When one logical change + touches several files, present them together as one step rather than + scattering them alphabetically. +- Brief: an edit the reader needs that carries none of the purpose. Give it a + sentence or two inside the core step it belongs to. +- Table: every other path. The "Also changed" table lists it. + +An edit that changes behavior never goes to the table. It may be walked briefly, +but the reader has to meet it in the walkthrough. + +Say each thing once. When Intuition has already shown a mechanism, the +walkthrough points back to it rather than explaining it again. + +End the walkthrough with the "Also changed" table, a `table.vals` with the extra +class `also-changed`. Caption it `Every other changed file (N of M)`. N counts +the files the table covers. M counts the files in the diff, from the +`diff --git` headers in `/diff.txt`. The step 7 script checks both +numbers. + +- Give each file a row with its path and a one-sentence reason it changed. +- Leave the table out when no path is left for it. +- One row may cover a directory of generated or binary asset files, such as + converted images. The row gives the file count. +- Name a deleted file by its path, with no link, because it does not exist at + the target ref. + +A large change is walked by theme. Count the changed lines, additions plus +deletions: + +```bash +git apply --numstat < "/diff.txt" | { + total=0 + while read -r added removed path; do + [ "$added" = - ] || total=$((total + added + removed)) + done + echo "$total" +} +``` + +The command counts every file, and counts a binary file's row as 0. When the +diff carries a generated directory, subtract that directory's rows, which +`git apply --numstat` lists by path. + +The loop uses named variables on purpose. When Claude Code loads this file, it +replaces a dollar sign followed by a digit with a word from the user's request. +So this file never writes one. + +Above 2,000, walk themes instead of single edits. Each theme is an +`h3.core-step` that lists the paths it covers. The core edits inside a theme +are `h4` headings, and each one still gets the in-depth walk. Say in the flow +map, or in the first theme heading, that the walkthrough is summarized at theme +level. A separate sentence that says so reads as signposting. Name each file with a `path/to/file.ext:line` reference so a reader can find it, but let the flow, not the path, set the order. @@ -496,8 +590,8 @@ opens an unknown element that HTML5 never auto-closes, so it swallows the rest of the document and breaks the sections and table-of-contents anchors below it. Escaping also closes a self-XSS path when a diff carries `#$m#g" -e "s##$m#g" -e "s#][^$m]*$m# #g" \ + -e "s#
1{id=$0;sub(/".*/,"",id);sub(/<\/section>.*/,"");sub(/^[^>]*>/,""); + gsub(/<[^>]*>/," ");gsub(/&[#A-Za-z0-9]+;/," ");n=0; + for(i=1;i<=NF;i++)if($i~/[A-Za-z0-9]/)n++;t+=n;printf "%s %d ",id,n} + END{printf "total %d\n",t}' | sed 's/^/words: /' # Flatten, then strip anchors, so a linked reference still counts as a reference. refs=$(tr '\n' ' ' < "$page" | sed -E 's#]*>##g; s/ +/ /g' \ @@ -51,6 +94,89 @@ else echo "pass: every Markdown line link carries ?plain=1" fi +# The "Also changed" table's markup, and the text of its first column. Only the +# first column names files, because a reason such as "same fix as src/" must +# not cover anything. +table=$(flat | sed 's##\ +#g' | grep ']*also-changed' | sed 's#.*
]*also-changed[^>]*>##') +first_column=$(printf '%s\n' "$table" | sed 's#.*##; s#.*]*>##; s#<[^>]*># #g') +table_tokens=$(printf '%s\n' "$first_column" | tokens) + +# Coverage: every path in the diff appears on the page, and the table caption +# counts what the table covers. The paths come from the diff --git headers, +# because a binary file has no +++ line. +if [ -z "$work" ]; then + echo "skip: coverage, no work directory given" +elif [ ! -s "$work/diff.txt" ]; then + echo "FAIL: $work/diff.txt is missing or empty" + status=1 +else + page_text=$(flat | sed 's#<[^>]*># #g; s/ */ /g') + page_tokens=$(printf '%s\n' "$page_text" | tokens) + # Git quotes a path that holds unusual characters. + paths=$(sed -n -e 's#^diff --git "a/.*" "b/\(.*\)"$#\1#p' -e 't' \ + -e 's#^diff --git a/.* b/##p' "$work/diff.txt") + files=0 + in_table=0 + missing="" + while IFS= read -r f; do + [ -n "$f" ] || continue + files=$((files + 1)) + covered=no + # A path with a space never survives tokenizing, so match it as text. + case $f in + *' '*) + if printf '%s\n' "$first_column" | grep -Fq -- "$f"; then + covered=table + elif printf '%s\n' "$page_text" | grep -Fq -- "$f"; then + covered=page + fi + ;; + esac + if [ "$covered" != no ]; then + : + elif printf '%s\n' "$table_tokens" | grep -Fqx -- "$f"; then + covered=table + else + # A directory row names a parent directory with a trailing slash. + d=$f + while [ "$covered" = no ] && [ "${d%/*}" != "$d" ]; do + d=${d%/*} + printf '%s\n' "$table_tokens" | grep -Fqx -- "$d/" && covered=table + done + fi + if [ "$covered" = table ]; then + in_table=$((in_table + 1)) + elif [ "$covered" = no ] && ! printf '%s\n' "$page_tokens" | grep -Fqx -- "$f"; then + missing="$missing + $f" + fi + done <]*># #g' \ + | grep -oE 'Every other changed file \( *[0-9]+ +of +[0-9]+ *\)' \ + | tr -s ' ' | sed 's/( */(/; s/ *)/)/') + if [ "$caption" = "Every other changed file ($in_table of $files)" ]; then + echo "pass: table caption counts $in_table of $files" + else + echo "FAIL: table caption reads '${caption:-no caption}', expected ($in_table of $files)" + status=1 + fi + fi +fi + quiz() { sed -n '/
/p' "$page" \ | tr '\n' ' ' | sed -E 's/<[^>]+>/ /g; s/ +/ /g' @@ -68,4 +194,104 @@ fi echo "advisory: ordinals in the quiz, read each one:" quiz | grep -oEi 'the (first|second|third|last|former|latter)\b[^.]{0,40}' || echo " none" +# Quiz count: three questions for at most two core steps, five otherwise, or a +# lower count the quiz section declares with a reason. +section=$(flat | sed 's#
.*##') +if [ -z "$section" ]; then + echo "FAIL: the page has no quiz section" + status=1 +else + steps=$(flat | grep -oE '

]*class="[^"]*core-step' | wc -l | tr -d ' ') + asked=$(printf '%s\n' "$section" | grep -o 'class="[^"]*quiz-question' | wc -l | tr -d ' ') + expected=5 + [ "$steps" -le 2 ] && expected=3 + declared=$(printf '%s\n' "$section" | sed -n 's#^
]*data-quiz-count="\([0-9]*\)".*#\1#p') + reason=$(printf '%s\n' "$section" | sed -n 's#^
]*data-quiz-reason="\([^"]*\)".*#\1#p') + if [ -n "$declared" ]; then + if [ "$declared" -ge 1 ] && [ "$declared" -le "$expected" ] \ + && [ "$asked" -eq "$declared" ] && [ -n "$reason" ] \ + && ! printf '%s' "$reason" | grep -q 'FILL'; then + echo "pass: $asked questions, the declared count, because: $reason" + else + echo "FAIL: $asked questions, declared $declared of at most $expected, reason '${reason}'" + status=1 + fi + elif [ "$asked" -eq "$expected" ]; then + echo "pass: $asked questions for $steps core steps" + else + echo "FAIL: $asked questions for $steps core steps, expected $expected" + status=1 + fi + + # Longest option: count the questions whose correct option has more words + # than every other option. + longest=$(printf '%s\n' "$section" | sed 's#class="[^"]*quiz-question[^"]*"#\ +Q #g; s#]*>/, " ", t); gsub(/&[#A-Za-z0-9]+;/, " ", t) + n = split(t, a, " "); c = 0 + for (i = 1; i <= n; i++) if (a[i] ~ /[A-Za-z0-9]/) c++ + return c + } + function finish() { if (q && right > other) hits++ } + /^Q / { finish(); q = 1; right = -1; other = -1; next } + /^ +

When does the cache refill?

+

Which call reads it?

+
+ + + diff --git a/tests/validate-output/fail/check-banner/fill-only.html b/tests/validate-output/fail/check-banner/fill-only.html new file mode 100644 index 0000000..7638710 --- /dev/null +++ b/tests/validate-output/fail/check-banner/fill-only.html @@ -0,0 +1,20 @@ + + +Case + +
+ +

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/coverage/empty-diff.html b/tests/validate-output/fail/coverage/empty-diff.html new file mode 100644 index 0000000..b37a662 --- /dev/null +++ b/tests/validate-output/fail/coverage/empty-diff.html @@ -0,0 +1,16 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/coverage/empty-diff.work/diff.txt b/tests/validate-output/fail/coverage/empty-diff.work/diff.txt new file mode 100644 index 0000000..e69de29 diff --git a/tests/validate-output/fail/coverage/missing-file.html b/tests/validate-output/fail/coverage/missing-file.html new file mode 100644 index 0000000..b37a662 --- /dev/null +++ b/tests/validate-output/fail/coverage/missing-file.html @@ -0,0 +1,16 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/coverage/missing-file.work/diff.txt b/tests/validate-output/fail/coverage/missing-file.work/diff.txt new file mode 100644 index 0000000..fb2f234 --- /dev/null +++ b/tests/validate-output/fail/coverage/missing-file.work/diff.txt @@ -0,0 +1,12 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/b.py b/b.py +--- a/b.py ++++ b/b.py +@@ -1 +1 @@ +-DEFAULT = 0 ++DEFAULT = None diff --git a/tests/validate-output/fail/coverage/named-only-in-banner.html b/tests/validate-output/fail/coverage/named-only-in-banner.html new file mode 100644 index 0000000..45f2023 --- /dev/null +++ b/tests/validate-output/fail/coverage/named-only-in-banner.html @@ -0,0 +1,19 @@ + + +Case + +
+ +

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/coverage/named-only-in-banner.work/diff.txt b/tests/validate-output/fail/coverage/named-only-in-banner.work/diff.txt new file mode 100644 index 0000000..fb2f234 --- /dev/null +++ b/tests/validate-output/fail/coverage/named-only-in-banner.work/diff.txt @@ -0,0 +1,12 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/b.py b/b.py +--- a/b.py ++++ b/b.py +@@ -1 +1 @@ +-DEFAULT = 0 ++DEFAULT = None diff --git a/tests/validate-output/fail/coverage/named-only-in-reason.html b/tests/validate-output/fail/coverage/named-only-in-reason.html new file mode 100644 index 0000000..b86c780 --- /dev/null +++ b/tests/validate-output/fail/coverage/named-only-in-reason.html @@ -0,0 +1,23 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+

+ + + + + +
Every other changed file (1 of 3)
FileWhy it changed
docs/notes.mdSame fix as in src/.
+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+ + + diff --git a/tests/validate-output/fail/coverage/named-only-in-reason.work/diff.txt b/tests/validate-output/fail/coverage/named-only-in-reason.work/diff.txt new file mode 100644 index 0000000..4ddbf87 --- /dev/null +++ b/tests/validate-output/fail/coverage/named-only-in-reason.work/diff.txt @@ -0,0 +1,18 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/docs/notes.md b/docs/notes.md +--- a/docs/notes.md ++++ b/docs/notes.md +@@ -1 +1 @@ +-Zero. ++None. +diff --git a/src/b.py b/src/b.py +--- a/src/b.py ++++ b/src/b.py +@@ -1 +1 @@ +-DEFAULT = 0 ++DEFAULT = None diff --git a/tests/validate-output/fail/coverage/no-headers.html b/tests/validate-output/fail/coverage/no-headers.html new file mode 100644 index 0000000..b37a662 --- /dev/null +++ b/tests/validate-output/fail/coverage/no-headers.html @@ -0,0 +1,16 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/coverage/no-headers.work/diff.txt b/tests/validate-output/fail/coverage/no-headers.work/diff.txt new file mode 100644 index 0000000..b2b3d1a --- /dev/null +++ b/tests/validate-output/fail/coverage/no-headers.work/diff.txt @@ -0,0 +1 @@ +fatal: bad revision 'refs/explain/pr-12' diff --git a/tests/validate-output/fail/full-sha/non-hex-commit.html b/tests/validate-output/fail/full-sha/non-hex-commit.html index 4c87c74..e3ae802 100644 --- a/tests/validate-output/fail/full-sha/non-hex-commit.html +++ b/tests/validate-output/fail/full-sha/non-hex-commit.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

b.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/full-sha/other-commit.html b/tests/validate-output/fail/full-sha/other-commit.html index 34365c4..246480f 100644 --- a/tests/validate-output/fail/full-sha/other-commit.html +++ b/tests/validate-output/fail/full-sha/other-commit.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

b.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/full-sha/short-sha.html b/tests/validate-output/fail/full-sha/short-sha.html index b074a5d..2cc25fa 100644 --- a/tests/validate-output/fail/full-sha/short-sha.html +++ b/tests/validate-output/fail/full-sha/short-sha.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/lead-sentence/fill-comment-only.html b/tests/validate-output/fail/lead-sentence/fill-comment-only.html new file mode 100644 index 0000000..2944776 --- /dev/null +++ b/tests/validate-output/fail/lead-sentence/fill-comment-only.html @@ -0,0 +1,19 @@ + + +Case + +
+

+ +

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/lead-sentence/quote-before-second-sentence.html b/tests/validate-output/fail/lead-sentence/quote-before-second-sentence.html new file mode 100644 index 0000000..10af685 --- /dev/null +++ b/tests/validate-output/fail/lead-sentence/quote-before-second-sentence.html @@ -0,0 +1,17 @@ + + +Case + +
+

The cache now returns "None." It refills every hour.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/lead-sentence/two-sentences.html b/tests/validate-output/fail/lead-sentence/two-sentences.html new file mode 100644 index 0000000..88a39d1 --- /dev/null +++ b/tests/validate-output/fail/lead-sentence/two-sentences.html @@ -0,0 +1,17 @@ + + +Case + +
+

The cache returns a default value. It refills every hour.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/markdown-plain/column-anchor.html b/tests/validate-output/fail/markdown-plain/column-anchor.html index e971858..2f24900 100644 --- a/tests/validate-output/fail/markdown-plain/column-anchor.html +++ b/tests/validate-output/fail/markdown-plain/column-anchor.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

README.md:3-4

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/hash-before-query.html b/tests/validate-output/fail/markdown-plain/hash-before-query.html index f6a1130..b71f928 100644 --- a/tests/validate-output/fail/markdown-plain/hash-before-query.html +++ b/tests/validate-output/fail/markdown-plain/hash-before-query.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

README.md:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/loose-range.html b/tests/validate-output/fail/markdown-plain/loose-range.html index 238b4f8..4efc87f 100644 --- a/tests/validate-output/fail/markdown-plain/loose-range.html +++ b/tests/validate-output/fail/markdown-plain/loose-range.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

README.md:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/markdown-extension.html b/tests/validate-output/fail/markdown-plain/markdown-extension.html index c96789f..2fa34f2 100644 --- a/tests/validate-output/fail/markdown-plain/markdown-extension.html +++ b/tests/validate-output/fail/markdown-plain/markdown-extension.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

docs/guide.markdown:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/notplain-query.html b/tests/validate-output/fail/markdown-plain/notplain-query.html index 451dc83..a1250b0 100644 --- a/tests/validate-output/fail/markdown-plain/notplain-query.html +++ b/tests/validate-output/fail/markdown-plain/notplain-query.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

README.md:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/relative-href.html b/tests/validate-output/fail/markdown-plain/relative-href.html index bb3bb27..d4277a7 100644 --- a/tests/validate-output/fail/markdown-plain/relative-href.html +++ b/tests/validate-output/fail/markdown-plain/relative-href.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

README.md:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/markdown-plain/uppercase-extension.html b/tests/validate-output/fail/markdown-plain/uppercase-extension.html index 88e7ccb..7c252b6 100644 --- a/tests/validate-output/fail/markdown-plain/uppercase-extension.html +++ b/tests/validate-output/fail/markdown-plain/uppercase-extension.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

README.MD:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-count/declared-above-expected.html b/tests/validate-output/fail/quiz-count/declared-above-expected.html new file mode 100644 index 0000000..b38a577 --- /dev/null +++ b/tests/validate-output/fail/quiz-count/declared-above-expected.html @@ -0,0 +1,17 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+

Which call writes it?

+
+
+ + diff --git a/tests/validate-output/fail/quiz-count/fill-reason.html b/tests/validate-output/fail/quiz-count/fill-reason.html new file mode 100644 index 0000000..8d8f4ef --- /dev/null +++ b/tests/validate-output/fail/quiz-count/fill-reason.html @@ -0,0 +1,15 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+
+
+ + diff --git a/tests/validate-output/fail/quiz-count/three-for-three-steps.html b/tests/validate-output/fail/quiz-count/three-for-three-steps.html new file mode 100644 index 0000000..459dd0b --- /dev/null +++ b/tests/validate-output/fail/quiz-count/three-for-three-steps.html @@ -0,0 +1,19 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+

The cache reads the default

+

The loader fills the cache

+

The route returns the value

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/quiz-count/two-questions.html b/tests/validate-output/fail/quiz-count/two-questions.html new file mode 100644 index 0000000..eca6236 --- /dev/null +++ b/tests/validate-output/fail/quiz-count/two-questions.html @@ -0,0 +1,15 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+
+
+ + diff --git a/tests/validate-output/fail/quiz-longest-option/longest-twice.html b/tests/validate-output/fail/quiz-longest-option/longest-twice.html new file mode 100644 index 0000000..9023332 --- /dev/null +++ b/tests/validate-output/fail/quiz-longest-option/longest-twice.html @@ -0,0 +1,16 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/quiz-positional/curly-possessive.html b/tests/validate-output/fail/quiz-positional/curly-possessive.html index f0f2c65..3e1a36e 100644 --- a/tests/validate-output/fail/quiz-positional/curly-possessive.html +++ b/tests/validate-output/fail/quiz-positional/curly-possessive.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

The first option’s claim is wrong, because the cache is empty.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/first-option.html b/tests/validate-output/fail/quiz-positional/first-option.html index d5faaca..1ab13d3 100644 --- a/tests/validate-output/fail/quiz-positional/first-option.html +++ b/tests/validate-output/fail/quiz-positional/first-option.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

The first option is right, because the cache is empty.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/former.html b/tests/validate-output/fail/quiz-positional/former.html index 8219cc1..15aac1c 100644 --- a/tests/validate-output/fail/quiz-positional/former.html +++ b/tests/validate-output/fail/quiz-positional/former.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Both could work, but the former reads the cache first.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/last-option.html b/tests/validate-output/fail/quiz-positional/last-option.html index 3fe1120..ccf252a 100644 --- a/tests/validate-output/fail/quiz-positional/last-option.html +++ b/tests/validate-output/fail/quiz-positional/last-option.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

The last option is right, because the cache is empty.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/latter.html b/tests/validate-output/fail/quiz-positional/latter.html index 07cbdf4..3528b12 100644 --- a/tests/validate-output/fail/quiz-positional/latter.html +++ b/tests/validate-output/fail/quiz-positional/latter.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Both could work, but the latter reads the cache first.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/possessive.html b/tests/validate-output/fail/quiz-positional/possessive.html index 79970ce..1bb04f1 100644 --- a/tests/validate-output/fail/quiz-positional/possessive.html +++ b/tests/validate-output/fail/quiz-positional/possessive.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

The first option's claim is wrong, because the cache is empty.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/second-option.html b/tests/validate-output/fail/quiz-positional/second-option.html index 0e692d9..5081979 100644 --- a/tests/validate-output/fail/quiz-positional/second-option.html +++ b/tests/validate-output/fail/quiz-positional/second-option.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Pick the second option.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-positional/third-option.html b/tests/validate-output/fail/quiz-positional/third-option.html index 4b5dca0..61c5924 100644 --- a/tests/validate-output/fail/quiz-positional/third-option.html +++ b/tests/validate-output/fail/quiz-positional/third-option.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Pick the third option.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/quiz-present/no-quiz.html b/tests/validate-output/fail/quiz-present/no-quiz.html index 5dc5d31..756d389 100644 --- a/tests/validate-output/fail/quiz-present/no-quiz.html +++ b/tests/validate-output/fail/quiz-present/no-quiz.html @@ -3,6 +3,7 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

diff --git a/tests/validate-output/fail/table-caption/fill-placeholder.html b/tests/validate-output/fail/table-caption/fill-placeholder.html new file mode 100644 index 0000000..beefd37 --- /dev/null +++ b/tests/validate-output/fail/table-caption/fill-placeholder.html @@ -0,0 +1,25 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+ + + + + + +
+ Every other changed file ( of ) +
FileWhy it changed
docs/cache.mdDocuments the default value.
+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/table-caption/fill-placeholder.work/diff.txt b/tests/validate-output/fail/table-caption/fill-placeholder.work/diff.txt new file mode 100644 index 0000000..8d79987 --- /dev/null +++ b/tests/validate-output/fail/table-caption/fill-placeholder.work/diff.txt @@ -0,0 +1,12 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/docs/cache.md b/docs/cache.md +--- a/docs/cache.md ++++ b/docs/cache.md +@@ -1 +1 @@ +-The cache returns zero. ++The cache returns None. diff --git a/tests/validate-output/fail/table-caption/wrong-count.html b/tests/validate-output/fail/table-caption/wrong-count.html new file mode 100644 index 0000000..5958eb7 --- /dev/null +++ b/tests/validate-output/fail/table-caption/wrong-count.html @@ -0,0 +1,23 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+ + + + + + +
Every other changed file (1 of 3)
FileWhy it changed
docs/cache.mdDocuments the default value.
+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/table-caption/wrong-count.work/diff.txt b/tests/validate-output/fail/table-caption/wrong-count.work/diff.txt new file mode 100644 index 0000000..8d79987 --- /dev/null +++ b/tests/validate-output/fail/table-caption/wrong-count.work/diff.txt @@ -0,0 +1,12 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/docs/cache.md b/docs/cache.md +--- a/docs/cache.md ++++ b/docs/cache.md +@@ -1 +1 @@ +-The cache returns zero. ++The cache returns None. diff --git a/tests/validate-output/fail/table-reason-sentence/two-sentence-reason.html b/tests/validate-output/fail/table-reason-sentence/two-sentence-reason.html new file mode 100644 index 0000000..7d00162 --- /dev/null +++ b/tests/validate-output/fail/table-reason-sentence/two-sentence-reason.html @@ -0,0 +1,25 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+ + + + + + + +
Every other changed file (2 of 3)
FileWhy it changed
docs/cache.mdDocuments the default value.
b.pyRenames a helper. Nothing else changes.
+
+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/fail/unlinked-reference/class-token.html b/tests/validate-output/fail/unlinked-reference/class-token.html index f8cc527..8f6d1a5 100644 --- a/tests/validate-output/fail/unlinked-reference/class-token.html +++ b/tests/validate-output/fail/unlinked-reference/class-token.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

b.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/unlinked-reference/dotfile.html b/tests/validate-output/fail/unlinked-reference/dotfile.html index 65df759..019b646 100644 --- a/tests/validate-output/fail/unlinked-reference/dotfile.html +++ b/tests/validate-output/fail/unlinked-reference/dotfile.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

src/.env:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/unlinked-reference/label-with-leading-text.html b/tests/validate-output/fail/unlinked-reference/label-with-leading-text.html index 285c537..119982b 100644 --- a/tests/validate-output/fail/unlinked-reference/label-with-leading-text.html +++ b/tests/validate-output/fail/unlinked-reference/label-with-leading-text.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

From b.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/unlinked-reference/span-srcref.html b/tests/validate-output/fail/unlinked-reference/span-srcref.html index 5f5bd07..07d980e 100644 --- a/tests/validate-output/fail/unlinked-reference/span-srcref.html +++ b/tests/validate-output/fail/unlinked-reference/span-srcref.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

b.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/fail/unlinked-reference/spare-srcref.html b/tests/validate-output/fail/unlinked-reference/spare-srcref.html index e034466..cd664b0 100644 --- a/tests/validate-output/fail/unlinked-reference/spare-srcref.html +++ b/tests/validate-output/fail/unlinked-reference/spare-srcref.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

See b.py:9.

the guide

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/advisory-ordinal.html b/tests/validate-output/pass/advisory-ordinal.html index e27dcdc..e895240 100644 --- a/tests/validate-output/pass/advisory-ordinal.html +++ b/tests/validate-output/pass/advisory-ordinal.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which is the second step in the flow? Pick one.

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/baseline.html b/tests/validate-output/pass/baseline.html index 688e140..4e4a12a 100644 --- a/tests/validate-output/pass/baseline.html +++ b/tests/validate-output/pass/baseline.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/coverage.html b/tests/validate-output/pass/coverage.html new file mode 100644 index 0000000..f80ed8c --- /dev/null +++ b/tests/validate-output/pass/coverage.html @@ -0,0 +1,27 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+

The loader in src/my file.py reads the default.

+ + + + + + + + + +
Every other changed file ( 4 of 6 )
FileWhy it changed
docs/cache.mdDocuments the default value.
tests/Covers the default value.
assets/logo.pngShows the new name.
src/café.pyReads the same default.
+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/pass/coverage.work/diff.txt b/tests/validate-output/pass/coverage.work/diff.txt new file mode 100644 index 0000000..cb358e1 --- /dev/null +++ b/tests/validate-output/pass/coverage.work/diff.txt @@ -0,0 +1,32 @@ +diff --git a/a.py b/a.py +--- a/a.py ++++ b/a.py +@@ -9 +9 @@ +- return 0 ++ return None +diff --git a/docs/cache.md b/docs/cache.md +--- a/docs/cache.md ++++ b/docs/cache.md +@@ -1 +1 @@ +-The cache returns zero. ++The cache returns None. +diff --git a/tests/unit/test_a.py b/tests/unit/test_a.py +--- a/tests/unit/test_a.py ++++ b/tests/unit/test_a.py +@@ -1 +1 @@ +-assert get() == 0 ++assert get() is None +diff --git a/assets/logo.png b/assets/logo.png +Binary files a/assets/logo.png and b/assets/logo.png differ +diff --git a/src/my file.py b/src/my file.py +--- a/src/my file.py ++++ b/src/my file.py +@@ -1 +1 @@ +-DEFAULT = 0 ++DEFAULT = None +diff --git "a/src/caf\303\251.py" "b/src/caf\303\251.py" +--- "a/src/caf\303\251.py" ++++ "b/src/caf\303\251.py" +@@ -1 +1 @@ +-DEFAULT = 0 ++DEFAULT = None diff --git a/tests/validate-output/pass/data-bare-before-class.html b/tests/validate-output/pass/data-bare-before-class.html index 8450e93..c729705 100644 --- a/tests/validate-output/pass/data-bare-before-class.html +++ b/tests/validate-output/pass/data-bare-before-class.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

main.py:8

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/data-bare-label-around-code.html b/tests/validate-output/pass/data-bare-label-around-code.html index f9493f3..d2d1e1f 100644 --- a/tests/validate-output/pass/data-bare-label-around-code.html +++ b/tests/validate-output/pass/data-bare-label-around-code.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

main.py:8

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/host-port-not-reference.html b/tests/validate-output/pass/host-port-not-reference.html index 6b6e62a..0bde909 100644 --- a/tests/validate-output/pass/host-port-not-reference.html +++ b/tests/validate-output/pass/host-port-not-reference.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

Pinned at example.com:8080.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/inner-code-data-bare.html b/tests/validate-output/pass/inner-code-data-bare.html index 8a027b3..0fc3be0 100644 --- a/tests/validate-output/pass/inner-code-data-bare.html +++ b/tests/validate-output/pass/inner-code-data-bare.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

main.py:8

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/markdown-heading-anchor.html b/tests/validate-output/pass/markdown-heading-anchor.html index d0a0fdb..ac3af47 100644 --- a/tests/validate-output/pass/markdown-heading-anchor.html +++ b/tests/validate-output/pass/markdown-heading-anchor.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

the license section

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/markdown-heading-digit-anchor.html b/tests/validate-output/pass/markdown-heading-digit-anchor.html index 2d35376..e31deb6 100644 --- a/tests/validate-output/pass/markdown-heading-digit-anchor.html +++ b/tests/validate-output/pass/markdown-heading-digit-anchor.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

README.md, L1 cache

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/markdown-plain-link.html b/tests/validate-output/pass/markdown-plain-link.html index 6922be4..5ed317c 100644 --- a/tests/validate-output/pass/markdown-plain-link.html +++ b/tests/validate-output/pass/markdown-plain-link.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

README.md:3

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/one-sentence-lead-and-reasons.html b/tests/validate-output/pass/one-sentence-lead-and-reasons.html new file mode 100644 index 0000000..ebdb97e --- /dev/null +++ b/tests/validate-output/pass/one-sentence-lead-and-reasons.html @@ -0,0 +1,25 @@ + + +Case + +
+

The loader reads os.Path values, e.g. Windows paths, before it starts.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+ + + + + + + +
Every other changed file (2 of 3)
FileWhy it changed
docs/cache.mdDocuments the default value.
b.pyCalls load(). Then the same way, i.e. Once per start.
+
+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/pass/quiz-declared-count.html b/tests/validate-output/pass/quiz-declared-count.html new file mode 100644 index 0000000..db7755b --- /dev/null +++ b/tests/validate-output/pass/quiz-declared-count.html @@ -0,0 +1,15 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+
+

What does the function return?

+

When does the cache refill?

+
+
+ + diff --git a/tests/validate-output/pass/quiz-five-for-three-steps.html b/tests/validate-output/pass/quiz-five-for-three-steps.html new file mode 100644 index 0000000..0ad64e5 --- /dev/null +++ b/tests/validate-output/pass/quiz-five-for-three-steps.html @@ -0,0 +1,21 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+

a.py:9

+

The cache reads the default

+

The loader fills the cache

+

The route returns the value

+
+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+

Which call writes it?

+

Where does the default live?

+
+
+ + diff --git a/tests/validate-output/pass/references-not-linked-wrapped.html b/tests/validate-output/pass/references-not-linked-wrapped.html index df7d81c..8b3ef73 100644 --- a/tests/validate-output/pass/references-not-linked-wrapped.html +++ b/tests/validate-output/pass/references-not-linked-wrapped.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08. References are not linked: the host is not GitHub.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/references-not-linked.html b/tests/validate-output/pass/references-not-linked.html index 0c734b3..1b987c8 100644 --- a/tests/validate-output/pass/references-not-linked.html +++ b/tests/validate-output/pass/references-not-linked.html @@ -3,10 +3,14 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08. References are not linked: the host is not GitHub.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/script-in-quiz.html b/tests/validate-output/pass/script-in-quiz.html index 5e93cc3..87e5695 100644 --- a/tests/validate-output/pass/script-in-quiz.html +++ b/tests/validate-output/pass/script-in-quiz.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/style-in-quiz.html b/tests/validate-output/pass/style-in-quiz.html index b60e401..4d46964 100644 --- a/tests/validate-output/pass/style-in-quiz.html +++ b/tests/validate-output/pass/style-in-quiz.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/template-in-quiz.html b/tests/validate-output/pass/template-in-quiz.html index 12d45b1..7692a3d 100644 --- a/tests/validate-output/pass/template-in-quiz.html +++ b/tests/validate-output/pass/template-in-quiz.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/version-not-reference.html b/tests/validate-output/pass/version-not-reference.html index dd1ca65..c98ead2 100644 --- a/tests/validate-output/pass/version-not-reference.html +++ b/tests/validate-output/pass/version-not-reference.html @@ -3,11 +3,15 @@ Case
+

The cache returns a default value when it is empty.

octo/repo at 0123456, explained 2026-10-08.

Pinned at v1.2:3.

a.py:9

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

diff --git a/tests/validate-output/pass/words-per-section.html b/tests/validate-output/pass/words-per-section.html new file mode 100644 index 0000000..d9aed1c --- /dev/null +++ b/tests/validate-output/pass/words-per-section.html @@ -0,0 +1,23 @@ + + +Case + +
+

The cache returns a default value when it is empty.

+

octo/repo at 0123456, explained 2026-10-08.

+
+

Background

+

The cache keeps one value → per key.

+
def get(): return None
+ +
+
+

Quiz

+

Which value does the function return when the cache is empty?

+

What does the function return?

+

When does the cache refill?

+

Which call reads it?

+
+
+ + diff --git a/tests/validate-output/validate-output.test.ts b/tests/validate-output/validate-output.test.ts index cee55d6..1b9ad71 100644 --- a/tests/validate-output/validate-output.test.ts +++ b/tests/validate-output/validate-output.test.ts @@ -1,14 +1,23 @@ // Runs the validator on every page in this folder. A page in pass/ must pass // every check. A page in fail// must fail that check and no other. -// To add a case, add a page; this file needs no edit. +// To add a case, add a page; this file needs no edit. A case that needs a diff +// adds a .work/diff.txt beside the page. import { spawnSync } from "node:child_process"; -import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { + cpSync, + existsSync, + mkdtempSync, + readdirSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; import { tmpdir } from "node:os"; import { basename, dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { expect, test } from "vite-plus/test"; -import { checks, parsePage, validate } from "../../src/validate-output.ts"; +import { checks, parsePage, readDiff, validate } from "../../src/validate-output.ts"; // The bundle is what the skill ships, so the command-line tests run it. const script = fileURLToPath( @@ -17,9 +26,16 @@ const script = fileURLToPath( // Every case page links at 0123456789abcdef0123456789abcdef01234567. const sha = "0123456"; +// The page's work directory as a command-line argument, or none. +function getWork(path: string): string[] { + const work = path.replace(/\.html$/, ".work"); + return existsSync(work) ? [work] : []; +} + function getFailedCheckIds(path: string): string[] { const document = parsePage(readFileSync(path, "utf8")); - return validate({ document, sha }) + const [work] = getWork(path); + return validate({ document, sha, diff: work ? readDiff(work) : undefined }) .filter(({ result }) => result.isFailed) .map(({ id }) => id); } @@ -41,7 +57,7 @@ const passFolder = join(import.meta.dirname, "pass"); for (const path of getPages(passFolder)) { test(`pass/${basename(path)}`, () => { expect(getFailedCheckIds(path)).toEqual([]); - const { status, stdout } = runScript(path, sha); + const { status, stdout } = runScript(path, sha, ...getWork(path)); expect(status).toBe(0); expect(stdout).toMatch(/^pass: /m); expect(stdout).not.toMatch(/^FAIL: /m); @@ -62,7 +78,7 @@ for (const checkId of checkIds) { for (const path of getPages(join(failFolder, checkId))) { test(`fail/${checkId}/${basename(path)}`, () => { expect(getFailedCheckIds(path)).toEqual([checkId]); - const { status, stdout } = runScript(path, sha); + const { status, stdout } = runScript(path, sha, ...getWork(path)); expect(status).toBe(1); expect(stdout).toMatch(/^FAIL: /m); }); @@ -76,6 +92,28 @@ test("an unlinked reference is listed by its text", () => { expect(unlinked?.result.isFailed ? unlinked.result.findings : []).toEqual(["b.py:9"]); }); +// Background is 8 words: the arrow, the
, and the 
   
@@ -539,753 +636,729 @@
 
       
-

Published before it was finished

+

Thread-safe route building in included routers

- FastAPI - pull request 16013 - adds a lock to a route cache. The change that fixes the bug is - smaller than the lock: the rebuilt list is assigned before the - version is stamped, and that order is what the fast path depends on. + Each included router now rebuilds its cached route lists under its + own lock and publishes each list only when it is complete, so + threads that share one app can no longer read a half-built list or + append into the same one.

- fastapi/fastapi PR 16013 at 9f919ff, explained 2026-09-01. References link to this commit. + fastapi/fastapi PR 16013 at 9f919ff, explained 2026-11-16. + References link to this commit.

Background

-
- New to FastAPI routers, or to data races? Expand for the deeper - background. + New to this area? Expand for the deeper background.

- A FastAPI application is a tree of routers. You group endpoints - into an APIRouter, then attach it: -

-
-router = APIRouter()
-
-@router.get("/items/{id}")
-def read_item(id: int):
-    return {"id": id}
-
-app = FastAPI()
-app.include_router(router, prefix="/api")
-

- Routers nest, and each level can add a prefix, dependencies, tags, - and response settings. So the path a request matches, and the - settings that apply to it, depend on the whole chain from the root - down to the endpoint. + CPython, the standard Python interpreter, runs one thread at a time + under its global interpreter lock (GIL), and it can switch threads + between any two bytecode steps. So a single assignment + such as self.items = new_list lands as one step that + another thread sees whole. A loop that appends ten items is ten + steps, and another thread can run, and read the half-filled list, + between any two of them. Free-threaded CPython removes the GIL, + so its threads really do run at the same moment.

- Walking that tree on every request would be wasteful, so FastAPI - flattens it once and caches the result. The cache is invalidated - by a version number: add a route anywhere in the tree and the - version changes, and the next request rebuilds. + A check-then-act race happens when a thread checks a condition, + acts on it, and another thread changes the condition in between. + A threading.Lock prevents that by admitting one + thread at a time: code inside with lock: runs only + while the thread holds the lock, and any other thread reaching + that line waits for the release. The lock is not reentrant. A + thread that already holds it and asks again waits forever, on + itself.

- That leaves a lazy cache, which is a small piece of shared mutable - state. If two threads reach it at the same time while it is cold, - both decide to rebuild. What each one sees of the other's work is - the subject of this change. + A dataclass declares its attributes as fields. + field(default_factory=threading.Lock) calls + threading.Lock() once per new instance, so no two + instances share the object. repr=False and + compare=False leave a field out of the + __repr__ and __eq__ methods the + dataclass writes.

- One term for the rest of the page. A data race is two - threads touching the same state with no agreement about order, so - what each one observes depends on timing. That timing dependence - is what makes the symptoms hard to trace back to one cause. + The tests use three helpers. threading.Barrier(n) + holds threads until n of them arrive, then releases + them together. threading.Event lets one thread wait + until another calls set(). pytest's + monkeypatch.setattr replaces an attribute for one + test.

- The cached object lives on a small internal class called - _IncludedRouter: a dataclass, one instance per included - router, holding the flattened list plus the version that list was - built for. It has two methods that build and cache such a list, - effective_candidates for ordinary routes and - effective_low_priority_routes for routes that are tried - last. Both changed in the same way, and both share one lock. + Discussion 15914 + reported that an app's first requests could go wrong when several + threads sent them at once. The setup was a test suite in which each + thread creates its own TestClient, Starlette's test + client, against one shared app. Each client runs the app on its own + event loop in its own thread. A valid route could answer 404. The + route list FastAPI caches for an included router could keep + duplicate entries for the life of the app: 283 entries for 120 routes in one of the reporter's runs. The + global warnings.filters list could gain stray entries. + The reporter noted that a server running one event loop matches + every request on one thread, so it is not exposed. The reply + that links this pull request calls the issue "mostly harmless", + since it would mainly apply to parallel test runs that use threads, + and says the fix shipped in FastAPI 0.139.2.

-

fastapi/routing.py:1571

-
-@dataclass
-class _IncludedRouter(BaseRoute):
-    original_router: "APIRouter"
-    include_context: _RouterIncludeContext
-

- The version is not a plain counter on one router. It is a sum over - the subtree, so a change to any nested router changes the version - every ancestor sees. + The race lives in _IncludedRouter, a dataclass this + page calls the wrapper. include_router(router) appends one + wrapper to the parent's routes (fastapi/routing.py:3260-3262). The wrapper holds original_router, the router that + was included, and include_context, a + _RouterIncludeContext with the prefix, tags, + dependencies, and other settings the include adds. According to the + discussion, the wrapper arrived in FastAPI 0.137.0 with + pull request 15745, a refactor of the router internals.

-

fastapi/routing.py:2530

-
-    def _get_routes_version(self, seen: set[int] | None = None) -> int:
-        if seen is None:
-            seen = set()
-        router_id = id(self)
-        if router_id in seen:
-            return self._routes_version
-        seen.add(router_id)
-        version = self._routes_version
-        for route in self.routes:
-            if isinstance(route, _IncludedRouter):
-                version += route.original_router._get_routes_version(seen)
-        return version
-

- Six methods bump a router's own counter: - add_route, add_websocket_route, - add_api_route, add_api_websocket_route, - include_router, and frontend, which mounts - a static frontend build as low-priority routes. All six are - construction-time APIs. Nothing on the request path bumps the - counter, which is why a retained cache is built once, on the first - request, and then left alone. + The wrapper builds the routes it serves on demand, in two lists. + effective_candidates() returns one entry for each route + of original_router that it knows how to serve. Each route that is not itself an included router becomes an + _EffectiveRouteContext, the route with the include + context applied, built by _build_effective_context() + (fastapi/routing.py:1639). For an API route, that means compiling the prefixed path into a + regex, creating the response model fields, and building the + dependency tree in _populate_api_route_state() (fastapi/routing.py:947). A router included inside the included router becomes a child + wrapper, child_branch in the code, whose context is the + two include contexts joined by combine(). The second + list, from effective_low_priority_routes(), holds + routes tried only after every regular route has failed to match. + Those are the routes that APIRouter.frontend() registers + to serve a built frontend from a directory, kept in + _low_priority_routes (fastapi/routing.py:2661).

- Here is the rebuild before the change. Three steps, and every one of - them writes to shared state. + Each list is cached on the wrapper beside a version stamp: + _effective_candidates with + _effective_candidates_version, and + _effective_low_priority_routes with + _effective_low_priority_routes_version. Both stamps + start as None. Every APIRouter keeps an + integer, _routes_version, and + _mark_routes_changed() (fastapi/routing.py:2527-2528) adds one to it each time a route or a router is added. + _get_routes_version() (fastapi/routing.py:2530) returns that integer plus the integers of every router included + below. Each method compares the version that call returns with its + stamp, returns the + cached list on a match, and rebuilds on a mismatch. A stamp of + None never matches, so the first request through a + wrapper does the build.

-

fastapi/routing.py, before the change

-
-        self._effective_candidates = []
-        candidates = self.original_router.routes
-        for route in candidates:
-            ...
-            self._effective_candidates.append(route_context)
-        self._effective_candidates_version = routes_version
-        return self._effective_candidates
- -
- Key concept - The first line installs an empty list where other threads can see - it. Everything after it fills that list in place. So for the whole - duration of the rebuild, the cache attribute holds a list that is - real, reachable, and wrong. -
+

+ The app's top-level APIRouter asks each route whether it matches, + in its app method (fastapi/routing.py:2670). For a wrapper, that question ends in the wrapper's + _match() (fastapi/routing.py:1714), which loops over effective_candidates() (fastapi/routing.py:1718) and returns the first full match. When no route matches and no + slash-toggled redirect does either (fastapi/routing.py:2697), + app calls _match_low_priority() (fastapi/routing.py:2717), + which reaches effective_low_priority_routes() through + _iter_low_priority_routes() (fastapi/routing.py:2760). When that fails too, self.default (fastapi/routing.py:2732) answers 404. +

Intuition

- -

- The pull request body is two sentences and a link. The reasoning is - in the linked discussion, and the reported symptoms go past "two - threads corrupted a list". -

-

- The discussion is titled "Router-tree lazy rebuild (0.137.0+) is not - thread-safe: valid routes can 404 under concurrent first requests". - Its author reports three effects. The first is the one that reaches - a user. The third column is my reading of how long each lasts, not - something the report states. + A version stamp makes a promise: when it matches, the list beside it + is complete and current. The old rebuild broke that promise for a + moment. These lines, from the diff, did it:

- - - - - - - - - - - - - - - - - - - - - - -
EffectHow it appearsHow long it lasts
A valid route returns 404 - A reader iterates a half-built list, matches nothing, and falls - through to the default handler - One request
The cache holds too many entries - Concurrent rebuilds append into whichever list was assigned - last, so entries accumulate - The life of the process
Global warning filters leak - Building model fields saves and restores a process-global list, - and overlapping builds restore each other's copies - The life of the process
- +

fastapi/routing.py before the change, from the diff

+
self._effective_candidates = []
+candidates = self.original_router.routes
+for route in candidates:
+    # elided: the loop body, which appends one entry per route
+    # to self._effective_candidates
+self._effective_candidates_version = routes_version
+return self._effective_candidates

- For the second effect the reporter counted 283, 166, 226, 247, and - 375 cached entries across five runs of an application with 120 - routes. The list never shrinks back, because nothing rebuilds it - once the version has been stamped. + Take a router with three routes, /a, /b, + and /c, included once, and three threads sending the + app's first requests. Thread A reads the stamp, sees + None, and the interpreter pauses it just before the + reset line, self._effective_candidates = []. Thread B reads None too, builds the full + list, and stamps it 3, the router's version after its + three routes were added. Then A wakes up and runs its + next line.

- -

How two threads get there

- -
+          
---
+config:
+  sequence:
+    useMaxWidth: false
+    mirrorActors: false
+    actorMargin: 16
+    width: 100
+    messageFontSize: 14
+    noteFontSize: 14
+    actorFontSize: 14
+---
 sequenceDiagram
-    autonumber
     participant A as Thread A
-    participant C as the cache. shared state
+    participant R as Shared cache
     participant B as Thread B
-
-    Note over A,B: before the fix. no lock. list published empty
-    A->>C: version differs. start rebuilding
-    A->>C: self._effective_candidates = []
-    B->>C: version still differs. start rebuilding too
-    A->>C: append route 1 of 120
-    B->>C: self._effective_candidates = []
-    Note over C: Thread A's work is discarded mid flight
-    B->>C: append route 1 of 120
-    A->>C: append into the list B just replaced
-    A->>C: set version to current
-    B->>C: reads a list that is neither complete nor its own
-    B--)B: a valid route 404s
- -

- Step 8 is the one to look at. Thread A stamps the version while - thread B is still appending. From then on the version says current, - so every later reader takes the fast path and trusts a list that two - threads are still writing to. Step 10 is what a user sees. -

- -

Two changes, and which one is the fix

- + participant C as Thread C + A->>R: stamp None, rebuild + Note over A: paused before the reset + B->>R: stamp None, rebuild + B->>R: list = [a, b, c] + B->>R: stamp = 3 + A->>R: list = [] + Note over R: stamp 3, list [] + C->>R: stamp 3, use the list + R-->>C: [], so /c is a 404

- The diff does two separable things, and they are easy to conflate. + A's reset puts an empty list on the wrapper while B's stamp still + says 3. Thread C asks for /c, finds the + stamp current, loops over the empty list, matches nothing, and gets + a 404 for a route that exists. This is a check-then-act race: A + acted on a check that B had made stale. Once A finishes its loop the list is + whole again, so this failure is brief and depends on timing. A + different overlap leaves extra entries in the list, and because the + stamp then matches, they stay until a route is added. That is the + duplication the discussion measured.

- -

- The first is a lock, with the version re-checked after acquiring it. - That is the standard double-checked pattern: the check outside the - lock keeps a warm cache from paying for synchronization at all. It - is not free, since computing the version walks the subtree, but it - costs no lock. -

-

- The second is that the list is built into a local variable and - assigned to the attribute in one statement, once complete. This is - the change that fixes the bug, and the reason is that a reader on - the fast path never takes the lock. A lock alone would still leave - that reader looking at a partially filled list. Building locally - means the attribute only ever holds a finished list. -

- -

- Before: the container is shared while filling + The fix changes who builds and where. Only one thread builds at a + time, and it builds where nobody else can look: in a local list, + which other threads see only when one assignment puts the finished + list on the wrapper. This page calls that assignment publishing. That assignment comes before the stamp, so a thread that + sees the new stamp also sees the new list. A thread that had to wait + for the builder checks the stamp again once it holds the lock, finds + it current, and takes the list the builder made.

-
-
rebuild starts
-
-
- [] -
-
visible to readers
-
-
-
- append x120 -
-
still visible
-
-
- -

- After: the container is private while filling -

-
-
rebuild starts
-
-
- local list -
-
nobody can see it
-
-
-
- one assignment -
-
visible, complete
-
-
- -
- Edge case - The two publishing lines are ordered, and the order carries the - invariant. In fastapi/routing.py:1608-1609 the list is - assigned first and the version second. A reader who lands between - them sees the new complete list with the old version, fails the - check, takes the lock, and gets the published list from the - re-check. Swap the two lines and that same reader sees the new - version with the old list, passes the check, and returns stale data - that nothing will ever correct. +
---
+config:
+  sequence:
+    useMaxWidth: false
+    mirrorActors: false
+    actorMargin: 16
+    width: 100
+    messageFontSize: 14
+    noteFontSize: 14
+    actorFontSize: 14
+---
+sequenceDiagram
+    participant A as Thread A
+    participant R as Shared cache
+    participant B as Thread B
+    participant C as Thread C
+    A->>R: stamp None, take lock
+    B->>R: stamp None, wait for lock
+    Note over A: build a local [a, b, c]
+    A->>R: list = [a, b, c]
+    A->>R: stamp = 3, unlock
+    Note over B: gets the lock
+    B->>R: stamp 3, skip rebuild
+    R-->>B: the list A built
+    C->>R: stamp 3, no lock
+    R-->>C: [a, b, c], /c matches
+
+ Key concept + This pattern is double-checked locking: check without the lock, take + the lock, then check again. The rest of this page + calls the two checks the check before the lock and the check inside + the lock.

Code walkthrough

- -

- The flow, end to end. A request needs the flattened routes. The - method compares the subtree version against the cached one. On a - match it returns the cached list and stops. On a mismatch it takes - the lock, checks again in case another thread just did the work, - builds a fresh list locally, publishes it, stamps the version, and - returns what it built. -

- -

Two files: the fix, and a test file that gains two tests.

- -

1. The whole method

- -

fastapi/routing.py:1587

-
-    def effective_candidates(self) -> list["_EffectiveRouteContext | _IncludedRouter"]:
-        routes_version = self.original_router._get_routes_version()
-        if routes_version == self._effective_candidates_version:
-            return self._effective_candidates
-        with self._effective_routes_lock:
-            routes_version = self.original_router._get_routes_version()
-            if routes_version == self._effective_candidates_version:
-                return self._effective_candidates
-            effective_candidates: list[_EffectiveRouteContext | _IncludedRouter] = []
-            for route in self.original_router.routes:
-                # elided: builds a child branch for a nested router, or an
-                # effective route context for a plain route
-                ...
-            self._effective_candidates = effective_candidates
-            self._effective_candidates_version = routes_version
-            return effective_candidates
- -

- Four things to name: the duplicated check, the local list, the - publish-then-stamp order, and the fact that the method returns the - local rather than reading the attribute back. -

- -

2. The lock field

- -

fastapi/routing.py:1575

-
+    _effective_routes_lock: Any = field(
-+        default_factory=threading.Lock, repr=False, compare=False
-+    )
- -

- default_factory gives each instance its own lock, so - two routers never contend. The two keyword arguments matter because - the bare @dataclass generates both a - __repr__ and an __eq__. -

- -

- repr=False keeps the lock out of the string form, which - would otherwise print a memory address that changes every run. - compare=False matters more: the generated - __eq__ compares the tuple of fields, and a - threading.Lock only ever equals itself. Left in, two - _IncludedRouter instances with identical routers and - contexts would always compare unequal, because their locks are - different objects. -

- -

3. Checking the version twice

-

- The check at the top runs without the lock, and the same check runs - again immediately after acquiring it. The two do different jobs. The - first is the fast path: a warm cache computes the subtree version, - compares it, and returns, without touching the lock. The second - covers the window between failing the first check and getting the - lock, during which another thread may have finished the whole - rebuild. + Flow: include_router creates a wrapper with its own + lock → a request reaches _match() → + effective_candidates() checks, locks, checks again, + builds, and publishes → an unmatched request reaches + effective_low_priority_routes(), which repeats the + pattern under the same lock.

+

Each wrapper gets its own lock

- Without the second check, every thread that queued on the lock would - rebuild the list again in turn, each one throwing away the work of - the thread before it. + fastapi/routing.py now imports threading + (fastapi/routing.py:10) and gives the wrapper dataclass one new field:

- -

4. Publish, then stamp

- -

- This is the ordering from the edge case above, and it is the reason - the unlocked fast path is safe. The invariant the code maintains is: - if the version says current, the list is complete. -

- -

- The first three rows are states this code produces. The fourth is - the counterfactual, and the only one where the reader has no way - back. -

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
A reader arrivesSees versionSees listOutcome
before the publisholdthe previous list, or the empty defaultfails the check, takes the lock
between publish and stampoldnew, completefails the check, takes the lock
after the stampnewnew, completepasses the check, returns it
- the counterfactual: after a stamp, had the lines been swapped - newthe previous list, or the empty defaultpasses the check, never corrected
- -

5. Returning the local

- -

- Both methods end with return effective_candidates, the - local variable, rather than - return self._effective_candidates. -

- -

- At this commit that makes no observable difference. The return value - is evaluated while the thread still holds the lock, and both writes - to those attributes happen under that same lock, so no other thread - can have replaced either one in between. Returning the local would - still hold if something later wrote the attribute without the lock. - Whether that was the reason, the record does not say. +

+ fastapi/routing.py:1572-1577

- -

6. The nested-router asymmetry

- +
class _IncludedRouter(BaseRoute):
+    original_router: "APIRouter"
+    include_context: _RouterIncludeContext
+    _effective_routes_lock: Any = field(
+        default_factory=threading.Lock, repr=False, compare=False
+    )

- Inside the rebuild, a nested router becomes a fresh - _IncludedRouter object, constructed on the spot. The - two methods then do opposite things with it, so read this before - either one. + Because the field uses default_factory, every wrapper + gets a fresh lock. That covers the wrapper + include_router creates and every + child_branch the two methods create. + repr=False and compare=False leave the + lock out of the wrapper's __repr__ and + __eq__.

-

- effective_candidates appends the child into the list it - publishes, so the child survives. Callers reach it through the - parent's cached list and call its own - effective_candidates, which fills the child's own - cache. So a nested router's cache is reused across requests. It is - discarded whenever the parent rebuilds, because the parent then - constructs a new child object, and the old one becomes garbage along - with its warm cache and its lock. +

+ effective_candidates() checks, locks, checks again, + then publishes +

+

+ fastapi/routing.py:1587-1610

- +
def effective_candidates(self) -> list["_EffectiveRouteContext | _IncludedRouter"]:
+    routes_version = self.original_router._get_routes_version()
+    if routes_version == self._effective_candidates_version:
+        return self._effective_candidates
+    with self._effective_routes_lock:
+        routes_version = self.original_router._get_routes_version()
+        if routes_version == self._effective_candidates_version:
+            return self._effective_candidates
+        effective_candidates: list[_EffectiveRouteContext | _IncludedRouter] = []
+        for route in self.original_router.routes:
+            if isinstance(route, _IncludedRouter):
+                child_context = self.include_context.combine(route.include_context)
+                child_branch = _IncludedRouter(
+                    original_router=route.original_router,
+                    include_context=child_context,
+                )
+                effective_candidates.append(child_branch)
+                continue
+            route_context = self._build_effective_context(route)
+            if route_context is not None:
+                effective_candidates.append(route_context)
+        self._effective_candidates = effective_candidates
+        self._effective_candidates_version = routes_version
+        return effective_candidates

- effective_low_priority_routes does not keep the child - at all. It builds one, calls the child's method once, extends the - flattened result into its own list, and drops the child. So that - recursion always runs against a cold cache. + The first four lines are unchanged. When the stamp matches, the + method returns the cached list before it reaches the lock, so a + wrapper whose list is built serves requests the way it did before.

-

- So one nested router is represented by more than one - _IncludedRouter. Two persist: - include_router appends one into the parent's - routes, which is the object the - isinstance check reads during a rebuild, and the - rebuild then constructs a second and stores it in the parent's - candidate cache. A third exists only while a low-priority rebuild is - in flight, and is dropped when it ends. None of them share a cache - or a lock. + On a mismatch, the thread enters + with self._effective_routes_lock: (fastapi/routing.py:1591), and only one thread per wrapper gets past that line at a time. + The check inside the lock (fastapi/routing.py:1592-1594) calls _get_routes_version() afresh and compares + again. A thread that waited while another built finds the stamp + current here and returns the list the other thread published.

-

- That is also why the recursion cannot deadlock. - threading.Lock is not reentrant, so a thread that holds - one and tries to acquire the same one again blocks forever. Here the - parent holds its own lock while the child acquires the child's, and - those are different objects. The throwaway child's lock is one no - other thread can reach at all. + The build appends to a local variable, also named + effective_candidates (fastapi/routing.py:1595), instead of to self._effective_candidates. The loop body is the old one, + indented under the with, and it walks + self.original_router.routes directly instead of through + the old candidates name. No other thread can reach the + local list while it fills.

- -

7. The two tests

- -

tests/test_router_include_context.py:903

-
-def test_included_router_candidate_cache_is_thread_safe():
-    router = APIRouter()
-    route_count = 120
-    thread_count = 6
-

- The test uses the same shape as the discussion's example code, 120 - routes and six threads, driven through the internal API instead of - test clients. It releases the six threads simultaneously through a - threading.Barrier, and each calls - effective_candidates() on a cold cache. Then four - assertions, at lines 929 to 932: + The last three lines publish it (fastapi/routing.py:1608-1610). The list goes onto the wrapper first and the stamp second. The + order matters because the check before the lock reads both + attributes with no lock held, so a thread that sees the new stamp + also sees the new list.

- -
-    assert len(results) == thread_count
-    assert all(result is results[0] for result in results)
-    assert len(results[0]) == route_count
-    assert TestClient(app).get("/items/0").json() == {"index": 0}
-

- The second is the interesting one. It uses - is, not ==, so it demands that all six - threads received the same list object. The third pins the count at - exactly 120, which is the assertion the duplication would break. The - fourth checks that routing still works afterwards. + The first new test, + test_included_router_candidate_cache_is_thread_safe + (tests/test_router_include_context.py:903), uses the sizes from the discussion's reproduction: 120 routes and + six threads. A + threading.Barrier (tests/test_router_include_context.py:916) releases the six threads together, and each calls + effective_candidates() on the unbuilt wrapper. The test + asserts that all six got the same list object (tests/test_router_include_context.py:930), that it holds 120 entries (tests/test_router_include_context.py:931), and that a request for /items/0 still answers.

+

+ effective_low_priority_routes() repeats the pattern + under the same lock +

- On the pre-fix code this test can pass. It is a real race and - nothing in it forces a schedule, so a run where the threads do not - interleave would report green. The discussion's author ran the - equivalent script and recorded corruption in five runs out of five, - with the counts listed above, which is the only frequency evidence - either the report or this page has. + The second method gets the same moves: the unchanged check before + the lock (fastapi/routing.py:1613-1615), the lock (fastapi/routing.py:1616), the check inside it (fastapi/routing.py:1617-1619), and a local list (fastapi/routing.py:1620). It takes the same _effective_routes_lock as + effective_candidates(), so one wrapper never builds + both of its lists at the same moment. Its ending differs, because it + folds nested routers in as it goes:

- -

tests/test_router_include_context.py:935

-
-def test_included_router_low_priority_cache_rechecks_version_after_lock(monkeypatch):
- -

- The second test targets the branch that only exists because of this - change: the early return inside the lock. It holds the lock on the - main thread, starts a worker, waits on an - Event to prove the worker has already failed the - outside check, then sets the version to current and releases the - lock. The worker acquires it, re-checks, finds the version now - matches, and returns early. +

+ fastapi/routing.py:1625-1637

- +
for route in self.original_router.routes:
+    if isinstance(route, _IncludedRouter):
+        child_context = self.include_context.combine(route.include_context)
+        child_branch = _IncludedRouter(
+            original_router=route.original_router,
+            include_context=child_context,
+        )
+        effective_low_priority_routes.extend(
+            child_branch.effective_low_priority_routes()
+        )
+self._effective_low_priority_routes = effective_low_priority_routes
+self._effective_low_priority_routes_version = routes_version
+return effective_low_priority_routes

- That test fails deterministically on the pre-fix code, and not - because of timing: the lock attribute does not exist there, so - reaching for it raises AttributeError on every run. + For each router included inside original_router, the + method makes a child_branch and calls the child's + effective_low_priority_routes() while it still holds + its own lock. The child is a new wrapper with a new lock of its own, + from the dataclass field, so that inner call checks and takes the + child's lock, not the parent's. The parent copies the child's + entries into its local list with extend and then drops + the child. Publishing keeps the same order: list, then stamp.

- +
+ Out of scope + The lock keeps two threads from building one wrapper's lists at + once. Two different wrappers can still build at the same moment. A + build creates model fields for each API route, and each + ModelField enters warnings.catch_warnings() + (fastapi/_compat/v2.py:142), which saves and restores the process-wide + warnings.filters. The discussion traces its third + symptom, the stray filter entries, to those calls overlapping, and + this change does not touch that code. The reply says that code "will + be refactored either way". +

- The file holds 40 tests in total, counted with - grep -c "^def test_\|^async def test_". + The second new test, + test_included_router_low_priority_cache_rechecks_version_after_lock + (tests/test_router_include_context.py:935), aims at the check inside the lock. It includes an empty router + and uses monkeypatch.setattr to replace that router's + _get_routes_version() with a stub, get_routes_version (tests/test_router_include_context.py:943-945), which sets a threading.Event named + version_checked and returns a fixed version. Then it + runs this:

- -

8. What the change does not do

- -

- The discussion's third symptom, leaking global warning filters, is - not fixed here. Building a model field opens - warnings.catch_warnings(), which saves the - process-global filter list and restores it on exit. Overlapping - builds save and restore each other's copies, so the last restore - wins and entries leak. +

+ tests/test_router_include_context.py:953-958

- +
with included_router._effective_routes_lock:
+    thread = threading.Thread(target=build_low_priority_routes)
+    thread.start()
+    assert version_checked.wait(timeout=1)
+    included_router._effective_low_priority_routes_version = routes_version
+thread.join()

- Serializing one router's rebuild removes those overlapping builds. - It does not make catch_warnings thread-safe, and model - fields are built on other paths too. The maintainer wrote in the - discussion: "For the warnings, it's also pretty much harmless and - that will be refactored either way so it should be fine." + The main thread holds the wrapper's lock, starts a thread that calls + effective_low_priority_routes(), waits for version_checked, + stamps the wrapper with the current version, and only then releases + the lock. In that schedule the thread, once it holds the lock, finds + the stamp current and returns from inside the with + block. The final assertion, result == [[]] (tests/test_router_include_context.py:960), holds on either path. result collects the thread's + return value, so [[]] means one empty list, and an empty + router rebuilds to an empty list too. So what the test adds is a run through that return. + That looks aimed at test coverage, which CI holds at 100% (.github/workflows/test.yml:242), + though nothing in the record says so.

- -
- The assumption underneath - Any unlocked fast path over a published value rests on a memory - model: the reader that sees the new flag has to see the new value - too. On a build with the global interpreter lock, that follows from - how attribute stores work, and this code takes that route. On a - free-threaded build the question is a different one, and this - repository runs its tests against both, including - 3.14t in its CI matrix. So when you read a pattern like - this one, the interpreter it runs under is part of the pattern. -
- -
- The transferable part - When you cache something built in steps, build it somewhere private - and publish it once. The lock is about who does the work; the local - variable is about what everyone else can see while it happens, and - those are different problems. Then order the publishing writes so - that the flag saying "this is ready" is written last. Anything else - leaves a window in which the flag says ready and the state is not, - and a reader that trusts the flag has no way to find out otherwise. -

Quiz

- -

- Five questions about why the change is shaped the way it is. Click - an option to see the answer. -

-

- 1. The fix assigns the list, then stamps the version. If those two - lines were swapped, what would a reader on the unlocked fast path - see? + Before this change, a router has three routes. Threads A and B + both read the stamp as None. A resets the list, then + B resets it, then both run their loops to the end. How many + entries does _effective_candidates hold afterward?

+
- Holding the lock does not stop a fast-path reader, because that - reader never acquires it. The invariant is that the version means - "the list is complete", and stamping first breaks it in the - direction that cannot recover: the reader passes the check, so it - never looks again. The current order fails in the harmless - direction instead, costing one unnecessary lock acquisition. + The old loop called self._effective_candidates.append(), + which looks the attribute up again on every call. After B's reset, + that attribute names B's list, so both loops append there and the + list A assigned is dropped empty. Which thread stamps last does not + matter, because both write the same version. This is how the + reporter's run ended with 283 entries for 120 routes, and why the + merged code appends to a local variable.

- 2. Suppose the change had added the lock and the double check, but - kept building the list in place on self. Would that - have fixed the reported 404s? + Suppose _effective_routes_lock were one lock shared by + every wrapper instead of one per instance. The app includes a + router that itself includes another router. What happens to the + first request that matches no regular route and falls through to + the low-priority routes?

- +
- That is the difference between what the lock fixes and what the - local list fixes. A commenter on the discussion put it directly: - "The second point is important even with a lock: publishing a - mutable empty list before it is complete creates an observable - invalid state." The lock does fix the duplication, since only one - thread appends at a time. It does nothing for the reader that - trusts a stamped version. + effective_low_priority_routes() creates each + child_branch and calls the child's method while it + still holds the parent's lock. With one lock per instance, that + call takes the child's own lock. With one shared lock, the thread + asks for a lock it already holds, and a + threading.Lock is not reentrant, so the thread waits + forever. The regular path escapes this, because + effective_candidates() only creates the children; they + build their own lists later, from _match(), after the + parent has released the lock.

- 3. Why does the version get checked a second time, immediately - after the lock is acquired? + The discussion proposed building into a local list and publishing + it, with no lock. Compared with that proposal, what does the merged + version add?

+ -
- Without it, six threads arriving at a cold cache would rebuild the - list six times in sequence, each discarding the previous result. - The version can also change during the wait, and the re-read - handles that too, but the reason the check earns its place is the - queued-threads case. Reentrancy is a separate matter, and the - recursion in this class always crosses to a different lock object. + Both versions publish only a finished list, so both close the + empty-list window and the shared-append duplication, and in both a + request on a built wrapper skips the lock. The lock and the check + inside it add one thing: threads that arrive while the list is + unbuilt wait, then take the builder's list, so the build runs once + per wrapper instead of once per thread. The six-thread test checks + that with result is results[0]. The reporter + also noted that free-threaded Python builds may want the lock + anyway.

- 4. The lock field is declared with - compare=False. What breaks without it? + In + test_included_router_low_priority_cache_rechecks_version_after_lock, + delete the line assert version_checked.wait(timeout=1) + and keep everything else. What can now happen?

+
- A bare @dataclass generates __eq__ from - the tuple of fields that opt in, so a field with identity-only - equality poisons the comparison. Per-instance locks come from - default_factory, which is a different keyword and the - reason the shared-default answer is wrong. + Without the wait, the main thread can stamp the wrapper before the + new thread has read the version at all. The thread's check before + the lock then matches, it returns at once, and the return inside + the with block never runs. The test still passes, + because the result is [[]] either way, so nothing + reports the lost path. The stub sets version_checked + from inside that check, so the wait holds the stamp back until the + thread has started reading the version. The thread then nearly + always reaches the lock first, though nothing strictly forces it.

- 5. effective_low_priority_routes holds its own lock, - then recurses into a child _IncludedRouter that - acquires a lock too. threading.Lock is not reentrant. - Why is that not a deadlock? + The app runs under a server with one event loop, so every request + is a coroutine on the same thread. Two requests arrive together at + an app whose lists are unbuilt. What does the second request do + when it reaches effective_candidates()?

+ -
- Each instance gets its own lock from - default_factory, so parent and child never contend. - The recursion does happen inside the parent's - with block, and if the child shared the parent's lock - this would hang on the first nested router. Python has - RLock for the case where re-acquiring is wanted, and - this code does not need it. + Coroutines on one event loop switch only at an await. + APIRouter.app reaches + effective_candidates() through ordinary function + calls, and the rebuild has no await inside, so the + first request finishes the build and the stamp before the loop can + run the second. The second request returns at the check before the + lock and never touches it. That matches the discussion's note that a + single-loop server does not contend on the rebuild.
diff --git a/samples/fastapi/2026-09-01-pr-16102-explanation.html b/samples/fastapi/2026-09-01-pr-16102-explanation.html index cab7f5d..bf60b9c 100644 --- a/samples/fastapi/2026-09-01-pr-16102-explanation.html +++ b/samples/fastapi/2026-09-01-pr-16102-explanation.html @@ -3,7 +3,7 @@ - FastAPI PR 16102 explanation + PR 16102 explanation @@ -539,889 +636,682 @@
-

A default that asks where it is running

+

FastAPI PR 16102: check_dir="auto" for app.frontend()

- FastAPI - pull request 16102 - changes one default from True to - "auto". Getting that to work needed a function that - collapses the third value immediately, and a fixed stack depth so the - warning blames the right line. + The check_dir argument of app.frontend() and + router.frontend() now defaults to "auto", which turns a + missing frontend folder into a warning when FASTAPI_ENV is + "development", the value fastapi dev sets, and keeps the + error at app creation for any other FASTAPI_ENV value, or none.

- fastapi/fastapi PR 16102 at 7abcdfb, explained 2026-09-01. References link to this commit, except one naming a file that is not in the repository. + fastapi/fastapi + PR 16102 at 7abcdfb, + explained 2026-11-16. References link to this commit.

Background

-
- New to serving a frontend from FastAPI? Expand for the deeper - background. + New to this area? Expand for the deeper background.

- A single-page application is, once built, a folder of files. A - build tool reads your source and writes HTML, JavaScript, and CSS - into an output directory, conventionally named - dist or build. -

-

- You can serve that folder from the same FastAPI application that - serves your API, which means one deployment instead of two. - app.frontend() does it: -

-
app = FastAPI()
-
-@app.get("/api/users")
-def read_users():
-    return [{"name": "Ada"}]
-
-app.frontend("/", directory="dist")
-

- The frontend is added as low-priority routes, meaning FastAPI - tries them last. So /api/users still reaches your - endpoint, and everything else falls through to the files in - dist. The class that serves those files is called - _FrontendStaticFiles, and it sits at the bottom of - this story. + FastAPI added app.frontend() in + PR 15800. It serves the + static files a frontend build tool writes into a folder, usually dist, + from inside the FastAPI app. The files sit on low-priority routes: FastAPI path + operations match first, and a request reaches the files only when no path operation + matched. router.frontend() does the same on an APIRouter.

- One more piece of vocabulary. An APIRouter is a group - of routes you can build separately and attach to an application, - the way a Django or Flask developer would think of a blueprint. - FastAPI holds one internally, so - app.frontend() does its work by calling - router.frontend() on it. Both are public, and both - matter later. + fastapi dev and fastapi run are commands from the separate + fastapi-cli package, which the fastapi[standard] extra + installs. fastapi dev starts a reloading server for local work, and + fastapi run starts one for production. Both import your module, so a + module-level call such as app.frontend("/", directory="dist") runs once + while the app is created, before any request arrives. An extra is a named group of + optional dependencies, such as standard.

- One detail matters for what follows. That last line runs when the - module is imported, at application startup, long before any - request arrives. So FastAPI has a choice: check that - dist exists now, or wait and fail when someone asks - for a file. + An environment variable is a named string a process receives when it starts. Python + reads them through os.environ, and child processes inherit them. + os.environ.setdefault(name, value) writes the value only when the name + is absent.

- Checking now is usually right. A missing directory is a deployment - mistake, and a crash at startup is far easier to diagnose than a - broken page in production. Programmers call this failing fast. + warnings.warn(message) reports a problem without stopping the program. + With no category it emits a UserWarning, which Python's default filters + print to standard error with a file name and line number. Each function call still + running is a frame on the call stack, and the stacklevel argument + picks whose file and line the warning reports: 1 is the line that calls + warnings.warn, 2 is the line that called the function + holding it, and 3 goes one caller further up.

- Before this change, app.frontend() took a boolean, and - it defaulted to checking: + Before this change, check_dir was a bool that defaulted to + True on both public methods: FastAPI.frontend, the method + app.frontend() calls, and APIRouter.frontend, the method + router.frontend() calls. Each parameter is declared as + Annotated[type, Doc(...)], which attaches its documentation to its type. + The value travels this chain, in order:

- -

fastapi/applications.py, before the change

-
check_dir: Annotated[
-    bool,
-    Doc(
-        """
-        Check that the frontend directory exists when the app is created.
-        """
-    ),
-] = True,
- +
    +
  1. FastAPI.frontend passes it to its router's APIRouter.frontend.
  2. +
  3. + APIRouter.frontend hands it to + _FrontendRouteGroup.add_frontend_route, which collects the router's + frontend routes. +
  4. +
  5. add_frontend_route builds a _FrontendRoute, the route object that matches paths.
  6. +
  7. + _FrontendRoute builds a _FrontendStaticFiles, FastAPI's + subclass of Starlette's StaticFiles, which serves the files. +
  8. +

- The check lives at the bottom of the stack, in - _FrontendStaticFiles, the class that serves the files. - It is five lines, and it raises before the application object - finishes being built. + _FrontendStaticFiles.__init__ is where the value is used. When + check_dir is true and the folder is missing, it raises + RuntimeError with the folder name and its absolute path, which + _get_resolved_absolute_path computes. The fallback argument + names the file served for a path with no matching file. When check_dir + is true and fallback is "index.html" or + "404.html", _check_fallback_file also confirms that file + exists. Starlette's StaticFiles constructor runs its own folder check + when it gets a true check_dir. With check_dir=False, all + three checks are skipped, and Starlette's check_config runs on the first + request instead, raising if the folder is still missing. +

+

+ So the old default made a missing dist fatal at app creation. + The pull request body names the case: "Frontend build output might not exist yet when + starting the backend during development." check_dir=False avoided the + crash, but it also dropped the error at app creation in production, where the body + says missing files should keep "failing early".

- -

fastapi/routing.py:1907

-
if check_dir and not os.path.isdir(directory):
-    raise RuntimeError(
-        f"Frontend directory '{directory}' does not exist. "
-        f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'"
-    )
-

- Now consider running that on your laptop. You clone the repository, - create a virtual environment, start the API to work on an endpoint, - and the process refuses to boot, because you have not run the - frontend build and dist does not exist. You did not - want the frontend. You wanted the endpoint. + The change adds one input, the FASTAPI_ENV environment variable. No code + in the fastapi package reads it at the pull request's base commit, + 628663f. fastapi-cli 0.0.32 sets it inside fastapi dev with + os.environ.setdefault("FASTAPI_ENV", "development"), at + src/fastapi_cli/cli.py:402 in that release. + fastapi-cli PR 477 added + that line, and it is the only place the CLI sets the variable, so + fastapi run leaves it unset. fastapi dev is where the flow + map at the top of the Code section starts: it sets the variable, then imports the + module that calls app.frontend().

Key concept - The same check is right in one place and wrong in another. In - production a missing build directory is a deployment failure and - should stop the process. On a developer's machine it is Tuesday. + A frontend folder can be checked at two moments: at app creation, when + app.frontend() runs during import, or at the first request, when + Starlette's check_config runs. check_dir=True picks app + creation and check_dir=False picks the first request. The new + "auto" value picks one of those two moments when + app.frontend() runs.
- -

- One workaround is check_dir=False. It also silences the - check in production, where you wanted it, so quieting a local - annoyance costs the safeguard everywhere. -

Intuition

-

- The change gives the option a third value. Instead of yes or no, the - default is now "auto", meaning: decide for me, based on - where I am running. + "auto" is a question FastAPI answers when app.frontend() + runs: is this a development process? A helper named + _resolve_frontend_check_dir asks it. If FASTAPI_ENV is + exactly "development", the answer becomes check_dir=False, + with a warning when the folder is missing. Any other value, or no value, becomes + check_dir=True, which this page calls the strict branch. From there on, + only code that already existed runs.

- -

- The signal is an environment variable. When - FASTAPI_ENV is "development", a missing - directory produces a warning and the application starts. Anywhere - else, it raises as before. -

-

- You do not set that variable yourself. The - fastapi dev command sets it for you, which is what makes - the default useful: run your project the way you already run it - locally, and the friendlier behavior follows. That command ships in a - separate package, and section 6 of the walkthrough returns to what - this repository can and cannot prove about it. + Take a main.py that calls app.frontend("/", directory="dist"), + in a project where no dist folder exists yet:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
check_dirFASTAPI_ENVDirectoryWhat happens at startup
"auto"developmentmissingWarning. The application starts
"auto"developmentpresentNothing. The application starts
"auto"anything else, or unsetmissingRuntimeError
TruedevelopmentmissingRuntimeError
Falseanymissing - Nothing at startup. RuntimeError per request -
What happens when the app is created, with no dist folder and + nothing exported unless the row says so
Started withFASTAPI_ENVAt app creation
fastapi dev"development", set by the commandWarning, and the server starts
fastapi rununsetRuntimeError
uvicorn main:app"staging", exported by handRuntimeError
fastapi dev, with check_dir=True"development", set by the commandRuntimeError
- -

- Row four matters most. Passing check_dir=True still - means check, even in development. The convenience is in the default, - and an explicit value always wins. -

-

- Row five is worth a second look, because False does not - mean safe. It moves the failure rather than removing it: the - application starts, and then the first request for a file raises - RuntimeError from inside the static-file layer, which - reaches the client as a 500. The test for that behavior is named - test_check_dir_false_allows_missing_directory_and_fails_on_request, - which says it plainly. + In development the folder check moves to request time. Starlette sets its + config_checked flag only after check_config passes, at + starlette/staticfiles.py:93-95 in Starlette 1.3.1, + the version the repository's lock file, uv.lock, pins. So within one + process, a request that fails before the frontend build runs does not block requests + made after the build writes dist:

- -

What the developer sees

- -
-
Before: fastapi dev, with no frontend built
-
RuntimeError: Frontend directory 'dist' does not exist. -Resolved absolute path: '/home/ada/project/dist'
-
-

- The process exits. To work on an API endpoint you must either build - the frontend or edit the source to pass - check_dir=False. -

- -
-
After: fastapi dev, with no frontend built
-
main.py:8: UserWarning: Frontend directory 'dist' does not exist. -Resolved absolute path: '/home/ada/project/dist' - -INFO: Uvicorn running on http://127.0.0.1:8000
-
-

- The server starts. Note the first token: the warning is attributed to - main.py:8, the line in your own file that called - app.frontend(). Getting that attribution right is what - most of this page is about. -

- -

Three values in, two values out

- -

- A three-valued option is a hazard if the third value is allowed to - travel. Every layer downstream would have to know what - "auto" means. Concretely: the class that serves the - files would read FASTAPI_ENV to decide whether to raise, - and the class above it would read it again to decide whether to warn. - Two readings, two chances to disagree. -

- -

- So the change resolves it once, immediately, at the public surface. - One small function turns bool | Literal["auto"] into a - plain bool, and everything below it receives a value - that carries no ambiguity. -

- -

The one place the third value exists

-
-
your code
-
-
- "auto" -
-
app.frontend
-
-
-
- "auto" -
-
the resolver
-
-
-
- False -
-
everything below
-
-
- -

- The type says this out loud. The resolver's return annotation is - bool, so "auto" cannot leave it, and the - three internal layers below now declare - check_dir: bool with no default at all. A caller that - forgets to pass it gets a TypeError rather than a - silent True. -

- -

- The whole decision, in one picture. Read the top half as the - resolver and the bottom half as the layer that mounts the files. -

- -
flowchart TD
-    A["app.frontend(directory='dist')"] --> B{"check_dir is 'auto'?"}
-    B -->|no. True or False| C["return it unchanged"]
-    B -->|yes| D{"FASTAPI_ENV is 'development'?"}
-    D -->|no| E["return True. check the directory"]
-    D -->|yes| F{"directory exists?"}
-    F -->|yes| G["return False. nothing to warn about"]
-    F -->|no| H["warn at stacklevel 3<br/>then return False"]
-    C --> I["_FrontendStaticFiles"]
-    E --> I
-    G --> I
-    H --> I
-    I --> J{"check_dir and directory missing?"}
-    J -->|yes| K["raise RuntimeError"]
-    J -->|no| L["mount the static files"]
- -
- Edge case - Follow the yes branch out of "directory exists?". It - returns False, which switches off the downstream check - even though that check would have passed. The resolver has already - looked at the filesystem itself, so re-checking would be redundant - work with the same answer. Harmless here, and worth noticing: the - return value means "has this been settled", not "does the directory - exist". -
+
    +
  1. + 1fastapi dev sets + FASTAPI_ENV=development, then imports main.py +
  2. +
  3. + 2app.frontend("/", directory="dist") warns that + dist does not exist, and the server starts +
  4. +
  5. + 3GET / gets a 500: check_config finds + no dist, so config_checked stays false +
  6. +
  7. 4The frontend build writes dist/index.html
  8. +
  9. + 5GET / gets a 200: check_config passes + and the file is served +
  10. +

Code walkthrough

-

- The flow, end to end: your code calls - app.frontend(), the resolver collapses three values into - two, and a plain boolean travels down four functions to the class - that serves the files, which either raises or mounts them. The chain - is FastAPI.frontend, then - APIRouter.frontend, then - add_frontend_route, then _FrontendRoute, - then _FrontendStaticFiles. Only the last one acts on the - value; the rest pass it along. + Flow: fastapi dev sets FASTAPI_ENV → + app.frontend() or router.frontend() accepts + "auto" → _resolve_frontend_check_dir turns it into a bool → + _FrontendStaticFiles raises at app creation or leaves the check to the first + request.

+

Both public methods accept "auto" and default to it

- Six files changed: two in the library, one the docs, one the tests, - and two the dependency pins. + FastAPI.frontend and APIRouter.frontend declare + check_dir with the same annotation and the same docstring. The type + widens from bool to bool | Literal["auto"], and the default + changes from True to "auto". Literal["auto"] + is a typing form that admits exactly the string "auto", so a type checker + still rejects check_dir="yes".

- -

1. The public surface, twice

- -

- frontend() exists on both FastAPI and - APIRouter, with the same signature. Both change - identically. +

+ fastapi/applications.py:1249-1259

- -

fastapi/applications.py:1249

-
         check_dir: Annotated[
--            bool,
-+            bool | Literal["auto"],
-             Doc(
-                 """
--                Check that the frontend directory exists when the app is created.
-+                Check that the frontend directory exists when the app is created. When
-+                set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is
-+                `"development"`, and check it otherwise. The `fastapi dev` command
-+                sets `FASTAPI_ENV` to `"development"` if it is not already set.
-                 """
-             ),
--        ] = True,
-+        ] = "auto",
- +
        check_dir: Annotated[
+            bool | Literal["auto"],
+            Doc(
+                """
+                Check that the frontend directory exists when the app is created. When
+                set to `"auto"`, skip the check with a warning when `FASTAPI_ENV` is
+                `"development"`, and check it otherwise. The `fastapi dev` command
+                sets `FASTAPI_ENV` to `"development"` if it is not already set.
+                """
+            ),
+        ] = "auto",

- The same hunk lands on APIRouter.frontend at - fastapi/routing.py:2645. Changing a default is a - compatibility decision, and this one is safe in the direction that - matters: code that passed an explicit - True or False behaves exactly as before, - and code that passed nothing only becomes more permissive, and only - when FASTAPI_ENV says development. + The router's copy at + fastapi/routing.py:2645-2655 + matches it line for line. A caller who already passes check_dir=True or + check_dir=False keeps the old behavior, because the helper in the next + step returns both unchanged. Only callers who relied on the default see a difference, + and only when FASTAPI_ENV is "development".

-

2. The resolver

- -

fastapi/routing.py:1880

-
def _resolve_frontend_check_dir(
-    *,
-    directory: str | os.PathLike[str],
-    check_dir: bool | Literal["auto"],
-) -> bool:
-    if check_dir != "auto":
-        return check_dir
-    if os.environ.get("FASTAPI_ENV") != "development":
-        return True
-    if not os.path.isdir(directory):
-        warnings.warn(
-            f"Frontend directory '{directory}' does not exist. "
-            f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'",
-            stacklevel=3,
-        )
-    return False
- +

_resolve_frontend_check_dir turns "auto" into a bool

- Sixteen lines, and each one is an early exit. Read the signature - first: it takes bool | Literal["auto"] and returns - bool. That narrowing is the function's whole purpose. It - converts a wider type into a narrower one, so nothing downstream has - to handle the wider case. + The new helper sits in fastapi/routing.py, and both public methods call + it. It takes the folder and the raw argument, and it always returns a plain + bool.

- -

- Note how it reads the environment: an inequality against one exact - string. Any other value takes the strict branch, so - FASTAPI_ENV=dev is not development, and neither is - Development. That is a reasonable choice given who - writes the variable, which is a tool rather than a person, though the - code does not say so and I am inferring it. +

+ fastapi/routing.py:1880-1895

- -

3. Why calling it twice is safe

- +
def _resolve_frontend_check_dir(
+    *,
+    directory: str | os.PathLike[str],
+    check_dir: bool | Literal["auto"],
+) -> bool:
+    if check_dir != "auto":
+        return check_dir
+    if os.environ.get("FASTAPI_ENV") != "development":
+        return True
+    if not os.path.isdir(directory):
+        warnings.warn(
+            f"Frontend directory '{directory}' does not exist. "
+            f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'",
+            stacklevel=3,
+        )
+    return False
+

The three if statements run in order:

+
    +
  • + Any value other than "auto" goes straight back. That is the + pass-through for explicit True and False. +
  • +
  • + Outside development the answer is True, the strict branch. + os.environ.get returns None for an unset variable, and + None is not "development", so an unset variable lands here + too. +
  • +
  • + In development, the helper warns if the folder is missing and then returns + False. The return False sits outside the if, + so in development the answer is False whether or not the folder exists. + The warning is then the only signal at app creation, and it covers only a missing + folder. +
  • +

- FastAPI.frontend resolves, then delegates to - APIRouter.frontend, which resolves again. On the - app.frontend() path the resolver runs twice for one - call. + The warning text repeats the RuntimeError message that + _FrontendStaticFiles raises at + fastapi/routing.py:1909-1910, so the same folder name and absolute path appear whichever branch runs.

- -

fastapi/applications.py:1291

-
+        check_dir = routing._resolve_frontend_check_dir(
-+            directory=directory, check_dir=check_dir
-+        )
-         self.router.frontend(
-             path,
-             directory=directory,
-             fallback=fallback,
-             check_dir=check_dir,
- +
+ Edge case + The comparison is != against the exact string + "development". A hand-set Development, dev, or + development with a trailing space takes the strict branch, and the app + raises at app creation when the folder is missing. +

- The first line of the resolver is what makes that harmless. It - returns bool, so the second call receives - True or False, and - check_dir != "auto" sends it straight back out. The - function is idempotent: applying it twice gives the same answer as - applying it once, because every value it can return falls into its - own early-exit branch. + pyproject.toml raises the fastapi-cli minimum version in + three extras, so installing fastapi[standard] brings a CLI that sets the + value. At + pyproject.toml:61, + pyproject.toml:80, and + pyproject.toml:98, the standard, standard-no-fastapi-cloud-cli, and + all extras move from >=0.0.8 to >=0.0.32. + The + fastapi-cli 0.0.32 + release is the one that sets FASTAPI_ENV. With an older CLI, the + variable stays unset, and "auto" takes the strict branch even under + fastapi dev.

+

Each public method resolves first, so the warning names the caller's line

- The warning depends on that early return, as the next step shows. + FastAPI.frontend calls the helper before it delegates, and hands its + router the result rather than the raw argument:

- -

4. Counting frames

- -

- A warning is only useful if it points at the line that caused it. - Python's warnings.warn takes a - stacklevel argument saying which frame to blame, - counting from the frame that contains the - warnings.warn call itself as 1. The change passes - stacklevel=3. +

+ fastapi/applications.py:1291-1299

- +
        check_dir = routing._resolve_frontend_check_dir(
+            directory=directory, check_dir=check_dir
+        )
+        self.router.frontend(
+            path,
+            directory=directory,
+            fallback=fallback,
+            check_dir=check_dir,
+        )

- So the question is what sits in position 3. Here is the stack when - your code calls app.frontend(), counted the way - stacklevel counts. The highlighted frame is the one - stacklevel=3 selects. + APIRouter.frontend makes the same call at the top of its body, so a + router.frontend() call from user code resolves there:

- -
    -
  1. - 1the warn call, inside - _resolve_frontend_check_dir   routing.py:1890 -
  2. -
  3. - 2FastAPI.frontend   - applications.py:1291 -
  4. -
  5. - 3your code   main.py:8 -
  6. -
- -

And when your code calls router.frontend() instead:

- -
    -
  1. - 1the warn call, inside - _resolve_frontend_check_dir   routing.py:1890 -
  2. -
  3. - 2APIRouter.frontend   routing.py:2689 -
  4. -
  5. - 3your code   main.py:8 -
  6. -
- +

+ fastapi/routing.py:2689-2691 +

+
        check_dir = _resolve_frontend_check_dir(
+            directory=directory, check_dir=check_dir
+        )

- Your code lands in position 3 on both paths, so - stacklevel=3 is correct for both. Called from lower - down, in add_frontend_route or below, the distance to - user code would differ by entry point and no single number would - work. That looks like why the resolver is called at the top of each - public method, though the code does not say so. + When user code calls app.frontend(), the helper therefore runs twice. The second + run gets a bool, the helper's opening if returns it unchanged, and no second warning fires.

-

- Now recall step 3. On the app.frontend() path the - resolver is reached a second time, through - APIRouter.frontend. Count that stack the same way: + The double call keeps the warning's location in user code. That looks like the reason + the helper runs in both methods rather than only in the router, though the code does + not say so; the tests below show the location is intended. + stacklevel=3 counts three frames up from the warnings.warn + call. When main.py calls app.frontend(), the frames are:

-
  1. - 1the warn call, inside - _resolve_frontend_check_dir   routing.py:1890 + 1 + fastapi/routing.py:1890 + warnings.warn(...) in the helper
  2. - 2APIRouter.frontend   routing.py:2689 + 2 + fastapi/applications.py:1291 + FastAPI.frontend calls the helper
  3. - 3FastAPI.frontend   - applications.py:1294 -
  4. -
  5. - 4your code   main.py:8 + 3 + main.py, the line app.frontend("/", directory="dist"), + which the warning names
-

- One frame deeper, so position 3 is now FastAPI's own source. A - warning from this second call would blame - applications.py instead of your file, and the reader - would get two warnings for one mistake. The early return at - check_dir != "auto" is what stops the second call before - it reaches the warn. + If FastAPI.frontend passed "auto" through, the warning would + come from the router's call at + fastapi/routing.py:2689 + instead. The stack + would gain a frame, and level 3 would land on the self.router.frontend( + call inside FastAPI, which sits at + fastapi/applications.py:1294 + in the merged code. Because each public method resolves + at its top, the user's call is frame 3 from either method.

-

- Two tests pin exactly this, one per entry point, and both assert on - the filename rather than the message. + The tests pin that location. pytest.warns records the warnings raised + inside its block, and + tests/test_frontend.py:1194 + asserts warnings[0].filename == __file__, the test file's own path, for + app.frontend(). + tests/test_frontend.py:1204 + asserts the same for router.frontend(), in a test named + test_check_dir_auto_router_warning_points_to_user_code. The Validation + section of the pull request body says the author saw the warning "at the user call + site".

- -

tests/test_frontend.py:1197

-
def test_check_dir_auto_router_warning_points_to_user_code(monkeypatch, tmp_path: Path):
-    monkeypatch.setenv("FASTAPI_ENV", "development")
-    router = APIRouter()
-
-    with pytest.warns(UserWarning, match="does not exist") as warnings:
-        router.frontend("/", directory=tmp_path / "missing")
-
-    assert warnings[0].filename == __file__
-

- warnings[0] also quietly asserts there is a first - warning to inspect, and the app-path test at - tests/test_frontend.py:1186 makes the same assertion - from the side where a duplicate could appear. + The other new tests cover the strict branches. Explicit check_dir=True still + raises under development at + tests/test_frontend.py:1207-1212, and "auto" raises under FASTAPI_ENV=production at + tests/test_frontend.py:1215-1220. The existing strict test now passes check_dir=True at + tests/test_frontend.py:1179, so its result no longer depends on what the test process has in + FASTAPI_ENV.

- -

5. Removing a default so it cannot be forgotten

-

- Three internal signatures lose = True. They keep the - type and lose the default. + Below the public methods, the resolved bool reaches _FrontendStaticFiles, + _FrontendRoute, and add_frontend_route, and each signature + drops its default: check_dir: bool = True, becomes + check_dir: bool,. Every internal caller already passed the value, at + fastapi/routing.py:2056, + fastapi/routing.py:2128, and + fastapi/routing.py:2703, so nothing changes at run time. My reading is that a + required argument stops a future internal caller from getting True by + leaving it out; the pull request does not give a reason. The value lands in the + unchanged checks the Background section describes:

- -

fastapi/routing.py:1904, :2047, :2121, one line each

-
-        check_dir: bool = True,
-+        check_dir: bool,
- -

- All three parameters are keyword-only, marked by the bare - * earlier in each signature, so a call site that omits - check_dir now raises TypeError at call time - instead of quietly defaulting to True. Before the - change, a new internal caller that forgot to thread the resolved - value through would have silently reinstated the strict behavior. - Deleting the default removes that failure mode. +

+ fastapi/routing.py:1904-1919

- -

Only the lowest of the three acts on the value.

- -

fastapi/routing.py:1898

-
class _FrontendStaticFiles(StaticFiles):
-    def __init__(
-        self,
-        *,
-        directory: str | os.PathLike[str],
-        fallback: Literal["auto", "index.html", "404.html"] | None,
-        check_dir: bool,
+          
        check_dir: bool,
     ) -> None:
         self.fallback = fallback
         if check_dir and not os.path.isdir(directory):
             raise RuntimeError(
                 f"Frontend directory '{directory}' does not exist. "
                 f"Resolved absolute path: '{_get_resolved_absolute_path(directory)}'"
-            )
- -

- The warning message and the exception message are identical text. - That is what lets the tests match "does not exist" - against both a UserWarning and a - RuntimeError. -

- -

6. The dependency floor

- -

pyproject.toml:61

-
-    "fastapi-cli[standard] >=0.0.8",
-+    "fastapi-cli[standard] >=0.0.32",
- -

- The whole feature rests on something setting - FASTAPI_ENV=development, and that something is the - fastapi dev command, which lives in the separate - fastapi-cli package. The pull request raises that - package's floor from 0.0.8 to 0.0.32 in all - three extras that include it: standard at line 61, - standard-no-fastapi-cloud-cli at line 80, and - all at line 98. The first two request the matching - fastapi-cli extra; all requests - fastapi-cli[standard], the same one line 61 does. - uv.lock follows, moving the resolved version from - 0.0.20 to 0.0.32. -

- -
- What this page cannot show you - fastapi-cli is an external dependency, and - fastapi/cli.py is thirteen lines that try to import it - and raise a helpful error if it is absent. So the claim that - fastapi dev sets - FASTAPI_ENV appears in this repository only as prose, in - two docstrings and one documentation page. Nothing in the library - sets the variable, and no test here can prove the CLI does. The - version floor is the only enforcement, and it is not testable from - this checkout either. Everything else on this page is verifiable - against the code; that one link in the chain is not. -
- -

7. The test that had to change

- -

- Four tests are new. One was edited, and it is the interesting one. -

- -

tests/test_frontend.py:1179

-
-        app.frontend("/", directory="missing")
-+        app.frontend("/", directory="missing", check_dir=True)
- -

- The test asserts that a missing directory raises. It sets no - environment variable, so under the new default it takes the - non-development branch and still raises. It would still pass. -

- + ) + super().__init__( + directory=directory, + html=True, + check_dir=check_dir, + follow_symlink=False, + ) + if check_dir and fallback in {"index.html", "404.html"}: + self._check_fallback_file(fallback)

- What the edit buys is independence from the shell. A developer with - FASTAPI_ENV=development exported would get a warning - instead of the exception, and - pytest.raises(RuntimeError) would fail. FastAPI also - sets filterwarnings = ["error"] in its pytest - configuration, so that warning becomes a - UserWarning exception, which is still not the - RuntimeError the test demands. Pinning - check_dir=True makes the test check the explicit - contract it was always about, whatever the environment says. + The same edit appears at + fastapi/routing.py:2047 + in _FrontendRoute and at + fastapi/routing.py:2121 + in add_frontend_route. The bool also reaches Starlette through + super().__init__, where False skips the check + StaticFiles runs in its constructor and leaves check_config + to run on the first request.

-

The four new tests map onto the four branches of the resolver.

- - - - - - - - - - - - - - - - - - - - - - - - - - - +
TestLineBranch it pins
auto_warns_in_development1186auto, dev, missing: warns, and blames user code
auto_router_warning_points_to_user_code1197the same, through the router entry point
true_fails_in_development1207explicit True beats development mode
auto_fails_outside_development1215 - auto with FASTAPI_ENV=production: still raises -
+ + + + + + + + + + + + + + + + +
+ Every other changed file (2 of 6) +
FileWhy it changed
+ docs/en/docs/tutorial/frontend.md + + The tutorial's Check Directory section now describes the "auto" + default, the FASTAPI_ENV rule, and explicit check_dir=True. +
+ uv.lock + + The lock file records the new fastapi-cli minimum and moves the locked + version from 0.0.20 to 0.0.32. +
- -

- The last one sets production rather than leaving the - variable unset. That pins the resolver's treatment of any - non-development value, which an unset variable would not reach: unset - would pass whether the code compared against one exact string or - merely asked whether the variable had a value at all. -

- -

8. Documentation

- -

docs/en/docs/tutorial/frontend.md:109

-
-By default, `app.frontend()` checks that the directory exists when the app is created.
-+By default, `app.frontend()` uses `check_dir="auto"`.
-+
-+When the `FASTAPI_ENV` environment variable is set to `development`, **FastAPI** only
-+shows a warning if the frontend build output directory is missing. ...
-+
-+In any other environment, **FastAPI** raises an error when the app is created. ...
- -

- The surrounding section, unchanged, already explained - check_dir=False and why the directory might legitimately - be absent when the application object is built: the frontend is - produced by a separate build step. This change adds the case that - sits between always-check and never-check. -

- -
- The transferable part - When one option needs different behavior in different environments, - the shape that works is a widened type at the public boundary and a - resolver that narrows it immediately. Keep the extra value in exactly - one place, return the narrow type so it cannot travel, delete the - defaults underneath so nobody can skip the resolver by accident, and - let an explicit argument always win over the automatic one. Here the - logic took sixteen lines. The stack depth took the care. -

Quiz

- -

- Five questions about why the change is shaped the way it is. Click an - option to see the answer. -

-

- 1. FASTAPI_ENV=development, check_dir left - at its default, and the dist directory - does exist. What does the resolver return? + A project moves its frontend setup into a helper in ui.py: + def mount_ui(app): app.frontend("/", directory="dist"). Then + main.py calls mount_ui(app). Under fastapi dev + with no dist folder, which line does the warning name?

- - - + + + +
- Both development branches return False; the only - difference is whether a warning is emitted on the way. The resolver - has already asked the filesystem, so the downstream check would - repeat that work for the same answer. The return value means "this - is settled", not "the directory exists". And - "auto" can never be returned: the annotation is - bool. + stacklevel=3 counts frames up from the warnings.warn call, + not down from the program's entry point. Level 1 is the warn call, level 2 is + FastAPI.frontend, and level 3 is whatever line called + app.frontend(), which here sits inside mount_ui. The + main.py line is one frame further up. A wrapper around the call moves + the warning's location into the wrapper.

- 2. Why is the resolver called at the top of both - FastAPI.frontend and - APIRouter.frontend, rather than once, lower down, in - add_frontend_route? + A developer's shell profile still exports FASTAPI_ENV=production from + an old deploy script. They run fastapi dev before the frontend has ever + been built. What happens?

- - - + + + +
- From add_frontend_route the distance to user code - differs by entry point, so no single stacklevel could - be right and the warning would point into FastAPI's own source. - add_frontend_route is public, but that is not what - constrains this. The environment is read once either way, and the - ordering does not matter because the second resolver call never - reaches the read. + fastapi dev uses os.environ.setdefault, which writes + "development" only when FASTAPI_ENV is absent. The exported + "production" survives, the helper takes its strict branch and returns + True, and _FrontendStaticFiles raises while the module + imports. Unsetting the variable restores the warning.

- 3. On the app.frontend() path the resolver runs twice - for a single call. In development with a missing directory, why is - there exactly one warning? + Under fastapi dev, a project calls + app.frontend("/", directory="dist", fallback="index.html"). The + dist folder exists, but the build has not written + index.html into it yet. What happens when the app is created?

- - - + + + +
- The early return does the work, and this is why idempotence matters - here rather than being a tidy property. A second warning would also - be attributed to applications.py rather than to the - caller, which is what - assert warnings[0].filename == __file__ would catch. - Python's warning registry does dedupe by location, but relying on - that would be relying on a default a caller can change. + In development the helper returns False whether or not the folder + exists, and it warns only about a missing folder, so this run prints nothing. With + check_dir false, _FrontendStaticFiles also skips + _check_fallback_file, so the missing index.html surfaces + later, as a RuntimeError when a browser navigation needs the fallback. + Once the build writes the file, the same process serves it. Under + fastapi run the same call raises at app creation.

- 4. The three internal signatures went from - check_dir: bool = True to - check_dir: bool. What does deleting the default buy, - given that every existing call site already passes a value? + The "auto" default covers the situation fastapi dev + creates. When is an explicit check_dir=False still the better choice?

- - - + + + +
- The payoff is for call sites nobody has written yet. A silent - True would switch development mode off for whichever - path forgot to pass the value, while the other path kept working, - and nothing would point at the omission. The parameters stay - keyword-only, and the narrowed type is what keeps - "auto" out. + Outside development, "auto" means the strict check, so a process that + only gets its files after import would crash at app creation. check_dir=False + moves that process's check to request time, whatever FASTAPI_ENV says. + The fastapi dev session is the case "auto" already handles, + and the image and the CI job both want the error at app creation that + "auto" keeps.

- 5. An alternative design: drop the resolver, and let - _FrontendStaticFiles read FASTAPI_ENV - itself and decide whether to raise or warn. What does that cost? + The change keeps the import-time error everywhere except a process marked as + development, where it warns and leaves the check to request time. Which principle is + that an instance of?

- - - + + + +
- Locality is a real argument, which is what makes it worth - considering. Locality is a virtue, and the original directory check - does live in that class. What defeats it is the stack. - Attribution depends on the distance to the caller, and the deeper - you push a warning the less it can know about who to blame. An - explicit check_dir would still be honored, since the - class would receive it either way. + The strict branch stays the default for every process not marked as development, + because there a missing build means something shipped without its files. Lazy + initialization and graceful degradation each describe the development branch alone; + under fastapi run the app still fails at creation. Convention over + configuration is about inferring the folder, and the change never touches + directory.
diff --git a/samples/fastapi/2026-09-13-pr-15800-explanation.html b/samples/fastapi/2026-09-13-pr-15800-explanation.html index f49842a..83f1096 100644 --- a/samples/fastapi/2026-09-13-pr-15800-explanation.html +++ b/samples/fastapi/2026-09-13-pr-15800-explanation.html @@ -3,7 +3,7 @@ - Serving a built frontend from FastAPI: app.frontend() + FastAPI PR 15800: app.frontend() - +