<?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 Amitavaa Ag on Medium]]></title>
        <description><![CDATA[Stories by Amitavaa Ag on Medium]]></description>
        <link>https://medium.com/@amitavaa.ag?source=rss-91bd28167c3e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*dTv1ltfodbB9sSb_.jpg</url>
            <title>Stories by Amitavaa Ag on Medium</title>
            <link>https://medium.com/@amitavaa.ag?source=rss-91bd28167c3e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 18:21:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitavaa.ag/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[Proximity based word correction on keyboard]]></title>
            <link>https://medium.com/@amitavaa.ag/improvements-in-prediction-beyond-n-grams-6a152e0239bb?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a152e0239bb</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[keyboard]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Fri, 28 Aug 2026 01:38:42 GMT</pubDate>
            <atom:updated>2026-08-29T09:17:01.615Z</atom:updated>
            <content:encoded><![CDATA[<p>This is from the second phase of <a href="https://medium.com/@amitavaa.ag/building-next-word-prediction-for-a-keyboard-app-pipeline-smoothing-algorithms-and-vocabulary-64fb4155a62c">CodeKeyBoard Series</a></p><p>While typing, I realized, word correction, is not just about LV or Symspell or BK-Trees. I mean there are optimizations and choices of data-structures but there is something else.</p><p>In a T9 key prediction, a set of numbers map to a possible words, similarly, in a bigger keyboard, to accommodate for fat-fingers, we need to consider the proximity of each character — the keyboard is not ABCDE its QWERTY</p><p>QWERTY adjacency map (physical key neighbors) would somewhat look like this:</p><pre>q: a s w        r: d e f g t      u: h i j k y<br>w: a d e q s    t: f g h r y      i: j k l o u<br>e: d f r s w    y: g h j t u      o: i k l p<br>a: q s w x z    h: b g j m n t u y<br><br>s: a c d e q w x z<br>j: h i k m n u y<br>d: c e f r s v w x<br>k: i j l m o u<br>f: b c d e g r t v<br>l: i k o p<br>g: b f h n r t v y<br>z: a s x<br>b: c f g h n v<br>x: a c d s z    n: b g h j m<br>c: d f s v x    m: h j k n<br>v: b c d f g</pre><p>For any key typed, we only have a handful of characters to reach, which reduces the search space.</p><p>So instead of jumping straight to pre-generating the deletes for Symspell, this is an easier addition that can be made which feels more useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*KAt0DIJSiKJn29tVjWr3ew.png" /><figcaption><strong>Here we can see, “search” come up, because the pattern of strokes match</strong></figcaption></figure><p><strong>Related Works:</strong></p><ul><li>FUTO Swipe models</li><li>NLnet: Gesture Typing for AOSP-derived Keyboards</li><li>Kristensson &amp; Zhai, IUI 2005 — “Relaxing stylus typing precision by geometric pattern matching”</li></ul><p>the neural models don’t work in our case, probably because ours is not exactly horizontal qwetry and I am not bothered to add a neural model for the sake of it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a152e0239bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Smarter Research Assistant — Three Ideas to steal]]></title>
            <link>https://medium.com/@amitavaa.ag/building-smarter-research-assistant-three-ideas-to-steal-96c043b62e7a?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c043b62e7a</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[research]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 21:04:29 GMT</pubDate>
            <atom:updated>2026-08-25T21:04:29.379Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ve been developing a research assistant specifically for material science — a tool capable of addressing inquiries like “what are the failure mechanisms of high-strength steel under hydrogen exposure?” and providing a true synthesis rather than a mere aggregation of retrieved content.</p><p>The conventional Retrieval-Augmented Generation (RAG) approach brings us partway to this goal. However, we encountered three recurring issues: gaps in terminology leading to missed retrievals, visualizations that misrepresent the actual data, and rigid pipelines that enforce a predetermined sequence of steps irrespective of the query’s requirements.</p><p>We explored unexpected areas for partial solutions — one from retrieval methods, another from generative user interfaces, and a third from planning theories in game AI. Below are the concepts we adopted and their rationale.</p><p>The whole system uses a combination of <strong>Progressive Indexing, ReACT, Reflection, Query Expansion, Planning Redirection.</strong></p><p>The idea was to initially avoid having a separate stage to categorise queries into Think vs No-Think mode and make it inherent to the system</p><h3>1. Reversing HyDE: Augmenting Questions in Sections</h3><p>HyDE (Hypothetical Document Embeddings) offers a clever retrieval strategy: during the query phase, ask a large language model (LLM) to imagine a plausible answer, embed that response, and use it to locate authentic documents. The important realization is that a hypothetical answer is often closer in embedding space to actual answers than the original question.</p><p>The twist: implement this concept during the indexing phase instead of the querying phase.</p><p>As you divide a document into sections, formulate 3–5 questions that each section could reasonably answer. Embed these questions alongside — or instead of — the original chunk of text. Consequently, when a user poses a question, it aligns with the pre-generated questions crafted from the same semantic register. This method facilitates a match between questions rather than simply between questions and answers.</p><p>In the context of material science, this approach is significant. A section focused on <em>grain boundary segregation in austenitic steel</em> is unlikely to mention “what causes intergranular corrosion?” — but a generated question is likely to include it. Thus, the gap in retrieval is minimized.</p><p><strong>Practical Implementation:</strong></p><ul><li>Process the document into chunks as usual</li><li>For each chunk: generate_questions(chunk, n=5) — utilizing a small model for efficiency</li><li>Combine questions and chunk text for embedding (concatenate or store as parallel vectors and choose the maximum score during retrieval)</li><li>At query time: perform standard dense retrieval, maintaining the same approach</li></ul><p>The trade-off is increased indexing time, but the benefit is enhanced query-time recall concerning terminology mismatches, which is a persistent issue in scientific literature. A researcher inquiring about <em>delayed fracture</em> will now locate sections discussing <em>hydrogen-assisted cracking</em> — thanks to the questions generated during indexing.</p><h3>2. AdaptUI: Crafting the Interface Based on Data</h3><p>Most scientific dashboards are designed to accommodate average queries. The user interface remains static while data is fed into it. This model falters when the data fails to conform to the pre-established template — for instance, a property table being represented as a line chart or a phase diagram awkwardly fitted into a scatter plot.</p><p>The core of the AdaptUI concept: generate the interface dynamically based on the data’s structure and semantics during rendering.</p><p>The system holds a catalog of visualization components — including phase diagrams, stress-strain curves, crystallographic structure renders, comparison tables, and citation graphs. When results are generated from a query, a lightweight classifier (or the LLM itself) assesses: <em>what type of information is this, and what does the user intend to achieve with it?</em> It then selects and configures the appropriate visualization component.</p><p>This process involves generating code within a defined framework. Rather than asking the LLM to produce arbitrary React code — it’s tasked with choosing from a selection of components and populating the properties. The resulting output is both predictable and verifiable.</p><p><strong>An intriguing challenge:</strong> implementing an adaptive UI necessitates that the system comprehends <em>intent</em>, not just <em>data type</em>. Queries like “Show me the fatigue life of this alloy” versus “compare fatigue life across five alloys” share the same data type but demand different rendering responses. Intent cues can arise from the structure of the query, the user’s previous interactions, and their recent activities.</p><p>This remains a complex challenge. However, the guiding principle — create the interface dynamically rather than configuring it — is a promising direction in fields where the variety of data surpasses the limits of fixed templates. Material science embodies this reality, where the data types encompass crystallographic parameters, thermodynamic curves, microstructure images, and elemental composition tables. A single static dashboard cannot adequately represent this diversity.</p><h3>3. A DAG Planning Layer Focused on Goals and Collision Prevention</h3><p>This idea is more theoretical but merits careful consideration.</p><p>Most current multi-step AI workflows operate in a linear fashion: retrieve → reason → generate. When these processes branch, the paths are typically hardcoded. There exists no layer that <em>plans</em> the workflow according to the goal — the execution sequence remains fixed despite the requirements of the query.</p><p>Game AI has addressed a similar issue. <strong>Goal-Oriented Action Planning (GOAP)</strong>, discussed in the game AI literature and utilized in titles like <em>F.E.A.R.</em>, conceptualizes planning as a search problem:</p><ul><li>Establish the <em>current world state</em> — what information is available, what has been retrieved, what calculations have been made</li><li>Define the <em>goal state</em> — what conditions must be satisfied for the query to be resolved</li><li>Specify <em>actions</em> with their preconditions and outcomes — for example, retrieve_papers necessitates a query string and results in papers_available=true</li><li>Seek a valid sequence of actions that transitions from the current state to the goal state</li></ul><p>The plan takes the form of a <strong>Directed Acyclic Graph (DAG)</strong>, not a straightforward list. Actions that are independent can be executed concurrently. Conflicts — instances where two branches might produce contradictory intermediate states — are identified during the planning phase instead of at execution.</p><p><strong>Collision avoidance during planning</strong> implies that, prior to finalizing a plan, the system checks for conflicts among concurrent branches. In game AI, this aspect manages agents navigating the same space simultaneously. Within a research pipeline, it prevents scenarios such as two retrieval paths querying the same corpus with overlapping filters (resulting in redundant processing), or two reasoning branches yielding contradictory evidence that a subsequent synthesis step cannot reconcile (yielding erroneous output silently).</p><p><strong>Plan refinement</strong> completes the feedback loop: execute a portion of the plan, assess the actual outcomes against the planner’s expectations, and replan based on the current state. This method parallels the Hierarchical Task Network (HTN) strategy — overarching tasks are broken down into subtasks, with flexibility to revise the breakdown mid-execution when circumstances diverge from the initial plan.</p><p>For a research pipeline in material science, a tangible scenario might look like:</p><pre>Goal: create a synthesis on hydrogen embrittlement in high-strength steels</pre><pre>Plan (initial DAG):<br>  retrieve_primary_papers<br>    → extract_mechanisms         ─┐<br>    → extract_material_systems   ─┼→ synthesize → format_output<br>    → retrieve_citing_papers ────┘</pre><pre>Collision check:<br>  extract_mechanisms and extract_material_systems: parallel, no shared writes ✓<br>  retrieve_citing_papers: depends on retrieve_primary_papers ✓<br>  synthesize: prerequisites demand completion of all three branches ✓</pre><pre>Refinement trigger:<br>  retrieve_primary_papers yields fewer than 5 results (sparse)<br>  → replan: insert retrieve_adjacent_fields node before synthesize<br>  → reassess collisions on the new graph<br>  → proceed</pre><p>The planning component need not be a large model. The representation of goal states, the action library, and the conflict detection could be rule-based or supported by a small trained classifier. The semantic tasks within each action node can be managed by the LLM; the planner oversees the graph’s structure above that layer.</p><p><strong>The significance of this approach over improved prompting:</strong> prompt chaining optimizes isolated steps. Planning enhances the <em>framework</em> of work. For intricate, multi-hypothesis research inquiries — the types commonly posed by material scientists — the distinction between an effective plan and a poor one outweighs the variations in prompts within each step.</p><h3>The Common Thread</h3><p>These three concepts share a fundamental principle: introduce intelligence earlier within the pipeline.</p><ul><li>HyDE inversion promotes semantic coordination during indexing rather than during the query phase</li><li>AdaptUI enables interface generation at render time, influenced by the data’s structure and the user’s intention</li><li>DAG planning shifts structural decisions to the planning phase instead of the execution phase</li></ul><p>Each approach sacrifices upfront computational effort for increased flexibility down the line. This trade-off is often beneficial in systems where the range of queries is extensive, and the pitfalls of a rigid pipeline can be costly. In the realm of material science research, where inquiries cover various domains, data types are diverse, and incorrect answers carry tangible consequences, such an adjustment is typically advantageous.</p><p>We are progressing toward integrating all three concepts. None are completely resolved yet. If you’re engaged in this area, I would appreciate hearing what strategies are proving effective for you.</p><p>The entire project, which encompasses the retrieval pipeline, the component registry for AdaptUI, and initial experiments with the planning layer, can be found detailed on the blog: <a href="https://ikouchiha47.github.io/materials-science/">ikouchiha47.github.io/material-science</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c043b62e7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Crisp-Engine: *sodic memory for ai agents]]></title>
            <link>https://medium.com/@amitavaa.ag/crisp-engine-sodic-memory-for-ai-agents-2c8923a87d2e?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c8923a87d2e</guid>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[open-code]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-memory]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 20:43:55 GMT</pubDate>
            <atom:updated>2026-08-25T20:43:55.269Z</atom:updated>
            <content:encoded><![CDATA[<p>I got tired of explaining context to my AI coding assistant every single session.</p><p>So I built Crisp Engine — an episodic memory layer for AI coding agents.</p><p>Not RAG. Not a vector store wrapper. A structured memory system that watches what your agent actually does — every file edit, git commit, bash failure — and builds a record that persists across sessions.</p><p>Crisp remembers:</p><ul><li>what you’ve tried and why it didn’t work</li><li>patterns in your frustration (yes, really)</li><li>what files you keep touching and what broke near them</li><li>lessons extracted from your own commit messages</li></ul><p>The architecture is agent-agnostic. Claude Code, OpenCode, Pi — same memory layer, adapter pattern handles the differences.</p><p>implements the full academic memory stack:</p><ul><li>CoALA 4-layer taxonomy (working → episodic → semantic → procedural)</li><li>MemGPT-style hierarchical paging (L0 raw → L1 summaries → L2 clusters → L3 arcs)</li><li>Ebbinghaus decay per layer, access-frequency promotion, conflict detection</li><li>A-MEM Zettelkasten links between episodes (similar/caused/contradicts/corrected_by)</li><li>5-layer zoom retrieval with reranking (vector + recency + importance + access freq)</li></ul><p>The interesting parts:</p><p>-&gt; Tool Watchers: pluggable observers that turn tool calls into memory episodes. Git push rejected? Frustration score goes up. Hard reset? Flagged as destructive. Write your own watcher in ~30 lines.</p><p>-&gt; Instinct distillation: repeated patterns graduate into named instincts. High-confidence instincts can generate new watchers automatically.</p><p>-&gt; Embedding fallback chain: Ollama flaky? Crisp falls through to HuggingFace, then word2vec. Never silently drops your data.</p><p>Still building. Open to collaborators who think agents should get smarter the longer you work with them.</p><p><a href="https://github.com/ikouchiha47/crisp-engine">repo</a></p><p>N.B. I don’t know how much its working, still measuring.<br> N.B. Before you ask, how its different from hernia-agent, its very different, the last thing I want in life rn is another md file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c8923a87d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building next-word prediction for a keyboard app — pipeline, smoothing algorithms, and vocabulary…]]></title>
            <link>https://medium.com/@amitavaa.ag/building-next-word-prediction-for-a-keyboard-app-pipeline-smoothing-algorithms-and-vocabulary-64fb4155a62c?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/64fb4155a62c</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Fri, 21 Aug 2026 15:58:45 GMT</pubDate>
            <atom:updated>2026-08-21T15:58:45.810Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building next-word prediction for a keyboard app — pipeline, smoothing algorithms, and vocabulary tradeoffs</h3><p>This is a summary of three recent posts from my CodeKeyboard rebuild series. CodeKeyboard is an open-source Android keyboard for programmers — layers, modifier keys, fuzzy autocorrect, and now a real statistical next-word prediction engine.</p><p>The prediction model</p><p>The keyboard trains a trigram language model on the Coursera SwiftKey corpus: 583MB of blogs, news, and Twitter text, 4.27 million lines. A trigram model stores, for every two-word context (“I am”), a ranked list of likely next words (“going”, “a”, “sure”…). At typing time, the keyboard looks up whatever the last two committed words were and surfaces the top candidates.</p><p>Three algorithm variants were built:</p><p>Kneser-Ney (KN) — instead of counting how often a word appears, it counts how many different contexts a word appears in. The word “Francisco” appears frequently in the corpus, but almost always after “San”. KN scores it low as a generic next-word guess because it continues so few contexts. Good for cold-start guessing; harder to tune under size constraints.</p><p>Katz backoff — uses Good-Turing discounting to redistribute probability mass toward words the model has seen less of. More stable when the model gets pruned aggressively to fit on a phone.</p><p>SwiftKey WDP — takes the Katz model and asks of every stored next-word candidate: “does knowing the two-word context actually change this word’s odds compared to the one-word context alone?” Candidates that merely restate the simpler model get dropped. Result: 31% smaller file, 99.2% top-1 agreement with Katz. This one ships.</p><p>The pipeline problem</p><p>The first full-corpus AWS run consumed all memory and produced nothing. The second attempt ran for over two hours and was killed manually.</p><p>The fix: switched to a streaming SQLite pipeline — counts flow through a rolling merge rather than loading into RAM, intermediate results checkpoint to disk, and the whole build now completes in 11 minutes on a spot t3.xlarge.</p><p>The vocabulary question</p><p>The trained model has a 427,651-word vocabulary. 85% of those words appear fewer than 15 times across 85 million tokens. Zipf’s law in action.</p><p>Four vocabulary caps were tested: 16K, 32K, 64K, 128K words. The measurement: how often does the right next word fall outside the cap? At 64K, coverage reaches 99.3% of real next-word targets. Above that,<br>gains are marginal. The 64K cap ships.</p><p>The result</p><p>Everything — vocabulary, character trie, bigram/trigram follower lists, phrase data — comy .cklm file. 22MB. Loaded via memory-map at startup. Three separate JSON files are gone.APK: 302MB down to 94MB.</p><p>Full write-ups:</p><ul><li><a href="https://ikouchiha47.github.io/keyboard/08-ngram-pipeline-optimization.html">Part 8 - Pipeline</a></li><li><a href="https://ikouchiha47.github.io/keyboard/09-ngram-smoothing-katz-swiftkey-wdp.html">Part 9 — Smoothing</a></li><li><a href="https://ikouchiha47.github.io/keyboard/10-vocab-tail-analysis.html">Part 10 - Vocabulary</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64fb4155a62c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shrinking a materials dataset]]></title>
            <link>https://medium.com/@amitavaa.ag/shrinking-a-materials-dataset-3838348a19ef?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3838348a19ef</guid>
            <category><![CDATA[sqlite3]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 16:44:25 GMT</pubDate>
            <atom:updated>2026-08-11T16:44:25.779Z</atom:updated>
            <content:encoded><![CDATA[<p>Shrinking datasets is quite contextual. It depends on how the dataset is going to be used. Its the same concept as optimizing databases, based on the read/write patterns.<br>PACLEC and Traffic Patterns are the key determining factors.</p><p>Hosted on fly.io : <a href="https://materials-db.fly.dev/">https://materials-db.fly.dev/</a></p><p>The need for this was not to integrate with <a href="https://next-gen.materialsproject.org/materials">another external API</a> for retrieving information on different materials and not think about rate-limiting. This was made as a part of a bigger system: <a href="https://ikouchiha47.github.io/p/b8e2c4/materials-science-notes/">Research Agent for Researchers</a></p><p>The materials trajectory database was around 12Gigs and is mostly used for training models like <a href="https://github.com/CederGroupHub/chgnet">CHGNet</a>. <br>But I needed it only for responding to query on finding materials and it didn’t need all the variations.</p><p>The aim was to be able to serve it using my most loved database — sqlite, in under reasonable timeframe: &lt;500ms.</p><p>A detailed write up is provided in my blog: <a href="https://ikouchiha47.github.io/2026/08/05/materialsdb-11gb-to-266mb.html">https://ikouchiha47.github.io/2026/08/05/materialsdb-11gb-to-266mb.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3838348a19ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rebuilding Sofle-Choc on Android]]></title>
            <link>https://medium.com/@amitavaa.ag/rebuilding-sofle-choc-on-android-decf5ab1e18f?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/decf5ab1e18f</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[deepseek]]></category>
            <category><![CDATA[keyboard]]></category>
            <category><![CDATA[open-code]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 13:31:31 GMT</pubDate>
            <atom:updated>2026-08-10T13:31:31.999Z</atom:updated>
            <content:encoded><![CDATA[<p>I built a custom Android keyboard. It got weird.</p><p>A full IME — written in Kotlin, handling every keypress, suggestion, and cursor movement myself. The idea was to replicate the Sofle Choc split. Because.</p><h3>How it all started</h3><p>I was stuck at a hospital all day, with nothing but my phone, getting bored and worried sick, I needed some way to vent.</p><p>Termux saved the day. I had used termux sparingly for some experimentation, but never considered it be a proper dev environment. After poking around with it, I found out its possible to run X using pdistro.</p><p>So I installed:</p><ul><li>pdistro and debian</li><li>a bunch of libraries I could find on a reddit thread</li><li>neovim</li><li>opencode</li><li>github’s gh cli</li></ul><p>Since there was no way to run the builds fast enough, the build setup went something like this:</p><ul><li>generate the templates for ADRs, Tasks with Acceptance Criterias’</li><li>typescript and kotlin linter (got rid of the kotlin one later)</li><li>some instructions on claude.md to adopt Test First</li><li>when stuck look for other libraries and solutions on internet</li><li>github actions to build and run tests</li><li>opencode with deepseek v4 flash free set to max (for ~85% of the build)</li></ul><p>Before any UI building the instructions were to build it out using html-css and use python server to locally host it out.</p><p>One of the problems that I still face today is the way to share screenshots. The method I adopted was a pretty crude one.</p><ol><li>Take the screenshot and convert to base64</li><li>Share the base64 to opencode and use a /command</li><li>Decode and save it as image, and let deepseek-v4-pro read and understand</li><li>Write the understanding back to a debug log.</li></ol><h3><strong>Some realizations and surprises while building this:</strong></h3><p><strong>Backspace into a committed word is a whole thing:</strong></p><p>Once a word is committed, the suggestion engine loses track of it. Backspacing into it looks like a new character to the IME. Getting autocomplete to pick up the fragment again meant wrapping three API calls in beginBatchEdit/endBatchEdit to stop the editor firing callbacks mid-operation. AnySoftKeyboard does the same thing. Took me way too long to figure out why.</p><p><strong>Next-word prediction is more interesting than I expected</strong>:</p><p>After every committed word, surface what probably comes next — T9 style, but without the hardware. Two layers: a static English seed (Norvig’s bigram corpus, MIT licensed) and a personal layer that learns from your actual typing. The scoring uses temporal decay from `librime` — recent use contributes a near-full boost, something you typed 1000 commits ago contributes almost nothing. Old habits fade. New ones take over within a few hundred keystrokes.</p><p>Learned about bigrams, infigrams, suffix-array with binary search and a new shit called <a href="http://github.com/rime/librime">beam_search</a></p><p>Mixed language (Banglish, Hinglish) works without any language detection, kinda — the personal layer is just a string map. It doesn’t care what language you’re in. Again, ASK showed the way for MVP.</p><p>The suggestion interface mirrors librime’s Grammar pattern, context passes through the function call, not stored as shared mutable state. Took one refactor to get there but it cleaned up everything downstream.</p><p>This can be further improved by looking into how HeliBoard does prediction. I found a <a href="https://codeberg.org/Helium314/aosp-dictionaries">bunch of dictionaries</a> on codeberg, which can be compiled to a dict.</p><p>A seven part series on the same:<br><a href="https://ikouchiha47.github.io/keyboard/">https://ikouchiha47.github.io/keyboard/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=decf5ab1e18f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimux: on the fly image/video optimizer]]></title>
            <link>https://medium.com/@amitavaa.ag/optimux-on-the-fly-image-video-optimizer-25c30095e7a5?source=rss-91bd28167c3e------2</link>
            <guid isPermaLink="false">https://medium.com/p/25c30095e7a5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Amitavaa Ag]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 12:44:37 GMT</pubDate>
            <atom:updated>2026-08-10T13:15:21.623Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://github.com/go-batteries/optimux">Optimux</a> is a Go service that resizes, re-encodes, and streams images and video on the fly — /resize?image_url=…&amp;sizes=300x0&amp;format=webp&amp;quality=60, done. It’s been running as an internal service for a while. I’m open-sourcing it now, AGPL-3.0, because the worker pool underneath it — the part that decides how many goroutines are doing image processing at any given moment — ended up being the most interesting thing in the codebase, and it deserves to exist somewhere other than a private repo.</p><p>This is the story of how that worker pool got there, including the part where the pattern everyone starts with turned out to be actively wrong for this workload.</p><h3>Starting point: the Job/Dispatcher pattern</h3><p>I started from Marcio Castilho’s <a href="https://medium.com/smsjunk/handling-1-million-requests-per-minute-with-golang-f70ac505fcaa">Handling 1 Million Requests per Minute with Golang</a>. Worth being precise about what that article actually builds, because the mismatch with image processing turned out to matter a lot:</p><ul><li>A Job struct wraps one unit of work (there, a POST payload headed to S3).</li><li>A buffered JobQueue chan Job receives incoming jobs.</li><li>A Dispatcher owns a WorkerPool chan chan Job — a <strong>channel of channels</strong>.</li><li>Each Worker has its own chan Job, and the moment a worker finishes a job, it pushes its <em>own</em> channel back into the shared WorkerPool. The dispatcher’s loop just pulls one worker-channel off WorkerPool and hands it the next job.</li><li>No worker ever polls for work or reports “I’m free” via a flag — availability <em>is</em> “my channel is currently sitting in the pool.” MAX_WORKERS and MAX_QUEUE are env-configured, fixed for the process lifetime.</li></ul><p>The article’s numbers are genuinely good:</p><blockquote>They took a system that needed ~100 EC2 instances down to 4 `c4.Large` instances handling close to a million requests a minute, by replacing unbounded goroutine spawning with this bounded pool.</blockquote><p>But the workload is uploading JSON payloads to S3 — almost entirely I/O wait, barely any CPU. I built the same pattern, pointed it at image resizing instead, and it did not translate.</p><h3>The pattern didn’t fit, and pprof proved it</h3><p>I wired up the Job/Dispatcher pattern for image jobs and it was slow in a way that didn’t make sense from the throughput numbers alone. So I pulled a blocking profile, and it was unambiguous:</p><blockquote>pprof blocking profile shows **67.99%** of total time spent waiting on chanrecv1.</blockquote><p>That’s workers blocked waiting for jobs, and the dispatcher blocked waiting for workers to hand their channel back — a pattern built for a workload where a worker is <em>cheap and fast</em> per unit (fire an S3 PUT, wait on the network, done) turns into mostly idle channel choreography when a unit of work is <em>hundreds of milliseconds of CPU-bound image processing</em> instead.</p><p>The channel-of-channels handoff, the dispatcher loop, the per-job registration — all of that overhead is invisible when a worker’s actual job takes microseconds of your attention and the rest is network wait. It stops being invisible when the job itself is the bottleneck. Target throughput was 8.6rps; no matter what I tuned in this shape, it sat at 2.0xrps.</p><p>So I threw it out and rebuilt from a synchronous baseline up, one variable at a time, so I’d actually know what each change bought me instead of tuning inside a pattern that was wrong from the start.</p><h3>Rebuilding from zero, one variable at a time</h3><p><strong>Synchronous baseline, no workers at all</strong> — inline resize, respond directly. 2.9rps. Already ahead of the dispatcher pattern’s 2.0x, which was the first sign the problem wasn’t “not enough workers,” it was the shape of the concurrency itself.</p><p><strong>Single channel, single worker</strong>: The smallest thing that still queues — one goroutine pulling off one channel, closer to a single core churning a work list than to a “pool” in any real sense. 2.1rps — <em>worse</em> than doing nothing concurrent at all. Concurrency has a floor cost, and this workload was paying it without buying anything back yet.</p><p><strong>Single queue, 4 workers:</strong> 3.15rps, average latency 1.37s. First real win, and a small one.</p><p><strong>Two queues</strong> — fetch and process, split apart — 4 workers each.3.07rps, marginally *lower* throughput than the single queue, but the latency distribution across percentiles visibly smoothed out.</p><p>Tracing explained why: fetching a source image from tmpfs cost 40–100ms; processing it (libvips, resizing a 3.1MB source down to a 120×240 webp) cost ~700ms. Those are two stages with wildly different service times sharing a queue and worker pool — an impedance mismatch, where a burst of cheap fetches can queue up behind a slow processor, or the reverse.</p><p><strong>Two queues, but weighted 2 fetchers / 4 processors</strong>, leaning into the imbalance on purpose. Performed <strong>worse</strong> than the even split, still around 3+rps.</p><p>My read at the time: this isn’t a batch pipeline where you can freely over-provision the expensive stage and let a queue absorb the mismatch — it’s a real-time request path where the caller is still on the other end of the HTTP connection waiting, so over-provisioning one stage just moves the queueing, it doesn’t remove it.</p><p>I also tried a demand-driven producer/consumer setup along the way — closer to Elixir’s GenStage, where the consumer explicitly asks the producer for N items instead of the producer pushing whenever it has something. It didn’t pan out for this workload, and honestly the specifics didn’t survive in my notes — only the conclusion: the demand/ack round-trip was adding coordination cost that a plain buffered channel already got for free, without a corresponding improvement in how work actually got scheduled.</p><p>Separately, before any dynamic scaler existed, I added something orthogonal to worker count entirely: instead of buffering the whole encoded image and writing it in one response, the handler started flushing early and streaming bytes out as the encoder produced them. That alone moved the needle independent of worker shape — 3.28rps, latency down to 1.31s.</p><h3>What actually generalizes, and what doesn’t</h3><p>Here’s the actual lesson, not just the numbers:</p><p>The Job/Dispatcher pattern isn’t wrong, it’s scoped to a specific kind of workload — one where the *external* resource (S3, a network call, a database) is the thing you’re rationing, and your own CPU is basically idle waiting on it.</p><p>In that world, a large fixed worker count is nearly free — you’re just capping how many outstanding waits you allow. libvips-backed image processing inverts that: the constrained resource is <em>your own CPU and memory</em>, fetch and process have genuinely different cost profiles, and a fixed MAX_WORKERS picked once has no way to track a queue that swings between bursty and empty.</p><ul><li>iostat on the EC2 box backed this up directly — CPU usage swinging from 80%+ down to 40% inside the same short window</li><li>%steal spiking as high as 8.74% (hypervisor-stolen cycles, which no amount of worker returning fixes).</li></ul><p>A workload like that needs the worker count itself to be a live variable, not a constant — which is what actually motivated moving off any fixed-size pool entirely, GenStage-shaped or otherwise, toward something that watches queue depth and scales.</p><p>It’s worth being precise about *where* the two patterns actually diverge structurally, because it’s not just “one has a scaler and one doesn’t.”</p><p>The dispatcher pattern’s availability signal is a second layer of indirection: each worker owns a private chan Job, and “I’m free” is expressed by pushing that channel into a shared WorkerPool chan chan Job.</p><p>That’s N+1 channels for N workers — one pool channel plus one per-worker channel — and a dispatcher goroutine whose whole job is shuttling a channel out of the pool, handing it a job, and waiting for it to come back. It’s a clean pattern, but it exists to solve a problem optimux’s worker pool doesn’t have: every worker in DynamicScaler pulls directly off one shared Queue chan T.</p><p>There’s no dispatcher goroutine, no per-worker channel, no explicit “I’m free” message at all — a worker’s availability <em>is</em> nothing more than “currently blocked on a receive from Queue,” which Go’s own runtime already arbitrates correctly among however many goroutines are competing to receive.</p><p>The single-shared-queue shape showed up as early as the “single queue, 4 workers” experiment above, well before any scaler existed, and every version since kept it — the channel-of-channels indirection never came back, because a single channel with competing receivers gave equal or better throughput without the extra bookkeeping.</p><p>The other divergence is what each pattern treats as fixed. The article’s MAX_WORKERS is an env var read once at startup — there’s no concept of a worker ever leaving the pool short of the whole process dying, because the workload it targets doesn’t need one: S3 upload capacity doesn’t really shrink at 2am.</p><p>DynamicScaler has an explicit opposite belief baked into its registry — every WorkerSlot can be marked Retiring and needs a defined, race-free way to leave the pool without dropping in-flight work, because for this workload the *right* worker count at any moment is itself the thing under contention (CPU cores, memory for concurrently-decoded images), not a constant you get to pick once.</p><h3><strong>What DynamicScaler does</strong></h3><p>DynamicScaler[T] (src/mediahose/schedulers.go) is a generic worker pool that grows and shrinks based on queue pressure instead of running a fixed goroutine count.</p><p>The type parameter is the job type, so the same scaler independently drives image jobs, video jobs, and batch jobs off different queues with different thresholds. The registry is a single ordered slice, append-only in creation order:</p><pre>type WorkerSlot[T any] struct {<br> Idx int64<br> Retiring bool // marked for retirement; reclaimed only on exit notify<br> worker Worker[T]<br> cancel context.CancelFunc<br> retire chan chan bool<br>}<br><br>type DynamicScaler[T any] struct {<br> WorkerFactory func(idx int64, done chan int64) Worker[T]<br> Queue chan T<br> MinWorkers, MaxWorkers int<br> ScaleUpThreshold, ScaleDownThreshold int<br> CheckInterval, ScaleCooldown, RetireGrace time.Duration<br> workers []*WorkerSlot[T] // tail = newest<br>}</pre><p>Because the slice is append-only, the tail is always the newest worker — which makes “retire the newest worker first” (LIFO) a deterministic scan instead of a random pick. There’s no separate counter tracking how many workers are active; the live count is derived on read:</p><pre>func countLive[T any](workers []*WorkerSlot[T]) int {<br> live := 0<br><br> for _, wsl := range workers {<br>   if !wsl.Retiring {<br>     live++<br>   }<br> }<br> return live<br>}</pre><p>Nothing else exists to fall out of sync with the registry, because there’s nothing else — the count is a computation over the one piece of state, not a second piece of state someone has to remember to update alongside it.</p><p><strong>Retirement happens at an idle boundary, not on demand</strong>. A worker that opts in (FetchWorker, the image/video processing worker, does) runs a single blocking select over three cases — context cancellation, a retire request, and the job queue — with no default branch:</p><pre>select {<br>  case &lt;-ctx.Done():<br>   return<br>  case retireReq := &lt;-fw.RetireCh:<br>   select {<br>   case retireReq &lt;- true:<br>   default:<br>   }<br>   return<br>  case job := &lt;-jobQueueChan:<br>   // process it<br>}</pre><p>A retire request lands the instant the worker goes idle, not after it happens to finish whatever job comes next.</p><p>When the scaler decides to shrink the pool, it marks the newest slot Retiring: true and sends a one-shot ack request; the slot stays in the registry, still counted toward the hard MaxWorkers cap, until the worker actually exits and notifies the scaler on a close channel.</p><p>There’s a bounded grace period (default 2s) — if the worker hasn’t idled out by then, the scaler cancels its context as a fallback nudge, but removal from the registry only ever happens on the real exit notification, never on the timeout itself.</p><p><strong>Scale decisions are cooled down, with an escape hatch</strong>. The signal driving scale() is len(ds.Queue) — instantaneous backlog, sampled on a ticker.</p><p>That’s not the same thing as, say, SQS handing you ApproximateNumberOfMessagesVisible alongside an in-flight count, smoothed over a window before an alarm fires. A raw instantaneous queue length is noisy under bursty traffic: it can cross ScaleUpThreshold and ScaleDownThreshold within a couple of ticks without the underlying load actually having changed, and a scaler with no way to tell a real trend from a blip would happily add a worker and retire it right back.</p><p>The cooldown (default 30s between scale actions) exists because that better signal doesn’t exist yet — it’s a blunt fix for a noisy input, not a fundamental property of dynamic pools. The one case that bypasses it entirely: if live workers ever drop below MinWorkers, the scaler refills immediately regardless of cooldown, so a crash storm can’t leave the pool sitting empty for a full cooldown window waiting on a timer that doesn’t care capacity is gone.</p><p>That’s the whole mechanism: one ordered registry as the single source of truth for both “who’s alive” and “who retires next,” idle-boundary handshakes instead of blind cancellation, and a cooldown standing in for a smarter scaling signal that isn’t built yet.</p><h3>What I didn’t test: prefork</h3><p>One pattern from a different corner of the same problem space I never actually tried: <a href="https://docs.gofiber.io/">Fiber’s prefork mode</a> — instead of one Go process handling everything under a single GOMAXPROCS, use SO_REUSEPORT to run N forked OS processes, each getting its own slice of cores, with the kernel load-balancing connections across them.</p><p>My honest guess is it wouldn’t have moved the throughput numbers above. Every pool-shape experiment — single worker, 4 workers, split queues, weighted split — barely moved throughput (2.1 to 3.15rps), because the real cost is ~700ms of libvips CPU work per image, not goroutine-scheduling or channel overhead.</p><blockquote>Prefork changes how many OS processes share a machine’s cores, not how many cores exist; the same physical CPU is doing the same total amount of resize work whether it’s one process running N goroutines or K processes each running fewer, and Go’s scheduler already multiplexes goroutines across cores efficiently for CPU-bound work like this.</blockquote><p>Where I’d actually expect it to help is somewhere none of these benchmarks were looking: tail latency and fault isolation. This worker loop allocates large image byte slices per job (there’s a byts = nil in it as a GC hint) — a GC pause or heavy mark-assist period in one process adds jitter to <em>every</em> concurrent request in that process.</p><p>With prefork, GC pressure in one fork doesn’t stall requests being served by a sibling fork. Same story for a pathological input (corrupt file, huge dimensions) wedging or OOMing one process — the kernel keeps routing new connections to the survivors instead of the whole fleet going down. Neither of those is a throughput property, and neither is something Progression.md’s numbers (throughput, average latency) would have caught even if true. Genuinely untested — not a claim, a gap.</p><h3>What’s next</h3><p>Three things this codebase is deliberately waiting on or missing rather than half-building now, documented in the repo for anyone who wants to pick them up.</p><p><strong>Streaming instead of buffering, once govips ships it.</strong> Every image today gets fully buffered into a `[]byte` at each stage — load, encode, respond — before the next stage starts. govips just merged native streaming support (LoadImageFromReader, SaveToWriter, PR <a href="https://github.com/davidbyttow/govips/pull/539">davidbyttow/govips#539</a>), which would let a load and an encode work directly against io.Reader/io.Writer instead of a fully materialized buffer — real memory savings for a service whose job is exactly this: dynamic compression of non-standard sizes at request time.</p><p>It’s not in a tagged release yet (latest tag predates the merge by months), so this is parked as `docs/ADR-003` in the repo until that lands, rather than pinned to an untagged commit in something serving production traffic.</p><p><strong>A real HTTP/2 cross-stream priority scheduler.</strong></p><p>This one came out of a completely different rabbit hole: <a href="https://blog.cloudflare.com/parallel-streaming-of-progressive-images/">Cloudflare’s parallel-streaming-of-progressive-images</a> work, where a server multiplexing many concurrently-loading images over one HTTP/2 connection sends every image’s size header first, then every preview, then remaining refinement data — instead of blasting one image’s full body before starting the next. Optimux already does the single-image version of this (StreamEncoder/ProgressiveStreamEncoder chunk header→preview→remainder), but the cross-stream scheduling piece — deciding, across every concurrently open image request, whose bytes go out next — turned out to be something almost nobody exposes as a plugin point.</p><p>Go’s x/net/http2.WriteScheduler is deprecated by its own maintainers (“provides too much visibility into implementation internals, is difficult to use”); nginx has an internal RFC 7540 priority tree that’s private to its core module, not reachable from third-party modules; fasthttp/http2 parses the PRIORITY frame’s weight and never reads it again anywhere.</p><p>The real prior art turned out to be H2O (a genuine O(1) scheduler, but measurably unfair — Tempesta Tech’s own simulation found only 2 of 256 streams got ideal scheduling against it), nghttp2 (correct WFQ, but O(n)), and <a href="https://github.com/tempesta-tech/tempesta/pull/1973">Tempesta FW</a>, who landed on WFQ backed by HAProxy’s ebtree specifically for the 100–1000-stream range this kind of service would actually see. The plan, is to write a from-scratch server on golang.org/x/net/http2.Framer directly — bypassing the deprecated hook entirely — staged from a toy proving the interleaving works, up to real flow control, up to wiring in the actual image pipeline.</p><p><strong>A scale-up signal that knows when adding a worker won’t help.</strong> scale() only ever asks “is the queue long” — it has no way to tell a genuine burst apart from a backlog that’s building because libvips’s own thread pool is already saturated, in which case another Go worker just queues behind the same C-level pool without adding real capacity, while still paying for a decoded image buffer’s worth of memory.</p><p>I went looking for a way to read that saturation directly from govips and it isn’t there: ConcurrencyLevel is write-only in practice (set once via vips_concurrency_set, read back only for a startup log line), and RuntimeStats tracks cumulative operation counts, not current thread-pool occupancy.</p><p>libvips’s underlying GThreadPool (GLib) does expose real introspection — g_thread_pool_unprocessed(), g_thread_pool_get_num_threads() — govips just never wraps it. The more practical fix doesn’t need any of that: an atomic in-flight counter around each worker’s processor.Process() call, gating addWorkerLocked when in-flight already matches VipsConcurrency. Documented as a finding, not built yet.</p><h3>Notes</h3><p>The scaler is the part of this codebase I’d actually want other people to read, argue with, or reuse — a fairly small, self-contained piece of generic Go with real constraints (goroutine lifecycle, backpressure, graceful shutdown) that most worker-pool tutorials, mine included at the start, wave away. The rest of optimux — image/video transforms, S3 wiring, the HTTP surface — is useful but unremarkable by comparison.</p><p>Repo: <a href="http://github.com/go-batteries/optimux](https://github.com/go-batteries/optimux">optimux</a>, AGPL-3.0.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25c30095e7a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>