"""SOURCE render logic for TI-AN-04 (REFERENCE ONLY).
This is the exact function from our pipeline. It is DB-coupled — you cannot run it without our database.
The query result it produces is materialized for you in data.csv, and the rendered output is figure.json
(load that to display the chart). This file is provided so you can understand / re-theme the logic.
"""
def render_TI_AN_04(reg: dict) -> dict:
"""The Season Report Card (quarterly) - for every anime season that aired the most recently
completed cour: finale-week share of US panel viewing as a multiple of its own premiere week
(panel-safe on both ends), graded against the cour's OWN distribution (bars grow from the cour
median, not from 1x - anime seasons normally end bigger than they start). M051 finish-rate chip
only where episode coverage allows; absence is structural, never a verdict."""
chart_id = "TI-AN-04"
output_dir = THIS_DIR / chart_id / ROLE
# ARTIFACT INTEGRITY (AN-04 fix 2026-06-19): purge stale stitched-component crops/previews from
# earlier rounds. The canonical screenshot.png is rewritten by export_chart below, but the helper
# _t_*.png / _v_*.png crops are NOT regenerated here and so froze an older title ("kept their
# audience" - the banned retention verb). A verifier or downstream consumer reading those component
# crops would mis-grade the title. Deleting them every render guarantees no stale companion artifact
# can outlive the current copy; only the live canonical screenshot remains.
if output_dir.exists():
for f in output_dir.glob("_*.png"):
f.unlink()
conn = lib.connect_readonly()
t0 = time.time()
d0row = lib.run_query(conn, "SELECT MAX(file_date) AS d0 FROM title_metrics_daily WHERE geo_code = 'US';")
if d0row.empty or d0row["d0"].iloc[0] is None:
conn.close()
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_seasonal.md"),
reg.get("pc_id", "PC-AN-04"), "No US panel data")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
d0 = pd.Timestamp(d0row["d0"].iloc[0]).date()
cs, ce, cour_label = _an_last_completed_cour(d0)
df = lib.run_query(conn, f"""
WITH d AS (SELECT MAX(file_date) AS d0 FROM title_metrics_daily WHERE geo_code = 'US'),
ep AS ( -- season shape from the TMDb episode calendar
SELECT e.imdb_id, e.season_number, MIN(e.air_date) AS first_air,
MAX(e.air_date) AS last_air, COUNT(*) AS n_eps
FROM categorization_tv_episodes e
WHERE e.air_date IS NOT NULL AND e.season_number > 0
GROUP BY e.imdb_id, e.season_number
),
cohort AS ( -- premiered with the cour, finished with the cour, full-cour episode count
SELECT ep.* FROM ep, d
WHERE ep.first_air BETWEEN %(prem_lo)s AND %(prem_hi)s
AND ep.last_air BETWEEN %(fin_lo)s AND %(fin_hi)s
AND ep.n_eps BETWEEN %(eps_lo)s AND %(eps_hi)s
AND ep.last_air + 6 <= d.d0
),
lane AS (
SELECT c.*, b.primary_title FROM cohort c
JOIN categorization_imdb_title_basics b USING (imdb_id), d
WHERE b.title_type IN ('tvSeries','tvMiniSeries') AND {_AN_LANE_WHERE}
),
prem AS ( -- premiere-week share of panel (same-window sums: panel swings cancel)
SELECT c.imdb_id, c.season_number, SUM(t.reach)::numeric AS r,
(SELECT SUM(ph.total_reach) FROM metrics_panel_health ph
WHERE ph.file_date BETWEEN c.first_air AND c.first_air + 6)::numeric AS tot
FROM lane c JOIN title_metrics_daily t ON t.imdb_id = c.imdb_id
WHERE t.geo_code = 'US' AND t.file_date BETWEEN c.first_air AND c.first_air + 6
GROUP BY c.imdb_id, c.season_number, c.first_air
),
fin AS (
SELECT c.imdb_id, c.season_number, SUM(t.reach)::numeric AS r,
(SELECT SUM(ph.total_reach) FROM metrics_panel_health ph
WHERE ph.file_date BETWEEN c.last_air AND c.last_air + 6)::numeric AS tot
FROM lane c JOIN title_metrics_daily t ON t.imdb_id = c.imdb_id
WHERE t.geo_code = 'US' AND t.file_date BETWEEN c.last_air AND c.last_air + 6
GROUP BY c.imdb_id, c.season_number, c.last_air
),
m051 AS (
SELECT mb.imdb_id, mb.season, mb.completion_pct
FROM metrics_binge_completion mb
WHERE mb.file_date = (SELECT MAX(file_date) FROM metrics_binge_completion)
)
SELECT l.imdb_id, l.primary_title, l.season_number, l.first_air, l.last_air, l.n_eps,
10000.0 * prem.r / NULLIF(prem.tot, 0) AS prem_bps,
10000.0 * COALESCE(fin.r, 0) / NULLIF(fin.tot, 0) AS fin_bps,
m.completion_pct, (SELECT d0 FROM d) AS d0
FROM lane l
LEFT JOIN prem ON (prem.imdb_id, prem.season_number) = (l.imdb_id, l.season_number)
LEFT JOIN fin ON (fin.imdb_id, fin.season_number) = (l.imdb_id, l.season_number)
LEFT JOIN m051 m ON m.imdb_id = l.imdb_id AND m.season = l.season_number;
""", {"prem_lo": cs - timedelta(days=7), "prem_hi": cs + timedelta(days=45),
"fin_lo": ce - timedelta(days=30), "fin_hi": ce + timedelta(days=15),
"eps_lo": AN_RC_EPS_RANGE[0], "eps_hi": AN_RC_EPS_RANGE[1]})
ph = lib.run_query(conn, """SELECT degraded FROM metrics_panel_health
WHERE file_date = (SELECT MAX(file_date) FROM title_metrics_daily
WHERE geo_code = 'US');""")
panel_degraded = bool(ph["degraded"].iloc[0]) if len(ph) else False
q_sec = time.time() - t0
conn.close()
if df.empty:
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_seasonal.md"),
reg.get("pc_id", "PC-AN-04"), f"No {cour_label} anime cohort in the episode calendar")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
n_blocked = df.loc[df["imdb_id"].isin(ANIME_SOURCE_BLOCKLIST), "imdb_id"].nunique()
df = df[~df["imdb_id"].isin(ANIME_SOURCE_BLOCKLIST)].copy() # content policy (see constant)
df["prem_bps"] = pd.to_numeric(df["prem_bps"], errors="coerce")
df["fin_bps"] = pd.to_numeric(df["fin_bps"], errors="coerce")
df["retention"] = df["fin_bps"] / df["prem_bps"].replace(0.0, np.nan)
freshness = str(df["d0"].iloc[0])
meas = df[df["retention"].notna()].copy()
graded = meas[meas["prem_bps"] >= AN_RC_FLOOR_BPS].sort_values("retention") # weakest at bottom
if len(graded) < AN_RC_MIN_GRADED:
lib.needs_spec_review(output_dir, chart_id, reg.get("spec_file", "_anime_section_mock/mock_seasonal.md"),
reg.get("pc_id", "PC-AN-04"),
f"Only {len(graded)} gradable {cour_label} seasons (floor {AN_RC_MIN_GRADED})")
write_shim(output_dir, chart_id); return {"status": "needs_spec_review"}
med = float(meas["retention"].median()) # the cour's OWN distribution, all measurable seasons
n_dust = int(len(meas) - len(graded))
rets = graded["retention"].astype(float)
# Neutral dead-band around the median: a green-vs-red verdict on a row whose multiple sits within a
# hair of the median line is meaningless (the gap to the line is inside measurement noise). Bars are
# ZERO-BASED (length reads as the quoted multiple off the x-axis), so the verdict is read by WHICH SIDE
# OF THE MEDIAN LINE a bar's right edge falls on; the dead-band straddles that line. EPS is ~2% of the
# plotted multiple span; rows inside it get a NEUTRAL hue and an 'about typical' tag instead of a
# green/red paint the reader cannot justify so close to the line (closes the invisible-verdict defect).
_ret_lo = min(float(rets.min()), 0.95); _ret_hi = float(rets.max())
rc_eps = max(0.02, 0.02 * (_ret_hi - _ret_lo))
# Value labels are now SPLIT into two pieces with two different homes (AN-04 ROOT-CAUSE fix
# 2026-06-19): the growth-MULTIPLE ("2.31x") is drawn INSIDE the bar at its left edge (white ink
# on the colored fill), and the secondary CHIPS ("about typical", "NN% finish rate") sit at/after
# the bar tip. Splitting them is what permanently ends the median-line strike-through: the only
# piece that ever landed near the 1x (x=1) or median (x=med) lines was the multiple sitting at the
# bar TIP, and that piece now lives far-left at x~0 on every row, by construction, for all data.
ylabels, mult_texts, chip_texts, colors = [], [], [], []
for _, r in graded.iterrows():
t = lib.ellipsize(clean_title(r["primary_title"]), 36)
if int(r["season_number"]) == 1: # amber NEW = a first season, per the color contract
ylabels.append(f"{t} NEW")
else:
# SELF-DECODING season tag (AN-04 fix): 'Season N' spelled out, not a bare 'S16' that has no
# on-chart decoder. A layman reads 'Season 16' directly; 'S#' needed a legend the chart lacked.
ylabels.append(f"{t} Season {int(r['season_number'])}")
ret_v = float(r["retention"])
near_med = abs(ret_v - med) <= rc_eps
mult_texts.append(f"{ret_v:.2f}x") # the multiple ALONE -> inside the bar, left edge, white ink
# CHIPS (secondary, muted) sit at the bar tip, never inside: 'about typical' for near-median rows
# plus the bonus finish-rate. The no-spotlight band keeps its bar and its uniform multiple label
# but NEVER a chip (founder content policy; the chip still ships for every row in data.csv).
chip = ""
if near_med:
chip += f"about typical"
if pd.notna(r["completion_pct"]) and str(r["imdb_id"]) not in ANIME_NO_SPOTLIGHT:
sep = " · " if chip else ""
chip += f"{sep}{float(r['completion_pct']):.0f}% finish rate"
chip_texts.append(chip)
# three-way: neutral when essentially at the median (no invisible/meaningless verdict),
# else green above / red below the season's typical build
colors.append(lib.MUTED if near_med else (lib.GREEN if ret_v >= med else lib.RED))
fig = go.Figure()
# ZERO-BASED bars (AN-02 pattern; Tufte lie-factor fix): each bar runs from 0 to the title's
# finale-vs-premiere multiple, so the bar LENGTH literally equals the quoted multiple and its right
# edge lands EXACTLY on that number on the x-axis. The prior base=1.0 encoding drew length =
# (multiple - 1), which clipped the four sub-1x seasons to identical stubs at the axis edge (a
# lie factor). The grading is read by which side of the SEASON-MEDIAN reference line a bar's right
# edge falls on; the dashed 1x line marks each season's own premiere-week level inside the bars.
fig.add_trace(go.Bar(
x=rets, y=ylabels, orientation="h",
marker=dict(color=colors, line=dict(width=0)),
cliponaxis=False, showlegend=False,
customdata=np.stack([rets.round(2)], axis=-1),
hovertemplate="%{y}
finale week read %{customdata[0]}x its premiere-week share of "
"US panel viewing",
))
# VALUE LABELS - ROOT-CAUSE FIX (AN-04 2026-06-19): the growth-multiple label is drawn INSIDE the
# bar, hard against its LEFT edge (x just past 0, left-anchored), in white ink on the colored fill.
# WHY THIS PERMANENTLY ENDS THE MEDIAN-LINE STRIKE-THROUGH (recurring for several rounds): the only
# label piece that ever collided with the 1x line (x=1) or the median line (x=med ~ 1.29) was the
# multiple sitting at the bar TIP near those lines. With every multiple now anchored at the far LEFT
# (x~0), NO label digit is ever near x=1 or x=med - so no reference stroke can bisect a digit, by
# construction, for ALL current and future data. The prior bar-tip placement, its white-bg box, its
# y-nudge and its crosses-median collision logic are all REMOVED as unnecessary.
# White-on-fill legibility: bar fills are GREEN #2D8B5F, RED #B0464E and MUTED #68707D - all are
# mid-dark (relative luminance ~0.20-0.27), so near-white #F7F9FB text is clearly legible on each.
# SHORT-BAR FALLBACK: a bar too short to seat its multiple inside (sub-1x rows) gets the label JUST
# RIGHT of its tip instead. This is safe precisely because such tips are sub-1x: they sit well LEFT
# of both the dashed 1x line and the solid median line, so an outside label there is far from either
# reference and cannot be struck. The threshold is generous so only genuinely tiny bars fall back.
LABEL_WHITE = "#F7F9FB"
span = float(rets.max()) * 1.22 # plotted x-range (matches update_xaxes below)
inside_min = 0.085 * span # a bar at least this long can seat the multiple inside
for ylab, ret_v in zip(ylabels, rets):
rv = float(ret_v)
if rv >= inside_min:
# inside, left edge, white ink on the colored fill - far from x=1 and x=med
fig.add_annotation(x=0.0, y=ylab, xref="x", yref="y", text=f"{rv:.2f}x", showarrow=False,
xanchor="left", xshift=7, align="left",
font=dict(size=11, color=LABEL_WHITE))
else:
# sub-1x stub too short to seat the label inside: place it just RIGHT of the tip. The tip is
# well left of both the 1x and median lines, so this outside label is never near a stroke.
fig.add_annotation(x=rv, y=ylab, xref="x", yref="y", text=f"{rv:.2f}x", showarrow=False,
xanchor="left", xshift=6, font=dict(size=11, color=lib.INK))
# CHIP LABELS (secondary 'about typical' / 'finish rate'), drawn at/after the bar tip with a near-
# opaque white background so the solid median stroke (the only line near the tip cluster) passes
# cleanly BEHIND the text rather than striking it. Emitted only for rows that have a chip.
for ylab, ret_v, chip in zip(ylabels, rets, chip_texts):
if not chip:
continue
fig.add_annotation(x=float(ret_v), y=ylab, xref="x", yref="y", text=chip, showarrow=False,
xanchor="left", xshift=7,
bgcolor="rgba(255,255,255,0.9)", borderpad=1,
font=dict(size=10, color=lib.MUTED))
# ZERO-BASED axis (AN-02 pattern): the scale starts at 0 so every bar's length reads off the axis as
# the multiple it quotes and NOTHING is clipped - the four sub-1x seasons render as short-but-distinct
# bars of different visible lengths. Headroom past the longest bar clears its outside value label.
# AXIS DOUBLE-ANCHOR FIX (AN-04 2026-06-19): the 2x-tick text used to read "1x = premiere week", which
# anchored "premiere week" to the 1x mark in TWO places (here AND the dashed-line label) and, with
# zero-based bars that visibly start at 0x, fed the false read that 1x is where bars start. The axis now
# carries ONLY plain multiple ticks (0x, 0.5x, 1x, ...); "premiere week" / 1x meaning lives in exactly
# one place, the dashed-line label below, which is reworded to describe 1x as the break-even level a bar
# REACHES (not an origin it starts from).
hi_val = float(rets.max())
fig.update_xaxes(range=[0, hi_val * 1.22],
tickvals=[v / 2.0 for v in range(0, int(2 * (hi_val + 0.5)) + 1)],
ticktext=[f"{v / 2.0:g}x" for v in range(0, int(2 * (hi_val + 0.5)) + 1)])
# Median = the GRADING reference (which side a bar's right edge falls on = the verdict): draw it
# SOLID and darker so it reads as the line bars are judged against. 1x = the break-even level (finale
# week equal to premiere week); a bar REACHING it returned to its premiere-week size. Lighter DASHED
# mark. Subtitle, on-face labels, and these two strokes must all agree (solid = season median / grading
# line, dash = 1x / premiere-week break-even level, NOT a bar origin - bars are zero-based off 0x).
vline_above(fig, med, color=lib.INK, width=1.8, dash="solid")
vline_above(fig, 1.0, color=lib.MUTED, width=1.0, dash="dash")
named = graded[~graded["imdb_id"].isin(ANIME_NO_SPOTLIGHT)]
# Headline counts the GRADED (rendered) bars only, and counts the SAME comparison the colors paint
# (vs the cour median). The count = every row NOT painted red = outgrew the median (GREEN) OR landed
# about typical inside the neutral dead-band (GREY). WORDING: 'were about typical or better than this
# quarter's typical build' (AN-04 fix 2026-06-19). This maps the two non-red color states EXACTLY:
# 'better than' = green (outgrew the median), 'about typical' = grey (within +/-eps of the median). The
# prior 'matched or beat' had a pedantic hole: the dead-band straddles the median, so a grey row can sit
# a HAIR BELOW it (Frieren 1.28x vs the 1.29x median) and 'matched or beat' implies that row at least
# equalled the line, which is false. 'about typical or better' never asserts equal-or-above for the grey
# ties: a sub-median grey row is reported as 'about typical' (exactly what its on-face tag reads), and
# only the green rows carry 'better than'. So no below-median show is described as having met or beaten
# the line; the disjunction is literally true for every counted row. Red (trailed) is the only excluded
# group. The count predicate is unchanged (green OR grey); only the human wording is tightened.
n_beat_median = int(((graded["retention"].astype(float) >= med)
| ((graded["retention"].astype(float) - med).abs() <= rc_eps)).sum())
# Clear, non-confusing cour label (founder 2026-06-19): "Winter 2026" alone confuses in summer, so
# always name it as the most recent COMPLETED anime season. The selection is already rule-based and
# auto-rolling (_an_last_completed_cour picks the latest cour whose finale week is fully behind the
# panel anchor), so this phrase rolls forward to Spring 2026, Summer 2026, etc. on its own. It now
# lives ONLY in the subheader (sentence 1 below), NOT the title (SEASON DOUBLE-MEANING FIX, see below).
# SEASON DOUBLE-MEANING FIX (AN-04 2026-06-19): on this chart "season" means two things, the
# broadcast quarter and a show's Season 2. The QUARTER (cour) is named exactly once, in the subheader,
# as the simulcast slate, so a reader can never confuse it with a show-season ("S2"/"Season 2", which
# the row labels carry). The TITLE no longer carries the cour name nor the nested appositive that
# buried the subject.
# TITLE = ONE BREATH, LEADER-LED, DECLARATIVE (AN-04 ROOT-CAUSE fix 2026-06-19). The old title was a
# two-part question+colon+compound ("Which anime built their audience this quarter: grew ...,
# and N of M ..."), which carried TWO clauses and the count in the headline. It is replaced by a single
# declarative clause, subject (the leader) first, with a rule-based interpolation of the leader name +
# its multiple + an accurate GROW verb (the bars are growth multiples; the leader is >2x). The "N of M
# matched/beat the typical build" count moves OUT of the title and INTO the subheader (sentence 2).
# "this quarter's" (not "the season's") keeps the cour sense so the headline never reads as a show-run
# "season" - "quarter" cannot collide with the y-axis "Season N" installment tags.
best_id = str(graded.iloc[-1]["imdb_id"]) # global strongest build (ascending sort -> last row)
if len(named) and str(named.iloc[-1]["imdb_id"]) == best_id:
# the strongest build is spotlightable: name it as the quarter's strongest finale, one clause.
best = named.iloc[-1]
takeaway = (f"{clean_title(best['primary_title'])} built this quarter's strongest finale, "
f"growing to {float(best['retention']):.2f}x its premiere week")
elif len(named):
# the global leader is in the no-spotlight band: lead with the strongest spotlightable grower,
# described as among the quarter's strongest (not THE single strongest), still one clause.
best = named.iloc[-1]
takeaway = (f"{clean_title(best['primary_title'])} was among this quarter's strongest finales, "
f"growing to {float(best['retention']):.2f}x its premiere week")
else:
# no spotlightable grower: a leader-free one-clause headline on the cohort's build.
takeaway = (f"This quarter's anime finales grew past their premieres, the strongest reaching "
f"{float(graded.iloc[-1]['retention']):.2f}x")
# Subheader carries the COUR NAME (named once), the COUNT moved down from the title (AN-04 ROOT-CAUSE
# fix 2026-06-19), and the encoding + three-color legend, in EXACTLY TWO sentences (footer/subtitle
# rule). SENTENCE 1 names the broadcast quarter once, explicitly, as the simulcast season covering new
# and returning shows alike, and carries the "N of M matched or beat the typical build" count relocated
# from the headline - this is the ONLY place the cour name appears, so the headline's "season" can never
# collide with the y-axis "Season N" show-installment tags. SENTENCE 2 states the GRADING (longer = grew
# more relative to this quarter, read off the SOLID median line) and names all three color states to
# match the legend. "this quarter's" carries the cour sense ("quarter" cannot read as a show-season).
# COUNT WORDING stays the validated honest map of the two non-red color states - green (beat the median)
# PLUS grey (about typical, within a hair of the line, which can sit a touch BELOW the median): "about
# typical or better" never asserts equal-or-above for a grey tie, so no below-median row is described as
# having matched or beaten the line. NO generic "season" denotes a show's run anywhere in the copy
# ("show"/"Season N installment" only); "season" appears solely as the cour appositive to the quarter.
what = (f"The most recent completed simulcast season, {cour_label}, covering new shows and returning "
f"ones alike, where {n_beat_median} of {len(graded)} graded titles were about typical or better "
f"than this quarter's typical build. The longer the bar, the more a show's finale-week viewing "
f"grew over its premiere week, scored against the solid line (this quarter's median): green "
f"outgrew the typical build, grey was about typical, and red trailed it.")
why = ("Anime audiences naturally stack up as episodes land, so simply growing is only average. Grading every "
"finale against this quarter's own median separates the titles, new series and returning ones alike, "
"that genuinely outbuilt their peers and held the audience from the ones that just rode the tide.")
cautions = ["graded against this quarter's own spread of outcomes, not a fixed bar"]
# FINISH-RATE chip DEFINED in the footer (AN-04 fix): names the bonus completion signal so the tag
# reads as a defined extra (like NEW), not an arbitrarily-missing per-row metric. POSITIVE framing
# only - it defines what the chip means and never announces where the chip is absent (the
# panel-internals bar forbids coverage-hole / 'where available' disclosure). Emitted only when at
# least one chip is actually on the face.
any_finish_chip = bool((graded["completion_pct"].notna()
& ~graded["imdb_id"].astype(str).isin(ANIME_NO_SPOTLIGHT)).any())
if any_finish_chip:
cautions.append("a 'finish rate' tag is a bonus completion signal, the share of viewers who stuck with a show through to its finale")
if panel_degraded:
cautions.append("panel volume atypical on this date; multiples compare like-for-like weeks")
# 'cour' defined inline once for laymen (anime's broadcast quarter). No coverage-floor / sample-size
# disclosure on any reader surface (panel-internals rule): below-floor seasons are simply not graded
# and silently omitted; the data file still carries every measurable season with its graded flag.
extra = "shows whose run aired in full this quarter (a cour, anime's broadcast quarter)"
extra += " · refreshed quarterly · metrics decoded at METH-03"
footer = drop_census(lib.assemble_footer(pc_id=reg.get("pc_id", "PC-AN-04"),
caution_labels=cautions, freshness_date=freshness,
sources=["title_metrics_daily", "metrics_panel_health",
"TMDb episode calendar", "metrics_binge_completion"],
extra=extra))
fig.update_layout(**lib.layout_v2(takeaway, what, width=1180, height=700),
xaxis=lib.standard_xaxis("", showgrid=False),
yaxis=lib.standard_yaxis(showgrid=False))
# Reference-line labels share one reserved band above the plot, anchored apart so they
# cannot collide (median label grows right, the 1x label grows left).
fig.layout.margin.t = int(fig.layout.margin.t or 95) + 18
fig.layout.height = int(fig.layout.height or 700) + 18
# Median label doubles as the NON-COLOR grading cue AND names ALL THREE color states so the legend
# matches the encoding (AN-04 fix 2026-06-19). The old binary "bars crossing it outgrew it, bars short
# of it trailed" ignored the grey neutral dead-band: a bar a hair off the median (e.g. Sentenced to Be
# a Hero at 1.30x vs a 1.29x median) renders GREY "about typical" yet sits on the "crossing" side, so
# the binary label mislabeled it. The label now spells the three outcomes in the exact color words the
# bars use - green outgrew it, grey is about typical (within a hair of the line), red trailed it - so
# the verdict is recoverable from position-near-the-line alone, not color, and the legend is honest.
fig.add_annotation(x=med, y=1.0, yref="paper",
text=(f"solid line = typical this quarter, {med:.2f}x · green outgrew it, "
f"grey about typical (within a hair of the line), red trailed it"),
showarrow=False, xanchor="left", xshift=4, yanchor="bottom",
font=dict(size=10, color=lib.INK))
# 1x = BREAK-EVEN, not a bar origin (BLOCKING FIX AN-04 2026-06-19). Bars are ZERO-BASED and visibly
# start at 0x; the dashed line sits at 1x. The old label "1x = premiere week (every bar starts here)"
# was placed AT the 1x mark yet claimed bars start there, contradicting the zero-based geometry and its
# own manifest rule (the L-048 'label at the WRONG dot' class). 1x is the level where a season's finale
# week EQUALS its premiere week, so a bar that REACHES this line returned to its premiere-week size, one
# past it grew, one short of it shrank. The label now names that meaning and never implies a starting
# point (the only baseline bars grow from is 0x, the axis origin).
fig.add_annotation(x=1.0, y=1.0, yref="paper",
text="dashed line = 1x: finale week equal to premiere week (reach it = held its premiere size)",
showarrow=False, xanchor="right", xshift=-4, yanchor="bottom",
font=dict(size=9.5, color=lib.MUTED))
# Below-floor seasons are silently left ungraded with no 'too small to grade' callout (panel-internals
# rule): a sample-size floor disclosure is forbidden on the face. The finish-rate chip is NAMED in the
# footer caution above (so it reads as a defined bonus signal, not an arbitrary per-row metric), with
# NO coverage-hole / 'where available' language (the panel-internals bar outranks the minor cosmetic).
# SILENT-EXCLUSION FINDING, RESOLVED IN FAVOR OF THE PANEL-INTERNALS RULE (AN-04 2026-06-19): a strong
# grower like 'In the Clear Moonlit Dusk' (2.21x but premiere week below the floor) is dropped with no
# on-chart trace. A verifier flagged the invisible measurable-14 vs graded-13 gap as a minor silent
# exclusion. The ONLY way to surface it on the face ("a strong season was excluded because its premiere
# read too small to grade") is exactly a coverage / measurement-gap disclosure the panel-internals rule
# forbids, and that rule is higher authority than a minor cosmetic. So the omission stays silent BY
# DESIGN; the title is scoped honestly with the word 'graded' (it counts the graded subset, never claims
# to show every season), and data.csv still carries every measurable season with its graded flag for any
# downstream reader. No face change here is rule-compatible.
lib.add_why_and_footer(fig, why, footer)
# TI-AN display contract (founder-locked): NO cross-comparable absolute levels anywhere,
# data.csv included - the old premiere/finale share-of-TOTAL-panel bps columns were exactly
# such a leak. The csv ships the momentum multiple plus a WITHIN-COUR premiere index (this
# cour's biggest premiere = 100), which preserves relative size without cross-lane comparability.
out = meas.sort_values("retention", ascending=False)[
["imdb_id", "primary_title", "season_number", "first_air", "last_air", "n_eps",
"prem_bps", "retention", "completion_pct"]].copy()
out["primary_title"] = out["primary_title"].map(clean_title) # no spaced-hyphen in the sidecar
prem_top = float(out["prem_bps"].max()) or 1.0
out["premiere_week_cour_index"] = (out["prem_bps"] / prem_top * 100.0).round(1)
out["graded"] = out["prem_bps"] >= AN_RC_FLOOR_BPS
out = out.drop(columns=["prem_bps"])
out = out.rename(columns={
"first_air": "first_episode_air", "last_air": "last_episode_air", "n_eps": "episodes",
"retention": "finale_vs_premiere_multiple", "completion_pct": "season_finish_rate_pct"})
out["new_series"] = out["season_number"].astype(int) == 1
out["cour"] = cour_label
out["cour_median_multiple"] = round(med, 2)
out["freshness_date"] = freshness
lib.save_csv(out, output_dir, full_rows=len(meas))
lib.export_chart(fig, output_dir, width=1180, height=int(fig.layout.height))
what_plain = re.sub(r"?b>", "", what)
lesson = {"reader_title": takeaway, "reader_subtitle": what_plain, "claim_strength": "strong",
"rules_applied": (f"cour derived rule-based ({cour_label}: {cs}..{ce}); cohort = premiere within "
f"[cour start - 7d, +45d], last episode within [cour end - 30d, +15d], "
f"{AN_RC_EPS_RANGE[0]}-{AN_RC_EPS_RANGE[1]} eps, finale week complete; "
f"board-faithful anime lane + recurrent rule + softened gate; retention = "
f"finale-week / premiere-week share of panel (panel-safe both ends); graded "
f"vs the cour's OWN median {med:.2f} over {len(meas)} measurable seasons; "
f"ZERO-BASED bars (length = the quoted multiple; nothing clipped); solid median "
f"line carries the grading, dashed 1x line marks premiere week; "
f"premiere floor {AN_RC_FLOOR_BPS:.0f} bps gates bars, not the median; "
f"M051 finish chip only where covered AND suppressed on no-spotlight rows "
f"(values still ship in data.csv); H1 'about typical or better' count = every "
f"graded bar NOT painted red = better-than (green, above the median) PLUS about-typical "
f"(grey, within the +/-{rc_eps:.2f}x neutral dead-band of the median, which "
f"includes rows a hair below it - reported as 'about typical', never 'beat'); "
f"blocklist removed {n_blocked}; "
f"no-spotlight band barred from callouts")}
lib.write_lesson_design(output_dir, chart_id, f"# {chart_id}\n\n{takeaway}\n\n{what_plain}\n")
write_shim(output_dir, chart_id)
lib.write_manifest(output_dir, chart_id, "ok", reg.get("spec_file", "_anime_section_mock/mock_seasonal.md"),
pc_id=reg.get("pc_id", "PC-AN-04"),
intended_lesson_from_spec="Quarterly cour report card: finale-vs-premiere share retention, graded vs the cour's own median",
rendered_lesson=lesson, row_count=len(graded), freshness_date=freshness,
query_seconds=q_sec, render_seconds=time.time() - t0 - q_sec,
extra={"cour": cour_label, "cour_window": [str(cs), str(ce)],
"cohort_size": int(len(df)), "measurable": int(len(meas)),
"graded": int(len(graded)), "below_floor": int(n_dust),
"cour_median": round(med, 3),
# The headline's metric (the one the chart's thesis turns on): graded bars that
# MATCHED OR BEAT the cour median = green (beat, outgrew the median) + grey dead-band
# (matched, about typical). Named to match the on-face 'matched or beat' count exactly,
# so a reader cross-referencing the data file sees the headline's number here.
"matched_or_beat_median_graded": n_beat_median,
# SEPARATE, explicitly-labeled diagnostic: grew past its OWN PREMIERE WEEK (vs 1x,
# the dashed context line) - NOT a grading-vs-median count and NOT the headline's
# metric. Renamed from the bare 'grew_among_graded' so it can never read as a
# second, competing 'success' count alongside the headline's median-based count.
"grew_vs_premiere_week_among_graded": int((graded["retention"].astype(float) > 1.0).sum()),
"grew_vs_premiere_week_among_measurable": int((meas["retention"].astype(float) > 1.0).sum()),
"m051_covered": int(meas["completion_pct"].notna().sum()),
"blocklist_removed": int(n_blocked),
"no_spotlight_rendered": sorted(set(graded["imdb_id"]) & ANIME_NO_SPOTLIGHT)})
return {"status": "ok", "rows": len(graded)}