Skip to content
Merged
184 changes: 119 additions & 65 deletions .github/scripts/search_excerpt_smoke.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
* Loads the BUILT Sphinx search machinery (doctools.js + searchtools.js) and
* the shipped shims (searchtools-css-escape.js, legacy-fragment-redirect.js)
* into a jsdom window, then drives the exact code path search results use -
* Search.htmlToText(pageHtml, anchor) - against built tutorial HTML for every
* CSS-special anchor class (apostrophe, parentheses+comma, colon, and a
* synthetic legacy digit anchor). Without the CSS.escape wrapper each of
* these throws SyntaxError and the excerpt is dropped; the test asserts a
* non-empty, section-scoped excerpt instead. Also asserts the
* Search.htmlToText(pageHtml, anchor) - against every section id in the
* built tutorial HTML that is not a plain CSS identifier, and against a
* synthetic page with one id per CSS-special class (apostrophe,
* parentheses+comma, colon, legacy leading digit). Without the CSS.escape
* wrapper each of these throws SyntaxError and the excerpt is dropped; the
* test asserts a non-empty, section-scoped excerpt instead. Also asserts the
* legacy-fragment redirect rewrites a pre-rename numbered hash.
*
* The real anchors are DISCOVERED from the built pages, never hard-coded:
* tutorial headings get reworded, and a pinned heading would fail this test
* for a reason that has nothing to do with search.
*
* Run from the repo root after a docs build (jsdom is pinned by the
* committed package.json + package-lock.json next to this script):
* npm ci --prefix .github/scripts --ignore-scripts
Expand All @@ -29,7 +34,9 @@ const check = (label, ok, detail) => {
// jsdom quirks vs browsers: window.CSS is absent (Part 1's env stub inlines
// a minimal spec-subset escaper so the wrapper's guard passes and its logic
// runs against jsdom's real selector engine; "\3<digit> " is the correct
// CSS hex escape for ASCII digits since '0'-'9' are 0x30-0x39), and
// CSS hex escape for ASCII digits since '0'-'9' are 0x30-0x39; "&" is
// also emitted as its hex escape "\26 ", because jsdom's selector engine
// does not match the equally valid "\&" that browsers accept), and
// document.readyState stays "loading" until jsdom finishes its async load
// (so shims register DOMContentLoaded listeners - await before asserting).
const domLoaded = (window) =>
Expand All @@ -38,6 +45,47 @@ const domLoaded = (window) =>
else window.document.addEventListener("DOMContentLoaded", () => resolve());
});

// --- Anchor discovery ----------------------------------------------------
// Section ids in the built tutorial pages that a bare `#id` selector cannot
// address (anything outside [A-Za-z0-9_-], or a leading digit), each with
// the text of its own heading. Sorted by file so the run is deterministic.
const TUTORIALS_DIR = `${ROOT}/tutorials`;
const NEEDS_ESCAPE = /[^A-Za-z0-9_-]|^\d/;

const headingText = (section) => {
const heading = section.querySelector("h1, h2, h3, h4, h5, h6");
if (!heading) return null;
const clone = heading.cloneNode(true);
clone.querySelectorAll(".headerlink").forEach((el) => el.remove());
return clone.textContent.trim();
};

const discoverSpecialAnchors = () => {
const found = [];
const files = readdirSync(TUTORIALS_DIR).filter((f) => f.endsWith(".html")).sort();
for (const file of files) {
const html = readFileSync(`${TUTORIALS_DIR}/${file}`, "utf8");
const { document } = new JSDOM(html).window;
for (const section of document.querySelectorAll('[role="main"] section[id]')) {
const heading = headingText(section);
if (heading && NEEDS_ESCAPE.test(section.id)) {
found.push({ file, html, id: section.id, heading });
}
}
}
return found;
};

const specialAnchors = discoverSpecialAnchors();
// A zero here means discovery broke (theme markup changed) or the tutorials
// no longer have a single CSS-special heading. Either way the real-page
// checks below would pass without testing anything, so fail and look.
check(
"built tutorial pages contain CSS-special section ids to test",
specialAnchors.length > 0,
`${specialAnchors.length} found`,
);

// --- Part 0: production emit order on the built search page --------------
// The shim relies on being emitted BEFORE searchtools.js (it wraps at
// DOMContentLoaded, and listener order follows script order). Pin that
Expand Down Expand Up @@ -75,7 +123,8 @@ const domLoaded = (window) =>
const envStub =
"<script>window.DOCUMENTATION_OPTIONS = {}; window.CSS = { escape: " +
"(value) => String(value).replace(/[\\0-,./:-@[-^`{-~]|^\\d/g, " +
"(ch) => (ch >= '0' && ch <= '9' ? `\\\\3${ch} ` : `\\\\${ch}`)) };" +
"(ch) => (ch >= '0' && ch <= '9' ? `\\\\3${ch} ` : " +
"ch === '&' ? '\\\\26 ' : `\\\\${ch}`)) };" +
"</script>";
const harnessHtml = [
"<!doctype html><html><head>",
Expand All @@ -93,82 +142,88 @@ const domLoaded = (window) =>
await domLoaded(window);
const Search = window.eval("Search");

const page = readFileSync(`${ROOT}/tutorials/02_staggered_did.html`, "utf8");
// Expected prefixes are the section heading TEXT (note the typographic
// apostrophe in rendered prose vs the straight one in the id): asserting
// startsWith proves the excerpt is section-scoped, not the whole-page
// fallback searchtools uses when the anchor lookup finds nothing.
const cases = [
["#Callaway-Sant'Anna-Estimator", "Callaway-Sant’Anna Estimator"],
["#Group-Time-Effects-ATT(g,t)", "Group-Time Effects ATT(g,t)"],
[
"#Understanding-Why-TWFE-Fails:-Goodman-Bacon-Decomposition",
"Understanding Why TWFE Fails: Goodman-Bacon Decomposition",
],
["#Aggregating-Effects", "Aggregating Effects"],
];
for (const [anchor, expectedPrefix] of cases) {
const excerptCheck = (label, page, anchor, expectedPrefix) => {
try {
const text = Search.htmlToText(page, anchor);
check(
`section-scoped excerpt for ${anchor}`,
label,
typeof text === "string" && text.trim().startsWith(expectedPrefix),
text ? `got ${JSON.stringify(text.trim().slice(0, 60))}` : "empty result",
);
} catch (err) {
check(`section-scoped excerpt for ${anchor}`, false, `threw ${err}`);
check(label, false, `threw ${err}`);
}
};

// Real pages: every discovered anchor. The expected prefix is the
// section's own heading text (rendered prose, so a typographic apostrophe
// where the id has a straight one): startsWith proves the excerpt is
// section-scoped, not the whole-page fallback searchtools uses when the
// anchor lookup finds nothing.
for (const { file, html, id, heading } of specialAnchors) {
excerptCheck(`section-scoped excerpt for ${file}#${id}`, html, `#${id}`, heading);
}

// Legacy digit anchors no longer exist in built pages (headings were
// renumbered) but still arrive via old inbound search/deep links; the
// wrapper must keep them from throwing. Synthetic page keeps this case
// covered independently of the notebook content.
const legacyPage =
'<div role="main"><section id="3.-Legacy-Digit-Heading"><h2>Legacy Digit Heading</h2>' +
"<p>legacy digit section body</p></section></div>";
try {
const text = Search.htmlToText(legacyPage, "#3.-Legacy-Digit-Heading");
check(
"excerpt for synthetic legacy digit anchor",
typeof text === "string" && text.includes("legacy digit section body"),
text ? undefined : "empty result",
// Synthetic page: one id per CSS-special class, so each class stays
// covered whatever the tutorials' headings currently are. The digit case
// is a legacy anchor: built pages no longer have them (headings were
// renumbered) but they still arrive via old inbound search/deep links,
// and the wrapper must keep them from throwing.
const syntheticCases = [
["Callaway-Sant'Anna-Estimator", "apostrophe"],
["Group-Time-Effects-ATT(g,t)", "parentheses and comma"],
["Understanding-Why-TWFE-Fails:-Goodman-Bacon-Decomposition", "colon"],
["3.-Legacy-Digit-Heading", "legacy leading digit"],
];
const syntheticPage =
'<div role="main">' +
syntheticCases
.map(
([id, kind]) =>
`<section id="${id}"><h2>${kind} heading</h2><p>${kind} section body</p></section>`,
)
.join("") +
"</div>";
for (const [id, kind] of syntheticCases) {
excerptCheck(
`excerpt for synthetic ${kind} anchor`,
syntheticPage,
`#${id}`,
`${kind} heading`,
);
} catch (err) {
check("excerpt for synthetic legacy digit anchor", false, `threw ${err}`);
}
}

// --- Part 2: legacy fragment redirect ------------------------------------
{
const page = readFileSync(`${ROOT}/tutorials/02_staggered_did.html`, "utf8");
const legacyHash = "#3.-Callaway-Sant'Anna-Estimator";
const dom = new JSDOM(page, {
url: `http://localhost/tutorials/02_staggered_did.html${legacyHash}`,
runScripts: "outside-only",
});
const { window } = dom;
window.eval(readFileSync(`${ROOT}/_static/legacy-fragment-redirect.js`, "utf8"));
await domLoaded(window);
// Runs the shipped shim against a real built page: a numbered form of an id
// that exists must be rewritten to that id, and the id itself left alone.
// The target is the first discovered anchor, so it is also CSS-special.
if (specialAnchors.length) {
const { file, html, id } = specialAnchors[0];
const shim = readFileSync(`${ROOT}/_static/legacy-fragment-redirect.js`, "utf8");
const hashAfterShim = async (fragment) => {
const dom = new JSDOM(html, {
url: `http://localhost/tutorials/${file}#${encodeURIComponent(fragment)}`,
runScripts: "outside-only",
});
dom.window.eval(shim);
await domLoaded(dom.window);
return decodeURIComponent(dom.window.location.hash);
};

const redirected = await hashAfterShim(`3.-${id}`);
check(
"legacy numbered fragment redirects to renamed target",
window.location.hash === "#Callaway-Sant'Anna-Estimator",
`hash is ${JSON.stringify(window.location.hash)}`,
`legacy numbered fragment redirects to renamed target (${file})`,
redirected === `#${id}`,
`hash is ${JSON.stringify(redirected)}`,
);

// A hash that still resolves (or matches nothing) must be left alone.
const dom2 = new JSDOM(page, {
url: "http://localhost/tutorials/02_staggered_did.html#Aggregating-Effects",
runScripts: "outside-only",
});
dom2.window.eval(
readFileSync(`${ROOT}/_static/legacy-fragment-redirect.js`, "utf8"),
);
await domLoaded(dom2.window);
const untouched = await hashAfterShim(id);
check(
"valid fragment left untouched",
dom2.window.location.hash === "#Aggregating-Effects",
`hash is ${JSON.stringify(dom2.window.location.hash)}`,
untouched === `#${id}`,
`hash is ${JSON.stringify(untouched)}`,
);
}

Expand All @@ -181,10 +236,9 @@ const domLoaded = (window) =>
// so a toolchain change that starts emitting duplicate ids fails here
// instead of silently making redirects ambiguous.
{
const tutorialsDir = `${ROOT}/tutorials`;
let dupPages = 0;
for (const file of readdirSync(tutorialsDir).filter((f) => f.endsWith(".html"))) {
const ids = [...readFileSync(`${tutorialsDir}/${file}`, "utf8").matchAll(/\sid="([^"]+)"/g)]
for (const file of readdirSync(TUTORIALS_DIR).filter((f) => f.endsWith(".html"))) {
const ids = [...readFileSync(`${TUTORIALS_DIR}/${file}`, "utf8").matchAll(/\sid="([^"]+)"/g)]
.map((m) => m[1]);
const dupes = ids.filter((id, i) => ids.indexOf(id) !== i);
if (dupes.length) {
Expand Down
1 change: 1 addition & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ Related tracking surfaces:
| `ImputationDiDResults.pretrend_test()` emits pandas' `Pandas4Warning` ("The inplace keyword in DataFrame.drop is deprecated", PDEP-8) on pandas 3.1: three `drop(..., inplace=True)` calls in the lead-regression path. Rebind instead of dropping in place, and grep the package for the remaining `inplace=True` uses in the same pass. | `imputation_aggregation.py` | 4.0 tutorial review | Quick | Low |
| Conley bandwidth diagnostic: when `conley_cutoff_km` covers the whole treated set (one treated spatial cluster inside the bandwidth), the spatial-HAC meat collapses and the SE falls far below HC1 on data with no spatial correlation (tutorial 23's panel: HC1 0.117; Conley 0.117 at 0.5 km, 0.090 at 25 km, 0.062 at 100 km). This is the usual large-bandwidth HAC degeneracy, not a variance bug, but nothing warns. Candidate: a `UserWarning` when the share of treated-treated pairs inside the cutoff exceeds a threshold; the threshold needs a small simulation to choose. | `conley.py`, `spillover.py` | 4.0 tutorial review | Mid | Low |
| No public idiom for a static staggered TWFE with a time-varying covariate (`Y ~ D_it + X_it` with unit and calendar fixed effects): `TwoWayFixedEffects.fit` is 2x2-shaped in static mode and `decompose()` takes no covariates, so tutorial 33's "include the bad control" benchmark builds it from `within_transform` plus `solve_ols`. Either document that route as the supported one or add a staggered static mode. | `twfe.py`, `docs/tutorials/33_bad_controls.ipynb` | 4.0 tutorial review | Mid | Low |
| `SyntheticDiD` Frank-Wolfe convergence on an ordinary panel (tutorial 03: 3 treated and 40 control units, 14 periods, outcomes 30-80, noise sd 0.5): (1) `variance_method="bootstrap"` warns "Frank-Wolfe did not converge on 199 of 199 valid bootstrap draws" on the Rust backend, so the refit bootstrap cannot be shown warning-free and the tutorial demonstrates placebo and jackknife only; (2) on the pure-Python backend the placebo and jackknife fits warn "Frank-Wolfe SC weight solver did not converge in 100 iterations" and "... in 10000 iterations" where the Rust backend is silent on the same data and returns the same ATT. Establish whether the iteration cap or tolerance is too tight for refits, and why the two backends differ in what they report. Same family as the tutorial-18 row below. | `synthetic_did.py`, `utils.py`, `rust/src/` | 4.0 tutorial review | Mid | Low |

### Performance

Expand Down
25 changes: 25 additions & 0 deletions changelog.d/20261125-tutorials-fundamentals.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
### Documentation
- **Fundamentals tutorials repaired and brought to the tutorial conventions**
(`01_basic_did`, `02_staggered_did`, `03_synthetic_did`, `08_triple_diff`,
`09_real_world_examples`). Each now states its estimand and identifying
assumptions before the first fit, checks estimates against a stated truth
where the data is simulated, clusters panel fits at the unit, and is
committed with executed outputs and a drift test. Corrections of substance:
- `01`: the clustering example printed "Cluster-robust SE is 0.26x larger"
for a cluster-robust standard error that is smaller; the section now
explains why it is smaller in that design and when the opposite holds.
- `02`: the true effect path is stated (it was mis-described and never
compared with an estimate); `aggregate("event")`, which raises in 4.0, is
gone; pre-treatment estimates are read with simultaneous bands instead of
pointwise pass/fail; the Callaway-Sant'Anna vs Sun-Abraham "robustness
check" is replaced by an explanation of why the two coincide there.
- `03`: time weights are described correctly (fit on control units); the
count-based placebo p-value and its floor are explained; shipped
diagnostics replace hand-rolled ones.
- `08`: both plain two-way DiDs are shown to miss the truth where the triple
difference recovers it; the staggered example states its truth and
explains the two overall summaries.
- `09`: the Card-Krueger conclusion no longer rests on unclustered standard
errors; the Castle doctrine section explains the TWFE vs
Callaway-Sant'Anna gap by the baseline period and reads the pre-treatment
estimates as a warning rather than passing over them.
Loading
Loading