<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://sir-teo.github.io/blogs/feed.xml" rel="self" type="application/atom+xml" /><link href="https://sir-teo.github.io/blogs/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-08T00:31:42-05:00</updated><id>https://sir-teo.github.io/blogs/feed.xml</id><title type="html">Teo’s blog</title><subtitle>Things I build, explained with figures you can play with.</subtitle><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><entry><title type="html">How I’d build an airline pricing analysis product</title><link href="https://sir-teo.github.io/blogs/2026/10/26/turning-millions-of-fare-searches-into-a-pricing-alert.html" rel="alternate" type="text/html" title="How I’d build an airline pricing analysis product" /><published>2026-10-26T21:00:00-04:00</published><updated>2026-10-26T21:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/26/turning-millions-of-fare-searches-into-a-pricing-alert</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/26/turning-millions-of-fare-searches-into-a-pricing-alert.html"><![CDATA[<p>Working on airline pricing taught me that the difficult part starts before the chart: two prices can refer to different products, be observed at different times, or include different taxes. I’d build the product around making those differences inspectable.</p>

<p>Here’s how I’d approach it from scratch. The design draws on what I learned, with generic component names and a fictional example: <strong>A → B on November 17</strong>, observed <strong>October 27</strong>, twenty-one days before departure. Our economy fare is <strong>$240</strong>; a competitor offers discount economy at <strong>$220</strong> and regular economy at <strong>$270</strong>. An airline’s revenue-management team uses this evidence when choosing which prices to offer.</p>

<h2 id="1-collect-once-keep-the-evidence">1. Collect once, keep the evidence</h2>

<p>I’d store collection definitions in Postgres: route, departure range, cabin, trip type, country of sale, sources, freshness limit and delivery deadline. Expand them into dated queries, merge duplicates, and retain a separate query-to-collection ownership table. Two teams requesting the same public search should share the supplier call.</p>

<p>Each provider gets a queue, a token-bucket rate limit and a concurrency cap. Workers fetch the reply; provider-specific parsers emit a common offer schema. I’d retain raw replies in object storage for parser replay, with normalized offers in a short-lived Redis cache. Reusing a cached result must preserve its original observation time.</p>

<figure class="fig wide fs" id="fs-collect">
<!-- Generated from one shared fictional dataset. -->
<div class="fs-technical"><div class="fs-overline"><strong>Collect → normalize</strong><span>A → B · November 17</span></div><svg class="fs-schematic fs-schema-wide" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 260" role="img" aria-label="Two watchlists merge into eighty source queries. Twenty cache hits and sixty fetches produce one hundred twenty offers. Blue follows the November 17 flight."><defs><marker id="fs-art-intake-800" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 1L7 4L0 7" class="arrow" /></marker></defs><path d="M142 69C165 69 165 121 188 121" class="wire" marker-end="url(#fs-art-intake-800)" /><path d="M142 147C165 147 165 121 188 121" class="wire" marker-end="url(#fs-art-intake-800)" /><path d="M330 121C363.5 121 363.5 63 397 63" class="wire cache-wire" marker-end="url(#fs-art-intake-800)" /><path d="M330 121C363.5 121 363.5 173 397 173" class="wire strong" marker-end="url(#fs-art-intake-800)" /><path d="M535 63C579 63 579 112 623 112" class="wire cache-wire" marker-end="url(#fs-art-intake-800)" /><path d="M535 173C544.5 173 544.5 173 554 173" class="wire strong" marker-end="url(#fs-art-intake-800)" /><path d="M610 173C616.5 173 616.5 150 623 150" class="wire strong" marker-end="url(#fs-art-intake-800)" /><rect x="8" y="43" width="134" height="52" rx="5" class="node " /><text x="75" y="64" class="node-title" text-anchor="middle">Watchlist 1</text><text x="75" y="82" class="node-sub" text-anchor="middle">40 dates × 2 sources</text><rect x="8" y="121" width="134" height="52" rx="5" class="node " /><text x="75" y="142" class="node-title" text-anchor="middle">Watchlist 2</text><text x="75" y="160" class="node-sub" text-anchor="middle">same public searches</text><rect x="188" y="49" width="142" height="135" rx="5" class="region" /><text x="201" y="70" class="node-title" text-anchor="start">80 source queries</text><rect x="202" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="213.5" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="225" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="236.5" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="248" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="259.5" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="271" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="282.5" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="294" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="305.5" y="84" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="202" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="213.5" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="225" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="236.5" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="248" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="259.5" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="271" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="282.5" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="294" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="305.5" y="93" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="202" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="213.5" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="225" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="102" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="202" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="213.5" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="225" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="111" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="202" y="120" width="7.5" height="5.5" rx="1.2" class="query tracked" /><rect x="213.5" y="120" width="7.5" height="5.5" rx="1.2" class="query tracked" /><rect x="225" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="120" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="202" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="213.5" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="225" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="129" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="202" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="213.5" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="225" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="138" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="202" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="213.5" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="225" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="236.5" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="248" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="259.5" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="271" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="282.5" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="294" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="305.5" y="147" width="7.5" height="5.5" rx="1.2" class="query fresh" /><text x="201" y="171" class="node-sub blue" text-anchor="start">2 follow our departure</text><rect x="397" y="37" width="138" height="52" rx="5" class="node cache-node" /><text x="466" y="58" class="node-title" text-anchor="middle">Fresh cache</text><text x="466" y="76" class="node-sub" text-anchor="middle">source time + TTL</text><rect x="397" y="147" width="138" height="52" rx="5" class="node trace-node" /><text x="466" y="168" class="node-title" text-anchor="middle">Provider queue</text><text x="466" y="186" class="node-sub" text-anchor="middle">rate + inflight cap</text><rect x="554" y="152" width="56" height="42" rx="5" class="node parser-node" /><text x="582" y="177" class="node-title" text-anchor="middle">Parse</text><text x="623" y="43" class="label" text-anchor="start">Normalized offers</text><rect x="623" y="56" width="169" height="147" rx="4" class="offer-sheet" /><text x="636" y="80" class="small" text-anchor="start">Our airline</text><text x="636" y="95" class="small muted" text-anchor="start">economy</text><text x="780" y="86" class="price own" text-anchor="end">$240</text><path d="M633 106L782 106" class="rule" /><text x="636" y="123" class="small" text-anchor="start">Competitor</text><text x="636" y="138" class="small muted" text-anchor="start">discount</text><text x="780" y="129" class="price comp" text-anchor="end">$220</text><path d="M633 149L782 149" class="rule" /><text x="636" y="166" class="small" text-anchor="start">Competitor</text><text x="636" y="181" class="small muted" text-anchor="start">economy</text><text x="780" y="172" class="price comp" text-anchor="end">$270</text><text x="623" y="223" class="label blue" text-anchor="start">A → B · Nov 17</text><text x="346" y="48" class="small muted" text-anchor="start">20 reuse</text><text x="346" y="194" class="small blue" text-anchor="start">60 fetch</text><path d="M464 199V224H397" class="wire dashed" /><text x="397" y="244" class="small muted" text-anchor="start">raw reply → replay log</text><text x="192" y="221" class="small muted" text-anchor="start">Merge ownership, not evidence.</text></svg><svg class="fs-schematic fs-schema-small" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 472" role="img" aria-label="Two watchlists merge into eighty source queries. Twenty cache hits and sixty fetches produce one hundred twenty offers. Blue follows the November 17 flight."><defs><marker id="fs-art-intake-360" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 1L7 4L0 7" class="arrow" /></marker></defs><path d="M87 72V95H86V121" class="wire" marker-end="url(#fs-art-intake-360)" /><path d="M275 72V95H86" class="wire" /><path d="M158 174C177 174 177 151 196 151" class="wire cache-wire" marker-end="url(#fs-art-intake-360)" /><path d="M158 213C177 213 177 239 196 239" class="wire strong" marker-end="url(#fs-art-intake-360)" /><path d="M336 151H349V343H116V356" class="wire cache-wire" marker-end="url(#fs-art-intake-360)" /><path d="M266 265V289" class="wire strong" marker-end="url(#fs-art-intake-360)" /><path d="M266 325V336H98V356" class="wire strong" marker-end="url(#fs-art-intake-360)" /><rect x="6" y="20" width="162" height="52" rx="5" class="node " /><text x="87" y="41" class="node-title" text-anchor="middle">Watchlist 1</text><text x="87" y="59" class="node-sub" text-anchor="middle">40 dates × 2 sources</text><rect x="192" y="20" width="162" height="52" rx="5" class="node " /><text x="273" y="41" class="node-title" text-anchor="middle">Watchlist 2</text><text x="273" y="59" class="node-sub" text-anchor="middle">same public searches</text><rect x="16" y="121" width="142" height="135" rx="5" class="region" /><text x="29" y="142" class="node-title" text-anchor="start">80 source queries</text><rect x="30" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="41.5" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="53" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="64.5" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="76" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="87.5" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="99" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="110.5" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="122" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="133.5" y="156" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="30" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="41.5" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="53" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="64.5" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="76" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="87.5" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="99" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="110.5" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="122" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="133.5" y="165" width="7.5" height="5.5" rx="1.2" class="query cached" /><rect x="30" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="41.5" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="53" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="174" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="30" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="41.5" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="53" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="183" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="30" y="192" width="7.5" height="5.5" rx="1.2" class="query tracked" /><rect x="41.5" y="192" width="7.5" height="5.5" rx="1.2" class="query tracked" /><rect x="53" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="192" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="30" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="41.5" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="53" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="201" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="30" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="41.5" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="53" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="210" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="30" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="41.5" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="53" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="64.5" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="76" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="87.5" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="99" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="110.5" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="122" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><rect x="133.5" y="219" width="7.5" height="5.5" rx="1.2" class="query fresh" /><text x="29" y="243" class="node-sub blue" text-anchor="start">2 follow our departure</text><rect x="196" y="125" width="140" height="52" rx="5" class="node cache-node" /><text x="266" y="146" class="node-title" text-anchor="middle">20 cache hits</text><text x="266" y="164" class="node-sub" text-anchor="middle">keep source timestamp</text><rect x="196" y="213" width="140" height="52" rx="5" class="node trace-node" /><text x="266" y="234" class="node-title" text-anchor="middle">60 source fetches</text><text x="266" y="252" class="node-sub" text-anchor="middle">rate + inflight cap</text><rect x="196" y="289" width="140" height="36" rx="5" class="node parser-node" /><text x="266" y="311" class="node-title" text-anchor="middle">Parse + validate</text><text x="6" y="374" class="label blue" text-anchor="start">A → B · November 17 · 3 offers</text><rect x="6" y="383" width="111" height="79" rx="3" class="offer-sheet own" /><text x="15" y="401" class="small" text-anchor="start">Our airline</text><text x="15" y="418" class="small" text-anchor="start">economy</text><text x="15" y="445" class="price own" text-anchor="start">$240</text><rect x="126" y="383" width="111" height="79" rx="3" class="offer-sheet comp" /><text x="135" y="401" class="small" text-anchor="start">Competitor</text><text x="135" y="418" class="small" text-anchor="start">discount</text><text x="135" y="445" class="price comp" text-anchor="start">$220</text><rect x="246" y="383" width="111" height="79" rx="3" class="offer-sheet comp" /><text x="255" y="401" class="small" text-anchor="start">Competitor</text><text x="255" y="418" class="small" text-anchor="start">economy</text><text x="255" y="445" class="price comp" text-anchor="start">$270</text><text x="16" y="286" class="small muted" text-anchor="start">One shared plan</text><text x="16" y="303" class="small blue" text-anchor="start">80 physical queries</text></svg><div class="fs-equation">160 assignments <i>→</i> <b>80 queries</b> <i>=</i> 20 cached + 60 fetched <i>→</i> <b>120 offers</b></div><div class="fs-record-strip"><span>One normalized offer</span><pre><code>route=A-B · departure=2026-11-17 · cabin=economy · trip=OW · stops=0 · sale=US
source=airline-site · observed_at=08:05Z · currency=USD · tax=included · total_minor=24000</code></pre></div></div>

<figcaption>Merged watchlists share source calls; cached replies retain their original observation times.</figcaption>
</figure>

<p>A retry checks prior success and the deadline before choosing a substitute. Invalid currency or an unparseable price goes into a rejection log. It must never become a zero-dollar fare.</p>

<h2 id="2-build-an-offer-table-with-a-precise-grain">2. Build an offer table with a precise grain</h2>

<p>The central table would contain <strong>one itinerary offer, from one source, at one observation time</strong>. I’d keep monetary amounts as decimal values or integer minor units, along with currency, tax basis, product group, booking class and fare restrictions. A normalized product group maps different airline bundle names onto a comparison category; it does not prove identical benefits.</p>

<p>A batch job joins offers to collection ownership, run metadata, exchange rates, city mappings and product mappings. Preserve the UTC observation timestamp separately from the customer’s local reporting date. Partition Parquet by customer and reporting date, cluster files by route, and compact small files. Avoid creating a partition for every search.</p>

<figure class="fig wide fs" id="fs-commit">
<!-- Generated from one shared fictional dataset. -->
<div class="fs-technical"><div class="fs-overline"><strong>Curate → materialize</strong><span>A → B · November 17</span></div><svg class="fs-schematic fs-schema-wide" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 270" role="img" aria-label="Raw replies, run ownership and reference maps join into curated offer rows, then branch to customer export, comparison and history."><defs><marker id="fs-art-storage-800" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 1L7 4L0 7" class="arrow" /></marker></defs><path d="M154 89C186.5 89 186.5 145 219 145" class="wire" marker-end="url(#fs-art-storage-800)" /><path d="M154 171C186.5 171 186.5 145 219 145" class="wire" marker-end="url(#fs-art-storage-800)" /><path d="M401 55V60H235V130" class="wire reference-wire" marker-end="url(#fs-art-storage-800)" /><path d="M249 145H282" class="wire strong" marker-end="url(#fs-art-storage-800)" /><path d="M576 145H608V52H637" class="wire" marker-end="url(#fs-art-storage-800)" /><path d="M608 145H637" class="wire strong" marker-end="url(#fs-art-storage-800)" /><path d="M608 145V232H637" class="wire" marker-end="url(#fs-art-storage-800)" /><rect x="7" y="59" width="142" height="54" rx="4" class="paper-back" /><rect x="12" y="64" width="142" height="54" rx="4" class="node" /><text x="83" y="85" class="node-title" text-anchor="middle">Raw replies</text><text x="83" y="103" class="node-sub" text-anchor="middle">one source response</text><rect x="12" y="145" width="142" height="52" rx="5" class="node " /><text x="83" y="166" class="node-title" text-anchor="middle">Run ownership</text><text x="83" y="184" class="node-sub" text-anchor="middle">customer / local day</text><rect x="267" y="19" width="268" height="36" rx="5" class="node reference-node" /><text x="401" y="41" class="node-title" text-anchor="middle">FX · city · product maps</text><circle cx="234" cy="145" r="15" class="join-dot" /><text x="234" y="150" class="join-mark" text-anchor="middle">+</text><rect x="282" y="84" width="294" height="121" rx="4" class="offer-sheet" /><text x="294" y="104" class="small muted" text-anchor="start">airline</text><text x="405.48" y="104" class="small muted" text-anchor="start">group</text><text x="562" y="104" class="small muted" text-anchor="end">USD cents</text><path d="M292 113L566 113" class="rule" /><text x="294" y="131" class="small" text-anchor="start">Our airline</text><text x="405.48" y="131" class="small" text-anchor="start">economy</text><text x="562" y="131" class="small mono own" text-anchor="end">24000</text><path d="M292 141L566 141" class="rule" /><text x="294" y="159" class="small" text-anchor="start">Competitor</text><text x="405.48" y="159" class="small" text-anchor="start">discount</text><text x="562" y="159" class="small mono comp" text-anchor="end">22000</text><path d="M292 169L566 169" class="rule" /><text x="294" y="187" class="small" text-anchor="start">Competitor</text><text x="405.48" y="187" class="small" text-anchor="start">economy</text><text x="562" y="187" class="small mono comp" text-anchor="end">27000</text><text x="282" y="73" class="label blue" text-anchor="start">Curated offers</text><text x="282" y="225" class="small blue" text-anchor="start">A → B · Nov 17 · 21 days out</text><rect x="637" y="26" width="151" height="52" rx="5" class="node " /><text x="712.5" y="47" class="node-title" text-anchor="middle">Customer export</text><text x="712.5" y="65" class="node-sub" text-anchor="middle">format / release delay</text><rect x="637" y="119" width="151" height="52" rx="5" class="node trace-node" /><text x="712.5" y="140" class="node-title" text-anchor="middle">Comparison view</text><text x="712.5" y="158" class="node-sub" text-anchor="middle">cell × airline × product</text><rect x="637" y="206" width="151" height="52" rx="5" class="node " /><text x="712.5" y="227" class="node-title" text-anchor="middle">History table</text><text x="712.5" y="245" class="node-sub" text-anchor="middle">departure × observation</text><text x="282" y="250" class="small muted" text-anchor="start">Partition by customer / day; cluster by route.</text></svg><svg class="fs-schematic fs-schema-small" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 360 421" role="img" aria-label="Raw replies, run ownership and reference maps join into curated offer rows, then branch to customer export, comparison and history."><defs><marker id="fs-art-storage-360" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto"><path d="M0 1L7 4L0 7" class="arrow" /></marker></defs><path d="M85 69V83H180V96" class="wire" marker-end="url(#fs-art-storage-360)" /><path d="M275 69V83H180" class="wire" /><path d="M180 130V156" class="wire strong" marker-end="url(#fs-art-storage-360)" /><path d="M180 277V326H63V349" class="wire" marker-end="url(#fs-art-storage-360)" /><path d="M180 326V349" class="wire strong" marker-end="url(#fs-art-storage-360)" /><path d="M180 326H297V349" class="wire" marker-end="url(#fs-art-storage-360)" /><rect x="10" y="17" width="150" height="52" rx="5" class="node " /><text x="85" y="38" class="node-title" text-anchor="middle">Raw replies</text><text x="85" y="56" class="node-sub" text-anchor="middle">one source response</text><rect x="200" y="17" width="150" height="52" rx="5" class="node " /><text x="275" y="38" class="node-title" text-anchor="middle">Run ownership</text><text x="275" y="56" class="node-sub" text-anchor="middle">customer / local day</text><rect x="10" y="96" width="340" height="34" rx="5" class="node reference-node" /><text x="180" y="117" class="node-title" text-anchor="middle">Join FX · city · product maps</text><rect x="10" y="156" width="340" height="121" rx="4" class="offer-sheet" /><text x="22" y="176" class="small muted" text-anchor="start">airline</text><text x="152.79999999999998" y="176" class="small muted" text-anchor="start">group</text><text x="336" y="176" class="small muted" text-anchor="end">USD cents</text><path d="M20 185L340 185" class="rule" /><text x="22" y="203" class="small" text-anchor="start">Our airline</text><text x="152.79999999999998" y="203" class="small" text-anchor="start">economy</text><text x="336" y="203" class="small mono own" text-anchor="end">24000</text><path d="M20 213L340 213" class="rule" /><text x="22" y="231" class="small" text-anchor="start">Competitor</text><text x="152.79999999999998" y="231" class="small" text-anchor="start">discount</text><text x="336" y="231" class="small mono comp" text-anchor="end">22000</text><path d="M20 241L340 241" class="rule" /><text x="22" y="259" class="small" text-anchor="start">Competitor</text><text x="152.79999999999998" y="259" class="small" text-anchor="start">economy</text><text x="336" y="259" class="small mono comp" text-anchor="end">27000</text><text x="10" y="298" class="small blue" text-anchor="start">A → B · Nov 17 · 21 days out</text><rect x="10" y="349" width="106" height="52" rx="5" class="node " /><text x="63" y="370" class="node-title" text-anchor="middle">Export</text><text x="63" y="388" class="node-sub" text-anchor="middle">format / delay</text><rect x="127" y="349" width="106" height="52" rx="5" class="node trace-node" /><text x="180" y="370" class="node-title" text-anchor="middle">Compare</text><text x="180" y="388" class="node-sub" text-anchor="middle">cell × pair</text><rect x="244" y="349" width="106" height="52" rx="5" class="node " /><text x="297" y="370" class="node-title" text-anchor="middle">History</text><text x="297" y="388" class="node-sub" text-anchor="middle">date × time</text></svg><div class="fs-pair fs-storage-code"><div class="fs-subsection"><h3>Minimum fare per cell / airline / product</h3><pre><code>SELECT route, departure, stops, cabin, trip,
       stay_nights, country_of_sale, carrier,
       product_group, MIN(total_usd_minor) AS fare
FROM offers
WHERE customer = :customer AND reporting_day = :day
  AND collection_run = :run
GROUP BY 1,2,3,4,5,6,7,8,9;</code></pre></div><div class="fs-subsection"><h3>Physical layout and readiness</h3><div class="fs-tree"><span>curated offers</span><div>└ customer / reporting_day<div>└ route-clustered Parquet files</div></div></div><p>Keep source timestamps; compact small files.</p><p><b>Export:</b> format, destination and release policy.<br /><b>Analytics:</b> batch completion and late-input audit.</p></div></div></div>

<figcaption>Different table grains, one shared dataset. Exports and analytics branch after curation.</figcaption>
</figure>

<p>Customer exports get their own format, destination and release-delay policy. Analytics jobs track completion per batch and report late inputs. I’d avoid treating an export’s delivery time as the analytics completion signal.</p>

<h2 id="3-build-a-market-view-then-a-detector">3. Build a market view, then a detector</h2>

<p>I’d group by route, departure, stops, cabin and trip type, including stay length for return trips. Within one collection run, compute minimum fares per cell, airline and product group. Convert currency on a declared basis; a return fare can be halved for a one-way equivalent, while retaining its trip and stay-length group.</p>

<p>The comparison rule matters: use the lowest product, match the same group, or use a cheaper alternative when it beats our fare. Store the selected product and rule with the result. Below, changing the rule changes a <strong>$20 disadvantage into a $30 advantage</strong>.</p>

<figure class="fig wide fs" id="fs-compare" data-workspace="/blogs/assets/data/fare-system/workspace.json?v=20261027.2">
<!-- Generated from one shared fictional dataset. -->
<div class="fs-technical"><div class="fs-dashboard" aria-label="Market pricing dashboard concept"><div class="dash-header"><div><span class="dash-eyebrow">PRICING WORKSPACE · DESIGN PREVIEW</span><h3>Market monitor</h3><p>27 Oct 2026 · 08:10 UTC snapshot</p></div><span class="dash-status" data-state="ok">40/40 dates comparable</span></div><div class="dash-scope"><span><b>Market</b> A → B</span><span><b>Cabin</b> Economy</span><span><b>Trip</b> One way</span><span><b>Sale / currency</b> US / USD · tax included</span><span><b>Compare</b> Lowest available</span></div><dl class="dash-summary"><div><dt>Competitor cheaper</dt><dd>22/40</dd><small>Current position</small></div><div><dt>Dates to investigate</dt><dd>3</dd><small>1 grouped pricing event</small></div><div><dt>Selected source age</dt><dd>5 min</dd><small>Observed 08:05 UTC</small></div></dl><div class="dash-market-grid"><section class="dash-panel "><div class="dash-panel-title"><h3>Fares by departure</h3><span>Departure date →</span></div><div class="dash-legend"><span class="own">Our economy</span><span class="price">Competitor discount</span><span class="event">New move</span></div><svg class="dash-chart-wide" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 460 185" role="img" aria-label="Fares by departure date. November 17: our economy 240 dollars; competitor discount 220 dollars. Review shading tracks the discount product independently."><rect x="242.13141025641025" y="13" width="10.25" height="136" class="dash-event-band" /><rect x="252.64423076923072" y="13" width="10.25" height="136" class="dash-event-band" /><rect x="263.15705128205127" y="13" width="10.25" height="136" class="dash-event-band" /><path d="M37 139.28571428571428L447 139.28571428571428" class="dash-grid" /><text x="31" y="143.28571428571428" class="dash-tick" text-anchor="end">$200</text><path d="M37 81L447 81" class="dash-grid" /><text x="31" y="85" class="dash-tick" text-anchor="end">$260</text><path d="M37 22.714285714285708L447 22.714285714285708" class="dash-grid" /><text x="31" y="26.714285714285708" class="dash-tick" text-anchor="end">$320</text><path d="M37 116.02971428571428 L47.51282051282051 115.136 L58.02564102564102 114.184 L68.53846153846155 113.18342857142858 L79.05128205128204 112.144 L89.56410256410257 111.07542857142857 L100.07692307692308 109.99714285714285 L110.58974358974359 108.91885714285715 L121.1025641025641 107.86 L131.61538461538464 106.82057142857143 L142.12820512820514 105.82971428571429 L152.64102564102564 104.89714285714285 L163.15384615384616 104.02285714285713 L173.66666666666666 103.22628571428572 L184.17948717948718 102.50742857142856 L194.6923076923077 101.88571428571429 L205.2051282051282 101.37085714285715 L215.71794871794873 100.96285714285715 L226.23076923076925 100.67142857142858 L236.74358974358975 100.48685714285715 L247.25641025641025 100.42857142857143 L257.7692307692307 100.48685714285715 L268.28205128205127 100.67142857142858 L278.7948717948718 100.96285714285715 L289.3076923076923 101.37085714285715 L299.8205128205128 101.88571428571429 L310.3333333333333 102.50742857142856 L320.8461538461538 103.22628571428572 L331.35897435897436 104.02285714285713 L341.87179487179486 104.89714285714285 L352.3846153846154 105.82971428571429 L362.89743589743586 106.82057142857143 L373.4102564102564 107.86 L383.9230769230769 108.91885714285715 L394.43589743589746 109.99714285714285 L404.94871794871796 111.07542857142857 L415.4615384615385 112.144 L425.97435897435895 113.18342857142858 L436.4871794871795 114.184 L447 115.136" class="dash-own-line" /><path d="M37 116.02971428571428 L47.51282051282051 133.34057142857142 L58.02564102564102 132.4662857142857 L68.53846153846155 131.55314285714286 L79.05128205128204 130.60114285714286 L89.56410256410257 129.62 L100.07692307692308 128.62914285714285 L110.58974358974359 127.63828571428571 L121.1025641025641 126.66685714285714 L131.61538461538464 125.71485714285714 L142.12820512820514 124.81142857142856 L152.64102564102564 123.95657142857144 L163.15384615384616 104.02285714285713 L173.66666666666666 103.22628571428572 L184.17948717948718 102.50742857142856 L194.6923076923077 101.88571428571429 L205.2051282051282 101.37085714285715 L215.71794871794873 120.34285714285714 L226.23076923076925 120.08057142857143 L236.74358974358975 119.91542857142858 L247.25641025641025 119.85714285714286 L257.7692307692307 119.91542857142858 L268.28205128205127 120.08057142857143 L278.7948717948718 120.34285714285714 L289.3076923076923 120.72171428571428 L299.8205128205128 121.19771428571428 L310.3333333333333 121.76114285714286 L320.8461538461538 122.42171428571429 L331.35897435897436 104.02285714285713 L341.87179487179486 104.89714285714285 L352.3846153846154 91.25828571428572 L362.89743589743586 92.24914285714286 L373.4102564102564 93.28857142857143 L383.9230769230769 94.34742857142857 L394.43589743589746 95.42571428571429 L404.94871794871796 96.50399999999999 L415.4615384615385 97.57257142857142 L425.97435897435895 98.612 L436.4871794871795 99.61257142857143 L447 100.56457142857143" class="dash-price-line" /><path d="M247.25641025641025 13L247.25641025641025 149" class="dash-cursor" /><circle cx="247.25641025641025" cy="100.42857142857143" r="3" class="dash-own-dot" /><circle cx="247.25641025641025" cy="119.85714285714286" r="4" class="dash-price-dot" /><text x="255.25641025641025" y="92.42857142857143" class="dash-value dash-own" text-anchor="start">$240</text><text x="255.25641025641025" y="136.85714285714286" class="dash-value dash-price" text-anchor="start">$220</text><text x="37" y="172" class="dash-tick" text-anchor="start">Oct 28</text><text x="247.25641025641025" y="172" class="dash-tick" text-anchor="middle">Nov 17</text><text x="447" y="172" class="dash-tick" text-anchor="end">Dec 6</text></svg><svg class="dash-chart-small" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 185" role="img" aria-label="Fares by departure date. November 17: our economy 240 dollars; competitor discount 220 dollars. Review shading tracks the discount product independently."><rect x="172.08653846153845" y="13" width="6.75" height="136" class="dash-event-band" /><rect x="179.0096153846154" y="13" width="6.75" height="136" class="dash-event-band" /><rect x="185.9326923076923" y="13" width="6.75" height="136" class="dash-event-band" /><path d="M37 139.28571428571428L307 139.28571428571428" class="dash-grid" /><text x="31" y="143.28571428571428" class="dash-tick" text-anchor="end">$200</text><path d="M37 81L307 81" class="dash-grid" /><text x="31" y="85" class="dash-tick" text-anchor="end">$260</text><path d="M37 22.714285714285708L307 22.714285714285708" class="dash-grid" /><text x="31" y="26.714285714285708" class="dash-tick" text-anchor="end">$320</text><path d="M37 116.02971428571428 L43.92307692307692 115.136 L50.84615384615385 114.184 L57.769230769230774 113.18342857142858 L64.6923076923077 112.144 L71.61538461538461 111.07542857142857 L78.53846153846155 109.99714285714285 L85.46153846153845 108.91885714285715 L92.38461538461539 107.86 L99.30769230769232 106.82057142857143 L106.23076923076923 105.82971428571429 L113.15384615384615 104.89714285714285 L120.07692307692308 104.02285714285713 L127 103.22628571428572 L133.9230769230769 102.50742857142856 L140.84615384615387 101.88571428571429 L147.76923076923077 101.37085714285715 L154.69230769230768 100.96285714285715 L161.61538461538464 100.67142857142858 L168.53846153846155 100.48685714285715 L175.46153846153845 100.42857142857143 L182.3846153846154 100.48685714285715 L189.3076923076923 100.67142857142858 L196.23076923076923 100.96285714285715 L203.15384615384616 101.37085714285715 L210.0769230769231 101.88571428571429 L217 102.50742857142856 L223.9230769230769 103.22628571428572 L230.84615384615384 104.02285714285713 L237.76923076923077 104.89714285714285 L244.6923076923077 105.82971428571429 L251.6153846153846 106.82057142857143 L258.53846153846155 107.86 L265.46153846153845 108.91885714285715 L272.38461538461536 109.99714285714285 L279.3076923076923 111.07542857142857 L286.2307692307693 112.144 L293.15384615384613 113.18342857142858 L300.0769230769231 114.184 L307 115.136" class="dash-own-line" /><path d="M37 116.02971428571428 L43.92307692307692 133.34057142857142 L50.84615384615385 132.4662857142857 L57.769230769230774 131.55314285714286 L64.6923076923077 130.60114285714286 L71.61538461538461 129.62 L78.53846153846155 128.62914285714285 L85.46153846153845 127.63828571428571 L92.38461538461539 126.66685714285714 L99.30769230769232 125.71485714285714 L106.23076923076923 124.81142857142856 L113.15384615384615 123.95657142857144 L120.07692307692308 104.02285714285713 L127 103.22628571428572 L133.9230769230769 102.50742857142856 L140.84615384615387 101.88571428571429 L147.76923076923077 101.37085714285715 L154.69230769230768 120.34285714285714 L161.61538461538464 120.08057142857143 L168.53846153846155 119.91542857142858 L175.46153846153845 119.85714285714286 L182.3846153846154 119.91542857142858 L189.3076923076923 120.08057142857143 L196.23076923076923 120.34285714285714 L203.15384615384616 120.72171428571428 L210.0769230769231 121.19771428571428 L217 121.76114285714286 L223.9230769230769 122.42171428571429 L230.84615384615384 104.02285714285713 L237.76923076923077 104.89714285714285 L244.6923076923077 91.25828571428572 L251.6153846153846 92.24914285714286 L258.53846153846155 93.28857142857143 L265.46153846153845 94.34742857142857 L272.38461538461536 95.42571428571429 L279.3076923076923 96.50399999999999 L286.2307692307693 97.57257142857142 L293.15384615384613 98.612 L300.0769230769231 99.61257142857143 L307 100.56457142857143" class="dash-price-line" /><path d="M175.46153846153845 13L175.46153846153845 149" class="dash-cursor" /><circle cx="175.46153846153845" cy="100.42857142857143" r="3" class="dash-own-dot" /><circle cx="175.46153846153845" cy="119.85714285714286" r="4" class="dash-price-dot" /><text x="183.46153846153845" y="92.42857142857143" class="dash-value dash-own" text-anchor="start">$240</text><text x="183.46153846153845" y="136.85714285714286" class="dash-value dash-price" text-anchor="start">$220</text><text x="37" y="172" class="dash-tick" text-anchor="start">Oct 28</text><text x="175.46153846153845" y="172" class="dash-tick" text-anchor="middle">Nov 17</text><text x="307" y="172" class="dash-tick" text-anchor="end">Dec 6</text></svg><div class="dash-chart-foot">November 17: our $240 is <b>$20 above the competitor.</b></div><div class="dash-matrix-label"><b>Review map</b><span>3 review · 37 no review</span></div><svg class="dash-chart-wide" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 460 75" role="img" aria-label="Forty departure dates: three confirmed review dates and thirty-seven without a review event. November 17 is outlined."><g><title>Oct 28: no review</title><rect x="14" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 29: no review</title><rect x="35.6" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 30: no review</title><rect x="57.2" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 31: no review</title><rect x="78.80000000000001" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 1: no review</title><rect x="100.4" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 2: no review</title><rect x="122" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 3: no review</title><rect x="143.60000000000002" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 4: no review</title><rect x="165.20000000000002" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 5: no review</title><rect x="186.8" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 6: no review</title><rect x="208.4" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 7: no review</title><rect x="230" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 8: no review</title><rect x="251.60000000000002" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 9: no review</title><rect x="273.20000000000005" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 10: no review</title><rect x="294.8" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 11: no review</title><rect x="316.40000000000003" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 12: no review</title><rect x="338" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 13: no review</title><rect x="359.6" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 14: no review</title><rect x="381.20000000000005" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 15: no review</title><rect x="402.8" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 16: no review</title><rect x="424.40000000000003" y="5" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 17: review</title><rect x="14" y="26" width="17.6" height="12" rx="2" class="dash-hot-cell" /><rect x="12" y="23" width="21.6" height="18" rx="3" class="dash-selected-cell" /></g><g><title>Nov 18: review</title><rect x="35.6" y="26" width="17.6" height="12" rx="2" class="dash-hot-cell" /></g><g><title>Nov 19: review</title><rect x="57.2" y="26" width="17.6" height="12" rx="2" class="dash-hot-cell" /></g><g><title>Nov 20: no review</title><rect x="78.80000000000001" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 21: no review</title><rect x="100.4" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 22: no review</title><rect x="122" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 23: no review</title><rect x="143.60000000000002" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 24: no review</title><rect x="165.20000000000002" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 25: no review</title><rect x="186.8" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 26: no review</title><rect x="208.4" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 27: no review</title><rect x="230" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 28: no review</title><rect x="251.60000000000002" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 29: no review</title><rect x="273.20000000000005" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 30: no review</title><rect x="294.8" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 1: no review</title><rect x="316.40000000000003" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 2: no review</title><rect x="338" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 3: no review</title><rect x="359.6" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 4: no review</title><rect x="381.20000000000005" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 5: no review</title><rect x="402.8" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 6: no review</title><rect x="424.40000000000003" y="26" width="17.6" height="12" rx="2" class="dash-normal-cell" /></g><text x="14" y="64" class="dash-tick dash-own" text-anchor="start">Nov 17 selected · each cell is one departure</text></svg><svg class="dash-chart-small" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 75" role="img" aria-label="Forty departure dates: three confirmed review dates and thirty-seven without a review event. November 17 is outlined."><g><title>Oct 28: no review</title><rect x="14" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 29: no review</title><rect x="28.6" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 30: no review</title><rect x="43.2" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Oct 31: no review</title><rect x="57.8" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 1: no review</title><rect x="72.4" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 2: no review</title><rect x="87" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 3: no review</title><rect x="101.6" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 4: no review</title><rect x="116.2" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 5: no review</title><rect x="130.8" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 6: no review</title><rect x="145.4" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 7: no review</title><rect x="160" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 8: no review</title><rect x="174.6" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 9: no review</title><rect x="189.2" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 10: no review</title><rect x="203.79999999999998" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 11: no review</title><rect x="218.4" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 12: no review</title><rect x="233" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 13: no review</title><rect x="247.6" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 14: no review</title><rect x="262.2" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 15: no review</title><rect x="276.8" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 16: no review</title><rect x="291.4" y="5" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 17: review</title><rect x="14" y="26" width="10.6" height="12" rx="2" class="dash-hot-cell" /><rect x="12" y="23" width="14.6" height="18" rx="3" class="dash-selected-cell" /></g><g><title>Nov 18: review</title><rect x="28.6" y="26" width="10.6" height="12" rx="2" class="dash-hot-cell" /></g><g><title>Nov 19: review</title><rect x="43.2" y="26" width="10.6" height="12" rx="2" class="dash-hot-cell" /></g><g><title>Nov 20: no review</title><rect x="57.8" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 21: no review</title><rect x="72.4" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 22: no review</title><rect x="87" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 23: no review</title><rect x="101.6" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 24: no review</title><rect x="116.2" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 25: no review</title><rect x="130.8" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 26: no review</title><rect x="145.4" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 27: no review</title><rect x="160" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 28: no review</title><rect x="174.6" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 29: no review</title><rect x="189.2" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Nov 30: no review</title><rect x="203.79999999999998" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 1: no review</title><rect x="218.4" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 2: no review</title><rect x="233" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 3: no review</title><rect x="247.6" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 4: no review</title><rect x="262.2" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 5: no review</title><rect x="276.8" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><g><title>Dec 6: no review</title><rect x="291.4" y="26" width="10.6" height="12" rx="2" class="dash-normal-cell" /></g><text x="14" y="64" class="dash-tick dash-own" text-anchor="start">Nov 17 selected · each cell is one departure</text></svg></section><section class="dash-panel dash-queue"><div class="dash-panel-title"><h3>Review queue</h3><span>Grouped by market / product</span></div><a class="dash-event" href="#fs-product"><span class="dash-event-label">CONFIRMED PRICE MOVE</span><strong>Competitor cut discount fares</strong><span>A → B · Nov 17–19</span><b>$15 below expected</b><span>3 departure dates · 3 fresh checks</span><em>Investigate November 17 →</em></a><div class="dash-quiet"><strong>Other 37 dates</strong><span>No confirmed material move</span></div><div class="dash-rule-summary"><strong>Configured benchmark</strong><span>Discount gap &gt; $15: 22 matching dates</span><small>Rule matches are separate from anomalies.</small></div></section></div><div class="dash-context-note">Lowest available selects competitor discount at <b>$220</b>. Price-move reviews track the discount product against its own history.</div></div></div>

<figcaption>Switch the comparison rule: the same flight changes position. Reviews track the discount product against its own history.</figcaption>
</figure>

<p>I’d detect unexpected movement against a <strong>context-aware forecast</strong>: the same market, product, weekday and days before departure. The prototype takes the median of eight matching historical weekdays and calibrates a range from fifty-six past walk-forward forecast errors. Today never helps set its own threshold.</p>

<p>Our competitor’s <strong>$220</strong> offer is <strong>$15 below its $235 expected price</strong>. That differs from its $20 gap to us. I’d require a move of at least $10 or 3%, whichever is larger, confirmed by two of three fresh observations in the same direction, at least ten minutes apart. Stale data, a missing selected source or changed product scope stops the pricing decision. Duplicate cache reads cannot provide extra confirmations.</p>

<p>Configured fare/class benchmarks remain separate. A $15 gap rule can match a perfectly ordinary price; that alone should not create an anomaly.</p>

<h2 id="4-let-the-analyst-inspect-the-move">4. Let the analyst inspect the move</h2>

<p>I’d build two read paths: route prices across departure dates from partitioned Parquet, and one departure’s observation history from a time-series table. The API checks customer access, resolves an explicit observation cutoff, and returns the data with its coverage and comparison rule. A small Parquet response lets DuckDB-WASM handle browser-side filtering.</p>

<figure class="fig wide fs" id="fs-product">
<!-- Generated from one shared fictional dataset. -->
<div class="fs-technical"><div class="fs-dashboard" aria-label="Selected flight anomaly dashboard concept"><div class="dash-header"><div><span class="dash-eyebrow">PRICING WORKSPACE · DESIGN PREVIEW</span><h3>A → B · November 17</h3><p>21 days before departure · competitor discount product</p></div><span class="dash-status" data-state="ok">Confirmed price cut</span></div><dl class="dash-summary"><div><dt>Observed competitor</dt><dd>$220</dd><small>3 fresh observations</small></div><div><dt>Expected competitor</dt><dd>$235</dd><small>Matched historical context</small></div><div><dt>Unexpected movement</dt><dd>$15 lower</dd><small>Confirmed · raw gap to us: $20</small></div></dl><div class="dash-detail-grid"><section class="dash-panel "><div class="dash-panel-title"><h3>Price move in context</h3><span>Same departure · one observation per day</span></div><div class="dash-legend"><span class="price">Observed</span><span class="expected">Expected before observation</span><span class="band">Past-error range</span></div><svg class="dash-chart-wide" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 460 207" role="img" aria-label="Daily observations of the same November 17 departure. The last point is 220 dollars; confirmation evidence is listed separately below."><path d="M38 170L446 170" class="dash-grid" /><text x="32" y="174" class="dash-tick" text-anchor="end">$180</text><path d="M38 93.5L446 93.5" class="dash-grid" /><text x="32" y="97.5" class="dash-tick" text-anchor="end">$220</text><path d="M38 17L446 17" class="dash-grid" /><text x="32" y="21" class="dash-tick" text-anchor="end">$260</text><path d="M38 34.88187499999998 L67.14285714285714 29.89025000000001 L96.28571428571428 30.674374999999998 L125.42857142857143 22.890500000000003 L154.57142857142856 74.48975 L183.71428571428572 55.44125 L212.85714285714286 55.63249999999999 L242 90.899 L271.1428571428571 87.68599999999999 L300.2857142857143 83.70800000000001 L329.42857142857144 77.989625 L358.57142857142856 134.61875 L387.7142857142857 66.20862500000001 L416.8571428571429 55.36475 L446 57.162499999999994 L446 72.4625 L416.8571428571429 74.48975 L387.7142857142857 81.50862500000001 L358.57142857142856 149.91875 L329.42857142857144 97.114625 L300.2857142857143 102.833 L271.1428571428571 106.811 L242 110.024 L212.85714285714286 74.7575 L183.71428571428572 74.56625 L154.57142857142856 93.61475 L125.42857142857143 42.0155 L96.28571428571428 45.974374999999995 L67.14285714285714 45.190250000000006 L38 54.006874999999994 Z" class="dash-expected-band" /><path d="M38 44.444374999999994 L67.14285714285714 37.540249999999986 L96.28571428571428 38.324375 L125.42857142857143 32.453 L154.57142857142856 84.05225 L183.71428571428572 65.00375 L212.85714285714286 65.195 L242 100.4615 L271.1428571428571 97.2485 L300.2857142857143 93.27050000000001 L329.42857142857144 87.552125 L358.57142857142856 142.26875 L387.7142857142857 73.858625 L416.8571428571429 64.92725 L446 64.8125" class="dash-expected-line" /><path d="M38 51.138125 L67.14285714285714 45.190250000000006 L96.28571428571428 37.36812500000002 L125.42857142857143 41.05924999999999 L154.57142857142856 86.92099999999999 L183.71428571428572 65.96 L212.85714285714286 58.50125 L242 98.54899999999999 L271.1428571428571 89.5985 L300.2857142857143 99.96425 L329.42857142857144 85.63962500000001 L358.57142857142856 148.00625 L387.7142857142857 74.814875 L416.8571428571429 64.92725 L446 93.5" class="dash-price-line" /><path d="M446 17L446 170" class="dash-cursor" /><circle cx="446" cy="93.5" r="4" class="dash-price-dot" /><text x="439" y="112.5" class="dash-value dash-price" text-anchor="end">$220</text><text x="38" y="194" class="dash-tick" text-anchor="start">Oct 13</text><text x="242" y="194" class="dash-tick" text-anchor="middle">Oct 20</text><text x="446" y="194" class="dash-tick" text-anchor="end">Oct 27</text></svg><svg class="dash-chart-small" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 207" role="img" aria-label="Daily observations of the same November 17 departure. The last point is 220 dollars; confirmation evidence is listed separately below."><path d="M38 170L306 170" class="dash-grid" /><text x="32" y="174" class="dash-tick" text-anchor="end">$180</text><path d="M38 93.5L306 93.5" class="dash-grid" /><text x="32" y="97.5" class="dash-tick" text-anchor="end">$220</text><path d="M38 17L306 17" class="dash-grid" /><text x="32" y="21" class="dash-tick" text-anchor="end">$260</text><path d="M38 34.88187499999998 L57.14285714285714 29.89025000000001 L76.28571428571428 30.674374999999998 L95.42857142857142 22.890500000000003 L114.57142857142857 74.48975 L133.71428571428572 55.44125 L152.85714285714283 55.63249999999999 L172 90.899 L191.14285714285714 87.68599999999999 L210.2857142857143 83.70800000000001 L229.42857142857144 77.989625 L248.57142857142856 134.61875 L267.71428571428567 66.20862500000001 L286.8571428571429 55.36475 L306 57.162499999999994 L306 72.4625 L286.8571428571429 74.48975 L267.71428571428567 81.50862500000001 L248.57142857142856 149.91875 L229.42857142857144 97.114625 L210.2857142857143 102.833 L191.14285714285714 106.811 L172 110.024 L152.85714285714283 74.7575 L133.71428571428572 74.56625 L114.57142857142857 93.61475 L95.42857142857142 42.0155 L76.28571428571428 45.974374999999995 L57.14285714285714 45.190250000000006 L38 54.006874999999994 Z" class="dash-expected-band" /><path d="M38 44.444374999999994 L57.14285714285714 37.540249999999986 L76.28571428571428 38.324375 L95.42857142857142 32.453 L114.57142857142857 84.05225 L133.71428571428572 65.00375 L152.85714285714283 65.195 L172 100.4615 L191.14285714285714 97.2485 L210.2857142857143 93.27050000000001 L229.42857142857144 87.552125 L248.57142857142856 142.26875 L267.71428571428567 73.858625 L286.8571428571429 64.92725 L306 64.8125" class="dash-expected-line" /><path d="M38 51.138125 L57.14285714285714 45.190250000000006 L76.28571428571428 37.36812500000002 L95.42857142857142 41.05924999999999 L114.57142857142857 86.92099999999999 L133.71428571428572 65.96 L152.85714285714283 58.50125 L172 98.54899999999999 L191.14285714285714 89.5985 L210.2857142857143 99.96425 L229.42857142857144 85.63962500000001 L248.57142857142856 148.00625 L267.71428571428567 74.814875 L286.8571428571429 64.92725 L306 93.5" class="dash-price-line" /><path d="M306 17L306 170" class="dash-cursor" /><circle cx="306" cy="93.5" r="4" class="dash-price-dot" /><text x="299" y="112.5" class="dash-value dash-price" text-anchor="end">$220</text><text x="38" y="194" class="dash-tick" text-anchor="start">Oct 13</text><text x="172" y="194" class="dash-tick" text-anchor="middle">Oct 20</text><text x="306" y="194" class="dash-tick" text-anchor="end">Oct 27</text></svg><div class="dash-range-note">Today’s usual range: <b>$231–$239</b>. The $220 quote is outside this range.</div></section><section class="dash-panel "><div class="dash-panel-title"><h3>Evidence behind the review</h3><span>Source, product and freshness</span></div><ol class="dash-evidence"><li><span>Decision</span><b>3/3 confirm the move</b></li><li><span>Tracked product</span><b>Discount economy</b></li><li><span>Comparable coverage</span><b>40/40 departure dates</b></li><li><span>Materiality limit</span><b>At least $10</b></li><li><span>Price basis</span><b>USD · tax included</b></li></ol></section></div><div class="dash-quote-log"><div><span>07:35 UTC</span><b>$220</b><small>Fresh source observation</small></div><div><span>07:50 UTC</span><b>$220</b><small>Fresh source observation</small></div><div><span>08:05 UTC</span><b>$220</b><small>Fresh source observation</small></div></div><div class="dash-decision-note" data-state="review"><b>Ready for analyst review</b><span>Three fresh, time-separated $220 quotes confirm the move below the expected range.</span></div><div class="dash-fare-note"><strong>Published-fare lead: $210</strong><span>14-day purchase timing passes (21 days remain). Other fare rules, tax basis and seat availability are unverified.</span></div></div><div class="fs-model-design"><strong>Detector I’d build</strong><code>matched past → forecast error band → $10 / 3% materiality → 2 of 3 same-direction checks, 10+ min apart</code><code>GET /history?route=A-B&amp;departure=2026-11-17</code><span>Forecast and error calibration exclude today. Missing, stale or changed product scope stops the decision.</span></div></div>

<figcaption>Try one fresh check, a stale quote or a missing source. The price gap alone cannot confirm an alert.</figcaption>
</figure>

<p>For diagnosis, join shopping results to published fares and evaluate supported restrictions. Our $210 fare clears a fourteen-day advance-purchase check. Other restrictions, a comparable tax basis and seats available in that booking class—the fare’s inventory bucket—still need checking before anyone can treat $210 as sellable.</p>

<p>I’d audit planned, received, accepted, packaged and delivered work separately. Compare expected work with actual results, keep failed jobs in a dead-letter queue, and distinguish supplier failures from genuine empty results. A missing competitor reply reduces coverage; it does not mean their price stayed unchanged.</p>

<p>I’d ship collection, exports and history first. Detection comes once I can reproduce the comparison behind a warning. That gives an analyst a useful first product—and gives me a way to debug it.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[From supplier queues to comparable fares, anomaly detection and an analyst’s investigation: the schemas, calculations and query paths I’d build for an airline pricing analysis product.]]></summary></entry><entry><title type="html">Building a demand model from an unfinished curve</title><link href="https://sir-teo.github.io/blogs/2026/10/26/telling-more-shoppers-from-earlier-shoppers.html" rel="alternate" type="text/html" title="Building a demand model from an unfinished curve" /><published>2026-10-26T20:00:00-04:00</published><updated>2026-10-26T20:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/26/telling-more-shoppers-from-earlier-shoppers</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/26/telling-more-shoppers-from-earlier-shoppers.html"><![CDATA[<p>In one of my research projects at ATPCO, I explored a question: when ticket searches for a flight arrive faster than usual, how many are still to come before takeoff?</p>

<p>Each search counts, including repeats by the same person. The early lead might be extra interest, or simply earlier planning. We’ll use a made-up search history so we can check our forecast against a known ending.</p>

<h2 id="the-searches-so-far">The searches so far</h2>

<p>We draw a usual search pattern and call it the <strong>baseline</strong>. For a real flight, we’d estimate it from similar flights that have already taken off. Each bar covers a stretch of time before takeoff.</p>

<p>Then we change the pattern and <a class="act" href="#ts-input" data-view="today">hide the searches after today</a>. The beginning looks busy; the ending is still unknown.</p>

<figure class="fig wide ts" id="ts-input" data-stage="inputs" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>Move Now to reveal more of the same history; the forecasts below update together. Dots are recorded searches, gray bars the baseline. Future intervals stay hidden. Both axes use percentages of the baseline total and full time window.</figcaption>
</figure>

<h2 id="scaling-the-rest">Scaling the rest</h2>

<p>Add the dot values above to get the count seen so far, \(N\), and the gray bar values to get the expected count, \(N_0\). Our first forecast scales the baseline by their ratio:</p>

\[\hat s=\frac{N}{N_0}.\]

<p>The amber curve below is the gray baseline multiplied by \(\hat s\), including the part we haven’t seen.</p>

<figure class="fig wide ts" id="ts-naive" data-stage="flat" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>The dotted gaps show too few searches early and too many later. Dots from unfinished intervals are scaled up for comparison with a complete interval. The amber curve then overpredicts what remains.</figcaption>
</figure>

<p>The total fits, but the lead is fading across intervals. Some of the activity may have moved earlier. A multiplier can’t express that.</p>

<h2 id="moving-searches-earlier">Moving searches earlier</h2>

<p>Now draw a <strong>running total</strong>: each point adds up all searches received by that time. Its endpoint shows <strong>volume</strong>, the total number of searches. The path to it shows <strong>timing</strong>.</p>

<p>Let \(b_c\) be the baseline share in interval \(c\), and \(t_c\) its midpoint measured from the start. A timing control, \(\theta\), changes each share to</p>

\[p_c(\theta)=\frac{b_c\,e^{\theta t_c}}{\sum_j b_j\,e^{\theta t_j}}.\]

<p>Negative \(\theta\) favors earlier intervals. Dividing by the sum keeps the shares adding to one, so changing timing alone preserves the total.</p>

<p>With <a class="act" href="#ts-knobs" data-preset="earlier">earlier searches alone</a>, the curve gets ahead but reaches the same endpoint. Then allow <a class="act" href="#ts-knobs" data-preset="both">earlier searches and a larger total</a>. Both effects can be present in the same busy start.</p>

<figure class="fig wide ts ts-hero" id="ts-knobs" data-stage="design" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>The endpoint M is the full total; the dot at Now is what has arrived so far. Moving searches earlier raises the dot while M stays fixed. Increasing the total raises both.</figcaption>
</figure>

<p>The fraction already arrived, \(F\), comes straight from those two heights:</p>

\[F=\frac{\text{height at Now}}{M}.\]

<p>The live \(F\) readout changes with timing. Raising the total alone leaves this fraction unchanged.</p>

<h2 id="fitting-the-visible-part">Fitting the visible part</h2>

<p>To choose a timing curve, compare shares of searches seen so far. Write the recorded count in interval \(c\) as \(Y_c\), so each black dot below is \(Y_c/N\).</p>

<p>For the blue bars, multiply each full-interval share \(p_c\) by the fraction of that interval already elapsed, \(I_c\), then divide by the arrived fraction \(F\). Call this visible share \(q_c\). We adjust \(\theta\) until the fitted and recorded average arrival times agree:</p>

\[\begin{aligned}
q_c(\theta)&amp;=\frac{I_c\,p_c(\theta)}{F(\theta)},\\[0.6em]
\sum_c q_c(\hat\theta)\,t_c&amp;=\frac{\sum_c Y_c\,t_c}{N}.
\end{aligned}\]

<p>The two sides of the second line are the <strong>Fitted</strong> and <strong>Recorded</strong> averages. The markers below show when they agree.</p>

<figure class="fig wide ts" id="ts-fit" data-stage="timing" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>Blue bars show q; black dots show Y/N. The two markers underneath summarize their average arrival times. Only observed intervals enter the fit.</figcaption>
</figure>

<h2 id="forecasting-the-rest">Forecasting the rest</h2>

<p>The fitted share \(F\) is shown below. If \(N\) searches represent that fraction of the full total, the estimated endpoint is \(N/F\). Subtract the searches already recorded to get the rest:</p>

\[\begin{aligned}
\widehat M&amp;=\frac{N}{F},\\[0.4em]
\widehat R&amp;=\widehat M-N.
\end{aligned}\]

<figure class="fig wide ts" id="ts-future" data-stage="forecast" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>The blue R bar is the remaining count from the formula. Reveal the curve used to generate the hidden searches to check it. Here, allowing earlier searches brings the forecast closer to what remains.</figcaption>
</figure>

<p>The original multiplier was waiting for searches that had, in effect, already happened.</p>

<h2 id="too-early-to-tell">Too early to tell</h2>

<p>Move today farther back. With only one observed interval, changing the total or changing the timing can explain the same count. There isn’t enough of a pattern to separate them.</p>

<figure class="fig wide ts" id="ts-information" data-stage="identification" data-src="/blogs/assets/data/two-step/experiment.json?v=20261027.2">
<figcaption>The blue band shows different totals and timings that explain the same snapshot. Move the clock forward and the possibilities narrow. The cross is the setting used to generate the searches.</figcaption>
</figure>

<p>We keep the baseline forecast when the two effects can’t be separated. A brief burst of searches is another test for this smooth shape. Predicting ticket sales would require a further check: how often those searches turn into purchases.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[A busy start can mean more searches overall, or the same searches arriving earlier. Build a forecast, test it on synthetic histories, and check what remains.]]></summary></entry><entry><title type="html">One world, two players</title><link href="https://sir-teo.github.io/blogs/2026/10/26/one-world-two-players.html" rel="alternate" type="text/html" title="One world, two players" /><published>2026-10-26T13:00:00-04:00</published><updated>2026-10-26T13:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/26/one-world-two-players</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/26/one-world-two-players.html"><![CDATA[<p>The world from <a href="/2026/10/26/taking-minecraft-apart-one-block-at-a-time.html">Part 1</a> remembers the holes we dig, lets us walk through them, and carries torchlight into the next room. Now someone else joins. We both reach for the same block, almost at the same time. The world needs one answer about what happened.</p>

<p>I went back into the <strong>Java Edition 26.3 JAR</strong> to follow that answer through the connection listeners, block-action handlers, prediction records, remote-player updates, and save code. This time we’ll build a server as well as a client. The examples use an original WebSocket/JSON protocol and the same small landscape from Part 1, with real connections behind the diagrams.</p>

<p>Start with two copies of that world. Mine in the first one. The other copy has no way to know anything changed yet.</p>

<figure class="fig wide" id="mn-copies" data-minecraft-build="true" data-multi-stage="0">
<div class="ms-figure-head"><span class="ms-figure-index">00 / 07</span><strong>The same hillside, twice</strong><span class="ms-figure-meta">Two copies, two answers</span></div>
<figcaption>These first two arrays are independent. Removing the reference block changes the first copy. We need a connection before another player can see that edit.</figcaption>
</figure>

<h2 id="1-get-a-browser-into-the-world">1. Get a browser into the world</h2>

<p>Opening a connection only gives us a way to exchange bytes. The client still needs to know who it is, which world it joined, and when that world is ready to play.</p>

<p>In the JAR, the handshake chooses an intention such as login or status. <code class="language-plaintext highlighter-rouge">ServerLoginPacketListenerImpl</code> handles identity and login policy, including authentication when the server requires it. Configuration follows: feature flags, registry synchronization, and spawn preparation. The connection enters PLAY after those steps finish.</p>

<p>Our browser build has a smaller setup. A WebSocket opens, the browser asks to join a room, and the server replies with a player ID, the current block array, inventory, and player records. We validate that snapshot before enabling play. Each room begins with the same hillside; it then keeps its own edits.</p>

<figure class="fig wide" id="mn-connect" data-multi-stage="1">
<div class="ms-figure-head"><span class="ms-figure-index">01 / 07</span><strong>Join before you play</strong><span class="ms-figure-meta">Connection → snapshot → ready</span></div>
<figcaption>Connect to the running cave server. The browser receives all 8,192 cells and its own player record. The room code identifies this shared world.</figcaption>
</figure>

<p>Minecraft sends much more than this. <code class="language-plaintext highlighter-rouge">PlayerList.placeNewPlayer</code> initializes the player and world parameters, while <code class="language-plaintext highlighter-rouge">PlayerChunkSender</code> streams ready chunks in batches. A login packet is not the whole landscape. Our tiny world fits in one snapshot, so we can keep the state transition visible without implementing the full registry and chunk codecs.</p>

<h2 id="2-give-the-second-client-the-current-world">2. Give the second client the current world</h2>

<p>A joining player needs the world as it is now. Replaying an old list of edits would leave us deciding where that history begins and which changes still matter. A snapshot gives the newcomer a starting point; later updates carry it forward.</p>

<p>Connect the second client below. It opens another WebSocket to the same server, with its own identity and inventory. These two clients live on this page so we can inspect them together. At the end, the invitation opens the same world in a separate browser for another person.</p>

<figure class="fig wide" id="mn-second" data-multi-stage="2">
<div class="ms-figure-head"><span class="ms-figure-index">02 / 07</span><strong>Two clients, one room</strong><span class="ms-figure-meta">Current state, then live updates</span></div>
<figcaption>The second connection receives the server’s current snapshot. Both clients now follow the same room revision, including edits made before the second client arrived.</figcaption>
</figure>

<p>Our protocol assigns a revision number to each committed block change. The server sends the changed coordinate and its new state to everyone in the room. That revision is a choice for this reconstruction; it makes the ordering easy to inspect.</p>

<h2 id="3-ask-the-server-to-change-a-block">3. Ask the server to change a block</h2>

<p>The server owns the block array. A client can ask to mine a coordinate, but it cannot award itself cobblestone or replace the server’s blocks with its own copy.</p>

<p>That boundary is visible in <code class="language-plaintext highlighter-rouge">ServerGamePacketListenerImpl.handlePlayerAction</code> and <code class="language-plaintext highlighter-rouge">ServerPlayerGameMode.handleBlockBreakAction</code>. The game checks the player’s reach, world limits, protection, game mode, and mining progress. Placement goes through its own checks of the held item, hit location, and interaction rules.</p>

<p>Here, a break has a start and a finish. The server records the start tick and measures progress on its own <strong>20 Hz clock</strong>. It raycasts from the server’s player position, checks the target again, and only then changes the cell and inventory. Our small ruleset requires completed mining; the actual game also has delayed-destruction handling and finish tolerances. The next few diagrams zoom in on the same doorway.</p>

<figure class="fig wide" id="mn-authority" data-multi-stage="3">
<div class="ms-figure-head"><span class="ms-figure-index">03 / 07</span><strong>An action becomes a shared edit</strong><span class="ms-figure-meta">Request → validate → commit</span></div>
<figcaption>This experiment restores the reference block and returns both demo clients to the wall. The first client then mines through the server. A committed edit reaches both connections.</figcaption>
</figure>

<p>The server processes each request against the state left by the previous one. Each committed block change gets a revision, and the server applies each action’s inventory effects once. That gives us a definite order when the players start interfering with each other.</p>

<h2 id="4-let-the-client-predict-then-reconcile">4. Let the client predict, then reconcile</h2>

<p>Waiting for a network round trip before every visible change would make a pickaxe feel distant from your hand. The client can show a likely result immediately, while keeping enough information to correct it.</p>

<p>Minecraft’s <code class="language-plaintext highlighter-rouge">BlockStatePredictionHandler</code> retains known server state behind a predicted block change. Incoming block updates and processed-action acknowledgments travel through separate paths. The acknowledgment contains a sequence number: it says an action was processed, which can include a refused action. The authoritative block state supplies the answer.</p>

<p>Our client keeps <strong>confirmed blocks + pending predictions</strong>. A reply updates confirmed state and retires the processed prediction. We rebuild the visible array from that confirmed state plus any predictions still waiting. Our readable acknowledgment includes an explicit result as well as the sequence, instead of copying the game’s packet layout.</p>

<figure class="fig wide" id="mn-prediction" data-multi-stage="4">
<div class="ms-figure-head"><span class="ms-figure-index">04 / 07</span><strong>Show the hole before the reply</strong><span class="ms-figure-meta">Predict → confirm or correct</span></div>
<figcaption>The slider adds delay to real server replies. Try a completed break, then try finishing immediately after starting: the second prediction opens a hole that the server refuses, so the wall returns. Both experiments reset only the reference doorway and demo viewpoints.</figcaption>
</figure>

<p>The pending counter should return to zero after either outcome. Clearing a prediction means we received an answer; it doesn’t mean the answer was yes. The displayed delay is an experiment setting, not a measurement of Minecraft’s networking.</p>

<h2 id="5-make-the-players-disagree">5. Make the players disagree</h2>

<p>Now both clients start mining the same stone. Each request is plausible when it starts. Only one can remove the block that is actually there.</p>

<p>The first valid finish changes the server’s cell to air and awards cobblestone. The later finish finds that its mining target has changed. The server refuses that edit and returns the current state. Both clients settle on the same opening, and the room has awarded <strong>one</strong> piece of cobblestone.</p>

<figure class="fig wide" id="mn-race" data-multi-stage="5">
<div class="ms-figure-head"><span class="ms-figure-index">05 / 07</span><strong>One block cannot break twice</strong><span class="ms-figure-meta">Conflicting requests, one commit</span></div>
<figcaption>Reset the doorway and send two real mining attempts. The result comes from the server’s serialized requests. This reconstruction grants the winning player an inventory item directly; Minecraft’s full drop and pickup simulation is a larger system.</figcaption>
</figure>

<p>This is why validation happens at the moment of the edit. A target that was valid when the player pressed the button may already be gone when the finish arrives.</p>

<h2 id="6-send-movement-draw-another-player">6. Send movement, draw another player</h2>

<p>Blocks can wait for an edit message. Another player’s body keeps moving between updates. Drawing only the newest received position would make that motion jump from snapshot to snapshot.</p>

<p>The JAR has separate paths for your own movement and remote entities. <code class="language-plaintext highlighter-rouge">LocalPlayer.sendPosition</code> chooses which pose information to send; the server checks movement and can correct the position. <code class="language-plaintext highlighter-rouge">ServerEntity</code> handles another entity’s initial pairing data and later updates. In 26.3, position paths and <code class="language-plaintext highlighter-rouge">moveOrInterpolateTo</code> participate in those updates; this is more involved than sending an XYZ delta on every frame.</p>

<p>Our server receives <strong>movement inputs</strong> and runs the same collision function as the browser at 20 Hz. The local client predicts those steps, then replays unacknowledged input after a server correction. This input-based protocol is our design choice. Remote players are drawn from a small history of received poses, <strong>100 ms behind</strong> the newest receipt timeline, interpolating position and rotation between samples.</p>

<figure class="fig wide" id="mn-movement" data-multi-stage="6" data-multi-game="true">
<div class="ms-figure-head"><span class="ms-figure-index">06 / 07</span><strong>The other player gets a body</strong><span class="ms-figure-meta">Inputs + snapshots + interpolation</span></div>
<figcaption>Walk in the shared world. “Move the second client” brings both demo clients onto the hillside and sends real movement input from the second connection. The avatar you see is rendered from its received server poses.</figcaption>
</figure>

<p>Interpolation trades a little display delay for smoother remote motion. Its 100 ms buffer belongs to this example; it is not a recovered universal Minecraft setting. Large position changes snap rather than drawing an avatar traveling through the whole distance.</p>

<h2 id="7-leave-return-and-invite-someone">7. Leave, return, and invite someone</h2>

<p>Disconnecting removes a player from the live session. It shouldn’t erase their inventory or the world they helped build.</p>

<p>In the JAR, <code class="language-plaintext highlighter-rouge">PlayerList.remove</code> saves the player before removing it. <code class="language-plaintext highlighter-rouge">PlayerDataStorage</code> writes player data through a temporary file and safe replacement, retaining an older file for recovery. World and chunk saves have their own path through <code class="language-plaintext highlighter-rouge">MinecraftServer.saveEverything</code>; they are separate from that player cleanup.</p>

<p>Our server keeps a versioned room record containing blocks and player records, written with atomic file replacement. Reconnecting with a per-player token restores the identity, pose, and inventory, then sends a fresh snapshot. That token is for this anonymous demo, separate from Minecraft account authentication. The invitation contains the room code and gives the guest a new identity.</p>

<figure class="fig wide" id="mn-play" data-multi-stage="7" data-multi-game="true">
<div class="ms-figure-head"><span class="ms-figure-index">07 / 07</span><strong>A world you can share</strong><span class="ms-figure-meta">Two browsers, one server</span></div>
<figcaption>Create a world or enter a room code, then open or copy the invitation. The on-page second demo client leaves when you enter this final scene. Another browser joins as a real player, with its own body and inventory.</figcaption>
</figure>

<p>Both browsers need to reach the cave server. Two tabs can use <code class="language-plaintext highlighter-rouge">localhost</code>; another device needs the host’s LAN address or a public server address. The invitation uses the server endpoint selected in the first connection step. Save to keep a version on the server, disconnect, and reconnect in the same tab to resume your player.</p>

<p>Try opening the doorway together. Watch the other player come through, put a torch in the next room, and leave something on the hillside for them to find. The blocks, collision, light, inventory, and saved world now have to agree across a connection. There are two screens, but one world deciding what happened.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><category term="minecraft" /><category term="networking" /><category term="reverse-engineering" /><category term="game-development" /><summary type="html"><![CDATA[Trace multiplayer through the Minecraft 26.3 JAR, then build a real browser server: joining, shared edits, prediction, conflicts, movement, and saved worlds.]]></summary></entry><entry><title type="html">How Minecraft works</title><link href="https://sir-teo.github.io/blogs/2026/10/26/taking-minecraft-apart-one-block-at-a-time.html" rel="alternate" type="text/html" title="How Minecraft works" /><published>2026-10-26T09:00:00-04:00</published><updated>2026-10-26T09:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/26/taking-minecraft-apart-one-block-at-a-time</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/26/taking-minecraft-apart-one-block-at-a-time.html"><![CDATA[<p>I’ve always wondered how Minecraft actually works. A few swings of a pickaxe can open a doorway, change where you can walk, and let torchlight into the next room. I wanted to understand how the code connects those pieces.</p>

<p>So we took the latest stable Java Edition JAR available when we started, <strong>26.3</strong>, decompiled the relevant classes, and dug through the systems behind block storage, terrain generation, simulation, rendering, and saves.</p>

<p>This post works through what we found by rebuilding the core ideas in a small JavaScript world you can play in your browser. We’ll start with an empty grid and add one system at a time. It’s the same world throughout: a hole you dig in one view will still be there in the next. Follow the steps in order, or jump ahead and the example will build the pieces it needs.</p>

<figure class="fig wide" id="mc-grid" data-minecraft-build="true" data-build-stage="0" data-scene-label="An empty sixteen by sixteen ground grid, with no stored blocks. Drag or use arrow keys to rotate.">
<div class="ms-figure-head"><span class="ms-figure-index">00 / 08</span><strong>Start with nothing</strong><span class="ms-figure-meta">Coordinates, then a world</span></div>
<figcaption>Our starting point: an empty grid, with air in every cell.</figcaption>
</figure>

<h2 id="1-store-a-world-of-blocks">1. Store a world of blocks</h2>

<p>Before we can draw a block, the world needs to remember where it is. We’ll give each kind of block a number and store those numbers in an array. Zero means air; the other values stand for stone, dirt, grass, and the rest. Later, drawing a wall and walking into it will both depend on reading the right cell.</p>

<p>Minecraft groups its blocks into 16 × 16 × 16 sections. We’ll use two sections stacked on top of each other, giving us <strong>16 × 32 × 16 cells</strong>. The <code class="language-plaintext highlighter-rouge">Uint16Array</code> uses two bytes per cell, so these 8,192 cells take <strong>16 KiB</strong> before any compression. We store x positions next to each other, then z rows, then y layers. A short formula turns each <code class="language-plaintext highlighter-rouge">(x, y, z)</code> address into an array index:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">STONE</span> <span class="o">=</span> <span class="mi">7</span><span class="p">;</span>
<span class="kd">const</span> <span class="nx">blocks</span> <span class="o">=</span> <span class="k">new</span> <span class="nb">Uint16Array</span><span class="p">(</span><span class="mi">16</span> <span class="o">*</span> <span class="mi">32</span> <span class="o">*</span> <span class="mi">16</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">index</span> <span class="o">=</span> <span class="p">(</span><span class="nx">x</span><span class="p">,</span> <span class="nx">y</span><span class="p">,</span> <span class="nx">z</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">(</span><span class="nx">y</span> <span class="o">*</span> <span class="mi">16</span> <span class="o">+</span> <span class="nx">z</span><span class="p">)</span> <span class="o">*</span> <span class="mi">16</span> <span class="o">+</span> <span class="nx">x</span><span class="p">;</span>
<span class="nx">blocks</span><span class="p">[</span><span class="nx">index</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">7</span><span class="p">)]</span> <span class="o">=</span> <span class="nx">STONE</span><span class="p">;</span>
</code></pre></div></div>

<p>Write the first block below. Its address is <strong>(8, 7, 7)</strong>, which lands at index <strong>1,912</strong> in the array. Keep an eye on the amber marker. The world will grow around this block, and eventually we’ll mine it out of a cave wall.</p>

<figure class="fig wide" id="mc-palette" data-build-stage="1">
<div class="ms-figure-head"><span class="ms-figure-index">01 / 08</span><strong>One address. One block.</strong><span class="ms-figure-meta">Air → stone</span></div>
<figcaption>Write a stone block, then clear it. You’re changing the cell that the pickaxe will reach later.</figcaption>
</figure>

<p>Most of a stone-filled section repeats the same value. A palette saves space by listing the block states present and storing smaller indices into that list. We can add that later; the rest of the game only needs a way to read and change a block at a coordinate.</p>

<h2 id="2-turn-coordinates-into-terrain">2. Turn coordinates into terrain</h2>

<p>Placing every block by hand would take a while, even in this little world. A generator fills the grid by deciding what belongs at each coordinate.</p>

<p>Start with a function that gives the ground height at <code class="language-plaintext highlighter-rouge">(x, z)</code>. Then <code class="language-plaintext highlighter-rouge">height(x, z) − y</code> is positive below the surface and negative above it. Smooth changes in height give us hills. We combine the terrain and cave fields with <code class="language-plaintext highlighter-rouge">density = min(height − y, caveField(x, y, z))</code>. Positive density becomes solid; zero or negative density leaves air. A few material rules put grass on top, dirt beneath it, and stone farther down; trees and a small pool finish the scene.</p>

<p>Generate the landscape below. Our amber block is now part of the cave wall. This is the terrain we’ll keep working with, so any holes you dig from here on belong to you.</p>

<figure class="fig wide" id="mc-density" data-build-stage="2">
<div class="ms-figure-head"><span class="ms-figure-index">02 / 08</span><strong>Fill the grid with a landscape</strong><span class="ms-figure-meta">Coordinates → block states</span></div>
<figcaption>One corner is cut away so you can see the cave. The gray view shows which cells are filled; their materials are already stored in the array.</figcaption>
</figure>

<p>Minecraft takes terrain generation much further, with biomes, more noise fields, and rules for placing features. Our generator makes the same small hillside each time. Once it has filled the array, its job is done. Mining changes those stored blocks without asking the generator to put them back.</p>

<h2 id="3-turn-blocks-into-a-mesh">3. Turn blocks into a mesh</h2>

<p>Most of the stone in our hillside is buried against other stone. Drawing all those hidden faces would waste work. We need a mesh: a collection of vertices and triangles describing the surfaces we can see.</p>

<p>For each block, check its six neighbors. Skip a face if an opaque neighbor covers it. Keep the exposed faces, turning each square into two triangles:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>for each block:
    for each face:
        if the neighboring block does not cover it:
            append four vertices and two triangles
</code></pre></div></div>

<p>Build the mesh and look at the cave wall. The grid lines mark the faces we kept. The counts below are for this cutaway, including the surfaces revealed by removing its corner.</p>

<figure class="fig wide" id="mc-mesh" data-build-stage="3">
<div class="ms-figure-head"><span class="ms-figure-index">03 / 08</span><strong>Keep the surfaces you can see</strong><span class="ms-figure-meta">Blocks → faces → triangles</span></div>
<figcaption>The hillside gets its colors and surface mesh. Drag to turn it and look inside the cave. Mining a block later will change these faces too.</figcaption>
</figure>

<p>WebGL uploads the mesh into a vertex buffer. Each vertex carries a position, texture coordinates (UVs), and a color used for shading. A view-projection matrix maps its position into clip space; the fragment shader samples a texture atlas and applies the shading. The surface patterns here are generated for this example.</p>

<p>We still keep the block array. If the mesh gets out of date after an edit, we can rebuild it from those blocks.</p>

<h2 id="4-put-a-player-inside">4. Put a player inside</h2>

<p>So far, we’ve been looking at the world from outside. To stand on the hillside, we need a player with a body that the ground can support.</p>

<p>Ours is an <strong>axis-aligned bounding box (AABB)</strong>, <strong>0.6 blocks wide</strong> and <strong>1.8 blocks tall</strong>, with a camera near the top. Collision sweeps the box through nearby solid cells, clipping vertical movement first and then the horizontal axes. That lets the player slide along a wall while stopping the part of the movement that would enter it. Gravity pulls the body down; a jump gives it an upward push.</p>

<p>Add the player and take a walk. Try bumping into a tree or jumping up a block. You can also head back to the cave wall. The pickaxe comes next.</p>

<figure class="fig wide" id="mc-player" data-build-stage="4" data-gameplay="cave" data-spawn="surface">
<div class="ms-figure-head"><span class="ms-figure-index">04 / 08</span><strong>Step into the landscape</strong><span class="ms-figure-meta">Camera + body + collision</span></div>
<figcaption>You’re standing on the hillside we generated. Use WASD to walk, the arrow keys to look, and Space to jump. On a phone, move with the stick and drag to look.</figcaption>
</figure>

<p>The browser may draw frames at different rates on different devices. Movement uses short time steps so a long frame doesn’t carry the player through a wall. And because collision reads the block grid, removing a wall block will make that space walkable. We won’t need a separate rule to recognize a doorway.</p>

<h2 id="5-give-the-player-a-pickaxe">5. Give the player a pickaxe</h2>

<p>A pickaxe needs to know which block you’re pointing at. We cast a ray from the camera using grid traversal (DDA), stepping to the next x, y, or z cell boundary. The first block shape it hits within our <strong>4.5-block reach</strong> becomes the target. Breaking uses that cell; placing uses the empty cell beside the face you hit.</p>

<p>Mining also takes time. Our action loop runs at <strong>20 ticks per second</strong>, separately from drawing frames. An accumulator turns elapsed time into fixed 50 ms steps. With the iron pickaxe, this stone takes eight ticks—0.4 seconds—to break while you’re standing on the ground. Release the button or aim at another block, and that attempt starts over.</p>

<figure class="fig wide" id="mc-ticks" data-build-stage="5" data-gameplay="cave">
<div class="ms-figure-head"><span class="ms-figure-index">05 / 08</span><strong>Change the world, one block at a time</strong><span class="ms-figure-meta">Raycast + ticks + inventory</span></div>
<figcaption>Hold click or F to break the outlined block. You’ll need to mine the block below it as well before you can walk through. Press 2 for cobblestone, then right-click or press E to place it.</figcaption>
</figure>

<p>When the block breaks, its cell becomes air and you get a piece of cobblestone. Placing a block reverses that exchange: one item leaves your inventory, and an empty cell becomes solid. The placement check keeps you from building a block through your own body.</p>

<p>If you go back to steps 1 and 3, you can see the changed cell and mesh. Here in the cave, you can walk into the gap once it’s tall enough. That’s most of our doorway working already. The cave is still evenly lit so we can see what we’re doing; next we’ll give that light a source.</p>

<h2 id="6-let-light-travel-through-it">6. Let light travel through it</h2>

<p>Put a torch in one chamber and leave the other side of the wall dark. Now opening our doorway should let some light through.</p>

<p>The torch on the pedestal emits block light at level <strong>14</strong>. A queue-based flood fill spreads that value through the six face-adjacent air cells, losing one level at each step. We keep block light and skylight in separate <code class="language-plaintext highlighter-rouge">Uint8Array</code> buffers. A solid wall blocks the direct route, though light can travel around it if there’s another opening. Skylight has its own set of values: an open column can receive level 15 straight from the sky.</p>

<p>Add lighting below. You’ll start in the second chamber. If you’ve already opened the wall, the torch can light a path to you. If you haven’t, mine through from this side and watch the room brighten. Press 3 to place a torch of your own.</p>

<figure class="fig wide" id="mc-light" data-build-stage="6" data-gameplay="light">
<div class="ms-figure-head"><span class="ms-figure-index">06 / 08</span><strong>Give the cave a source of light</strong><span class="ms-figure-meta">Emission + propagation + shading</span></div>
<figcaption>This step adds the pedestal torch. Open the wall, place another torch, or remove one and watch the light change. Unlit surfaces stay faintly visible so you can still find your way.</figcaption>
</figure>

<p>After an edit, this small build recalculates both kinds of light and rebuilds the mesh. When drawing a face, it uses nearby light values and adds shading at the corners. A bigger engine can update only the affected areas to save work. The order is the same: <strong>change blocks → update light → rebuild surfaces → draw</strong>.</p>

<h2 id="7-make-your-changes-survive">7. Make your changes survive</h2>

<p>We’ve made a doorway, but so far it only exists in this page’s memory. Reloading would give us an empty grid again.</p>

<p>Saving serializes the world’s dimensions, blocks, inventory, and viewpoints into a versioned JSON record in <code class="language-plaintext highlighter-rouge">localStorage</code>. Before copying anything into the live array, the loader checks the format, dimensions, all 8,192 block-state values, and the saved inventory and viewpoints. Light and meshes are derived data, so we rebuild them from the restored blocks.</p>

<p>Try saving, changing a few blocks, and restoring. Or reload the page and choose <strong>Restore saved world</strong>. The save buttons are manual, so you can experiment and still return to the version you kept.</p>

<figure class="fig wide" id="mc-region" data-build-stage="7">
<div class="ms-figure-head"><span class="ms-figure-index">07 / 08</span><strong>Keep the world you built</strong><span class="ms-figure-meta">Blocks + inventory + viewpoints</span></div>
<figcaption>Save your world here. Restore brings back its blocks, inventory, and viewpoints, including after a page reload. The save stays in this browser.</figcaption>
</figure>

<p>Minecraft stores its much larger worlds in chunks and region files. We can keep this whole little world in one record. Either way, loading needs care: a damaged or incompatible save should leave the world you’re playing in alone.</p>

<h2 id="8-check-an-edit-before-accepting-it">8. Check an edit before accepting it</h2>

<p>A click tells us what the player wants to do. Before changing a block, we’ll have a separate rules function check that the action is allowed.</p>

<p>That function validates the request against the current world before any block or inventory value changes. It checks that the camera belongs at the player’s eye position, raycasts the target again, and verifies reach and mining progress. Placement needs an item in your inventory, an empty cell, and room for the player. Keeping these checks together gives every edit a consistent set of rules.</p>

<p>Finish the build below and play with what you’ve made. Your earlier edits are still here. The counters show which edits this final scene has accepted or refused.</p>

<figure class="fig wide" id="mc-world" data-build-stage="8" data-gameplay="cave">
<div class="ms-figure-head"><span class="ms-figure-index">08 / 08</span><strong>A world you can play</strong><span class="ms-figure-meta">Everything, together</span></div>
<figcaption>Dig another passage, light it, or build something on the hillside. The cutaway shows your work from outside. Save here when there’s a version you want to come back to.</figcaption>
</figure>

<p>This is an original Minecraft-style reconstruction running entirely in your browser. The rules run locally for one player. In a multiplayer game, a server would make those decisions and send the accepted changes back to everyone playing.</p>

<p>There’s plenty left to add: recipes for crafting, creatures with bodies and behavior, redstone changes scheduled for future ticks. For now, try the doorway. The block array remembers the opening, collision lets you through, torchlight reaches the next room, and a save keeps it there for another visit.</p>

<p>In <a href="/2026/10/26/one-world-two-players.html">Part 2</a>, another player joins. We follow multiplayer through the JAR and build the server that lets two browsers share this world.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><category term="minecraft" /><category term="graphics" /><category term="game-development" /><category term="world-generation" /><summary type="html"><![CDATA[A look inside Minecraft Java Edition 26.3, from decompiled classes to a playable browser world with blocks, movement, lighting, and saved edits.]]></summary></entry><entry><title type="html">Making the GOAT case for LeBron James</title><link href="https://sir-teo.github.io/blogs/2026/10/25/making-the-goat-case-for-lebron-james.html" rel="alternate" type="text/html" title="Making the GOAT case for LeBron James" /><published>2026-10-25T12:00:00-04:00</published><updated>2026-10-25T12:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/25/making-the-goat-case-for-lebron-james</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/25/making-the-goat-case-for-lebron-james.html"><![CDATA[<p>I have been a LeBron James fan for life—or at least since elementary school, when I was stuck following <a class="act" href="#lbj-playoffs" data-year="2013" data-scope="finals" data-game="6">Game 6 of the 2013 Finals</a> on a text-only play-by-play stream. I didn’t even have video, just lines of text refreshing on the screen as Miami fell behind late in the fourth quarter, LeBron piled up a 32-point, 10-rebound, 11-assist triple-double to keep them breathing, Chris Bosh tracked down the rebound, and Ray Allen backed into the right corner to force overtime. I became a fan for good that day, went back through old footage and box scores to learn the first Cleveland stint and the 2011 Dallas collapse I was too young to watch live, and have been checking his box scores every morning for the thirteen years since. After half a lifetime of having the same GOAT argument in classrooms and group chats, I wanted to put the whole career in one place where you can scrub through it yourself.</p>

<p>Every figure below runs directly in the browser on 1,924 regular-season and playoff box scores and 37,667 mapped field-goal attempts through 2025–26, compiled offline from public NBA archives with no chart library or live API behind it. The season bar just below steps all of the regular-season views together from his rookie year in 2003–04 to year twenty-three.</p>

<div class="lbj-timeline" id="lbj-timeline" role="group" aria-label="Shared season controls" hidden=""></div>
<p class="lbj-timeline-help lbj-visually-hidden" id="lbj-timeline-help">Scrub through the seasons to link the scoring curves, shot evolution, career roles, and age comparisons.</p>

<h2 id="passing-kareem-and-where-jordan-still-wins">Passing Kareem, and where Jordan still wins</h2>

<figure class="fig wide lbj lbj-opening" id="lbj-peak" data-src="/blogs/assets/data/lebron/overview.json">
<figcaption>Cumulative regular-season points for the ten all-time scoring leaders against 94 historical leaders in faint grey, stopping at retirement; switch to Peak seasons to stack each player's highest-scoring years segmented by season.</figcaption>
</figure>

<p>When LeBron hit that fading foul-line jumper against Oklahoma City in February 2023—finishing <a class="act" href="#lbj-peak" data-year="2023" data-player="Kareem Abdul-Jabbar">his twentieth season</a> just past Kareem Abdul-Jabbar’s 38,387 points, a mark that had stood since 1984—plenty of skeptics treated the record like an attendance trophy. Then he kept playing for three more years and stretched the margin out to <a class="act" href="#lbj-peak" data-year="2026" data-player="Kareem Abdul-Jabbar">5,053 points</a> (43,440 in all).</p>

<p>Raw totals alone, though, have never won an argument against someone who grew up on nineties Bulls basketball. Switch to Peak seasons on the chart and <a class="act" href="#lbj-peak-best" data-window="7" data-player="Michael Jordan">stack everyone’s seven highest-scoring years</a>: Michael Jordan clears LeBron by more than three thousand points (18,907 to 15,848), and <a class="act" href="#lbj-peak-best" data-window="7" data-player="Wilt Chamberlain">Wilt Chamberlain</a> clears everybody at 21,486. If your definition of greatness is the sharpest seven-year scoring blade ever swung, Jordan has the cleaner cut. The case for LeBron lives in what happened on either side of his first peak: how many times he tore his game down and rebuilt it while the league changed around him.</p>

<h2 id="rebuilding-the-jumper-in-public">Rebuilding the jumper in public</h2>

<figure class="fig wide lbj" id="lbj-shots" data-src="/blogs/assets/data/lebron/overview.json">
<figcaption>Regular-season shot mix across 37,667 mapped attempts, true shooting relative to that season's NBA baseline, and a half-court map sizing hexes by shot volume and coloring them by field-goal rate against the rest of the league in that zone.</figcaption>
</figure>

<p>If you watched <a class="act" href="#lbj-shots" data-year="2004">rookie LeBron in 2003–04</a>, teams guarded him by backing off to the foul line and daring him to shoot over the gap. More than a third of his attempts (36.9%) were mid-range twos, he finished 57.5% in the restricted area before he learned how to use his shoulders in traffic, and his true shooting (48.8%) came in 2.8 percentage points worse than the league—the only season in all twenty-three he ever spent below the NBA line.</p>

<p>Running into San Antonio in 2007 and Dallas in 2011 forced him to fix every flaw in full view of everyone watching. By <a class="act" href="#lbj-shots" data-year="2013">2012–13 in Miami</a>, working out of the low post and hunting corner threes, he had turned himself into an efficiency outlier: 76.0% at the rim, 40.6% from deep, and true shooting 10.6 percentage points clear of the league (+10.8 the following year).</p>

<p>Then NBA spacing blew wide open and he adapted a third time in Los Angeles. By <a class="act" href="#lbj-shots" data-year="2024">2023–24</a> he had pared mid-range jumpers down to 13.0% of his diet while hitting a career-high 41.0% from three at thirty-nine. That late shift wasn’t effortless: in <a class="act" href="#lbj-shots" data-year="2026">2025–26</a>, with threes up to 26.4% of his shots and mid-range at 17.2%, his outside touch cooled back to 31.7%. Yet if you <a class="act" href="#lbj-court-time" data-year="2026" data-zone="0">isolate the restricted area in year twenty-three</a>, the wildest number on the court is still sitting right under the basket. At forty-one years old, he converted 75.6% at the rim, essentially unchanged from peak Miami.</p>

<h2 id="handing-himself-the-keys-at-thirty-five">Handing himself the keys at thirty-five</h2>

<div id="lbj-age" class="lbj-anchor" aria-hidden="true"></div>
<figure class="fig wide lbj" id="lbj-career" data-src="/blogs/assets/data/lebron/overview.json">
<figcaption>Four regular-season trends aligned by age on February 1 against historical peers (dates shown are LeBron's; hollow dots mark seasons under 40 games), alongside a scoring-and-creation view tracing a five-season trail.</figcaption>
</figure>

<p>Box-score debates still talk about LeBron like a wing scorer who happens to pass, mostly because he averaged <a class="act" href="#lbj-career" data-year="2006" data-view="role">31.4 points a night at twenty-one</a>. Watching him every week felt like the exact opposite: he came into the league wired like a point guard in Karl Malone’s frame, averaging 5.9 assists as a teenager and catching grief on talk radio whenever he trusted a skip pass to an open shooter in the final seconds over a forced jumper. Once Anthony Davis arrived in <a class="act" href="#lbj-career" data-year="2020" data-view="role">2019–20</a>, LeBron took the ball full-time and led the NBA with 10.2 assists per game at thirty-five on the way to a fourth ring. Miami got his deadliest scoring efficiency; Los Angeles got his purest playmaking. Almost nobody gets two distinct primes a decade apart.</p>

<p>Just as strange is how stubbornly the floor held underneath him. He averaged at least 20 points in all 23 seasons and beat league-average true shooting in 22 of them, even as the NBA’s own efficiency climbed from 51.6% in his rookie year to 58.1% in 2025–26. A full quarter of his career points (10,897 across 424 games) came after he turned thirty-five. Line him up by age against the longest-lasting legends in the archive: at <a class="act" href="#lbj-career" data-age="39" data-player="Michael Jordan">thirty-nine</a>, Jordan’s final Wizards season stood at 20.0 points and 3.8 assists while LeBron put up 25.7 and 8.3; at <a class="act" href="#lbj-career" data-age="40" data-player="Kareem Abdul-Jabbar">forty</a>, LeBron gave the Lakers 24.4 points and 8.2 assists across 70 games where Kareem averaged 14.6 and 1.7; and at <a class="act" href="#lbj-career" data-age="41" data-player="Kareem Abdul-Jabbar">forty-one</a>, he was still good for 20.9 and 7.2 over 60 nights.</p>

<h2 id="alone-in-the-upper-right-corner">Alone in the upper-right corner</h2>

<figure class="fig wide lbj" id="lbj-two-jobs" data-src="/blogs/assets/data/lebron/overview.json">
<figcaption>Regular-season NBA/BAA career totals through 2025–26 for 94 all-time leaders—the union of the top 40 in points, assists, and rebounds. Shaded corners mark 40,000 points paired with 10,000 assists or rebounds. Pre-1950–51 rebounds were not recorded.</figcaption>
</figure>

<p>Put twenty-three years of doing three jobs at once onto a career scatter plot and that upper-right corner turns into a party of one. Out of the 94 players who rank top forty all-time in points, assists, or rebounds, nobody else sits inside the shaded 40,000-and-10,000 box on <em>either</em> chart—and LeBron sits comfortably inside both at 43,440 points, 12,016 assists, and 12,095 rebounds.</p>

<p>On the left panel, only <a class="act" href="#lbj-two-jobs" data-player="John Stockton">John Stockton</a>, <a class="act" href="#lbj-two-jobs" data-player="Chris Paul">Chris Paul</a>, and <a class="act" href="#lbj-two-jobs" data-player="Jason Kidd">Jason Kidd</a> have ever thrown more assists, putting LeBron 1,875 dimes ahead of <a class="act" href="#lbj-two-jobs" data-player="Magic Johnson">Magic Johnson</a> while scoring nearly two-and-a-half times as many points. On the right panel, a guy who spent half his career bringing the ball up the floor has cleared career bigs on the glass while outscoring <a class="act" href="#lbj-two-jobs" data-player="Wilt Chamberlain">Wilt Chamberlain</a> by twelve thousand.</p>

<h2 id="seven-nights-in-june">Seven nights in June</h2>

<figure class="fig wide lbj" id="lbj-playoffs" data-src="/blogs/assets/data/lebron/overview.json">
<figcaption>Postseason game logs against that year's regular-season average (dashed line), with elimination games shaded. On Finals views, paired bars below compare full-series totals against the next highest player from either team.</figcaption>
</figure>

<p>Still, nobody becomes a fan for life because of a career scatter plot. You fall in love with a player on nights when a season is seconds from dying and he refuses to let it end—whether that was reading the text play-by-play of his <a class="act" href="#lbj-playoffs" data-year="2013" data-scope="finals" data-game="6">32-10-11 fourth-quarter charge in Game 6 of 2013</a> and the <a class="act" href="#lbj-playoffs" data-year="2013" data-scope="finals" data-game="7">37-point Game 7</a> that followed, or watching what happened three Junes later back home in Ohio. In 2016, Cleveland fell behind a 73-win Golden State team 3–1 heading back to Oracle Arena. LeBron answered with <a class="act" href="#lbj-playoffs" data-year="2016" data-scope="finals" data-game="5">41 points, 16 rebounds, 7 assists, 3 steals, and 3 blocks in Game 5</a>, came home and hung <a class="act" href="#lbj-playoffs" data-year="2016" data-scope="finals" data-game="6">another 41 with 11 assists in Game 6</a>, and closed out <a class="act" href="#lbj-playoffs" data-year="2016" data-scope="finals" data-game="7">Game 7 on the road</a> with a 27-point triple-double and the chase-down block on Andre Iguodala that every Cavs fan can still replay with their eyes shut. When the series ended, he led every player on <em>both</em> rosters in total points (208), rebounds (79), assists (62), steals (18), and blocks (16).</p>

<p>If you are putting the whole career on the table, the nights without confetti belong here too. Two springs later came the <a class="act" href="#lbj-playoffs" data-year="2018" data-scope="all" data-metric="pts">2018 playoff run</a>, twenty-two games of dragging an outmatched Cleveland roster on his back at 34.0 points, 9.1 rebounds, and 9.0 assists a night, peaking in a <a class="act" href="#lbj-playoffs" data-year="2018" data-scope="finals" data-game="1">51-point Game 1</a> at Golden State that still stings to think about. And five years before 2016 sits the week no LeBron fan can talk around: the <a class="act" href="#lbj-playoffs" data-year="2011" data-scope="finals" data-game="4">2011 Finals against Dallas</a>, where he disappeared for 8 points in Game 4 and averaged 17.8 for the series.</p>

<p>Honestly, that scar is a big part of why I ended up rooting for him even harder. He didn’t hide from 2011; he went back into a gym, built a post game and a jumper he didn’t have at twenty-six, and spent the next fifteen years answering for it. You can still pick Jordan—six Finals, six rings, never once shrinking under those lights, and a seven-year scoring peak nobody has touched—and I won’t tell you you’re wrong. For me, greatness stretched across a whole basketball life looks like the kid who showed up at eighteen carrying impossible hype, stumbled in front of the entire world, reinvented his game three times, and was still giving you twenty-and-seven at forty-one.</p>

<details class="lbj-methods">
  <summary>Sources, definitions, and data downloads</summary>

  <p>The archive stops after the completed 2025–26 season (1,622 regular-season games and 302 playoff games, excluding play-in, exhibition, and NBA Cup final games that do not count toward official career totals). Career leaderboards cover NBA and BAA regular seasons; the 94-player comparison cohort is the union of the top 40 players in points, assists, and rebounds. Games played count appearances unadjusted for schedule length, and scoring rates are unadjusted for era or pace.</p>

  <p>True shooting is <code class="language-plaintext highlighter-rouge">PTS / [2 × (FGA + 0.44 × FTA)]</code>; league baselines are computed from full-league totals in that season rather than a mean of player rates, and zone field-goal benchmarks exclude LeBron. Shot-diet shares group NBA location zones (merging rare backcourt heaves with three-pointers) across all 37,667 located attempts; two missed shots from 2015–16 and 2016–17 carry no coordinates in the upstream NBA log and stay out of location shares while remaining in box-score true shooting. On the half-court map, Shot profile scales hex area logarithmically with attempt count and colors each cell by empirical-Bayes field-goal delta against the rest-of-NBA rate in that zone, Share uses equal hexagons on a fixed season-share scale, and Every shot plots individual makes and misses.</p>

  <p><a href="/blogs/assets/data/lebron/sources.json">Source manifest</a> · <a href="/blogs/assets/data/lebron/games.csv">LeBron game log (CSV)</a> · <a href="/blogs/assets/data/lebron/player-seasons.csv">Historical player-seasons (CSV)</a> · <a href="/blogs/assets/data/lebron/audit.json">Cross-source audit</a></p>

</details>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[Twenty-three seasons of box scores and 37,667 mapped shots from a lifelong LeBron fan—tracing how a teenage phenom rebuilt his jumper, turned himself into a point guard at thirty-five, and outlasted everyone who came before him.]]></summary></entry><entry><title type="html">Drawing 6,684 ideas in one dependency graph</title><link href="https://sir-teo.github.io/blogs/2026/10/18/drawing-six-thousand-ideas-in-one-dependency-graph.html" rel="alternate" type="text/html" title="Drawing 6,684 ideas in one dependency graph" /><published>2026-10-18T18:00:00-04:00</published><updated>2026-10-18T18:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/18/drawing-six-thousand-ideas-in-one-dependency-graph</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/18/drawing-six-thousand-ideas-in-one-dependency-graph.html"><![CDATA[<p><strong>Ideas, visualized</strong> started as an interactive companion to every numbered result in Walter Rudin’s three analysis books (<code class="language-plaintext highlighter-rouge">1,062</code> theorems, lemmas, corollaries, propositions, and definitions) and expanded into a single directed acyclic graph of <code class="language-plaintext highlighter-rouge">6,684</code> ideas (<code class="language-plaintext highlighter-rouge">6,621</code> interactive canvas simulations plus <code class="language-plaintext highlighter-rouge">6,890</code> planned syllabus nodes) across <code class="language-plaintext highlighter-rouge">85</code> collections and <code class="language-plaintext highlighter-rouge">13</code> fields. Every interactive figure below runs the atlas’s own zero-build canvas runtime (<code class="language-plaintext highlighter-rouge">assets/js/viz/core.js</code>, <code class="language-plaintext highlighter-rouge">math.js</code>, and its 17 domain kits) directly on the compiled graph.</p>

<h2 id="zero-build-in-the-browser-one-pass-on-disk">Zero build in the browser, one pass on disk</h2>

<figure class="fig wide" id="tv-arch">
<svg class="arch" viewBox="0 0 760 254" role="img" aria-label="Architecture: content/&lt;col&gt;/chNN.js modules, syllabus.js inventories, and bridges/*.js walks compile through scripts/build.mjs into data/index.json, 85 collection shards, and OKLCH CSS variables; in the browser, app.js and viz/core.js + math.js + 17 kits mount live canvas simulations; scripts/check.mjs and 161 verification suites audit every item in headless Chromium and Node.">
<defs>
<marker id="tv-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path class="head-strong" d="M0,1 L9,5 L0,9 z" /></marker>
</defs>
<rect class="box" x="12" y="12" width="236" height="54" rx="6" />
<text class="t" x="130" y="30">content/&lt;col&gt;/chNN.js</text>
<text class="st" x="130" y="48">85 collections · 6,684 items · viz(v)</text>
<rect class="box" x="264" y="12" width="232" height="54" rx="6" />
<text class="t" x="380" y="30">content/&lt;col&gt;/syllabus.js</text>
<text class="st" x="380" y="48">6,890 planned · 450 landmark papers</text>
<rect class="box" x="512" y="12" width="236" height="54" rx="6" />
<text class="t" x="630" y="30">content/bridges/*.js</text>
<text class="st" x="630" y="48">8 cross-field walks · 104 steps</text>
<path class="edge-strong" d="M130 68 V96" marker-end="url(#tv-arrow)" />
<path class="edge-strong" d="M380 68 V96" marker-end="url(#tv-arrow)" />
<path class="edge-strong" d="M630 68 V96" marker-end="url(#tv-arrow)" />
<rect class="box em" x="12" y="98" width="736" height="56" rx="6" />
<text class="t" x="380" y="116">scripts/build.mjs (DAG validation · transitive closure · 8-sweep barycentre layout · OKLCH palette)</text>
<text class="st" x="380" y="135">data/index.json · data/planned.json · data/col/&lt;id&gt;.json (85 shards) · data/atlas.css</text>
<path class="edge-strong" d="M210 156 V184" marker-end="url(#tv-arrow)" />
<text class="el" x="268" y="173">dynamic import()</text>
<path class="edge-strong" d="M566 156 V184" marker-end="url(#tv-arrow)" />
<text class="el" x="626" y="173">Playwright + Node</text>
<rect class="box" x="12" y="186" width="396" height="56" rx="6" />
<text class="t" x="210" y="204">assets/js/viz/core.js + math.js + 17 domain kits</text>
<text class="st" x="210" y="223">2D/3D stages · handles · RK45 / FFT / SVD / quantum · KaTeX</text>
<rect class="box" x="424" y="186" width="324" height="56" rx="6" />
<text class="t" x="586" y="204">scripts/check.mjs + 161 test suites</text>
<text class="st" x="586" y="223">headless Chromium · 6,906 numerical assertions</text>
</svg>
<figcaption>Each chapter is a plain ES module under <code>content/&lt;col&gt;/</code>. <code>scripts/build.mjs</code> resolves the global dependency DAG and writes static JSON shards; the browser imports chapter modules directly with no bundler.</figcaption>
</figure>

<p>Adding a collection requires only a folder with a <code class="language-plaintext highlighter-rouge">collection.js</code> descriptor and chapter modules exporting <code class="language-plaintext highlighter-rouge">statement</code>, <code class="language-plaintext highlighter-rouge">idea</code>, <code class="language-plaintext highlighter-rouge">deps</code>, and <code class="language-plaintext highlighter-rouge">viz(v)</code>. On build, <code class="language-plaintext highlighter-rouge">scripts/build.mjs</code> verifies that all <code class="language-plaintext highlighter-rouge">11,541</code> dependency edges form a cycle-free DAG, computes each item’s transitive ancestor and descendant closures, packs chapters into <code class="language-plaintext highlighter-rouge">88</code> shelf rows using eight forward-and-backward barycentre sweeps, and derives light and dark collection hues in perceptual OKLCH space.</p>

<h2 id="6684-ideas-in-one-dependency-graph">6,684 ideas in one dependency graph</h2>

<figure class="fig wide" id="tv-map" style="--reserve: 740px" data-src="/blogs/assets/data/theorems-visualizations-demo.json">
<figcaption>All 6,684 written ideas and 11,541 dependency edges across 85 collections and 13 fields. <span class="only-hover">Click or drag</span><span class="only-touch">Tap or drag</span> on the atlas to pan and zoom, select any node to light up its full transitive prerequisite and descendant cones, switch to the 13-field chord matrix, or scrub the 77-step longest reasoning chain.</figcaption>
</figure>

<p>Because <code class="language-plaintext highlighter-rouge">deps</code> cross chapter, book, and discipline boundaries, a single click traces how foundational definitions propagate across the entire graph: <a class="act" href="#tv-map" data-view="atlas" data-node="pma-1.5">an order on a set (<code class="language-plaintext highlighter-rouge">pma-1.5</code>)</a> sits at depth <code class="language-plaintext highlighter-rouge">0</code> with <code class="language-plaintext highlighter-rouge">3,286</code> downstream descendants; <a class="act" href="#tv-map" data-view="atlas" data-node="pma-4.19">uniform continuity on compact sets (<code class="language-plaintext highlighter-rouge">pma-4.19</code>)</a> bridges metric topology into integration and Fourier analysis; <a class="act" href="#tv-map" data-view="atlas" data-node="ladr-7.29">the real spectral theorem (<code class="language-plaintext highlighter-rouge">ladr-7.29</code>)</a> feeds <code class="language-plaintext highlighter-rouge">664</code> results across mechanics, quantum theory, and statistics; <a class="act" href="#tv-map" data-view="flows" data-field="math">the 1,989 cross-field links</a> carry mathematical structure into physics (<code class="language-plaintext highlighter-rouge">446</code>), engineering (<code class="language-plaintext highlighter-rouge">116</code>), statistics (<code class="language-plaintext highlighter-rouge">110</code>), computer science (<code class="language-plaintext highlighter-rouge">104</code>), and economics (<code class="language-plaintext highlighter-rouge">93</code>); and <a class="act" href="#tv-map" data-view="chain" data-step="76">the 77-step longest chain</a> runs unbroken from <code class="language-plaintext highlighter-rouge">pma-1.5</code> through complex and functional analysis, wave mechanics, and quantum gates to Grover’s search algorithm (<code class="language-plaintext highlighter-rouge">cplx-13.9</code>).</p>

<h2 id="thirteen-fields-one-canvas-runtime">Thirteen fields, one canvas runtime</h2>

<figure class="fig wide" id="tv-workbench" style="--reserve: 680px" data-src="/blogs/assets/data/theorems-visualizations-demo.json">
<figcaption>Thirteen live simulations—one from each field—mounted directly by <code>assets/js/viz/core.js</code>. Switch fields, drag handles and sliders on the canvas, flip hypotheses, or open the <code>viz(v)</code> source drawer to see the declarative stage calls behind each picture.</figcaption>
</figure>

<p>Every simulation in the repository is written against the same <code class="language-plaintext highlighter-rouge">3,531</code>-line runtime (<code class="language-plaintext highlighter-rouge">core.js</code> + <code class="language-plaintext highlighter-rouge">math.js</code>) and <code class="language-plaintext highlighter-rouge">17</code> domain kits. Instead of static diagrams, each <code class="language-plaintext highlighter-rouge">viz(v)</code> exposes the quantity the proof or mechanism controls: you can <a class="act" href="#tv-workbench" data-item="pma-4.19" data-seg="2">break compactness on (0, 1] in <code class="language-plaintext highlighter-rouge">pma-4.19</code></a> and watch the greatest admissible \(\delta(p)\) collapse to zero near the missing endpoint, <a class="act" href="#tv-workbench" data-item="mech-8.22">drag the launch velocity in <code class="language-plaintext highlighter-rouge">mech-8.22</code></a> as Keplerian velocities trace an exact circle in hodograph space, <a class="act" href="#tv-workbench" data-item="geog-4.4" data-seg="0">drag Greenland to the equator in <code class="language-plaintext highlighter-rouge">geog-4.4</code></a> to shed its Mercator area inflation (\(\sec^2\varphi\), about 14×), <a class="act" href="#tv-workbench" data-item="imaging-3.3">reconstruct a CT phantom from its Radon sinogram in <code class="language-plaintext highlighter-rouge">imaging-3.3</code></a>, <a class="act" href="#tv-workbench" data-item="soc-1.2">tip an integrated city into segregation in <code class="language-plaintext highlighter-rouge">soc-1.2</code></a>, or <a class="act" href="#tv-workbench" data-item="tech-2.9" data-toggle="0">snap one tooth off the Antikythera <code class="language-plaintext highlighter-rouge">b1</code> gear in <code class="language-plaintext highlighter-rouge">tech-2.9</code></a> and watch the Metonic pointer drift.</p>

<h2 id="one-mathematical-spine-many-disguises">One mathematical spine, many disguises</h2>

<figure class="fig wide" id="tv-bridges" style="--reserve: 690px" data-src="/blogs/assets/data/theorems-visualizations-demo.json">
<figcaption>Eight cross-field bridges (104 steps) and 450 landmark papers (350 BCE – 2020 CE) across the 13 field lanes. Select a bridge and click any step along its track to run that step's interactive simulation live below the swimlane.</figcaption>
</figure>

<p>The same mathematical skeleton repeatedly reappears under different physical or social names. Following <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="spectral" data-step="2">the spectral theorem bridge</a> walks from self-adjoint matrices (<code class="language-plaintext highlighter-rouge">ladr-7.29</code>) and SVD (<code class="language-plaintext highlighter-rouge">ladr-7.70</code>) to <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="spectral" data-step="7">coupled normal modes (<code class="language-plaintext highlighter-rouge">mech-11.4</code>)</a> and <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="spectral" data-step="8">standing waves on a string (<code class="language-plaintext highlighter-rouge">music-2.3</code>)</a>; <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="entropy" data-step="2">the entropy bridge</a> links Boltzmann microstates (<code class="language-plaintext highlighter-rouge">thermo-5.6</code>) to <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="entropy" data-step="5">Shannon information (<code class="language-plaintext highlighter-rouge">info-1.2</code>)</a> and <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="entropy" data-step="8">Landauer’s \(k_{\mathrm B}T\ln 2\) erasure bound (<code class="language-plaintext highlighter-rouge">thermo-5.17</code>)</a>; <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="fixed-points" data-step="1">the fixed-point bridge</a> connects Banach contraction (<code class="language-plaintext highlighter-rouge">pma-9.23</code>) to <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="fixed-points" data-step="4">Nash equilibria (<code class="language-plaintext highlighter-rouge">game-2.3</code>)</a> and <a class="act" href="#tv-bridges" data-mode="bridges" data-bridge="fixed-points" data-step="7">PageRank (<code class="language-plaintext highlighter-rouge">stoch-4.15</code>)</a>; and switching to <a class="act" href="#tv-bridges" data-mode="papers">the 450 landmark papers</a> plots each primary source on the field timeline alongside the graph nodes it introduced.</p>

<h2 id="auditing-6621-canvases-without-eyes">Auditing 6,621 canvases without eyes</h2>

<figure class="fig wide" id="tv-audit" style="--reserve: 580px" data-src="/blogs/assets/data/theorems-visualizations-demo.json">
<figcaption>Coverage across all 85 collections and live numerical audits from <code>scripts/check.mjs</code> and the 161 <code>tests/verification-*.test.mjs</code> suites (1,058 tests, 6,906 assertions).</figcaption>
</figure>

<p>Keeping <code class="language-plaintext highlighter-rouge">6,621</code> interactive canvases honest requires automated checks at two levels. In headless Chromium, <code class="language-plaintext highlighter-rouge">scripts/check.mjs --modes</code> mounts every item in <code class="language-plaintext highlighter-rouge">tools/harness.html</code>, clicks through every segmented control and toggle, verifies that every visible canvas paints non-transparent pixels, and flags raw-string TeX backslash escapes or missing live readouts. In Node, <code class="language-plaintext highlighter-rouge">161</code> primary-source verification suites test the underlying solvers against independent quadrature and published datasets—catching <a class="act" href="#tv-audit" data-case="radon">discarded negative <span class="math-inline" data-tex="k_x">kₓ</span> imaginary residuals and sub-Nyquist detector aliasing in Fourier CT (<code class="language-plaintext highlighter-rouge">imaging-3.4</code>)</a>, separating <a class="act" href="#tv-audit" data-case="popgen">exact discrete log-odds selection <span class="math-inline" data-tex="\ln(1+s)">ln(1 + s)</span> from the weak-selection <span class="math-inline" data-tex="s">s</span> approximation (<code class="language-plaintext highlighter-rouge">popgen-4.2</code>)</a>, and auditing <a class="act" href="#tv-audit" data-case="harness">every control mode and primitive family across the 85 collections</a>.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[How theorems-visualizations wires 6,684 theorems, laws, models, and mechanisms across 85 collections and 13 fields into a single directed acyclic graph—running 6,621 interactive canvas simulations on one zero-build runtime and verifying every frame headlessly.]]></summary></entry><entry><title type="html">Rendering twenty-two hours of math from code</title><link href="https://sir-teo.github.io/blogs/2026/10/18/rendering-twenty-two-hours-of-math-from-code.html" rel="alternate" type="text/html" title="Rendering twenty-two hours of math from code" /><published>2026-10-18T08:00:00-04:00</published><updated>2026-10-18T08:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/18/rendering-twenty-two-hours-of-math-from-code</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/18/rendering-twenty-two-hours-of-math-from-code.html"><![CDATA[<p><strong>explainer-videos</strong> builds feature-length mathematics, physics, machine learning, and markets films entirely from Python with <a href="https://www.manim.community/">Manim Community</a> and local neural text-to-speech. No video files or timeline projects live in git: every frame, equation, simulation, and subtitle track compiles from source.</p>

<h2 id="a-film-is-a-package">A film is a package</h2>

<figure class="fig" id="ev-arch">
<svg class="arch" viewBox="0 0 680 272" role="img" aria-label="Architecture: compute.py writes simulation checkpoints, sNN_*.py defines VoiceoverScene classes with semantic colors, and tts.py synthesizes cached WAVs with word timestamps through a 513-rule IPA lexicon; manim render runs scenes in parallel with isolated TeX caches; tools/build.py normalizes audio to ALAC, runs two-pass loudnorm, embeds subtitles and chapters, and hands the master to dead_air.py and contact_sheet.py.">
<defs>
<marker id="ev-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path class="head-strong" d="M0,1 L9,5 L0,9 z" /></marker>
</defs>
<rect class="box" x="16" y="16" width="202" height="54" rx="6" />
<text class="t" x="117" y="34">compute.py</text>
<text class="st" x="117" y="51">NumPy · SciPy · mpmath → .npz</text>
<rect class="box" x="239" y="16" width="202" height="54" rx="6" />
<text class="t" x="340" y="34">sNN_*.py + style.py</text>
<text class="st" x="340" y="51">VoiceoverScene · 222 C.* colors</text>
<rect class="box" x="462" y="16" width="202" height="54" rx="6" />
<text class="t" x="563" y="34">tts.py + narration_zh.json</text>
<text class="st" x="563" y="51">Kokoro · Qwen3-TTS · 513 IPA rules</text>
<path class="edge-strong" d="M117 72 V100" marker-end="url(#ev-arrow)" />
<path class="edge-strong" d="M340 72 V100" marker-end="url(#ev-arrow)" />
<path class="edge-strong" d="M563 72 V100" marker-end="url(#ev-arrow)" />
<rect class="box em" x="16" y="102" width="648" height="56" rx="6" />
<text class="t" x="340" y="120">manim render (parallel scene workers, longest scene first)</text>
<text class="st" x="340" y="138">isolated TeX dir per worker · 400-SVG LRU cache · up to 2,000 cached segments per scene</text>
<path class="edge-strong" d="M340 160 V188" marker-end="url(#ev-arrow)" />
<text class="el" x="350" y="178" style="text-anchor:start">.mp4 + .wav + .narration.json + .srt</text>
<rect class="box" x="16" y="190" width="396" height="56" rx="6" />
<text class="t" x="214" y="208">tools/build.py</text>
<text class="st" x="214" y="226">soundtrack check · ALAC pad · 2-pass EBU R128 loudnorm · chapters</text>
<rect class="box" x="434" y="190" width="230" height="56" rx="6" />
<text class="t" x="549" y="208">dead_air.py · contact_sheet.py</text>
<text class="st" x="549" y="226">320×180 pixel scan vs #0E1117</text>
<path class="edge-strong" d="M414 218 H432" marker-end="url(#ev-arrow)" />
</svg>
<figcaption>Each video lives in <code>videos/&lt;series&gt;/&lt;name&gt;/</code> and compiles from numerical checkpoints, scene scripts, and cached neural speech into a chaptered master.</figcaption>
</figure>

<p>Rendering a sixty-minute film in parallel exposes two bottlenecks in stock Manim: concurrent scene processes race on shared LaTeX files, and frame-by-frame numeric readouts fill <code class="language-plaintext highlighter-rouge">SVG_HASH_TO_MOB_MAP</code> past 6 GB of RAM. <code class="language-plaintext highlighter-rouge">tools/build.py</code> gives every scene worker its own TeX directory, orders jobs longest-first so a short scene never waits behind a long tail, and replaces Manim’s unbounded SVG dictionary with a 400-entry LRU cache.</p>

<h2 id="twenty-four-films-frame-by-frame">Twenty-four films, frame by frame</h2>

<figure class="fig wide" id="ev-atlas" style="--reserve: 760px" data-src="/blogs/assets/data/explainer-videos-demo.json">
<figcaption>All 24 completed films in the repository (16.4 hours in English, plus 5.6 hours of Chinese masters for <em>Analysis, Built</em>). Every horizontal ribbon is the film's vertical color profile over time; <span class="only-hover">click or drag</span><span class="only-touch">tap or drag</span> across any ribbon to inspect its rendered frames, subtitle track, and active-pixel density.</figcaption>
</figure>

<p>Each barcode strip compresses a full render into 300 vertical slices against the <code class="language-plaintext highlighter-rouge">#0E1117</code> background, making a film’s structure visible before pressing play. You can spot <a class="act" href="#ev-atlas" data-film="navier_stokes" data-sample="4">the Kármán vortex street</a> in <em>Navier–Stokes</em> where blue velocity gives way to orange vorticity, <a class="act" href="#ev-atlas" data-film="riemann" data-sample="1">the rainbow phase portrait of ζ(s)</a> in <em>The Riemann Hypothesis</em>, <a class="act" href="#ev-atlas" data-film="llm" data-sample="4">the orange attention matrices and purple MLP blocks</a> in <em>How LLMs Work</em>, and <a class="act" href="#ev-atlas" data-film="analysis7" data-sample="0">the domain-colored complex discs</a> opening <em>Analysis, Built</em> Part 7.</p>

<h2 id="the-voice-is-the-clock">The voice is the clock</h2>

<figure class="fig wide" id="ev-score" style="--reserve: 670px" data-src="/blogs/assets/data/explainer-videos-demo.json">
<figcaption><code>Contraction</code> (<code>videos/analysis/analysis4/s05_contraction.py</code>) rendered in English (144.8 s) and Chinese (151.3 s) from the same scene class. The 57 <code>self.play()</code> segments run for the exact same 58.6 s in both languages; the 25 <code>vo.wait_until()</code> holds stretch or contract around each language's word timestamps.</figcaption>
</figure>

<p>Scenes never hard-code pause durations. Instead, narration strings carry inline <code class="language-plaintext highlighter-rouge">&lt;bookmark mark='...'/&gt;</code> tags that <code class="language-plaintext highlighter-rouge">VoiceoverScene</code> strips before synthesis and maps to the exact start timestamp of the following word:</p>

<div class="language-py highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">with</span> <span class="bp">self</span><span class="p">.</span><span class="n">voiceover</span><span class="p">(</span>
    <span class="s">"&lt;bookmark mark='a'/&gt; To solve cosine of x equals x, just iterate ... "</span>
    <span class="s">"&lt;bookmark mark='b'/&gt; On the graph, bounce between the curve and the diagonal ..."</span>
<span class="p">)</span> <span class="k">as</span> <span class="n">vo</span><span class="p">:</span>
    <span class="bp">self</span><span class="p">.</span><span class="n">play</span><span class="p">(</span><span class="n">FadeIn</span><span class="p">(</span><span class="n">head</span><span class="p">[</span><span class="mi">0</span><span class="p">]),</span> <span class="n">Create</span><span class="p">(</span><span class="n">ax</span><span class="p">),</span> <span class="n">Create</span><span class="p">(</span><span class="n">dg</span><span class="p">),</span> <span class="n">FadeIn</span><span class="p">(</span><span class="n">dl</span><span class="p">))</span>
    <span class="n">vo</span><span class="p">.</span><span class="n">wait_until</span><span class="p">(</span><span class="s">"a"</span><span class="p">)</span>
    <span class="bp">self</span><span class="p">.</span><span class="n">play</span><span class="p">(</span><span class="n">Create</span><span class="p">(</span><span class="n">cg</span><span class="p">),</span> <span class="n">FadeIn</span><span class="p">(</span><span class="n">cl</span><span class="p">))</span>
    <span class="n">vo</span><span class="p">.</span><span class="n">wait_until</span><span class="p">(</span><span class="s">"b"</span><span class="p">)</span>
    <span class="bp">self</span><span class="p">.</span><span class="n">play</span><span class="p">(</span><span class="n">Create</span><span class="p">(</span><span class="n">web</span><span class="p">),</span> <span class="n">run_time</span><span class="o">=</span><span class="mf">4.0</span><span class="p">,</span> <span class="n">rate_func</span><span class="o">=</span><span class="n">linear</span><span class="p">)</span>
</code></pre></div></div>

<p>Because <code class="language-plaintext highlighter-rouge">self.play()</code> durations are fixed while <code class="language-plaintext highlighter-rouge">vo.wait_until()</code> absorbs the difference in speech cadence, translating a film requires zero timeline editing. Switching from <a class="act" href="#ev-score" data-beat="1" data-lang="en">the English cobweb</a> to <a class="act" href="#ev-score" data-beat="1" data-lang="zh">the Chinese render</a>, jumping to <a class="act" href="#ev-score" data-beat="2" data-lang="en">the shrinking Cauchy discs in Rudin 9.23</a>, or zooming ×127 into <a class="act" href="#ev-score" data-beat="3" data-lang="en">the √2 ∉ ℚ hole</a> runs the exact same 82 Manim segments in lockstep with each voice.</p>

<h2 id="one-color-per-concept-one-ipa-rule-per-term">One color per concept, one IPA rule per term</h2>

<figure class="fig wide" id="ev-palette" style="--reserve: 520px" data-src="/blogs/assets/data/explainer-videos-demo.json">
<figcaption>The 222 semantic color tokens in <code>explainer/style.py</code> (referenced 11,085 times across 705 scene files) and the 513 regex-to-IPA pronunciation rules in <code>explainer/tts.py</code> (firing 2,808 times across the narration corpus).</figcaption>
</figure>

<p>Across all 705 scene files, mobjects never pass raw hex strings; they import semantic roles from <code class="language-plaintext highlighter-rouge">explainer/style.py</code>—<a class="act" href="#ev-palette" data-mode="palette" data-group="Analysis, Built">tolerance bands in gold (<code class="language-plaintext highlighter-rouge">C.EPS</code>) and holes in coral (<code class="language-plaintext highlighter-rouge">C.HOLE</code>)</a> across <em>Analysis, Built</em>, or <a class="act" href="#ev-palette" data-mode="palette" data-group="Language Models &amp; RL">queries, keys, values, and attention</a> across the ML films. On the audio side, <a class="act" href="#ev-palette" data-mode="lexicon" data-rule="Poisson">a 513-rule pronunciation lexicon</a> injects inline IPA into Kokoro’s G2P front-end so <code class="language-plaintext highlighter-rouge">Poisson</code> is never read as <em>“poison”</em>, <a class="act" href="#ev-palette" data-mode="lexicon" data-rule="dy">the differential <code class="language-plaintext highlighter-rouge">dy</code></a> never becomes <em>“die”</em>, and <a class="act" href="#ev-palette" data-mode="lexicon" data-rule="F = m a"><code class="language-plaintext highlighter-rouge">F = m a</code></a> stays two letters instead of <em>“Emma”</em>.</p>

<h2 id="hunting-dead-air">Hunting dead air</h2>

<figure class="fig wide" id="ev-qa" style="--reserve: 580px" data-src="/blogs/assets/data/explainer-videos-demo.json">
<figcaption><code>tools/dead_air.py</code> downscales every frame to <code>320×180</code> and flags runs lasting at least 1.5 s where fewer than 0.30% of pixels differ from <code>#0E1117</code>—catching scenes where a <code>vo.wait_until()</code> hold sat before the drawing call instead of after it.</figcaption>
</figure>

<p>Watching twenty hours of 4K renders at real-time speed to check whether an equation appeared on time does not scale. <code class="language-plaintext highlighter-rouge">tools/dead_air.py</code> streams a render through <code class="language-plaintext highlighter-rouge">ffmpeg</code> at <code class="language-plaintext highlighter-rouge">320×180</code> and measures the fraction of pixels brighter than the <code class="language-plaintext highlighter-rouge">#0E1117</code> background, flagging any stretch of 1.5 seconds or longer below <code class="language-plaintext highlighter-rouge">0.30%</code> (a lone header or bare axes). Running it across the series caught places where a <code class="language-plaintext highlighter-rouge">vo.wait_until()</code> call sat <em>before</em> <code class="language-plaintext highlighter-rouge">self.play()</code>—leaving <a class="act" href="#ev-qa" data-case="balance">12.4 seconds of bare title before the router load replay</a>, <a class="act" href="#ev-qa" data-case="width">14.5 seconds before the μP scaling card</a>, or <a class="act" href="#ev-qa" data-case="steering">8.0 seconds before the chain-of-thought faithfulness schematic</a>—and cut sparse stretches across the eleven series films by 91%.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[How explainer-videos compiles twenty-four feature-length math, physics, ML, and markets films from Python—synchronizing Manim geometry to word-level TTS bookmarks in English and Chinese, enforcing a 222-token semantic color palette, and scanning every frame for dead air.]]></summary></entry><entry><title type="html">Putting a trading desk behind a dashboard</title><link href="https://sir-teo.github.io/blogs/2026/10/10/putting-a-trading-desk-behind-a-dashboard.html" rel="alternate" type="text/html" title="Putting a trading desk behind a dashboard" /><published>2026-10-10T08:00:00-04:00</published><updated>2026-10-10T08:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/10/putting-a-trading-desk-behind-a-dashboard</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/10/putting-a-trading-desk-behind-a-dashboard.html"><![CDATA[<p><strong>FinOS-AgentLab</strong> is a self-hosted financial research workspace that pairs a page-aware copilot on every screen with five specialist sub-agents and a multi-agent <code class="language-plaintext highlighter-rouge">TradingAgents</code> desk behind it. Every interactive figure below either runs the backend’s own Python routing, prompt-assembly, and scheduler code offline, or replays the 22 desk transcripts and scripted evaluation passes recorded in the repository.</p>

<h2 id="four-processes">Four processes</h2>

<figure class="fig" id="fa-arch">
<svg class="arch" viewBox="0 0 680 318" role="img" aria-label="Architecture: a Next.js app talks to a FastAPI backend over REST, server-sent events and a WebSocket; the backend starts a TradingAgents subprocess per desk run and keeps one warm quant worker, both speaking JSON lines; SQLite and provider caches sit underneath.">
<defs>
<marker id="fa-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path class="head-strong" d="M0,1 L9,5 L0,9 z" /></marker>
</defs>
<rect class="box" x="24" y="24" width="632" height="42" rx="6" />
<text class="t" x="340" y="38">Next.js app</text>
<text class="st" x="340" y="55">agent chat, home, dashboards, markets, stock pages, portfolio, watchlists, world, data</text>
<path class="edge-strong" data-flow="both" d="M340 68 V98" marker-start="url(#fa-arrow)" marker-end="url(#fa-arrow)" />
<text class="el" x="430" y="87">REST · SSE · WebSocket</text>
<rect class="box em" x="24" y="100" width="632" height="60" rx="6" />
<text class="t" x="340" y="116">FastAPI backend</text>
<text class="st" x="340" y="134">543 routes · 454 service modules · one scheduler</text>
<text class="st" x="340" y="150">copilot: 138 tools, 21 of them core · 5 specialists · 150 shipped commands</text>
<path class="edge-strong" data-flow="up" d="M176 162 V190" marker-start="url(#fa-arrow)" />
<text class="el" x="252" y="181" style="font-size:9.5px">JSONL, one event per line</text>
<path class="edge-strong" data-flow="both" d="M504 162 V190" marker-start="url(#fa-arrow)" marker-end="url(#fa-arrow)" />
<text class="el" x="582" y="181" style="font-size:9.5px">JSONL, request and reply</text>
<rect class="box" x="24" y="192" width="304" height="58" rx="6" />
<text class="t" x="176" y="208">agents-runtime</text>
<text class="st" x="176" y="225">TradingAgents 0.6.0 on LangGraph, its own venv</text>
<text class="st" x="176" y="240">one subprocess per run, at most five at once</text>
<rect class="box" x="352" y="192" width="304" height="58" rx="6" />
<text class="t" x="504" y="208">quant-runtime</text>
<text class="st" x="504" y="225">vectorbt and numba, its own venv</text>
<text class="st" x="504" y="240">one warm worker, respawned when it stalls</text>
<rect class="box" x="24" y="274" width="632" height="38" rx="6" />
<text class="t" x="340" y="287">On disk</text>
<text class="st" x="340" y="303">SQLite: dashboards, watchlists, runs, chats, specialists, settings · provider caches · the desk’s memory log</text>
</svg>
<figcaption>The desk and the quant engine run in their own virtual environments and talk to the backend one JSON line at a time.</figcaption>
</figure>

<p>Splitting a self-hosted workspace across four processes and three Python virtual environments was a truce with dependency management. <code class="language-plaintext highlighter-rouge">TradingAgents</code> pulls in the LangChain and LangGraph stack, while the quantitative backtesting engine relies on <code class="language-plaintext highlighter-rouge">vectorbt</code> and <code class="language-plaintext highlighter-rouge">numba</code>—and both pin transitive packages that clash directly with the FastAPI backend’s own dependencies.</p>

<p>Rather than forcing three incompatible dependency trees into a single environment, the backend isolates both runtimes behind newline-delimited JSON (<code class="language-plaintext highlighter-rouge">JSONL</code>) pipes over standard input and output. Each desk run spawns a fresh <code class="language-plaintext highlighter-rouge">agents-runtime</code> subprocess and relays its <code class="language-plaintext highlighter-rouge">stdout</code> lines to the browser as server-sent events; because each LangGraph process claims a few hundred megabytes of memory, a semaphore caps concurrent runs at five and queues the rest. The <code class="language-plaintext highlighter-rouge">quant-runtime</code> takes the opposite lifecycle: importing <code class="language-plaintext highlighter-rouge">numba</code> and <code class="language-plaintext highlighter-rouge">vectorbt</code> is slow, so the backend starts one worker at boot, keeps it warm across requests, and respawns it automatically if a calculation stalls.</p>

<h2 id="the-desk">The desk</h2>

<figure class="fig wide" id="fa-firm" style="--reserve: 900px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>TradingAgents 0.6.0's graph as the runner builds it, and the 22 desk runs recorded in the project's static export, each event a block sized by its bytes.</figcaption>
</figure>

<p>Convening the trading desk used to be a tool the chat copilot could invoke on its own, which meant a casual question could accidentally launch a multi-minute, twelve-node LangGraph debate. Now a desk run is always deliberate: typing <code class="language-plaintext highlighter-rouge">@TradingAgents NVDA</code> in chat starts the graph directly and streams every analyst report, bull-versus-bear rebuttal, and risk-committee turn into the thread without a model middleman deciding whether to.</p>

<p>Ten of the 22 recorded runs reached a final portfolio verdict (3 <code class="language-plaintext highlighter-rouge">BUY</code>, 5 <code class="language-plaintext highlighter-rouge">SELL</code>, 2 <code class="language-plaintext highlighter-rouge">HOLD</code>), and the runner’s <code class="language-plaintext highlighter-rouge">parse_action</code> extracts the exact same call from all ten. Replaying those transcripts surfaced two bugs that only appear when real model routers and LangGraph state dictionaries meet. In <a class="act" href="#fa-firm" data-run="e35b83">one NVDA run</a> and <a class="act" href="#fa-firm" data-run="a730e0">one MU run</a>, a free upstream model router intercepted the Bull Researcher’s turn and returned a bare content-safety classifier label (<code class="language-plaintext highlighter-rouge">safety: safe</code>) instead of a bull case; with nobody arguing for the stock, both desks marched straight to <code class="language-plaintext highlighter-rouge">SELL</code>. Since September, the runner checks every turn against a classifier pattern and redraws the reply up to three times before any downstream agent reads it:</p>

<div class="language-py highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">_CLASSIFIER_REPLY</span> <span class="o">=</span> <span class="n">re</span><span class="p">.</span><span class="nb">compile</span><span class="p">(</span>
    <span class="sa">r</span><span class="s">"^\s*(?:(?:user|response|prompt|agent)\s+)?safety\s*:\s*(?:un)?safe\b"</span><span class="p">,</span> <span class="n">re</span><span class="p">.</span><span class="n">IGNORECASE</span>
<span class="p">)</span>
</code></pre></div></div>

<p>A quieter bug hid in the risk committee at the end of the graph. Every finished run in the snapshot streamed only the <code class="language-plaintext highlighter-rouge">Neutral</code> risk analyst’s turn. All three risk voices had actually run, but the runner looked up <code class="language-plaintext highlighter-rouge">risky</code> and <code class="language-plaintext highlighter-rouge">safe</code> in the state dictionary where <code class="language-plaintext highlighter-rouge">TradingAgents 0.6.0</code> writes <code class="language-plaintext highlighter-rouge">aggressive</code> and <code class="language-plaintext highlighter-rouge">conservative</code>—silently dropping two of the three risk perspectives until a contract test pinned the state keys.</p>

<h2 id="what-a-turn-carries">What a turn carries</h2>

<figure class="fig wide" id="fa-pay" style="--reserve: 505px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>Prompt and tool schemas routed for one question on each of the app's pages, each tool a block, measured with the backend's <code>tools_for_request</code> against the ceilings its tests pin.</figcaption>
</figure>

<p>Because an LLM API call pays for every tool schema on every round, shipping the full registry of 138 tools on every turn would burn tens of thousands of prompt characters before the user asked a question. Instead, <code class="language-plaintext highlighter-rouge">tools_for_request</code> routes a slice of the catalogue per turn: the 21 core tools are always included, the current page adds its own domain group, and keywords in the user’s question trip any matching intent groups.</p>

<p>To keep schema bloat from creeping back in, a test pins a strict character ceiling for a plain question on each route and requires a written note in the test file whenever a ceiling is raised. The <code class="language-plaintext highlighter-rouge">/dashboards</code> page already sits at 28,923 characters against a 28,950 ceiling before any question keywords fire, and asking <a class="act" href="#fa-pay" data-q="1">a question about the book</a> (<code class="language-plaintext highlighter-rouge">"how is my book doing?"</code>) pulls in enough portfolio and risk tools to push almost every page past its baseline cap.</p>

<h2 id="ordered-by-how-often-it-changes">Ordered by how often it changes</h2>

<figure class="fig" id="fa-rungs" style="--reserve: 420px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>Six turns of one conversation as the loop assembles them, measured with the backend's own prompt, command, policy and context builders, with turn sizes from its scripted scenarios.</figcaption>
</figure>

<p>Routing fewer tools shrinks each request; ordering the prompt blocks keeps the provider’s prefix cache warm across turns. On every turn, the loop sends up to five system messages arranged strictly by how often each one changes: the base system prompt (<code class="language-plaintext highlighter-rouge">4,998</code> chars), the listing of 150 slash commands (<code class="language-plaintext highlighter-rouge">15,962</code> chars), and the mode policy (<code class="language-plaintext highlighter-rouge">1,073</code> chars) sit at the very top, followed by the growing conversation history.</p>

<p>The page context block (<code class="language-plaintext highlighter-rouge">687</code> chars) carries a wall-clock timestamp that changes every minute, so it is placed last, immediately before the newest user question. <a class="act" href="#fa-rungs" data-order="old">It used to sit before the history</a>—which meant that every time the clock ticked over a minute, that single changing line invalidated the provider’s prefix cache for the entire conversation history behind it.</p>

<h2 id="building-an-agent">Building an agent</h2>

<figure class="fig wide" id="fa-spec" style="--reserve: 450px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>The copilot's 138 tools, one cell each, and what the loop's <code>plan_tools</code> hands the parent turn and each shipped specialist for the same question.</figcaption>
</figure>

<p>When a question needs several rounds of data gathering, the copilot can delegate a sub-question to a specialist: a smaller child loop with its own instructions and a narrower slice of the tool catalogue, which runs the lookups in isolation and returns one synthesized paragraph. Five specialists ship with the app (<code class="language-plaintext highlighter-rouge">general</code>, <code class="language-plaintext highlighter-rouge">market</code>, <code class="language-plaintext highlighter-rouge">filings</code>, <code class="language-plaintext highlighter-rouge">web</code>, and <code class="language-plaintext highlighter-rouge">portfolio</code>), and a user can declare up to eight custom specialists in settings—each with a <code class="language-plaintext highlighter-rouge">@name</code> handle, up to 4,000 characters of instructions, a tool allowlist, a model choice, and a cap of eight rounds.</p>

<p>What a custom declaration cannot override is fixed in the loop itself: every child runs in <code class="language-plaintext highlighter-rouge">ask</code> mode with mutating actions disabled, its tool list can only ever narrow the parent’s read-only tools, and a specialist cannot delegate again. Because <a class="act" href="#fa-spec" data-agent="general">the general specialist</a> declares no tool filter of its own, <code class="language-plaintext highlighter-rouge">plan_tools</code> hands it the full read-only slice routed by the question—<code class="language-plaintext highlighter-rouge">research_subagent</code> included—and the loop refuses the call at depth one if it tries to recurse.</p>

<h2 id="one-fire-per-slot">One fire per slot</h2>

<figure class="fig wide" id="fa-jobs" style="--reserve: 680px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>A week of the ten system jobs on the backend's own scheduler, stepped a minute at a time, with one window of it drawn minute by minute.</figcaption>
</figure>

<p>A single scheduler drives the backend’s ten recurring system jobs—market snapshots, nightly syncs, thesis scans, and morning or evening briefs—stepping once a minute. Each job is keyed to a slot (a local calendar date or an hour bucket) and may succeed at most once per slot; during an <a class="act" href="#fa-jobs" data-scenario="outage">upstream outage</a>, a failing pass retries up to three times in that slot, one minute apart, before waiting for the next window.</p>

<p>Because a self-hosted box can reboot or sleep at any hour, a <a class="act" href="#fa-jobs" data-scenario="restart">restart</a> treats any pass left marked <code class="language-plaintext highlighter-rouge">running</code> in SQLite as failed and re-fires it immediately, while skipping any morning brief whose catch-up window has already closed rather than delivering a pre-market summary at noon.</p>

<h2 id="evals-without-a-key">Evals without a key</h2>

<figure class="fig wide" id="fa-evals" style="--reserve: 680px" data-src="/blogs/assets/data/finos-agentlab-demo.json">
<figcaption>The core suite run scripted on this machine and replayed at its recorded pace: the real loop, catalogue and checks against a model that plays a fixed script, with no network.</figcaption>
</figure>

<p>Half of the core evaluation suite (17 of 34 scenarios, 144 checks in all) runs in five seconds without an API key and with outbound network connections blocked, because what it guards is the loop rather than the model. A scripted fake model replays predetermined tool calls and failure modes against the real <code class="language-plaintext highlighter-rouge">CopilotLoop</code>, tool registry, and permission checks: verifying that <a class="act" href="#fa-evals" data-id="permission.attempt_is_refused">an action attempted in ask mode is stopped</a> before touching disk, that <a class="act" href="#fa-evals" data-id="leaked_call.retried_not_shipped">a tool call written as prose is handed back</a> for a retry rather than shown to the user, and that <a class="act" href="#fa-evals" data-id="horizon.early_lookup_survives">the sixteen-lookup turn</a> compacts older tool results out of its context window as it works and still answers using the very first lookup.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[How FinOS-AgentLab isolates a LangGraph trading desk and a vectorbt quant worker behind FastAPI, routes 138 copilot tools under strict token ceilings, caches prompt prefixes, and tests its agent loop offline.]]></summary></entry><entry><title type="html">Porting San Andreas to a browser tab</title><link href="https://sir-teo.github.io/blogs/2026/10/09/porting-san-andreas-to-a-browser-tab.html" rel="alternate" type="text/html" title="Porting San Andreas to a browser tab" /><published>2026-10-09T14:00:00-04:00</published><updated>2026-10-09T14:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/09/porting-san-andreas-to-a-browser-tab</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/09/porting-san-andreas-to-a-browser-tab.html"><![CDATA[<p><strong>web-gta</strong> recreates <em>Grand Theft Auto: San Andreas</em> inside a browser tab, streaming the original 900 MB world as you drive and executing the original mission scripts. Because the game’s map, models, scripts, and audio belong to Rockstar (“Native assets retain their original ownership,” the project’s notes state), none of that proprietary content appears on this page. Instead, every interactive figure below runs the port’s own TypeScript subsystems live on synthetic inputs built for this post.</p>

<h2 id="what-runs-where">What runs where</h2>

<figure class="fig">
<svg class="arch" viewBox="0 0 680 300" role="img" aria-label="Architecture: on the main thread, a fixed 60 Hz simulation, Rapier physics in WebAssembly, a three.js renderer and the region follower; in workers, the world streamer and the chunk fetcher; underneath, Cache Storage and a service worker.">
<defs>
<marker id="gta-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path class="head-strong" d="M0,1 L9,5 L0,9 z" /></marker>
</defs>
<text class="lbl" x="24" y="13">Main thread</text>
<text class="lbl" x="400" y="13">Workers</text>
<rect class="box" x="24" y="26" width="320" height="48" rx="6" />
<text class="t" x="184" y="42">Simulation, a fixed 60 Hz</text>
<text class="st" x="184" y="59">CJ, traffic, peds, police, the script interpreter</text>
<rect class="box" x="24" y="88" width="152" height="48" rx="6" />
<text class="t" x="100" y="104">Rapier</text>
<text class="st" x="100" y="121">physics, WebAssembly</text>
<rect class="box" x="192" y="88" width="152" height="48" rx="6" />
<text class="t" x="268" y="104">three.js</text>
<text class="st" x="268" y="121">WebGL, at most 30 fps</text>
<rect class="box" x="24" y="150" width="320" height="48" rx="6" />
<text class="t" x="184" y="166">Region follower</text>
<text class="st" x="184" y="183">asks for the window ahead, holds play if it is late</text>
<rect class="box" x="400" y="26" width="256" height="48" rx="6" />
<text class="t" x="528" y="42">World streamer</text>
<text class="st" x="528" y="59">placements, models, collision per window</text>
<rect class="box" x="400" y="88" width="256" height="48" rx="6" />
<text class="t" x="528" y="104">Chunk fetcher</text>
<text class="st" x="528" y="121">fetch, check, keep, inflate</text>
<path class="edge-strong" d="M346 174 H372 V50 H398" marker-end="url(#gta-arrow)" />
<text class="el" x="372" y="190">request</text>
<path class="edge" d="M528 76 V86" marker-end="url(#gta-arrow)" />
<rect class="box" x="24" y="222" width="632" height="62" rx="6" />
<text class="t" x="340" y="240">The browser's storage</text>
<text class="st" x="340" y="258">Cache Storage: 1,943 world chunks, each named by its hash</text>
<text class="st" x="340" y="274">Service worker: the app, the start package and scripts</text>
<path class="edge" d="M528 138 V220" marker-end="url(#gta-arrow)" />
</svg>
<figcaption>Everything a frame needs runs on the main thread; everything that touches the world's 900 MB runs in workers.</figcaption>
</figure>

<p>Keeping an open-world game smooth in a browser means keeping the 900 MB map off the thread that draws frames. On the main thread, the simulation steps at a fixed 60 Hz—updating CJ, ambient traffic, pedestrians, police, and the mission script interpreter—alongside Rapier physics in WebAssembly and a <code class="language-plaintext highlighter-rouge">three.js</code> renderer capped at 30 fps. Everything that touches storage or network lives in background workers: a chunk fetcher downloads, verifies, caches, and inflates raw world archives across 1,943 hash-addressed chunks, while a world streamer unpacks building placements, geometry, and collision meshes for the active region.</p>

<p>Gameplay systems are ported from <code class="language-plaintext highlighter-rouge">gta-reversed</code>, the community’s C++ reconstruction of the PC game; wherever <code class="language-plaintext highlighter-rouge">gta-reversed</code> has only a stub, the port cross-references the disassembled iOS executable to recover the missing logic.</p>

<h2 id="streaming-a-state">Streaming a state</h2>

<figure class="fig" id="gta-stream">
<figcaption>The port's region follower on a made-up road, one minute of driving with each window taking a fixed time to load. The strip at the bottom is the same follower in the real game, on a scripted 90-second drive, before and after the streaming worker stopped re-decoding models it already had.</figcaption>
</figure>

<p>The world arrives in 180-unit high-detail windows surrounded by low-detail LODs out to 1,000 units. A small state machine, the region follower, tracks a look-ahead point in front of the car: once that point drifts 30% of a radius from the current window’s center, it asks the worker for the next window; if the car travels 85% of the way to the edge before the new window arrives, the game pauses on a streaming hold rather than letting CJ drive off the end of the collision mesh.</p>

<p>On the synthetic straight road above, <a class="act" href="#gta-stream" data-speed="70" data-latency="2" data-lead="fixed">at 70 m/s, 2-second windows</a> land just in time and never stop the car. <a class="act" href="#gta-stream" data-speed="70" data-latency="2.1" data-lead="fixed">At 2.1 seconds</a>, that extra tenth of a second pushes the car past the 85% threshold and triggers repeated holds.</p>

<p>That exact cliff showed up in the real game. When players reported freezes on fast highways, a scripted route probe drove a 90-second diagonal across the map at 70 m/s and logged 53 streaming holds totaling 28.6 seconds—and along the way uncovered a Rapier physics body leak that no unit test had caught. The streaming worker had been decoding every model in each new window before discarding the ones already resident in memory. Skipping already-loaded models before decoding and caching collision data cut window load times from 1.3–1.9 seconds down to 60–350 ms, reducing the same 90-second drive to a single 1.4-second hold at the start.</p>

<h2 id="running-the-original-scripts">Running the original scripts</h2>

<figure class="fig wide" id="gta-vm">
<figcaption>The port's script decoder and interpreter on a six-instruction script assembled for this page. Below, the port's census of the 1,570 commands the original scripts use.</figcaption>
</figure>

<p>San Andreas’s story, side jobs, cutscene timing, and ambient triggers are all compiled into Rockstar’s SCM bytecode (<code class="language-plaintext highlighter-rouge">main.scm</code> plus roughly two hundred streamed mission scripts), and web-gta executes that original bytecode directly. Each cooperative script thread steps through instructions—a two-byte opcode followed by type-tagged arguments—until it reaches a <code class="language-plaintext highlighter-rouge">WAIT</code>, then sleeps until the game clock catches up. (<a class="act" href="#gta-vm" data-wait="1000" data-play="1">Set the wait to a full second</a> and the thread spends almost all its time asleep, which is what most of the game’s background threads are doing at any moment.)</p>

<p>Writing the bytecode interpreter is the small part; the real work is the opcode catalogue behind it. The original scripts call 1,570 distinct commands across 416,669 places in the bytecode, and each one needs an engine subsystem behind it to spawn a car, assign a pedestrian task, or start a phone call. When a thread hits one of the 127 commands that aren’t ported yet, the interpreter logs the skip, reports “nothing found” for its outputs, and lets the mission carry on rather than crashing the script.</p>

<h2 id="traffic-from-the-original-arithmetic">Traffic from the original arithmetic</h2>

<figure class="fig" id="gta-traffic">
<figcaption>Two made-up cars. The blue one brakes with the port of <code>CCarCtrl::SlowCarDownForOtherCar</code> for whatever gap the grey one leaves.</figcaption>
</figure>

<p>Ambient traffic runs a direct port of <code class="language-plaintext highlighter-rouge">CCarCtrl::SlowCarDownForOtherCar</code>. When another vehicle enters the scan zone ahead, the follower caps its target speed at roughly 62% of cruise and slows down in proportion to the closing gap.</p>

<p>Right behind a bumper, however, three consecutive branches in the original formula produce a quirk you can watch live above. <a class="act" href="#gta-traffic" data-place="8.5">Stopped 8.5 units behind</a> the lead car, the follower stays put in the outer stop zone. Place it <a class="act" href="#gta-traffic" data-place="7.5">one unit closer</a> and it lands in a middle branch that commands a crawl speed of <code class="language-plaintext highlighter-rouge">1</code>, creeping forward until it hits the inner stop zone at 5.9 units—closer than the spot where it was already stopped, it starts moving again. Both zones come straight out of the branching arithmetic ported from <code class="language-plaintext highlighter-rouge">reVC</code>.</p>

<h2 id="fitting-on-a-phone">Fitting on a phone</h2>

<figure class="fig" id="gta-res">
<figcaption>The port's adaptive-resolution controller on three made-up phones. Grey is frame time, blue the resolution scale.</figcaption>
</figure>

<p>Running a desktop open-world game inside a mobile browser hits three bottlenecks at once: fill-rate limits, thermal throttling, and tight memory ceilings. To protect frame rate, the adaptive-resolution controller watches the median frame time over a three-second window and drops a step down the resolution ladder (<code class="language-plaintext highlighter-rouge">100% → 85% → 72% → 60%</code>) whenever rendering stays slower than 26 fps. On <a class="act" href="#gta-res" data-kind="gpu" data-base="45">a GPU-bound phone</a>, stepping down to 85% immediately restores smooth frames; on <a class="act" href="#gta-res" data-kind="cpu" data-base="45">a CPU-bound phone</a>, fewer pixels make no difference, so the controller undoes the step after a single window and backs off—waiting twice as long before each retry—rather than blurring the screen for nothing.</p>

<figure class="fig" id="gta-dxt">
<figcaption>One 8-byte DXT1 block through the port's decoder, to 32-bit colour and to the 16 bits a phone gets. The two endpoint colours and the sixteen indices are the whole block.</figcaption>
</figure>

<p>Because few mobile GPUs can sample the PC release’s DXT-compressed textures directly, the port decodes them on the CPU as chunks stream in. Decoding DXT1 blocks into 16-bit colour (<code class="language-plaintext highlighter-rouge">RGB565</code>, or <code class="language-plaintext highlighter-rouge">RGB5A1</code> when a block uses DXT1’s transparency mode—<a class="act" href="#gta-dxt" data-swap="1">swap the two endpoints</a> to see <code class="language-plaintext highlighter-rouge">c0 &lt;= c1</code> turn index <code class="language-plaintext highlighter-rouge">3</code> clear) instead of 32-bit RGBA cut texture memory around Grove Street in half, from 93 MB to 46 MB.</p>

<figure class="fig" id="gta-steer">
<figcaption>The port's touch-stick steering against a stick that steers one for one. The stick springs back when let go.</figcaption>
</figure>

<p>Finally, because a thumb on glass has no physical resistance, the touch thumbstick uses the iOS port’s non-linear steering curve: the first third of the stick’s travel turns the wheels only a fifth of the way so you can make fine lane corrections at speed, while the outer range opens up to full lock.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[How web-gta streams San Andreas into a browser tab, executes the original SCM mission bytecode, ports CCarCtrl traffic arithmetic, and fits a 900 MB world onto a phone.]]></summary></entry><entry><title type="html">Replaying a village raid</title><link href="https://sir-teo.github.io/blogs/2026/10/09/replaying-a-village-raid.html" rel="alternate" type="text/html" title="Replaying a village raid" /><published>2026-10-09T13:00:00-04:00</published><updated>2026-10-09T13:00:00-04:00</updated><id>https://sir-teo.github.io/blogs/2026/10/09/replaying-a-village-raid</id><content type="html" xml:base="https://sir-teo.github.io/blogs/2026/10/09/replaying-a-village-raid.html"><![CDATA[<p><strong>Crown &amp; Clan</strong> is a village-building and raiding game in the mould of Clash of Clans, written in TypeScript and Phaser with no server behind it. Because it is an independent fan project (“Clash of Clans assets and trademarks belong to Supercell,” its README notes), the figures here draw plain geometric shapes instead of sprites. Every battle in them was simulated by the game’s own engine in Node across the twelve campaign villages the project designed itself.</p>

<h2 id="a-simulation-with-no-screen">A simulation with no screen</h2>

<figure class="fig">
<svg class="arch" viewBox="0 0 680 262" role="img" aria-label="Taps and recorded actions go into GameModel, a pure TypeScript simulation stepped at 20 Hz; a Phaser scene and a DOM HUD read it; saves and recordings go to the browser's storage.">
<defs>
<marker id="coc-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path class="head-strong" d="M0,1 L9,5 L0,9 z" /></marker>
</defs>
<rect class="box" x="16" y="30" width="168" height="52" rx="6" />
<text class="t" x="100" y="48">Your taps</text>
<text class="st" x="100" y="65">deploy, spell, end</text>
<rect class="box" x="16" y="104" width="168" height="52" rx="6" />
<text class="t" x="100" y="122">A recording</text>
<text class="st" x="100" y="139">the same actions, replayed</text>
<rect class="box em" x="234" y="56" width="212" height="76" rx="6" />
<text class="t" x="340" y="80">GameModel</text>
<text class="st" x="340" y="98">pure TypeScript, no Phaser</text>
<text class="st" x="340" y="114">step(0.05), twenty times a second</text>
<rect class="box" x="496" y="30" width="168" height="52" rx="6" />
<text class="t" x="580" y="48">Phaser scene</text>
<text class="st" x="580" y="65">draws between two steps</text>
<rect class="box" x="496" y="104" width="168" height="52" rx="6" />
<text class="t" x="580" y="122">HUD</text>
<text class="st" x="580" y="139">plain DOM, reads the model</text>
<path class="edge-strong" d="M184 56 H209 V84 H232" marker-end="url(#coc-arrow)" />
<path class="edge-strong" d="M184 130 H209 V104 H232" marker-end="url(#coc-arrow)" />
<path class="edge-strong" d="M448 84 H471 V56 H494" marker-end="url(#coc-arrow)" />
<path class="edge-strong" d="M448 104 H471 V130 H494" marker-end="url(#coc-arrow)" />
<rect class="box" x="16" y="190" width="648" height="52" rx="6" />
<text class="t" x="340" y="208">Saves</text>
<text class="st" x="340" y="225">IndexedDB with a localStorage backup · each raid kept as its setup, every step size and every action</text>
<path class="edge" d="M340 134 V188" marker-end="url(#coc-arrow)" />
</svg>
<figcaption>The simulation never imports Phaser, so the same code runs a battle on screen, in a replay, in a test or in Node.</figcaption>
</figure>

<p>One architectural rule governs the entire 66,000-line codebase: <code class="language-plaintext highlighter-rouge">GameModel</code> may never import Phaser, a scene class, or a single byte of rendering data. Fifty-three files in the repository touch Phaser, and none of them is reachable from the simulation. During a live battle, the Phaser scene steps <code class="language-plaintext highlighter-rouge">GameModel</code> twenty times a second (<code class="language-plaintext highlighter-rouge">step(0.05)</code>) and interpolates unit positions between ticks so movement looks smooth at any display refresh rate without the model knowing frames exist. Because the simulation is pure TypeScript, the exact same class runs live raids in the browser, verifies deterministic replays in CI, and generated every figure on this page from a Node script.</p>

<h2 id="where-you-attack-from">Where you attack from</h2>

<figure class="fig wide" id="coc-raid" style="--reserve: 560px" data-src="/blogs/assets/data/web-coc-demo.json">
<figcaption>One army, twelve landing points around Ember Keep, each raid run by the game's engine. Troops can't land in the shaded zone.</figcaption>
</figure>

<p>Once deployed outside the shaded exclusion zone, every unit follows a greedy target rule: Barbarians and Archers march toward the nearest building of any kind, while Giants ignore resource huts and head straight for the nearest defense. That makes your landing point decisive, because it determines which defenses your Giants engage first and how long your damage dealers survive behind them.</p>

<p>Deploy the exact same 42-troop army (6 Giants, 4 Wall Breakers, 16 Barbarians, 16 Archers) from twelve points around Ember Keep and the outcomes split completely. <a class="act" href="#coc-raid" data-point="3">From the northeast</a>, the army strings out into the village’s defenses one at a time and dies at 37% destruction with zero stars. <a class="act" href="#coc-raid" data-point="5">From lower down the same side</a>, four of the six Giants survive into the core and the raid clears the village for all three stars in 42 seconds:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">b</span><span class="p">.</span><span class="nx">stars</span> <span class="o">=</span> <span class="nb">Number</span><span class="p">(</span><span class="nx">b</span><span class="p">.</span><span class="nx">destruction</span> <span class="o">&gt;=</span> <span class="mi">50</span><span class="p">)</span>
  <span class="o">+</span> <span class="nb">Number</span><span class="p">(</span><span class="nx">townHallDead</span><span class="p">)</span>
  <span class="o">+</span> <span class="nb">Number</span><span class="p">(</span><span class="nx">b</span><span class="p">.</span><span class="nx">destruction</span> <span class="o">===</span> <span class="mi">100</span><span class="p">);</span>
</code></pre></div></div>

<h2 id="routes-through-walls">Routes through walls</h2>

<figure class="fig wide" id="coc-paths" style="--reserve: 480px" data-src="/blogs/assets/data/web-coc-demo.json">
<figcaption>Routes from 64 points around the village, from the game's own <code>findPath</code>. Red: walls a route breaks through.</figcaption>
</figure>

<p>Every ground unit finds its way across the 48×48 tile grid with four-directional A*. Buildings are solid obstacles, while walls are passable at a price: stepping onto open grass costs <code class="language-plaintext highlighter-rouge">1</code>, and stepping through a wall tile costs <code class="language-plaintext highlighter-rouge">7</code>. A troop will detour up to six extra tiles around a wall before deciding to stop and batter through it, recomputing its path whenever a building or wall segment falls.</p>

<p>Because <a class="act" href="#coc-paths" data-troop="giant">Giants</a> only target defenses—and Ember Keep’s defenses sit inside stone compartments—20 of the 64 perimeter starting points send them straight through a wall. <a class="act" href="#coc-paths" data-troop="barbarian">Barbarians</a> settle for the closest building of any kind, which from the perimeter is always an outside building, so their initial paths never break a wall at all.</p>

<h2 id="one-army-twelve-villages">One army, twelve villages</h2>

<figure class="fig" id="coc-sweep" style="--reserve: 420px" data-src="/blogs/assets/data/web-coc-demo.json">
<figcaption>Destruction on each of the campaign's twelve villages, for three armies deployed from the west.</figcaption>
</figure>

<p>Because <code class="language-plaintext highlighter-rouge">GameModel</code> runs without a screen, balancing the twelve-stage single-player campaign means sweeping test armies across every village in Node. Deployed from the west, the small starter army fades after the fourth village, while the medium ground force holds three stars through village eight. <a class="act" href="#coc-sweep" data-village="8">Air</a> (Balloons and Dragons) flies over every wall to clear the first eight villages just as easily as the ground army, then falls off sharply on the Expert stages as soon as villages gain a second Air Defense.</p>

<h2 id="every-step-recorded">Every step, recorded</h2>

<figure class="fig wide" id="coc-det" style="--reserve: 520px" data-src="/blogs/assets/data/web-coc-demo.json">
<figcaption>The same raid with the same taps, stepped every 0.05 s and every 0.1 s. Lines trace each troop.</figcaption>
</figure>

<p>Crown &amp; Clan does not record a battle as video or as a stream of unit positions. A replay saves only the initial setup and your timestamped taps, then simulates the battle again from scratch—45 actions and 317 step sizes for the 16-second raid above, under 10 KB in all.</p>

<p>That only works if simulating the raid a second time produces the exact same battle to the bit. Combat uses no ambient random number generator, hashing a fixed battle seed with a counter whenever a rule needs chance. Distances are computed with explicit arithmetic because browser implementations of <code class="language-plaintext highlighter-rouge">Math.hypot</code> can disagree by a few least-significant bits—enough for a projectile in Safari to arrive one tick later than in Chrome and fork the rest of the raid. And because a different tick rate produces a different battle—as the two boards above show <a class="act" href="#coc-det" data-time="8">halfway through the raid</a>—the recording logs every step size alongside every tap.</p>]]></content><author><name>Teo</name><email>zengwc.teo2016@outlook.com</email></author><summary type="html"><![CDATA[How Crown & Clan keeps its TypeScript battle simulation decoupled from Phaser, deterministic across browsers, and replayable from a 10 KB log of taps and step sizes.]]></summary></entry></feed>