<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ruslan Gilmullin on Medium]]></title>
        <description><![CDATA[Stories by Ruslan Gilmullin on Medium]]></description>
        <link>https://medium.com/@mellonis?source=rss-c572d2916ed8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NRM97HqmZ_CVR5WnSU-oVw.jpeg</url>
            <title>Stories by Ruslan Gilmullin on Medium</title>
            <link>https://medium.com/@mellonis?source=rss-c572d2916ed8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:26:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mellonis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Seven arrows, 429 trees: a Mermaid cleanup uncovered a 7-year naming bug]]></title>
            <link>https://medium.com/@mellonis/seven-arrows-429-trees-a-mermaid-cleanup-uncovered-a-7-year-naming-bug-59c8569556c6?source=rss-c572d2916ed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c8569556c6</guid>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[catalan]]></category>
            <category><![CDATA[turing-machine]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Ruslan Gilmullin]]></dc:creator>
            <pubDate>Mon, 15 Jun 2026 19:10:39 GMT</pubDate>
            <atom:updated>2026-06-15T19:10:39.495Z</atom:updated>
            <content:encoded><![CDATA[<p>Two Turing machines walked into a diagram. They had the same name.</p><p>What I really mean is: two distinct wrapper states in <a href="https://github.com/mellonis/turing-machine-js">@turing-machine-js/machine</a>, constructed differently, with different runtime behavior, and with byte-identical state.name. I’ve been developing the library as a hobby since 2019, and I’d missed this for seven years.</p><p>I caught it sideways, starting from what looked like a Mermaid cleanup ticket. It ended in a redesign of how state composition is <em>encoded in the name</em>. And along the way I learned that tucked inside that redesign is the number C7=429.</p><figure><img alt="Archer with bow drawn, contemplating which tree of a forest his arrow will hit" src="https://cdn-images-1.medium.com/max/1024/1*dNC4C1Cgv22MfQ0uuokxbQ.png" /></figure><h3>Where it started</h3><p>Composition in the engine is one primitive: bareState.withOverrodeHaltState(overrideState). It returns a copy of bareState whose would-be halt transitions fall through to overrideState. From here on I’ll call bareState the <em>bare state</em> and the returned copy a <em>wrapper</em> over it. Composition via wrapping is the only way to build a bigger machine out of smaller halt-on-completion subroutines.</p><p>The wrapper’s name, in the old API, was formed like this:</p><pre>state.#name = `${this.name}&gt;${override.name}`;</pre><p>So A.withOverrodeHaltState(B) is named A&gt;B. Simple, readable: “A, then B.”</p><p>That line shipped in 2019 and hadn’t been touched since. It’s the name logs use, the name error messages use, the name tests compare against, and the name any user-facing diagnostic surfaces.</p><p>The investigation began with the Mermaid output. <a href="https://github.com/mellonis/turing-machine-js/issues/138">turing-machine-js#138</a> asked for a cleaner emit. Before v7, toMermaid rendered a wrapper as a separate node whose transitions were <em>duplicated</em> from the bare — visually it looked like the wrapper had a life of its own. But the wrapper’s transitions are the bare’s — even #symbolToDataMap is the same reference, not a copy. What it does own is call-frame semantics: push the override onto the halt-stack on entry, pop on the bare’s halt. Behaviorally, the wrapper adds one thing on top of the bare: where halt goes.</p><p>Roughly, this is what it looked like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*OmS7j8eM8ZsIzvwyOkLZQw.png" /></figure><p>A and A&gt;B are two nodes with literally the same outgoing transition to A1, plus the wrapper gets a dashed onHalt arrow to B. The reader sees “two distinct machines,” when behaviorally it’s one machine with a single point of divergence — where halt goes.</p><p>The first fix attempt looked reasonable: render the wrapper as a single node that reuses the bare’s transitions, with the override-halt as a separate arrow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kOh6cIxsRNqqKor26YV4sA.png" /></figure><p>One A&gt;B node, transitions reused from the bare’s graph, override-halt as a separate dashed arrow from halt to B. Clean, compact, no visual noise. Almost worked.</p><h3>Almost worked — then broke</h3><p>Take minusOne from <a href="https://github.com/mellonis/turing-machine-js/tree/master/packages/library-binary-numbers">library-binary-numbers</a> — it’s built by nested wrapping:</p><pre>const minusOne = invertNumber<br>  .withOverrodeHaltState(<br>    plusOne<br>      .withOverrodeHaltState(<br>        invertNumber<br>          .withOverrodeHaltState(normalizeNumber),<br>      ),<br>  );</pre><p>Composite name: invertNumber&gt;plusOne&gt;invertNumber&gt;normalizeNumber — three &gt; separators in real code, and already one base (invertNumber) appears twice. When a name gets longer, it’s tempting to read it as a <em>walking instruction</em>. Take A&gt;B&gt;B&gt;A&gt;A&gt;B&gt;B&gt;A (seven separators): each letter is a bare state you land in after the previous one halts. The sequence of bases visited should equal the name.</p><p>Except that’s wishful reading. The name doesn’t formally determine the traversal. It <em>resembles</em> it. And only if the chain was constructed the one specific way I happened to picture when I wrote the naming rule in 2019.</p><h3>The catch</h3><p>Take a smaller example: A&gt;B&gt;A. How many ways to build it?</p><p>At least two:</p><pre>// Construction 1<br>const c1 = A.withOverrodeHaltState(B.withOverrodeHaltState(A));<br>// Construction 2<br>const c2 = A.withOverrodeHaltState(B).withOverrodeHaltState(A);</pre><p>Both flatten to the string A&gt;B&gt;A under ${this.name}&gt;${override.name}. But the wrapper topologies differ — each construction builds its own binary tree (internal • nodes are withOverrodeHaltState applications, leaves are plain State instances):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*3A4WsVlToaZMFgmmhJE4Rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*0uTADJlzkZsPGR_bDAUAxw.png" /></figure><p>And the runtime behavior differs too:</p><ul><li>Construction 1 (A.wohs(B.wohs(A))): A’s halt goes to a wrapper “B with halt redirected to A”. Runtime walk: A → B → A.</li><li>Construction 2 (A.wohs(B).wohs(A)): the wrapper “A with halt redirected to B” is wrapped once more — halt now goes to A. Runtime walk: A → A. The inner B override is dead: only the outermost .wohs()’s override makes it onto the halt stack.</li></ul><p>Same name. Just because the flat &gt; separator doesn’t remember <em>where</em> in the construction tree each arrow sat. And there was a tree there.</p><h3>The tree we forgot</h3><p>withOverrodeHaltState is a binary operation: a left argument (this) and a right argument (override). Each application is a new node in the tree. The node has two children: the bare and the override. If a child is itself a wrapper, the tree continues there with another node; otherwise it’s a plain State — a <em>leaf</em>. After N applications: N wrapper-nodes and N+1 leaves — standard binary-tree property. For minusOne above: 3 applications (3 wrapper-nodes), 4 leaves (invertNumber, plusOne, invertNumber, normalizeNumber). Here’s the tree explicitly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*yZcJFkrMDk4dswhVSLjqFA.png" /></figure><p>The name, meanwhile, is <em>flat</em>: a concatenation joined by &gt;. A binary tree gets serialized into a string, and the string can be reversed back into the tree only if the naming convention is <em>bijective</em>. The flat &gt; notation isn’t.</p><p>How many trees can correspond to one name with N separators? The standard answer from combinatorics: the <a href="https://en.wikipedia.org/wiki/Catalan_number">Catalan number</a> CN.</p><p>Cn=1/(n+1)(2n n) — the sequence that counts: the number of binary trees with n+1 leaves, the number of balanced-paren strings of length 2n, the number of Dyck paths of length 2n, the number of triangulations of an (n+2)-gon, and a dozen other isomorphic combinatorial objects. The kind of number that turns up <em>everywhere</em>.</p><p>The most direct angle for our case: parenthesization. For an arbitrary binary operator •, the number of ways to parenthesize a • b • c • ... (with n+1 operands) is Cn. withOverrodeHaltState is exactly such an operator — each parenthesization corresponds to a distinct composition tree.</p><p>The first eight values: C0=1, C1=1, C2=2, C3=5, C4=14, C5=42, C6=132, \boldsymbol{C_7 = 429}.</p><p>For our A&gt;B&gt;B&gt;A&gt;A&gt;B&gt;B&gt;A, that means 429 different construction trees, each with its own parent-child wiring, all collapsing to the same string. And 429 isn’t a theoretical upper bound — it’s the exact number of distinct structures hiding behind that one name.</p><p>A smaller example — A&gt;B&gt;C&gt;D (three separators). By the formula, C3=5; here are the five construction trees, written as code:</p><pre>// 1. fully left-associative<br>((A.wohs(B)).wohs(C)).wohs(D)<br>// 2.<br>(A.wohs(B.wohs(C))).wohs(D)<br>// 3.<br>(A.wohs(B)).wohs(C.wohs(D))<br>// 4.<br>A.wohs((B.wohs(C)).wohs(D))<br>// 5. fully right-associative<br>A.wohs(B.wohs(C.wohs(D)))</pre><p>All five collapse to the same flat string A&gt;B&gt;C&gt;D. Under the paren notation v7 will ship, each gets a distinct name — more on that below.</p><h3>The fix is parens</h3><p>If a flat separator throws the tree away, parens keep it. v7 (<a href="https://github.com/mellonis/turing-machine-js/issues/148">turing-machine-js#148</a>) changes the naming rule to:</p><pre>state.#name = `${this.name}(${override.name})`;</pre><p>A.withOverrodeHaltState(B) is now named A(B). Back to our two A&gt;B&gt;A constructions:</p><pre>// Construction 1: A(B(A))<br>const c1 = A.withOverrodeHaltState(B.withOverrodeHaltState(A));<br>// Construction 2: A(B)(A) - in pure paren notation<br>const c2 = A.withOverrodeHaltState(B).withOverrodeHaltState(A);</pre><p>Same characters, different brackets, different trees. Names distinguish them. Bijection!</p><p>And this isn’t an <em>invented</em> convention. Balanced-paren strings of length 2n are the canonical encoding of binary trees with n+1 leaves in combinatorics — the same bijection underlying one of the foundational counting results for Catalan numbers. A better convention wasn’t <em>designed</em> — what gets <em>recovered</em> is the structure the &gt; notation was always discarding.</p><p>The cost: state names from users can no longer contain ( or ) — the State constructor throws. Parens are reserved for composition. In exchange, &gt; is no longer reserved and is fine in user-provided names again.</p><h3>The other half of the story</h3><p>The clean paren bijection above is about <em>naming</em>. v7 also cleans up the runtime alongside. <a href="https://github.com/mellonis/turing-machine-js/issues/176">turing-machine-js#176</a> adds chain-collapse: inside withOverrodeHaltState, we now do bare = this.#bareState ?? this. So A.wohs(B).wohs(A) is recognized as “wrapping an already-wrapped A” — the inner override (B) is dead at runtime anyway (only the <em>outermost</em> wrapper’s override gets pushed onto the halt-stack), and instead of A(B)(A) you get A(A).</p><p>So in actual v7, Construction 2 doesn’t give you A(B)(A) — at construction time it collapses to A(A). Paren naming on its own is bijective (one tree, one name); chain-collapse adds a step on top, removing trees that are indistinguishable at runtime. The composite name in v7 describes how the machine behaves, not how it was built.</p><p>And while we were touching the operator: the method gets renamed. withOverrodeHaltState → withOverriddenHaltState (<a href="https://github.com/mellonis/turing-machine-js/issues/149">turing-machine-js#149</a>). Past-tense overrode never fit the idiom — it should have been the past participle overridden. A seven-year grammar typo on a public API. Hard cutover, no alias.</p><h3>Other places this shows up</h3><p>Non-injective serialization is a general pattern. If your codebase has a “name” formed by flat-separator concatenation of something tree-shaped, the odds of a C_n bug aren’t zero. A few examples:</p><ul><li><strong>File-extension chains</strong> — .tar.gz, .spec.ts, .d.ts. Works by convention because the extensions are well-known. Put a dot in the filename and the ambiguity is immediate: is my.app.tar.gz the basename my.app with extension .tar.gz, or the basename my.app.tar with extension .gz? Different tools answer differently.</li><li><strong>DB column aliases</strong> with _ separators: user_address_country. If user_address is already a table name (underscore is part of the identifier), then user_address_country is ambiguous: is it user.address_country or user_address.country? Fix via qualified namespacing or explicit aliases.</li><li><strong>Module paths in Java/Python</strong> — com.example.foo.Bar. Could be class Bar in package com.example.foo or nested class foo.Bar in package com.example. Resolved by convention (uppercase = class), not by the naming itself.</li></ul><p>Code-review heuristic: <strong>if your “identifier” is a flat-separator concatenation of something tree-shaped, look for the C_n bug</strong>. It’s almost always <em>latent</em>: in production the names happen not to collide on the actual data, but architecturally the hole is always there.</p><p>In my library the C_n bug hid for seven years because no one was trying to catch the engine on a name collision. To find it, you’d have to know to construct two structurally distinct trees and check whether their names differ. Nobody writes that test until they hear the collision is possible.</p><h3>What v7 ships</h3><p>Three tickets that were planned as three separate changes but, on closer look, are the same thought:</p><ul><li><strong>Paren-based naming</strong> (<a href="https://github.com/mellonis/turing-machine-js/issues/148">turing-machine-js#148</a>). The bijection between composition trees and their names.</li><li><strong>Cleaner Mermaid emit</strong> (<a href="https://github.com/mellonis/turing-machine-js/issues/138">turing-machine-js#138</a>, <a href="https://github.com/mellonis/turing-machine-js/issues/174">turing-machine-js#174</a>). Wrappers emit as separate [[composite-name]] nodes; the bare’s reachable subtree becomes a subgraph callable subtree of NAME block. The structural clarity of the name shows up as visual clarity in the diagram:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jEIj-whwZx6v60FyM66V1g.png" /></figure><p>Wrapper — <em>call site</em>; bare’s body — <em>callable subtree</em>; halt — <em>return</em>. Composition in the engine literally became a function call.</p><ul><li>withOverrodeHaltState<strong> → </strong>withOverriddenHaltState (<a href="https://github.com/mellonis/turing-machine-js/issues/149">turing-machine-js#149</a>). Grammar on a public API.</li></ul><p>All three are one idea: composition is tree-shaped, and its representations should keep the tree, not smear it.</p><h3>Closing</h3><p>A visualization cleanup turned into a naming overhaul. That’s the same pattern I described in “<a href="https://mellonis.ru/en/articles/dva-mazhora-odin-readme-odno-demo/">Two majors, one README, one demo</a>”: a design review tests can’t run catches what tests can’t see. There it was docs and the first consumer. Here it’s visualization. The genre is the same: put yourself in front of the task of <em>showing the structure</em>, and if the structure is bent, it starts protruding. Tests don’t do that — tests check behavior, and structural bentness is usually visible only in the <em>representation</em>.</p><p>Seven arrows, 429 trees. A name that looked like a traversal trace turned out to be one of 429 possible ones. v7 gives each its own name — and lets the visualization show how that tree actually grew. That the wrapper IS a call-frame and deserves its own type — that’s another story (<a href="https://github.com/mellonis/turing-machine-js/issues/213">turing-machine-js#213</a>).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c8569556c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DebugSession: Giving coordination its own home]]></title>
            <link>https://medium.com/@mellonis/from-worker-reinvention-to-engine-companion-lifting-the-coordination-layer-into-debugsession-37b525d533b7?source=rss-c572d2916ed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b525d533b7</guid>
            <dc:creator><![CDATA[Ruslan Gilmullin]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 15:32:49 GMT</pubDate>
            <atom:updated>2026-06-07T15:39:51.697Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/mellonis/turing-machine-js">turing-machine-js</a> is a Turing-machine interpreter. Over the last two majors, a two-part debugging API took shape: some hooks observe execution, others coordinate it. The first part is the subject of “<a href="https://mellonis.ru/en/articles/three-majors-two-mistakes/">Three majors, two mistakes: designing a pause API for a Turing-machine interpreter</a>” (1). The second is the subject of “<a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">A pause with two sides: the hook contract and the worker protocol</a>” (2). <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">Article (2)</a> ended on a working protocol between the main thread and the <a href="https://demo.machines.mellonis.ru/">machines-demo</a> worker: an idle/busy message pair, a stepRequested flag, a synthetic paused event on click, an intervalMs field on resume. Four mechanisms, each closing one concrete problem. This article is about the next step.</p><p>Suppose a second consumer comes to the engine. Not the demo’s worker — say, an IDE extension, or an in-process educational debugger without a Web Worker. What from <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>’s protocol does it carry over? It doesn’t need the watchdog timer — there’s no thread boundary. It doesn’t need a message queue — the handlers live in the same thread. But the “step flag”, the “pause coordination”, the “paused event with multiple causes” — <em>all of that</em>, it does need. And it, without having read <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>, will reinvent the whole thing.</p><p>This article is about why coordination keeps getting reinvented. Not because the worker is “special”, but because in v6 coordination had no home of its own in the library. v7 gave it one: a companion class, DebugSession, sitting next to TuringMachine in the same package.</p><h3>What the worker reinvented</h3><p>Re-read <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>’s protocol through the new lens. Four mechanisms:</p><ol><li>idle/busy around the async throttle in onIter — wrapping for the watchdog timer.</li><li>stepRequested flag inside the worker — the “step” modeled as a one-shot request.</li><li>Synthetic paused event on click-Pause — handling an external pause command.</li><li>intervalMs field on resume — reading the speed “at click time”, not “at run start”.</li></ol><p>Sort them by ownership. The first and the fourth are about the worker: the watchdog timer lives on the main thread because there’s a boundary between threads; intervalMs arrives with every resume because the interval input and the engine sit on different threads. The second and third are about <em>coordination</em>: the step modeled as a one-shot event, the translation of an external pause command into a standard event. Web Workers have nothing to do with any of that — the same mechanisms would be needed in any debugger that switches the engine between paused and running.</p><p>Two out of four mechanisms — candidates for lifting out of the consumer and into the library. The worker would be left with two: the watchdog wrapping and the speed parameter on resume. That isn’t “reinvention of coordination” anymore — it’s an adapter between two interfaces: between the worker’s message protocol and the session’s API.</p><h3>Where coordination can live</h3><p>In v6, there were two places to put coordination:</p><ul><li>On the consumer side. Every new debugger builds it from scratch. With only one consumer, its choice of where to put coordination looks principled: there’s nothing to compare it against. Two consumers would highlight the duplication; three would confirm the pattern.</li><li>In the engine’s hooks. This temptation is laid out in <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>: widening onStep to an async signature (v6.2.0) conflated observation with coordination. The appearance of a dedicated onIter hook (v6.4.0) solved the “where does the throttle live” question, but didn’t lift the underlying constraint: a hook is a notification point, not a state machine. A hook has no internal state of its own, no lifecycle, no control methods — it hands the listener the current moment and awaits the listener’s Promise. Coordination, however, is exactly a state machine: “pause on breakpoint → continue / step-in / step-over / step-out / stop”. For step-over and step-out, where the next pause lands is determined by stack depth.</li></ul><p>The third option didn’t appear in v6 because the question wasn’t <em>forced</em> yet. With two consumers (or three, or N) the answer becomes obvious: coordination lives in a <em>sibling</em> class next to the engine. Not down the dependency graph (in the consumer), not inside the engine class itself (as yet another hook), but sideways — in a companion class on the same level of the library.</p><p>A side effect that’s also evidence: in v7, TuringMachine.run() is sync-and-void again — no callbacks. In v4 the same method became async to host the async pause hook (onDebugBreak, renamed to onPause in v5). Lifting coordination out erased that reason, and the signature reverted to its earlier shape. If async had been intrinsic to the engine, removing onPause wouldn’t have restored run() to its pre-v4 shape — but it did. So the async in run() was carried for that hook, not for the engine’s own execution logic.</p><figure><img alt="Architecture: DebugSession as a sibling of TuringMachine in the engine package; a consumer composes both." src="https://cdn-images-1.medium.com/max/1024/1*Z0rMaM1Q3y2uWK_TYFEwJA.png" /></figure><h3>What DebugSession owns</h3><p>The class sits in packages/machine/src/classes/DebugSession.ts, alongside TuringMachine. Constructed directly — new DebugSession(machine, {initialState}). The engine knows nothing about the session; the session knows about the engine only through its public sync generator runStepByStep, plus one package-private accessor keyed by the symbol MACHINE_STATE_INTERNAL, which sibling modules can read and the public index.ts doesn’t re-export. Same package-private-via-Symbol pattern as STATE_INTERNAL (<a href="https://github.com/mellonis/turing-machine-js/issues/180">turing-machine-js#180</a>) — it lets the session reach the per-iter halt-stack snapshot without exposing it through the public API.</p><p>The session listens for four events, each with its own dispatch contract:</p><ul><li>step — fire-and-forget. Sync, hot-loop observation; the listener’s Promise (if any) is not awaited. One-to-one with the v6 onStep contract.</li><li>iter — <em>awaited</em>. Per-iter coordination: a throttle between iterations, step-boundary synthesis, anywhere the engine genuinely needs to wait on the listener. One-to-one with the v6 onIter contract from <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>.</li><li>pause — listeners are called fire-and-forget (just like for step and halt: the Promise that an async listener would return isn’t awaited). But after dispatching them, the session itself blocks on its own internal Promise — and until that Promise resolves, the #drive loop doesn’t pull the next step out of the generator. The Promise is resolved by one of the session’s control methods: continue() / stepIn() / stepOver() / stepOut() / stop(). All of them, by design, are called from outside — a UI click, a message from the main thread (when the session lives in a worker), or a timer.</li><li>halt — fire-and-forget. Terminal session event.</li></ul><p>Session controls mirror DevTools conventions where that makes sense. pause() is an external pause request; it fires on the before-side of the next iter with cause: &#39;manual&#39;. stepIn() — pause on the next iter. stepOver() — pause on the next iter where depth &lt;= clickTimeDepth: frames the current iter pushes onto the stack are played through to return without stopping. stepOut() — pause when the halt-stack depth drops below the click-time depth (depth &lt; clickTimeDepth): the current wrapper has finished, control has passed to its override. stepOut() from depth 0 throws an exception: “step out of nothing” is a programming error in the consumer’s code, not a silent no-op. setRunInterval(ms) sets a per-iter delay (in ms) between iterations. stop() is terminal — the session resolves. The session is single-use: start() is called once; to re-run, construct a fresh session.</p><p>Breakpoint detection <em>also moved here</em>. In v6 the runStepByStep generator itself decided which iteration should “fire” by state.debug. In v7 the generator yields a minimal MachineState, and the session reads the current tape symbol via MACHINE_STATE_INTERNAL, checks it against the before/after filters in state.debug with matchFilter, and dispatches pause itself with cause: &#39;breakpoint&#39;. The engine’s generator has no “debug” logic left — it’s pure execution. The session, in turn, carries all three pause causes (breakpoint, step, manual) in one descriptor PauseInfo { side, cause } with the precedence order breakpoint &gt; step &gt; manual for when several causes coincide on one iter.</p><p>This is exactly the “coordination as a state machine” that didn’t fit into a hook: internal state (the pause-Promise that holds the engine, the currently active step-in/over/out mode, the halt-stack depth captured at click time), control methods, a lifecycle — all in one object with its own constructor and its own start() method.</p><h3>What stays in the worker</h3><p>After the coordination lift, the worker isn’t empty. What it’s now responsible for:</p><ul><li>The Web Worker boundary itself — the message protocol, the user-code sandbox, the lifecycle of build / run / step requests. The worker is the natural home for that layer.</li><li>A per-iter delay wrapped with idle/busy messages for the WORKER_TIMEOUT_MS watchdog. The session has its own simple throttle — setRunInterval(ms). But it doesn’t fit the worker: that wait runs inside the session’s #drive loop, and there’s no way to bracket it with idle/busy from the outside — and without the bracketing, the main-thread watchdog trips on a legitimate delay as if the worker were hung. So the worker implements the wait in its own listener for the iter event (which the session awaits asynchronously): inside the listener, an idle / busy pair brackets await setTimeout(intervalMs) exactly where it needs to be.</li><li>Holding and updating intervalMs. The “withPause is read at click time” semantics from <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a> didn’t go anywhere — the interval input in the UI is a consumer-level concern. The worker keeps the current value in its own local variable and updates it on every resume message from the main thread.</li><li>Translating UI clicks to session methods: Pause click → activeSession.pause(), Step click → activeSession.stepIn(), Continue click → activeSession.continue(). The worker no longer synthesizes paused from onIter — all pauses (breakpoint, step, manual) come back through the single pause event on the session, with a cause discriminant.</li></ul><p>The line is clean. What stayed is what the session can’t own without stepping onto the consumer’s territory. What left was never worker-specific to begin with — it was <em>coordination</em>, disguised as worker-specifics. A different consumer — an in-process debugger built into an IDE, a DAP server, an educational demo without a Worker — will compose DebugSession differently (no postMessage, no watchdog), but consume <em>the same session API</em>.</p><h3>The lift generalizes</h3><p>PostMachine.debugRun() returns a PostDebugSession, which wraps the engine’s DebugSession. Same four events, same step methods, same lifecycle. On top: wrapping MachineState in post-specific arrivalPath / candidatePaths, and filtering by the PostMachine breakpoint registry before forwarding pause events outward. The demo’s worker handles both sessions through a structural SessionLike type — both look the same from the outside.</p><p>This is <em>companion-of-companion</em>: the pattern generalizes one library level up. The engine library lifts coordination once into its own companion class; the next library on top of it lifts its own specifics into its own companion class wrapping the engine’s. Evidence that “companion class” isn’t a one-off trick under one library — it’s a reproducible shape.</p><h3>What follows from this</h3><p>In the lineage of articles about the engine’s API, three lessons appear in a row:</p><ul><li>From <a href="https://mellonis.ru/en/articles/three-majors-two-mistakes/">article (1)</a>: naming the lifecycle pins decisions about the shape of the API — name the states correctly, and the surface lands in the right shape on its own.</li><li>From <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>: observation and coordination are different jobs, and each one needs its own hook contract with its own dispatch semantics.</li><li>From this one: when N consumers reinvent the same coordination scaffolding on top of your hooks, your hook contract isn’t <em>incomplete</em> — it’s at the wrong <em>granularity</em>. A coordination state machine is a <em>neighbor</em> to hooks, not an extension of them.</li></ul><p>The diagnostic for a library author: if you find yourself widening a hook’s signature so the consumer can do work the consumer already has to do (v6.2.0’s major from <a href="https://mellonis.ru/en/articles/pauza-dvojstvennaya-po-prirode/">article (2)</a>) — or if the same handler shape repeats from consumer to consumer without meaningful differences (the case that triggered this refactor) — then the hook is being asked to do something a hook fundamentally can’t.</p><p>For this engine, that landed as a clean boundary: a public sync runStepByStep, its coordination companion DebugSession, and any consumer — the demo’s worker, a DAP server, an in-process debug panel — writes an adapter between its own entry point and the session API, not a reinvented coordination layer.</p><p><em>Code: </em><a href="https://github.com/mellonis/turing-machine-js">turing-machine-js</a><em> (engine, v7 — </em>DebugSession<em>), </em><a href="https://github.com/mellonis/post-machine-js">post-machine-js</a><em> (</em>PostDebugSession<em>), and </em><a href="https://demo.machines.mellonis.ru/">machines-demo</a><em> (the demo worker, rewritten around the session in </em><a href="https://github.com/mellonis/machines-demo/pull/80"><em>PR #80</em></a><em>).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b525d533b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A pause with two sides: the hook contract and the worker protocol]]></title>
            <link>https://medium.com/@mellonis/a-pause-with-two-sides-the-hook-contract-and-the-worker-protocol-81fa4c6a66fb?source=rss-c572d2916ed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/81fa4c6a66fb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[async-programming]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[Ruslan Gilmullin]]></dc:creator>
            <pubDate>Thu, 21 May 2026 22:36:41 GMT</pubDate>
            <atom:updated>2026-05-21T22:36:41.929Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you’re writing a Turing-machine interpreter that runs in a Web Worker. The UI needs to show a trace — how the machine steps from state to state, what gets written to the tape, how the head moves. For the user to keep up with what’s on screen, the engine needs a short delay between iterations — milliseconds, regularly, on every step. That’s a throttle of the engine between iterations — regular and predictable, not the “Pause” of the UI button (which stops the machine until the user clicks “Continue”).</p><p>So where exactly in the iteration cycle does the worker apply that throttle? There are two candidates, and the choice between them pins two contracts at once: the engine’s hooks and the protocol between worker and main thread. Pick the right point, and you design both sides at once; pick the wrong one, and you break both. This article is about that choice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MtltS2BnTlTdXnj5XFccJw.png" /></figure><h3>Setup</h3><p><a href="https://github.com/mellonis/turing-machine-js">turing-machine-js</a> is a Turing-machine interpreter. The engine has an onStep hook — the handler runs after each machine step. That’s all the engine background you need for this article. For the rest of the engine’s design and previous API changes, see “Three majors, two mistakes: designing a pause API for a Turing-machine interpreter” (1) and “Two majors, one README, one demo: two cheap design reviews” (2).</p><p>The first real consumer of the engine is <a href="https://demo.machines.mellonis.ru/">machines-demo</a>, an interactive debugger. The user’s machine runs in a Web Worker; the UI on the main thread shows the trace. The same demo that, in article (2), surfaced two engine majors (#109, #108). This article is the next episode in the life of the same engine: v6.2 → v6.3 → v6.4.</p><p>The demo has a RUNNING_AUTO mode: the user picks an interval, clicks “Start”, and the machine steps automatically. Originally the mode was straightforward — the main thread drove step-by-step execution (via runner.step(), a wrapper over the engine’s runStepByStep() in the worker), with setTimeout(intervalMs) inserted between steps for the trace. Simple, and it worked — until the user set a breakpoint.</p><p>Breakpoints in the engine fire inside machine.run(): the iteration loop lives in the engine itself, and on hitting a debug-marked state, it pauses itself. runStepByStep(), on the other hand, is a generator: the consumer drives the loop, and breakpoints are invisible to it. <a href="https://github.com/mellonis/machines-demo/issues/43">machines-demo#43</a> was this hole — the user sets a breakpoint in RUNNING_AUTO mode, clicks “Start”, and the breakpoint is ignored. For breakpoints to fire, RUNNING_AUTO had to switch from runStepByStep() to run().</p><p>But run() keeps its iteration loop inside the engine and doesn’t yield control back. Previously the throttle lived between runner.step() calls on the main thread — that is, on the consumer side, where the consumer controlled the interval between steps. With the switch to run(), that consumer-side gap is gone — the throttle has to either be moved inside the engine (into an existing or new hook) or be dropped. That became the design question.</p><p>One more architectural detail we need: the main thread holds a watchdog timer over the worker. If the worker stays silent on messages longer than WORKER_TIMEOUT_MS, the main thread considers it hung (e.g., the user’s machine never reaches halt) and kills it. Whatever place we put the throttle in has to live with that timer.</p><h3>Where the throttle can live</h3><p>Two candidates:</p><ol><li><strong>Inside </strong>onStep — the synchronous hook the engine calls after each step. Its current signature is (state) =&gt; void. You could widen it to (state) =&gt; void | Promise&lt;void&gt;, and then the handler can await the delay right there.</li><li><strong>At the iteration boundary</strong> — add a new hook, designed for async waits. Naming aside, what matters is that it fires once at the end of each engine iteration, and the engine awaits the returned Promise.</li></ol><p>Both candidates answer “where does the throttle live”. But at the same time they dictate what the worker-main protocol looks like.</p><p>If the throttle sits in onStep, it ends up in the middle of each engine iteration — at the point where onStep is called. Everything else in the protocol has to be pinned to that same point: the watchdog timer and the user’s click on “Pause” both hang off this mid-iter delay.</p><p>If the throttle sits at the iteration boundary, the worker has a moment at the end of every iteration — the engine isn’t running, it’s awaiting a Promise. In that moment, it’s easy to make peace with the watchdog timer and to be ready for a click on “Pause”.</p><p>Now both contracts, one at a time.</p><h3>Contract “Inside onStep”</h3><p>v6.2.0 took the first path — it widened onStep’s signature from (state) =&gt; void to (state) =&gt; void | Promise&lt;void&gt;. The handler could now await the delay right where it used to only look at state. From the worker’s side it looked clean — one hook, one wait point, no new entities.</p><p>Within a few hours, I marked v6.2.0 as deprecated on npm. Not “a newer version is out, upgrade at your convenience”, but an explicit warning: this version is <em>wrong</em>.</p><p>v6.3.0 reverted the signature widening. The reason was straightforward: onStep was meant as an observation hook, not a coordination one. It runs synchronously, in the middle of each iteration, so the consumer can look at state and record it somewhere. Adding await to its signature glues two different jobs into one: observe and hold the engine. A reader of the signature can no longer tell: is this hook “look at this state” or “hold the engine here”? The hook’s purpose stops being visible from the signature.</p><p>The symptom that something was wrong showed up in the docs. The README had to explain how to use the widened onStep. An honest paragraph opened with a hedge: “onStep is an observation hook, but you can return a Promise from it, and the engine will await it before the next iteration.” Neither the “but” nor the second half could be cut. The docs were doing exactly what’s described in article (2): prose was pushing on shape — and the shape cracked.</p><p>v6.4.0 added a separate hook — onIter. Signature: (state) =&gt; void | Promise&lt;void&gt;. Contract: fires once at the end of every iteration, asynchronously, unconditionally. The name — iteration boundary — describes <em>what</em> the hook does (gives a point at the end of an iteration where you can wait), not <em>why</em> a consumer would use it. And it can be used in different ways: for throttling between trace steps, for syncing with the UI, for aborting a run (e.g., via AbortSignal).</p><p>The engine’s hook contract now distinguishes three jobs:</p><p>— onStep — synchronous, mid-iteration. Observation of state. — onPause — asynchronous, <em>conditional</em> (fires only on breakpoints). The boundary between running and stopped. — onIter — asynchronous, <em>unconditional</em> (fires on every iteration). Coordination: holding the engine for the consumer’s async work.</p><p>Three hooks, three jobs. Observation shouldn’t hold the engine; for that, there’s a separate asynchronous hook. Holding shouldn’t hide inside an observation hook; for that, there’s onIter. A pause from a breakpoint is its own scenario altogether; for that, there’s onPause, whose firing event is spelled out in its name.</p><h3>Contract “At the iteration boundary”</h3><p>Where the throttle lives is now clear: inside the onIter handler. But the onIter handler runs <em>inside</em> the worker, while the user’s pause comes from <em>outside</em> — from the main thread, on a click. They need a protocol.</p><p>This protocol has four mechanisms: a pair of idle/busy messages, a stepRequested flag, a synthetic paused event, and an intervalMs field in resume. Each one closes a specific problem that the throttle’s location creates.</p><h3>The idle and busy messages: pausing the watchdog</h3><p>The watchdog timer mentioned earlier starts to get in the way once we’re in onIter.</p><p>A throttle in onIter, on every iteration, can easily exceed the timeout — especially if the user dials intervalMs to “slow” (the demo lets you set the interval to, say, two seconds). The result is a false alarm: the worker isn’t hung, it’s just waiting.</p><p>The solution: the worker itself tells the main thread when it’s “working” and when it’s “waiting”. Before await-ing the throttle in onIter, the worker sends an idle message. After the throttle resolves, it sends a busy. The main thread suspends the watchdog for the gap between idle and busy. The watchdog still catches real hangs (e.g., an unreachable halt state) but no longer confuses them with legitimate trace slowdown.</p><p>Without this wrapping, the watchdog has two bad options. Either pick a generous threshold — then real hangs go undetected (or detected too late). Or pick a tight threshold — and you raise the probability of a false alarm (the worker gets killed on a legitimate delay). The idle/busy messages resolve both at once.</p><h3>Step is a flag inside the worker, not engine state</h3><p>When the user clicks “Step”, the main thread sends the worker a resume message with a step: true flag — “advance the machine one iteration and pause again”. The implementation: the worker sets stepRequested = true. On the next onIter, the handler sees the flag, resets it to false, synthesizes a paused event, and waits again. The machine has run exactly one iteration.</p><p>The key point: “step” is a flag <em>inside the worker</em>, not part of the engine’s state. The engine doesn’t know what “step” means — it simply finds itself in a waiting state again on the next iteration. The coordination lives outside the engine. onIter remains a thin await hook — it doesn’t mutate the engine, it only pauses the engine’s execution. That’s what made onIter viable as a contract: there’s no “step-specific logic” in it, only a Promise the worker controls itself. If “step” had been part of the engine’s state, the onIter contract would have to extend to “and also flip this flag”, and the hook would stop being thin.</p><h3>No throttle needed when Step is clicked</h3><p>When the user clicks “Step”, a throttle is redundant — the user plays the role of the timer, clicking as many times and as fast as they need. The implementation reflects this: on Step, intervalMs is ignored, and the onIter handler doesn’t insert a wait. This is the cleanest expression of “observation ≠ coordination” inside the worker: when the user is in control, the engine follows.</p><h3>Synthetic pause on click</h3><p>The scenario: the machine is in RUNNING_AUTO — the engine is running with onIter awaiting intervalMs between iterations. The user clicks the “Pause” button in the UI. The click arrives on the main thread. The main thread sends the worker a pause message. At that moment, the worker is holding the engine in a throttle — the Promise hasn’t resolved yet. What do we do?</p><p>The solution is to synthesize the same kind of pause as one from a breakpoint. The UI already has a handler in place: on paused from the worker, it switches to “stopped”. If the “Pause” click went down a different path, a second branch with the same behavior would appear. That’s why the worker synthesizes paused — to the UI, a “Pause” click is indistinguishable from a breakpoint firing.</p><p>The worker cancels the throttle (resolves it forcibly, ahead of schedule), sets stepRequested = false, and, from inside onIter after returning from the wait, dispatches a paused event — <em>synthetic</em>, not one that arose from the engine’s normal flow. Under the hood, the two scenarios differ (one cancels the throttle, the other lets it finish naturally), but the contract from outside is one — a single “pause” scenario.</p><h3>intervalMs is a parameter of resume, not run()</h3><p>The throttle in onIter is sized by intervalMs. Where does the worker get that value from? Not from the parameters passed to run() at start. From the latest resume message: each one arrives carrying a current intervalMs from the main thread.</p><p>The reason is that the user must be able to change the delay between throttles during the run. The value in the UI is read <em>at click time</em>, not at run() start; the next resume carries the new value, and starting with the next iteration, the throttle adjusts. A small cost for the protocol, a big win for the UX.</p><h3>Duality, explicit</h3><p>The throttle lives in one point of an iteration. From the engine’s perspective, that point is the onIter handler: a hook called once at the end of each iteration, asynchronously. From the protocol’s perspective, the same point is the gap between idle and busy messages — a gap where the watchdog is suspended, a “Pause” click can softly cancel the throttle, and intervalMs is read from the latest resume.</p><p>One point, two APIs. Every downstream design choice depends on this one. Put it in the middle of an observation hook, and you break both sides at once: the docs on a widened onStep can’t be written without a “but”, the idle/busy wrapping has nothing to attach to (the same hook stands for both observation and waiting), and the synthetic paused event has to be dispatched from an unnatural place. Without a clean iteration boundary, both the hook and the protocol suffer.</p><h3>Conclusion</h3><p>Separating observation from coordination is the reason the engine’s hook contract distinguishes three jobs instead of merging them into one. Gluing them together is the temptation v6.2.0 succumbed to. And the only thing that let me realize the approach was wrong within a few hours was that the engine’s README couldn’t be written honestly, and the demo’s smoke test wouldn’t pass. Two almost-free design reviews (article (2)).</p><p><em>Code: </em><a href="https://github.com/mellonis/turing-machine-js">turing-machine-js</a><em> (engine, v6.2 → v6.4) and </em><a href="https://demo.machines.mellonis.ru/">machines-demo</a><em> (the demo).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81fa4c6a66fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two majors, one README, one demo: two cheap design reviews]]></title>
            <link>https://medium.com/@mellonis/two-majors-one-readme-one-demo-two-cheap-design-reviews-a302fb8aea88?source=rss-c572d2916ed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a302fb8aea88</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[Ruslan Gilmullin]]></dc:creator>
            <pubDate>Mon, 18 May 2026 20:59:31 GMT</pubDate>
            <atom:updated>2026-05-19T08:54:21.709Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Writing the docs is what surfaced both mistakes. There’s a meta-lesson in there about how docs are the cheapest design review you can run, but that’s another post.</em></blockquote><p>This is “that other post” — and the first thing it has to do is correct the teaser. The teaser oversells. Docs caught one of the two mistakes. The other was caught by the first real consumer of the API, which I was building in parallel. The two reviews worked in tandem: docs review the shape of an API, the consumer reviews the use of it. Together they catch what tests can’t see.</p><p>If you ship anything behind an interface — a library, a CLI, any entity behind a contract — these are the two reviews you don’t want to skip.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNhOiSYhX8fptMwkOv5JPw.png" /><figcaption>Screenshot of demo.machines.mellonis.ru running a Brainfuck UTM: multi-tape view on the left, engine source on the right</figcaption></figure><h3>Recap</h3><p>“<a href="https://mellonis.ru/en/articles/three-majors-two-mistakes/">Three majors, two mistakes</a>” covers the engine and the v4 pause API — onStep, onDebugBreak, per-state debug flags — in detail. I’ll lean on it here without rehashing it. The v4 → v6 trajectory shipped three breaking majors: a hook rename, a halt-semantics hardening, and a dispatch-tick collapse. The first two surfaced in the demo. The third surfaced in the docs.</p><h3>The demo case: v4 → v5</h3><p>While shipping v4 I started building <a href="https://demo.machines.mellonis.ru/">machines-demo</a> — an interactive Turing-machine debugger and the engine&#39;s first non-test client.</p><p>The demo is a natural first consumer: it has a dual purpose. The product goal — public distribution and showing the engine in action. The technical goal — road-testing changes and validating concepts against a live API surface. Both goals make building the demo an integral part of the release cycle, not an optional add-on.</p><p>The demo used both hooks at once: onStep populated a per-iteration command buffer for the trace UI; onDebugBreak drove the pause/resume cycle.</p><p>The demo built. The tests passed. But it was uncomfortable to write, for two reasons.</p><p>First, onDebugBreak’s after-fire came with data from the previous yield — the same data the previous onStep had already shown. The demo processed the same thing twice, and the question “why two hooks for one event?” was being asked not by me but by the code itself, in a way. I filed <a href="https://github.com/mellonis/turing-machine-js/issues/109">turing-machine-js#109</a> as an RFC about the relationship between these hooks, listing four sketches; the resolution narrowed to <em>naming</em>. onDebugBreak framed the purpose of use as “debugging”, while the consumer’s verb was “pause”. Shameless rename, no alias. v5.</p><p>Second, the demo’s UI gained a “pause before halt” scenario — letting the user glimpse the machine’s final state before it shuts down. The natural implementation: a debug flag on haltState itself. The first test case set haltState.debug = { before: true, after: true } because the symmetry looked right. Only before fired. Worse: the after-fire on the iteration that <em>led to</em> halt never reached the consumer — the loop exited as soon as state.isHalt became true. <a href="https://github.com/mellonis/turing-machine-js/issues/108">turing-machine-js#108</a> split it in two: restore the lost after-fire (bug); throw on assignment to haltState.debug.after (API).</p><p>Both complaints came from the consumer side. The demo didn’t surface a code bug — it surfaced an <em>API interaction format</em>. The names didn’t fit the use. Being permissive in input didn’t match what the user was trying to do. The tests verified behavior against the engine’s own internal model — ok, green. The demo verified behavior against the consumer’s mental model — and produced two specific complaints (not ok).</p><h3>The docs case: v5 → v6</h3><p>v5 shipped. The README needed updating. The new dispatch-order section had to explain — in words — when each of onPause(before), onStep, and onPause(after) fired relative to the iteration they described.</p><p>The first honest paragraph went something like:</p><blockquote><em>onPause(after, K) fires on iteration K+1’s yield, with the payload substituted from iteration K’s snapshot, before </em><em>onPause(before, K+1) or </em><em>onStep(K+1) fire.</em></blockquote><p>I stared at that sentence for a while. There was no shorter version. The reader wasn’t supposed to need a sentence about substitution.</p><p>The code worked. The tests passed. The demo consumed the hooks correctly. The mistake wasn’t in any of those — it was in the <em>shape</em> of the dispatch, and that shape was only visible when you had to put it into words.</p><p>The fix collapsed the lifecycle: before(K) → step(K) → after(K) on the same yield. No substitution. No cross-iteration scheduling. No final drain for the halting iteration (in “Three majors, two mistakes” I called it “post-loop drain”; I’d probably shorten it to “final drain” now). The README paragraph now reads:</p><blockquote><em>On iteration K’s yield, hooks fire in lifecycle order.</em></blockquote><p>And that’s the kind of sentence the reader glides past without effort. <a href="https://github.com/mellonis/turing-machine-js/issues/119">turing-machine-js#119</a> shipped as v6.</p><p>A direct quote from the previous article:</p><blockquote><em>The code worked, the tests passed, and the docs were correct. The shape was just wrong.</em></blockquote><p>What I’d add: the docs were correct only on the condition that the reader accepted three explanatory sentences they shouldn’t have had to read. That’s not “correct docs” — that’s docs apologizing for the shape.</p><p>The docs review caught the <em>shape</em>, not the <em>use</em>. The demo worked. The tests passed. This time, only <em>prose pressure</em> uncovered the issues hiding in the implementation.</p><h3>Three reviews, three layers</h3><p>Here’s what each one checks:</p><ul><li><strong>Tests</strong> verify code against itself. Internal consistency. The engine yields what the engine should yield. Green tests are the baseline.</li><li><strong>The first real consumer</strong> verifies code against a consumer’s mental model. <em>Does the API format match what the user is trying to do?</em> Reviewing real interaction with the API forced API changes: a rename and a halt-after restriction.</li><li><strong>The docs as <em>prose</em></strong> (not JSDoc — a connected README narrative) verify code against the author’s own explanation. <em>Does the design have an honest one-paragraph description?</em> Without one, we had to look hard at the substitution dance — and abandon it.</li></ul><p>Each review catches what the layer below misses. Tests don’t catch shape; the consumer doesn’t catch interaction problems it can skillfully bypass; the docs don’t catch UX wrinkles they don’t have to mention.</p><p>The cost is asymmetric. Building a real consumer is the most expensive of the three reviews; writing the docs is the cheapest. Still, even the most expensive costs less than reworking the API after the problems surface for users — hence “cheap” in the title. The real consumer has to be built <em>before</em> the major cut — it’s the only review that makes the API comfortable to use. Docs then paper over what’s left.</p><h3>Heuristics for the next major</h3><ol><li><strong>Build the first real consumer before cutting the major.</strong> Not a test fixture — a consumer with its own mental model. The difficulties it encounters are the same difficulties your users will encounter later.</li><li><strong>Write the dispatch-order paragraph before locking the dispatch order.</strong> If you can’t describe in one sentence what fires when, the dispatch is wrong. Decisions of this kind belong at the design stage, not documentation — when not a single line of code has been written yet.</li><li><strong>Read the docs back as a stranger.</strong> If a paragraph reads as an apology for the shape, the docs are working — they’ve <em>revealed</em> a shape mistake. Fix the shape, not the paragraph.</li></ol><p>Three majors. One README. One demo. The tests had nothing to say.</p><p><em>Code: </em><a href="https://github.com/mellonis/turing-machine-js">turing-machine-js</a><em> (engine) and </em><a href="https://demo.machines.mellonis.ru/">machines-demo</a><em> (the first non-test consumer where v4 → v5 surfaced).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a302fb8aea88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Three majors, two mistakes: designing a pause API for a Turing-machine interpreter]]></title>
            <link>https://medium.com/@mellonis/three-majors-two-mistakes-designing-a-pause-api-for-a-turing-machine-interpreter-7ad5fba776ba?source=rss-c572d2916ed8------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ad5fba776ba</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api-design]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[turing-machine]]></category>
            <dc:creator><![CDATA[Ruslan Gilmullin]]></dc:creator>
            <pubDate>Mon, 11 May 2026 04:40:59 GMT</pubDate>
            <atom:updated>2026-05-19T09:50:36.532Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WESbLeNJ4WQ9ZO0VsMQIlQ.png" /><figcaption>Screenshot of demo.machines.mellonis.ru running a Turing machine</figcaption></figure><p>I spent the last two weeks shipping four breaking major versions of <a href="https://github.com/mellonis/turing-machine-js">@turing-machine-js/machine</a> — v3, v4, v5, v6 — and the most interesting part wasn’t any single feature. It was watching the same API surface (a pause/breakpoint hook on the run loop) get redesigned twice in three versions, each time because the previous shape exposed something it shouldn’t have.</p><p>This post is the post-mortem. If you’re designing pause/step/breakpoint APIs for a generator-loop interpreter, scheduler, or DSL runtime, the mistakes I made are easy to make and worth seeing in someone else’s code first.</p><h4>The setup</h4><p>The engine runs a Turing machine. Internally it’s a generator: each yield corresponds to one step (one transition firing on one tape symbol). The driver loop looks roughly like this:</p><pre>async function run({ initialState, onStep }) {<br>  for (const m of runStepByStep({ initialState })) {<br>    await onStep?.(m);<br>    if (m.state.isHalt) return;<br>  }<br>}</pre><p>MachineState (m) is a snapshot per iteration: the state about to execute, the current and next symbols, the moves the heads will make. A consumer (a logger, a UI, a test) can hang off onStep to observe.</p><p>What I wanted to add in v4 was a way to <em>pause</em> execution at chosen points — like a breakpoint in a debugger. Any State should be able to carry a debug config:</p><pre>myState.debug = { before: [symA], after: [symA] };</pre><p>…and the run loop should give the consumer a chance to inspect the machine and decide when to resume.</p><h4>v4: ship it</h4><p>The v4 shape was straightforward. I made run() async, added an onDebugBreak hook, and routed it like this:</p><pre>await machine.run({<br>  initialState,<br>  onStep: (m) =&gt; { /* every step */ },<br>  onDebugBreak: async (m) =&gt; {<br>    if (m.debugBreak?.before) console.log(&#39;before:&#39;, m.state.name);<br>    if (m.debugBreak?.after) console.log(&#39;after:&#39;, m.state.name);<br>    // hold here until promise resolves<br>  },<br>});</pre><p>The per-state debug field is mutable. state.debug= { before: true } sets a pre-step break; before: [synA] filters by what the head is reading. The hook is awaited, so any consumer can implement “freeze until the human clicks Resume” by simply not resolving the promise.</p><p>I also wanted breakpoints on halt:</p><pre>haltState.debug = { before: true }; // pause before exit</pre><p>That worked. Symbol-list filters on haltState were silent no-ops, because haltStatehas no head symbol to filter by. Fine, I thought — be permissive in input, the wildcard true is the one that matters.</p><p>Two things in this design were wrong. I didn’t notice either until I started writing docs and a UI on top.</p><h4>Mistake 1: the hook describes the engine, not the consumer</h4><p>onDebugBreakreads, on paper, like a perfectly reasonable name. The engine fires a “debug break”; you hook into it.</p><p>But what does the consumer <em>do</em> in that hook? They pause. They inspect. They wait for input. They resume. The hook isn’t really notifying you that a thing happened — it’s offering you a cooperation point.</p><p>The name onDebugBreakcarries one specific framing: “debugging”. But the same hook is exactly what you want for a step-through visualization, a slow-motion playback control, an animation tween, a “press space to advance” UI. None of those are debugging. They’re all <em>pausing</em>.</p><p>This sounds like a small thing. It’s not, because once consumers see the name they design around it: their code path is called handleDebugBreak, their state machine has a debugging boolean, their UI button says “Stop debugging”. The name leaks into every consumer’s vocabulary.</p><p>I wrote an RFC (<a href="https://github.com/mellonis/turing-machine-js/issues/109">turing-machine-js#109</a>) and renamed it in v5. Hard rename, no deprecation alias:</p><pre>await machine.run({<br>  initialState,<br>- onDebugBreak: (m) =&gt; { … },<br>+ onPause: (m) =&gt; { … },<br>});</pre><p>The payload field m.debugBreak stayed — it’s metadata describing <em>why</em> this yield fired ({ before: true } or { after: true }), and “break” works fine inside the payload. But the hook name is the consumer’s contract: onPause describes what <em>they</em> do, not what the engine does.</p><p><strong>Rule for next time:</strong> when naming a hook, name the consumer’s verb, not the engine’s event. Hooks are cooperation points, not event listeners.</p><h4>Restriction: haltState.debug.after is nonsense</h4><p>The second v4 mistake hid under an instinct to be permissive in input. haltState.debug.after accepted writes silently. It just didn’t fire.</p><p>Why? Because the after semantics in this engine mean “fire on the iteration <em>after</em> the one where the filter matched”. That makes perfect sense for normal states — you transition out of state K, the next iter (K+1) runs, <em>and at that yield</em> the consumer is told “by the way, K’s after-filter fired last step”. But halt is terminal. There is no K+1 after halt. The after event has nothing to anchor on.</p><p>I’d silently swallowed haltState.debug.after = true in v4. Worse, I’d let { before: true, after: true } through — half the assignment was meaningful, half was a no-op, and nothing told the consumer.</p><p>In v5 I made both throw at write time (<a href="https://github.com/mellonis/turing-machine-js/issues/108">turing-machine-js#108</a>, part 2):</p><pre>- haltState.debug = { before: true, after: true }; // v5: throws - &#39;after&#39; on halt has nothing to anchor on<br>+ haltState.debug = { before: true };</pre><p><strong>Rule for next time:</strong> if a configuration has no semantics, throw early. Silently no-op input <em>looks</em> user-friendly until a consumer spends an afternoon wondering why their UI doesn’t fire on halt. “Be permissive” is a false economy when permissiveness silences a real mistake.</p><p>While I was in there, I also fixed a related bug: the halting iter’s <em>own</em> after filter wasn’t firing either (<a href="https://github.com/mellonis/turing-machine-js/issues/108">turing-machine-js#108</a>, part 1). The driver loop exited as soon as state.isHalt became true — and the after-event from the previous iter, which would normally fire on this final yield, got dropped on the floor. v5 added a post-loop drain to fire it.</p><p>I’ll come back to this.</p><p>And one v5 bonus: a master switch on run() for the whole pause system.</p><pre>await machine.run({ initialState, debug: false, onPause: … });</pre><p>When false, all pause-fires are suppressed regardless of what state.debug says across the graph (<a href="https://github.com/mellonis/turing-machine-js/issues/106">turing-machine-js#106</a>). You can A/B “debug mode” without rewriting the graph or clearing every state.debug field. The flag dispatches onPause; the underlying m.debugBreak payload field still populates on the generator’s yields (it’s a property of the iteration, not of how run() chose to surface it).</p><h4>Mistake 2: the substitution dance</h4><p>This is the one I’m proudest to have caught, because the code worked, the tests passed, and the docs were correct. The shape was just wrong.</p><p>In v4 and v5, after K (the after-fire for iteration K) actually fired on iteration <strong>K+1</strong>’s yield. The driver loop carried a pendingAfterFromPref flag across yields, and on the next iter’s yield it dispatched the after hook <em>first</em>, then the before hook, then onStep. The hook for K’s after-fire had to see K’s state — not K+1’s. So I <em>substituted</em> the previous yield’s snapshot into the m.state field of K+1’s yield, just for the duration of the after dispatch.</p><p>This worked. But it had three knock-on effects:</p><ol><li><strong>The substitution leaked.</strong> Consumers wanted access to the un-substituted, “real” iteration state (the one the step hook saw) — see <a href="https://github.com/mellonis/turing-machine-js/issues/107">turing-machine-js#107</a>. Some users were reading raw MachineSatate.debugBreak from runStepByStep directly and were surprised that m.state referred to the iter on which the after-fired-from, not the iter that produced it.</li><li><strong>The halt case needed a special path.</strong> As mentioned: the halting iter’s own after fires <em>after</em> the loop exits. v5 added a post-loop drain to handle it. That drain is its own code path, with its own substitution, separate from the in-loop dispatch.</li><li><strong>The generator’s return type widened.</strong> Because the post-loop drain needed to <em>return</em> a final yielded value out of the iterator, runStepByStep’s return type became Generator&lt;MachineState, MachineState | null&gt; — a yield type <em>and</em> a return type. The canonical for…of consumer doesn’t see the return value, but anyone reading the type signature now had to understand why there were two slots.</li></ol><p>All of this came from one design choice: dispatching after K on iter K+1’s yield instead of on iter K’s own yield.</p><p>In v6 I collapsed it (<a href="https://github.com/mellonis/turing-machine-js/issues/119">turing-machine-js#119</a>). The per-iter lifecycle is now plainly before → step → after. The after fire rides on the same yield as the iter that produced it. No substitution. No pendingAfterFromPref. No post-loop drain. The generator return type narrows back to Generator&lt;MachineState&gt;.</p><pre>// v6<br>await machine.run({<br>  initialState,<br>  onStep: (m) =&gt; { /* unchanged */ },<br>  onPause: (m) =&gt; {<br>    if (m.debugBreak?.before) console.log(&#39;before:&#39;, m.state.name);<br>    if (m.debugBreak?.after) console.log(&#39;after:&#39;, m.state.name);<br> },<br>});</pre><p>The dispatch order <em>across</em> hooks changed (any test asserting pause(after K-1) → pause(before, K) → step(K) had to flip to pause(before K) → step(K) → pause(after K)), but the set of dispatched calls and per-iter semantics are unchanged. Consumers treating the hooks as independent observers see no change at all (<a href="https://github.com/mellonis/turing-machine-js/issues/107">turing-machine-js#107</a>) — “expose un-substituted state” — disappeared as a problem: there’s no substitution to expose around.</p><p><strong>Rule for next time:</strong> if your hook payload requires substituting state from a different iteration than the one that’s yielding, the dispatch sequence is wrong. Lifecycle phases (before, step, after) belong on the iter they describe. The substitution wasn’t a clever trick — it was a leak telling me the events were on the wrong tick.</p><h4>What I’d carry to the next pause/breakpoint API</h4><ol><li><strong>Name hooks for the consumer’s verb, not the engine’s event.</strong> onPause, not onDebugBreak. onProgress, not onChunkRecieved. The name leaks into every consumer’s mental model — pick the framing you want them to inherit.</li><li><strong>Throw on impossible configurations early.</strong> “Permissive in input” is fine for shapes that <em>might</em> be meaningful; it’s a trap for shapes that <em>can’t</em> be. haltState.debug.after = true had no possible semantics. Silently swallowing it cost an afternoon to one user before I noticed.</li><li><strong>Per-iter phases belong on the iter they describe.</strong> If you’re tempted to dispatch after K on K+1’s yield, ask what payload you have to substitute to make it look right. The substitution is the signal.</li><li><strong>A master switch is cheap and worth it.</strong> A boolean on the entry point to flip the whole feature off (without rewriting graph-level flags) makes the feature safe to ship to production and toggle in tests. run({ debug: false }) was one of the smaller v5 adds and one of the most-used by downstream consumers.</li><li><strong>Breaking changes are worth the major bump.</strong> Three majors in two weeks sounds expensive. It isn’t, if the lockstep downstream is one repo (in my case <a href="https://github.com/mellonis/post-machine-js">@post-machine-js/machine</a>, which bumped its peer dep v4.0.0 → v6.0.0 and renamed its own internal __onDebugBreak → __onPause in step). API ergonomics compound across every consumer for the life of the library — pay the migration cost while the API is young.</li></ol><p>The v6 shape is the one I should have shipped in v4. I didn’t have the vocabulary then — I was thinking “expose the engine’s events” instead of “design the consumer’s contract”. Writing the docs is what surfaced both mistakes. There’s a meta-lesson in there about how docs are the cheapest design review you can run, but that’s another post.</p><p><em>Code: </em><a href="https://github.com/mellonis/turing-machine-js"><em>turing-machine-js</em></a><em> (engine) and </em><a href="https://github.com/mellonis/post-machine-js"><em>post-machine-js</em></a><em>(a Post machine built on top, kept in lockstep). The interactive demo at </em><a href="https://demo.machines.mellonis.ru/">demo.machines.mellonis.ru</a> <em>consumes the v6</em> onPause <em>hook for its Step / Run / Stop controls</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ad5fba776ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>