<?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 Systems in the Mist on Medium]]></title>
        <description><![CDATA[Stories by Systems in the Mist on Medium]]></description>
        <link>https://medium.com/@dmkolesnikov?source=rss-56bcc01a8eac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OJh26MaVHzRjRxPDFcv8Tg.png</url>
            <title>Stories by Systems in the Mist on Medium</title>
            <link>https://medium.com/@dmkolesnikov?source=rss-56bcc01a8eac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:06:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dmkolesnikov/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[Beyond Agentic Coding: Can an AI Agent Do Science: 5 Lessons Learned the Hard Way?]]></title>
            <link>https://medium.com/@dmkolesnikov/beyond-agentic-coding-can-an-ai-agent-do-science-5-lessons-learned-the-hard-way-6a212f96b82a?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a212f96b82a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[neuroscience]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 08:11:01 GMT</pubDate>
            <atom:updated>2026-11-17T08:11:01.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pjf91P5gkh4hs8OXlUfdyA.png" /></figure><p>Agents are able to conduct an open-ended research project. Anthropic, OpenAI has shown substantial progress conducting research in mathematics, fundamental physics, cryptography and other fields using their proprietary flagship models. This is not the sole prerogative of Big Tech! Anyone is able to establish an agentic loop for exploratory research engineering using off-the-shelf models, but it succeeds only inside a frame that a person sets and enforces. Think about that frame as a written decision, falsifiable gates, null controls, ADRs and constitutions. Without it, an agent will quietly optimize the metric instead of answering the research question.</p><p>This post distills my lessons from autonomous research via agentic loop in the field of computational neuroscience. Janelia and Google mapped the central nervous system of a male Drosophila (fruit fly): 211,577 neurons and approximately 312 million synapses, published in the open MaleCNS dataset. I’ve launched MicroFly (<a href="https://github.com/fogfish/microfly">https://github.com/fogfish/microfly</a>), an autonomous research loop inspired by this dataset. The project starts with a scientific question: if you take a real biological neural circuit from a fruit fly’s connectome, translate it into a spiking neural network, and run it in a simulated environment, can the network generate coherent, biologically plausible behavior (involving sensory inputs, neural activity, food seeking, and danger avoidance)?</p><p><strong>Existing neuroscience cautions against assuming behavioural equivalence</strong>. Translating a biological connectome into a digital neural network does not guarantee behavioural equivalence to its biological source. Structural connectivity alone is insufficient to reconstruct the full dynamics and behavioural complexity of an organism. MicroFly therefore takes a deliberately reductionist approach: rather than attempting to reproduce the complete behaviour of a fruit fly, it investigates whether a minimal, biologically grounded neural circuit can generate elementary sensorimotor behaviour. Inspired by Braitenberg vehicles and research into Drosophila navigation circuits, <strong>the objective is to build a simple autonomous agent capable of responding to environmental signals</strong>, approaching food, avoiding danger, and performing rudimentary navigation.</p><p>MicroFly sits at the intersection of neuroscience, computational modeling, and software engineering. It is not simply implementing a known algorithm, nor doing biology in the traditional laboratory sense. It is about discovery of an executable leaky integrate-and-fire (LIF) network of a biological system and using experiments to prove its “correctness”. It is a good test of agentic loop because it mixes (i) plain engineering; (ii) data engineering; and (iii) open science; nobody knows in advance correct topology to cut or neural network weights and parameters. Agents were extremely good at the first two from day one. Most of what follows is about the third.</p><h3>The Most Expensive Early Mistake</h3><p>Everywhere on social media, people are saying, “I built X in Y hours…”. So I decided to give it a try myself but doing autonomous exploratory research engineering. I used an agentic workflow with Opus 5.5 to conduct research about spiking brains cut, LIF neural networks, and turn the findings into a modeling and simulation roadmap consisting of 30 features.</p><p>Six days. 39 commits. 6 million tokens generated. $500. Sonnet 5 running autonomous loops for 8–9 hours every night.</p><p>The core goal has not been achieved: digital creatures have not exhibited biologically plausible behavior. The engineering output is real, including a working extraction pipeline, a neural engine, a streaming protocol, and a browser app with 500 plus passing tests. It does not do the thing the project exists to show. The root cause is agents have verified components before verifying the primary claim that mattered: whether connectome-derived circuits produce the behavior. <strong>The first behavioral test ran on day 4 and failed</strong>. Agents then kept building around the failure instead of stopping to question preconditions. It keeps going to silently optimize the metric instead of focusing on the actual research question.</p><p>It’s hard to blame the agents. It did their best to follow the instructions, but the initial input was imperfect. I relied too heavily on an agent-generated roadmap without validating the assumptions behind it. The problem was that most of the roadmap features relied on neuroscience, an area where I had neither expertise nor practical experience.</p><p>The lesson? AI agents can accelerate research, but they can’t replace scientific expertise or evidence-based reasoning. Without sufficient domain knowledge, it’s easy to oversee plausible-sounding hypotheses for scientifically valid conclusions.</p><h3>Irreversible Collapse</h3><p>Autonomous development has brought the repository to a state from which recovery is no longer practical, making a restart the best course of action. Why is that? Song and Cai have demonstrated the agent collapse in terms of physics-inspired formalisms (<a href="https://arxiv.org/html/2606.31399v2">https://arxiv.org/html/2606.31399v2</a>). Many systems remain stable until a critical point is reached, for example water boiling. Similarly, long-horizon agents may work well for many steps before a small increase in task complexity causes sudden failure. The agent may continue to reason fluently but its internal model of the world has collapsed.</p><p>A series of plausible-sounding instructions, inconsistencies has saturated the project states toward a “collapse floor”. The agent was acting from a corrupted internal “software” representation rather than making incorrect decisions. Implemented harnesses were not capable of detecting a structural project collapse due to focus on a surface action-selection error. The collapse state is a thermodynamic-like trap to unwind that requires a lot of energy (manual unwind and cherry pick agent action).</p><p>And so, we begin again — from scratch!</p><h3>Make It Convergable</h3><p>Building sufficient domain knowledge is the first action that unblocks autonomous development! Correct specifications and goal settings are prerequisites for success. I cannot put fruit flies under a microscope, but I can build a software. I built a few tools to study the problem domain. A brain inspector is a tool for “digital brain surgery”: for each neuron it draws a real position of the body cell, groups neurons by superclass, class or cell type, and visualizes synapses. Second one is a command line utility to probe custom brain cuts and compare them against the whole dataset, reporting coverage, paths, damaged area, trapped signal, readout and few more. Both help to study the brain structure, purpose and responsibility of neuron classes and simulate what-if scenarios. Being able to see and cut the graph is what has enabled me to define the semantic description of the dataset for agents and control the autonomous development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Bwt7vk3_7JagFhjxu-6tA.png" /></figure><p>The “big bang” approach has failed. I have replaced it with an iterative research engineering process where small, end-to-end experiments validate results, capture learning, and guide the next round of experimentation. Building microfly (<a href="https://github.com/fogfish/microfly">https://github.com/fogfish/microfly</a>) is a sequence of dependent experiments:</p><ol><li>random LIF neural network to establish unbiased baseline;</li><li>smallest functional brain consists of 11 neurones that can drive a fly;</li><li>add the receptor layer of the antennal lobe about 35 neurones that can smell food from a distance and walk toward it;</li><li>a forager brain of 3,408 neurones that represents a hungry creature with smell, taste and feeding;</li><li>a forager brain of 11,000 neurones including whole functional classes instead of ranked based selections;</li><li>implement 12 senses, 6 motor outputs at 14,500 neurone brain;</li><li>implement mushroom-body learning with plasticity.</li></ol><p>The prerequisites for every step are a specification about the experiments to conduct,e what was failed and rejected before; a configuration file defining the new brain; and a set of gates that had to be passed before proceeding to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MQAaRErwlpAjZ4pUN3tZeA.png" /></figure><p><strong>Each experiment built on the established learnings and successes of the previous one, creating a foundation for the next.</strong></p><p>Not every experiment succeeded. Several failed, each isolated in its own branch due strict acceptance criteria. This ensured that failures remained contained and never compromised the integrity of the main branch. Example of unsuccessful experiments:</p><ul><li>brain extraction to score interneurons by whether they sit on a functional path (e.g. taste-to-brake);</li><li>15K brains with new LIF architecture, experiment has changed eight things at once;</li><li>new methodology for brain calibration;</li><li>sensing pheromones, output songs and following social contacts.</li></ul><p>Acceptance gates made autonomous research possible. Brain calibration is one of the core elements in the processes. Calibration discovers parameters of neurons, voltage of synapses, everything that is missing from the original fly brain dataset. It is a deterministic process consisting of multiple phases: (a) evaluates excitation, inhibition and circuits transition; (b) brain only readouts; © smoke test, closed loop and candidate seeds for calibration; (d) held-out seeds against both null controls for the final verdict. A failed gate tells agents what’s wrong. Successful outcomes are protected by the hash of its brain file (by experiment), so agents fail to load instead of misbehaving quietly.</p><p>Building an autonomous loop requires a definition of invariants to control the development behaviour and tell agents what is wrong. The agent’s experimentation is now deliberately controlled: ask for the target brain configuration and the budget, launch the run, report what it found and move to the next one.</p><p>Seventeen days. 50 commits. 10 million tokens generated. $1200. Sonnet 5 running autonomous loops for 8–9 hours every night. Accomplished the research goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*niMtv3PIeL4Bz1mw2rSDPA.png" /></figure><p>Below are five lessons I’ve learned while developing microfly!</p><h3>Lesson 1: write the rules before the agent can break them</h3><p>The constitution is a reason why I am using speckit as backbone within my agentic loops, and it is the most valuable file in the repository. It is written before any code and specifies binding principles, which is hard to violate under the pressure.</p><p>An unconstrained instruction asking an agent to “make a fly look for food” can lead to reward hacking. It can hand-wire a synapse, flip a turn sign, add a hunger override in world code, or pick the readout neurons that happen to correlate with the answer. Each is the correct engineering solution but each destroys the scientific claim and purpose of the project.</p><p>microfly’s constitution blocks those moves explicitly: brains come from the dataset, behaviour comes from the brain, LIF core stays pure, see the full constitution in the repository. Agents.md also repeats references to them as binding principles and requires explicit amendment from the user to break one.</p><p>The constitution evolves with the research itself through amendment protocol. The amendment was proposed by the agent as an outcome of prior learnings and ratified by the human before any code used it. Each change into rules is a visible decision. Deciding is the humans’ job, not the agent’s.</p><p>The constitution also comes with the cost. You have to watch out for rules that block further progress and amend it.</p><h3>Lesson 2: put the reasoning in memory, not in the chat</h3><p>Every decision and learning that matters must land in persistent repository memory so that agents will recall it during the next session. Microfly has not used any specific” memory architecture” but few kinds of durable record produced for each experiment:</p><ul><li>Speckit specifications explain agents scope of each experiment, expected deliverables and what software components to build, what adjust. About 20 specifications was crafted;</li><li>ADR format is used to define the brain topology, rules of extractions, neuron classes and functional requirements. The project has evaluated 11 distinct brain configurations;</li><li>Defects and learnings from previous experiments is a mandatory outcome. It is recorded as amends to ADRs, as calibration report and as bug reports;</li><li>Contracts define the exact shape of the delivery: brain snapshot format, LIF protocol and parameters, world config, etc. Contracts are more crucial for agents. Agents working on the brain extractor do not recall a context of historical changes unless it is written down. Because of the contracts, the compatibility of brain configurations has been preserved across the entire lifecycle, and earlier versions of brains (mock, v0, v1) still work today.</li></ul><h3>Lesson 3: run the agent like a lab, not like a build</h3><p>Agents default goal “make it pass”. This is a wrong goal for research and scientific exploration. You have to establish a lab protocol in which a failed experiment is a valid and complete outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Px31-3ccw2ifOHO__zIg1w.png" /></figure><p>Microfly has three protocols.</p><p><strong>Prevent overfitting with distinct calibration and evaluation environments</strong>. The LIF neuron varies about 960 parameter combinations (e.g. synaptic scale, inhibitory scale, noise, adaptation, threshold jitter and stimulus). It creates an exponential search space, which is impossible to explore without metaheuristic, statistical, sequential, and numerical approaches. MicroFly used a naive randomized and grid search only as part of the inner calibration process due to the compute capacity limitations. The project uses random worlds for tuning (about 10 worlds) and judging (about 130 worlds) so that the accepted configuration shows best performance on the environment the tuning never saw. Without a judge there is a chance to pass the tuning phase by luck so that random noise pushes the fly toward food and steering neurons produce plausible signals. This has already happened in the project. Without the judging, it would have shipped as a working brain topology.</p><p><strong>Always run null hypothesis validation (the null arms)</strong>. The outcome of calibration is meaningful only next to a baseline. I used a null hypothesis. The brain topology doesn’t matter for the behaviour, as the baseline for each experiment. Every outcome configuration is evaluated against the two null arms: (1) random walk with the brain’s signals are switched off but same body, world, food and seeds; (2) size-matched random brain topology with a spiking network containing same number of neurons and edges, and the same weight distribution, as the target brain but wiring is random. Null hypothesis validation is the strongest claim of microfly. It controls agents to deliver honest fly behaviour and whether the brain beats chance on worlds it was not tuned on. If experiments fail the findings are recorded for the next one. I acknowledge that the choice of null hypothesis are themselves subject to debate, and that beating a baseline does not establish biological equivalence. In the context of MicroFly, it validates that the biological wiring contributes anything measurable beyond random walk. If the connectome brain cannot outperform these controls on previously unseen environments, there is no evidence that its biological structure provides a functional advantage. That is a perfectly valid experimental outcome, and one worth reporting.</p><p><strong>Behaviour failures are findings</strong>. The most dangerous is when agents quietly “solve the problem at any cost” whenever an experiment misses success metrics. Microfly is research with the main question: “what does a brain cut from the real connectome do?”. A metric like find rate or eating time is how to estimate the answer. An agent with a goal “make the eat gate pass” has many easy ways to “cheat”:</p><ul><li>Have the body layer keep the fly at the flower a few more ticks after contact;</li><li>Add a special case in the decoder when feed is above some value;</li><li>Add one synapse from a gustatory neuron to a feeding motor neuron;</li><li>Change the metric so that 1-tick bouts count.</li></ul><p>The established rules prevent agents from measuring and accepting the success of their own patches. For example, LIF neural network changes are protected, the change means “re-running full experiment at a different setting including null arm”. Every change needs evidence and outcome, the failure is a recorded outcome.</p><p>Who validates the validators? Gates itself is a software and needs testing. As an example, in one of the experiments 0 candidates passed, and the agent concluded the brain could not be calibrated. A root cause analysis later showed software error in the gate. After the fix, the same run has shown 45 passing candidates. Boehm’s Law in action! For agentic loops and autonomous development, the recommendation is direct: shift investments in tooling to control correctness of the results toward the earliest phases of research cycles, even when it looks unnecessary.</p><h3>Lesson 4: The failure modes that brought down entire experiment</h3><p>Experiments fail! It comes from agents’ ways of working: they are fast, they are precise, and they will build extensively on an unverified assumption. Below are common failures.</p><p><strong>Too many changes at once</strong>. In one turn agents produced 13.8K lines touching neuron admission, mushroom-body config, weight rule, edge threshold, input encoding, and output filters together. All tests passed but nothing works, and no failure could be pinned on any one change. With agents, the cost of writing code is near zero, so the size of a change is limited only by discipline. You have to limit it on purpose.</p><p><strong>Validate the validator before the experiment</strong>. The brain extraction had silently dropped about 22,000 traced neurons without a standard transmitter label, and with them every path through them. No calibration has been successful, only 14 % of the food steering signal came through. Later a bug in the connectivity audit routine was found. A cheap, static check and better testing of validators’ harness saves days.</p><p><strong>Patching an objective until it fits</strong>. Neuron selection was based on a scoring function. Each experiment was changing the scoring budget. One small change to a single rule over and over, until the brain’s topology overgrown a real structure and it has collapsed. Scoring-based selection was a mistake for this problem domain, the whole functional classes selection is a right approach. When an agent keeps adding knobs to one function, the function is the problem. I should watch out for the frequency of change per function.</p><p><strong>Searching for a regime that does not exist</strong>. Over two weeks, agents were searching for steering parameters with consistent outcome: too little forward drive, and 0% find rate against 30% for the random walk. Agents were making research conclusions “impossible seeding LIF parameters” and kept repeating the same mistake over and over. Agents will keep doing as long as you let them. Set a budget, and when it runs out, ask a different question.</p><p><strong>Amplifying in the wrong direction</strong>. While doing research, agents consume information from other publications. It opens a risk of misinterpretation. It was a reason why adoption of Kenyon Cells (insects memory) has failed. Agents assumed wrong LIF parameters, which led to saturated spike signals so that 92.5% of memory cells were firing after one input spike. Essentially the fly memory was damaged. The lesson is that agents need a context to interpret parameters and apply the right transformation of open research data into your current context.</p><p>What has helped is write the finding down, preserve unsuccessful experiments in its own isolated branch to let agents learn from disasters.</p><h3>Lesson 5: make what you learn reusable across sessions</h3><p>The research became significantly faster when the principles of transferable knowledge between sessions were incorporated into day to day work.</p><p><strong>Skills for repeated procedures</strong>. Agents were re-discovering the calibration protocol over and over again until it was instructed to create a skill for the brain calibration. After that it became a deterministic and regulated procedure with strict compute budget, and principles for promoting a result into the main branch.</p><p><strong>Agent memory for things outside of the code</strong>. The code says what is working but nothing says what went wrong unless you explicitly establish a memory for your agents. Each saves the next session from repeating a dead end. In this project the memory is short notes.</p><p><strong>One research note per experiment</strong>. The experiments start with the research phase that explains what was measured in the repository by previous experiments, what was recalled from literature and what requires a verification. This research note becomes an experiment plan that other agents can take over into the execution.</p><p>And the test for any of these principles is simple. A fresh session, given the repository and nothing else, should not repeat a mistake the project has already paid for.</p><p><strong>A playbook for agentic R&amp;D</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oK6iAeLH_ndD6VSAj0eHFg.png" /></figure><p>Every experiment runs the same loop. A failure is a valid exit: learnings are written down, the useful parts are ported, and the next experiment spec starts from the finding.</p><p>Before the first line of code:</p><ul><li>Write a constitution that names what counts as a result and which shortcuts would invalidate it.</li><li>Put the hard rules in the agent’s instruction file, with “amend, don’t work around”.</li><li>Define the null arms and split the seeds into calibration and held-out sets.</li></ul><p>For each experiment:</p><ul><li>Spec, then plan with a constitution check, then tasks. Amend the constitution first if the check blocks.</li><li>Change one thing. If a branch changes more than one variable of the experiment, split it.</li><li>Check the input and the instrument before the search: a static fidelity check, then a test of the gate itself.</li><li>Give every search a budget. When it runs out, write what was learned and change the question.</li><li>Take verdicts on held-out seeds only, next to the null arms.</li><li>Record failures as findings, with the run that shows them.</li><li>Port what is sound to main on its own branch; roll back the rest.</li></ul><p>Across sessions:</p><ul><li>Turn any procedure done twice into a skill with its own guardrails.</li><li>Save why things failed in memory, not what the code does.</li><li>Keep the person on every decision that trades scientific validity for a better number.</li></ul><p>The agents in this project wrote nearly all the code, the tests, the extraction and the analysis. The person wrote the rules, chose the questions, read the verdicts and decided when to stop. That division held for three weeks and 20 features. It is the main thing to copy.</p><h3>Limitations , Counterarguments, and Debate</h3><p>My approach of building MicroFly is not intended to establish a universal recipe for autonomous scientific discovery. It is an engineering approach to making exploratory research more reproducible, constrained, and experimentally accountable. Several aspects of this approach require a discussion, especially some of my assumptions are challenged in existing literature.</p><p><strong>Agentic loops do not guarantee monotonic improvement</strong>. An agentic research loop is not a learning loop in the strict sense. Iterations do not guarantee that an agent becomes more capable, more accurate, or more aligned with its original objectives. Research on agent drift highlights it: Agent Drift: Quantifying Behavioral Degradation in Multi-Agent LLM Systems Over Extended Interactions (<a href="https://arxiv.org/abs/2601.04170">https://arxiv.org/abs/2601.04170</a>). MicroFly treats iteration as an opportunity to generate and test hypotheses and preserve experimental history, not as a guarantee of cumulative intelligence.</p><p><strong>Incremental validation is a strategy, not a universal optimum</strong>. I prefer small, end-to-end experiments with measurable acceptance criteria over large monolithic development cycles. This makes failures easier to isolate and reduces the cost of discovering incorrect assumptions early. The cost of running an incremental research is lower and affordable. However, incremental approaches are not universally superior. Batch approaches can outperform incremental ones in particular circumstances: A Comparison of Batch and Incremental Supervised Learning Algorithms (<a href="https://link.springer.com/content/pdf/10.1007/BFb0094828.pdf">https://link.springer.com/content/pdf/10.1007/BFb0094828.pdf</a>).</p><p><strong>Written principles do not eliminate specification gaming</strong>. Defining binding principles before implementation is one way to constrain autonomous agents. Nevertheless, written specifications are not a complete defence against reward hacking or shortcut learning. There are numerous examples by DeepMind of agents exploiting the literal objectives (<a href="https://deepmind.google/blog/specification-gaming-the-flip-side-of-ai-ingenuity/">https://deepmind.google/blog/specification-gaming-the-flip-side-of-ai-ingenuity/</a>). Human review is not a solution. The research has shown that human review misses reward hacking 30–50% of the time: Reward Hacking Challenges Oversight of Autonomous Research Agents (<a href="https://arxiv.org/abs/2609.28614">https://arxiv.org/abs/2609.28614</a>). Independent evaluation, adversarial testing, and inspection of intermediate results remain important.</p><p><strong>Null hypothesis validation does not eliminate false positives</strong>. An inadequate control can produce misleading conclusions even when the statistical procedure is correctly implemented. See: Controlling the Control Condition: A Critical Methodological Review of Control Conditions in Experimental Management Research (<a href="https://journals.sagepub.com/doi/full/10.1177/01492063261424849">https://journals.sagepub.com/doi/full/10.1177/01492063261424849</a>). For this reason, MicroFly’s two null arms should be understood as complementary controls, not exhaustive proofs of biological validity. It only tests a claim: whether the target biological topology provides measurable functional value. Statistical significance, effect sizes, repeated trials, and evaluation on environments not used for calibration. It is an element for further research.</p><h3>Closing perspective</h3><p>None of these limitations invalidates the use of agentic loops for exploratory research. However, it challenges assumptions about autonomy, iteration, written constraints, or statistical controls are sufficient on their own to guarantee scientific progress.</p><p>MicroFly is an experiment by itself. It does not attempt to prove that autonomous agents can independently solve neuroscience, nor that translating a connectome into a spiking network will reproduce an insect’s behaviour. Instead, it provides a concrete environment in which hypotheses can be formulated, biological structures can be translated into executable models, and the resulting behaviour can be tested against explicit controls.</p><p>The objective is not to make autonomous research infallible. It is to make its mistakes observable, its claims falsifiable, and its progress measurable.</p><h3>References</h3><ol><li>MicroFly: <a href="https://github.com/fogfish/microfly">https://github.com/fogfish/microfly</a></li><li>A connectomics milestone: Mapping the complete male fruit fly brain. <a href="https://research.google/blog/a-connectomics-milestone-mapping-the-complete-male-fruit-fly-brain/">https://research.google/blog/a-connectomics-milestone-mapping-the-complete-male-fruit-fly-brain/</a></li><li>Braitenberg Vehicles as Computational Tools for Research in Neuroscience. <a href="https://pubmed.ncbi.nlm.nih.gov/33042967/">https://pubmed.ncbi.nlm.nih.gov/33042967/</a></li><li>Boehm’s Law <a href="https://thinkinsights.net/digital-transformation/boehms-law">https://thinkinsights.net/digital-transformation/boehms-law</a></li><li>An Optimization Framework for Automated Assessment of Biological Plausibility of Spiking Neurons. <a href="https://arxiv.org/abs/2606.17853">https://arxiv.org/abs/2606.17853</a></li><li>The Effect of Statistical Hypothesis Testing on Machine Learning Model Selection. <a href="https://link.springer.com/chapter/10.1007/978-3-031-45389-2_28">https://link.springer.com/chapter/10.1007/978-3-031-45389-2_28</a></li><li>Agent Drift: Quantifying Behavioral Degradation in Multi-Agent LLM Systems Over Extended Interactions. <a href="https://arxiv.org/abs/2601.04170">https://arxiv.org/abs/2601.04170</a></li><li>Specification gaming: the flip side of AI ingenuity. <a href="https://deepmind.google/blog/specification-gaming-the-flip-side-of-ai-ingenuity/">https://deepmind.google/blog/specification-gaming-the-flip-side-of-ai-ingenuity/</a></li><li>Reward Hacking Challenges Oversight of Autonomous Research Agents.<a href="https://arxiv.org/abs/2609.28614">https://arxiv.org/abs/2609.28614</a></li><li>Controlling the Control Condition: A Critical Methodological Review of Control Conditions in Experimental Management Research. <a href="https://journals.sagepub.com/doi/full/10.1177/01492063261424849">https://journals.sagepub.com/doi/full/10.1177/01492063261424849</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a212f96b82a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASOS Data Breach & Snowflake Infrastructure Compromise: Investigative Report]]></title>
            <link>https://medium.com/@dmkolesnikov/asos-data-breach-snowflake-infrastructure-compromise-investigative-report-06bd8b75df6b?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/06bd8b75df6b</guid>
            <category><![CDATA[news]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[infosec]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Wed, 07 Oct 2026 09:11:36 GMT</pubDate>
            <atom:updated>2026-10-07T09:11:36.313Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>October 6, 2026 | Evidence-Graded Analysis</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pBF_nJhrf0_1MFH1" /><figcaption>Photo by <a href="https://unsplash.com/@tar1k?utm_source=medium&amp;utm_medium=referral">Tarik Haiga</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Executive Summary</strong></h3><p>On October 6, 2026, ASOS plc — one of Europe’s largest online fashion retailers with approximately 16.5 million active customers — experienced a confirmed security incident in which an unauthorized push notification was delivered to customers through the company’s official mobile application [1][2][3]. The notification, attributed to a previously unknown threat group operating a Telegram channel called “Xuanye Wen Gateway,” read verbatim: <em>”Dear ASOS DPO and IT, we have fully compromised the Snowflake instance. Engage with us, or we will leak it”</em> [4][5].</p><p>The incident is <strong>partially confirmed and partially unverified</strong>. What is definitively established: ASOS’s push notification delivery infrastructure was compromised; unauthorized communications reached customers via official ASOS app channels; ASOS’s shares on the London Stock Exchange fell approximately 10–14% on the day [6][7]; and the UK National Cyber Security Centre (NCSC) published an advisory confirming that “basic personal information including name and contact details may have been accessed” [8]. What remains unverified: the threat actor’s central claim of Snowflake environment access, the root cause of the notification infrastructure compromise, and the full scope of any customer data exfiltration [9][10].</p><p>The incident does not represent a novel attack methodology. Its technical architecture — credential-based access to cloud-connected infrastructure — follows the well-documented pattern of the 2024 Snowflake credential-stuffing campaign that affected over 160 organizations globally [11]. What is notable is the <em>tactical innovation</em>: the deliberate weaponization of ASOS’s own customer communication infrastructure to deliver an extortion demand to millions of users simultaneously, forcing public disclosure before any corporate or regulatory notification process could be managed [5][12]. This tactic is rare in published incident records and represents a meaningful escalation in threat actor pressure tactics against enterprise targets.</p><p>The incident must also be contextualized against a prior ASOS security event: in July 2026, ASOS US Sales LLC disclosed a credential-stuffing attack affecting 138,828 US customers [13]. Whether these two incidents are linked remains unresolved.</p><h3><strong>Current State of the Art</strong></h3><p>The compromise of cloud data warehouse environments via stolen credentials has been the defining enterprise security failure pattern of the mid-2020s. The 2024 discovery of the UNC5537 campaign — in which threat actors used infostealer-harvested credentials to authenticate directly into Snowflake customer tenants lacking multi-factor authentication (MFA) — established the foundational threat model against which the ASOS October 2026 incident must be assessed [11][14].</p><p>By 2026, the cloud security industry had broadly converged on a set of remediation controls specifically responding to the 2024 Snowflake campaign: mandatory MFA enforcement, IP allowlisting via Snowflake’s network policy controls, credential rotation following infostealer marketplace monitoring, and elimination of single-factor service accounts with broad data access privileges [15][16]. Snowflake itself began rolling out administrator-enforceable MFA requirements in the post-2024 period [17]. The question of whether ASOS had implemented these controls for its Snowflake instance — if it operated one — remains publicly unanswered and constitutes the most consequential unresolved technical question in this investigation [4].</p><p>Simultaneously, the mobile push notification delivery ecosystem — dominated by Apple Push Notification Service (APNs) and Google Firebase Cloud Messaging (FCM) — had become an increasingly attractive attack surface. Malwarebytes reporting identified that ASOS utilized <strong>Braze</strong> as its customer engagement and push notification platform, alongside <strong>Simon AI</strong> for marketing personalization [12]. Simon AI, critically, runs on Snowflake infrastructure [5]. This architectural detail — identified by Malwarebytes researcher Pieter Arntz — introduced a significant reframing: the “Snowflake instance” referenced in the threat actor’s notification may not refer to a self-managed ASOS Snowflake deployment, but rather to Simon AI’s Snowflake environment, which ASOS uses as a third-party marketing data layer [5]. This distinction has profound implications for regulatory liability attribution and root cause analysis.</p><p>The broader retail sector threat landscape in 2026 reflected continued exposure to credential-based attacks. The North Face credential-stuffing incident (2026) and ongoing infostealer marketplace activity — with Lumma, Vidar, and RedLine variants actively harvesting cloud service credentials — maintained pressure on large-scale e-commerce platforms holding high-value customer profiles [11][14]. ASOS’s specific profile — storing delivery addresses, purchase histories, partial payment data, and body measurement data for its fit technology features — makes its customer database a particularly high-value target for downstream account takeover (ATO) fraud [13].</p><p>— -</p><h3><strong>Technical Breakdown</strong></h3><h4><strong>The Push Notification Compromise: What Is Confirmed</strong></h4><p>The most forensically certain element of this incident is the delivery mechanism. Push notifications began appearing on customer devices at approximately 5:00 a.m. ET on October 6, 2026, transmitted through the <em>*official ASOS mobile application*</em> on iOS and Android platforms [1][5]. This is not a spoofed notification, an SMS phishing message, or a social media impersonation — it is a notification authenticated as originating from ASOS’s own infrastructure and delivered through the same channel that ASOS uses for promotional and transactional communications [2][8].</p><p>The significance of this confirmation cannot be understated. As The Standard reported: “Sending a push notification to ASOS’s app users would require access to the company’s notification system, which is separate from the Snowflake data platform the attackers claim to have compromised” [18]. This architectural separation — confirmed by the source — means that demonstrating access to push notification infrastructure does not, by itself, confirm access to Snowflake, and vice versa [18].</p><p>For a threat actor to deliver notifications via the official ASOS app channel, they would need one of the following access types [12][9]:</p><p>- <strong>Braze API key compromise</strong>: Braze is ASOS’s identified notification delivery platform; an exposed or stolen Braze API key would enable direct notification dispatch.</p><p>- <strong>FCM/APNs service credential theft</strong>: Compromise of the underlying push delivery service credentials.</p><p>- <strong>Backend service account access</strong>: Compromise of a service account with privileges to invoke ASOS’s notification delivery endpoints.</p><p>- <strong>Shared secrets management platform breach</strong>: If Braze credentials, Snowflake credentials, and other service keys were stored in a common secrets vault (e.g., HashiCorp Vault, AWS Secrets Manager), a single upstream compromise could theoretically yield access to multiple systems simultaneously [9].</p><p>The Rescana analysis assessed that the most probable mechanism was “compromised credentials or abuse of privileged API keys associated with either the notification system or the Snowflake environment” [9].</p><h4><strong>The Snowflake Claim: Architecture and Evidence Status</strong></h4><p>The threat actor’s notification claimed “full compromise” of ASOS’s Snowflake instance [1][4]. The forensic picture here is more complex and less resolved.</p><p>Snowflake’s security model operates on a shared responsibility framework: Snowflake as a platform provides the infrastructure, encryption at rest and in transit, and since mid-2024, administrator-enforceable MFA controls [17]. Customer-side responsibility covers MFA enforcement, network policy configuration (IP allowlisting), credential management, and role-based access control (RBAC) granularity [15][16]. The 2024 UNC5537 campaign — which compromised accounts at Ticketmaster, Santander, AT&amp;T, LendingTree, and over 160 other organizations — exploited precisely the customer-side gaps: specifically, Snowflake tenants where single-factor authentication remained active and credentials had been harvested by infostealer malware (Lumma, Vidar, RedLine) from infected employee or contractor devices [11][14].</p><p>Forensic investigations of the 2024 campaign confirmed that “the root cause was credential theft via infostealer malware infections on customer-managed devices combined with the absence of MFA enforcement on customer Snowflake accounts” [14]. Some of the harvested credentials dated as far back as 2020, having been sitting in criminal marketplaces for years before being weaponized [16].</p><p>The critical architectural nuance identified in the Infosecurity Magazine analysis changes the attribution landscape for the October 2026 ASOS incident: if the Snowflake environment in question belongs to <strong>**Simon AI**</strong> (ASOS’s marketing platform, which runs on Snowflake) rather than to a directly ASOS-administered Snowflake tenant, then the breach — if confirmed — would be a <strong>**supply chain compromise**</strong> rather than a direct infrastructure compromise [5]. In this scenario, the threat actor would have compromised a vendor’s cloud data environment that happened to contain ASOS customer marketing data. This is materially different from the claim as popularly understood, and it shifts regulatory liability, remediation responsibility, and the applicable threat model.</p><p>As of the evidence available, Snowflake denied involvement [10], ASOS did not confirm Snowflake access [2][3], and no independent security researcher published forensic evidence of data exfiltration from any Snowflake environment associated with ASOS [4][9].</p><p><strong>Evidence Grade — Snowflake Compromise Claim: [UNVERIFIED — Threat Actor Claim Only; Contested by Snowflake; Unconfirmed by ASOS]</strong></p><h4><strong>Prior Incident Context: July 2026 Credential Stuffing</strong></h4><p>On July 28, 2026, ASOS US Sales LLC detected unauthorized access to approximately 138,828 US customer accounts via credential stuffing — the use of credentials “obtained from outside the company” to authenticate to ASOS customer accounts [13]. ASOS notified affected customers on July 30 and disclosed the incident publicly by August 25, 2026 [13]. This incident followed an established pattern of retail-sector credential stuffing attacks and was attributed to external credential availability rather than any ASOS system vulnerability.</p><p>The relationship between the July 2026 credential-stuffing incident and the October 6, 2026 notification compromise is <strong>**unresolved**</strong> [9]. ASOS issued no statement linking the two. The July incident affected customer-facing accounts via credential stuffing; the October incident affected backend notification infrastructure. These are distinct attack surfaces. However, it is technically plausible that the same threat actor (or a different actor using the same credential markets) could have escalated from customer account takeover to service infrastructure compromise over the intervening weeks.</p><p><strong>Evidence Grade — Relationship Between July and October Incidents: [INCONCLUSIVE — Insufficient Linking Evidence]</strong></p><p>— -</p><h3><strong>Critical Analysis &amp; Novelty</strong></h3><h4><strong>Established Elements</strong></h4><p>The following components of the October 2026 ASOS incident represent well-documented, precedented threat patterns with no novel technical elements:</p><p><strong>1. Credential-Based Cloud Infrastructure Compromise</strong></p><p>The attack pattern alleged — credential theft enabling direct authentication to a cloud data environment — is the defining threat modality of the 2024 Snowflake campaign and has been exhaustively documented [11][14][16]. If the ASOS Snowflake claim is eventually confirmed, it would represent institutional failure to implement post-2024 remediation guidance (specifically MFA enforcement and network policy restrictions) rather than any novel exploitation technique.</p><p><strong>2. Infostealer Ecosystem as Credential Source</strong></p><p>The criminal marketplace ecosystem for infostealer-harvested credentials (Lumma, Vidar, RedLine) remained active throughout 2025–2026 [11][14]. ASOS credentials from prior infostealer infections — including potentially those behind the July 2026 credential-stuffing attack — could plausibly have been available for purchase and reuse against ASOS service accounts. This is a documented, established risk pathway [14][16].</p><p><strong>3. Push Notification API Key Exposure</strong></p><p>API key theft enabling unauthorized push notification delivery is a documented attack surface. Firebase Cloud Messaging API key exposures (through public code repositories, misconfigured environment files, or credential theft) have been reported across multiple incidents. The mechanism is established; ASOS’s specific configuration failure is not yet identified.</p><p><strong>4. Multi-Vector Retail Attack Pattern</strong></p><p>The sequential exposure of a major retailer to credential stuffing (July 2026) followed by infrastructure compromise (October 2026) follows a documented pattern in which initial customer-account-level credential theft precedes escalation to higher-privilege service account compromise [9][11].</p><h3><strong>The Innovation Gap</strong></h3><h4><strong>Tactical Innovation — Customer Channel as Extortion Vector</strong></h4><p>The genuinely novel element of this incident is not the breach mechanism but the extortion tactic: using the victim organization’s own customer communication infrastructure to deliver an extortion demand to millions of end users simultaneously [1][5][12]. This converts what would typically be a contained, privately negotiated extortion event (a threat actor contacting ASOS’s security team via email or dark web forum) into an immediate, public, irreversible disclosure event.</p><p>Prior published incident records document API key theft enabling notification spam [9]. What is uncommon — and constitutes a meaningful innovation in threat actor pressure tactics — is the deliberate crafting of a message addressed to ASOS’s DPO and IT team, delivered <em>*through the customer app channel*</em>, forcing ASOS into reactive public disclosure before any controlled notification or investigation timeline could be established [5][12]. ESET’s Global Cybersecurity Advisor Jake Moore assessed that if fully confirmed, this approach could make it “one of the most visible hacks in history” [5].</p><h4><strong>Forced Disclosure Inversion</strong></h4><p>The standard breach lifecycle runs: discovery → internal investigation → regulatory notification (72-hour ICO clock) → public disclosure → customer notification. The October 2026 ASOS incident inverted this entirely: customer notification occurred first (via the threat actor), forcing public disclosure, triggering media coverage, and compelling ASOS to issue a reactive corporate statement — all before any regulatory filing or investigation completion [5][18]. This represents a threat actor tactic that materially undermines corporate incident response frameworks and is unusual in published breach records.</p><h4><strong>Possible Supply Chain Dimension</strong></h4><p>If the Simon AI (Snowflake-hosted) vector is confirmed, this incident would represent a third-party marketing platform supply chain compromise that manifested through the client’s (ASOS’s) customer infrastructure. The technical chain — vendor’s cloud environment → client’s customer communication channel → end-user extortion — is not widely documented and may represent an emerging attack pattern targeting the increasingly complex MarTech stack of large e-commerce platforms [5].</p><p>— -</p><h3><strong>Risks</strong></h3><h4><strong>Risk 1: The Snowflake Claim May Be Fabricated or Inflated</strong></h4><p>Threat actor claims against major consumer brands are frequently exaggerated, recycled from prior breaches repackaged as new, or fabricated entirely for criminal marketplace credibility [9]. The “Xuanye Wen Gateway” group has no documented prior history in any published threat intelligence database, MITRE ATT&amp;CK attribution, Mandiant reporting, or CrowdStrike intelligence [4][9]. An attacker who successfully accessed only push notification infrastructure — a significant but limited breach — has obvious incentive to claim broader Snowflake access as a pressure amplification tactic. The absence of any proof-of-hack data (customer record samples, Snowflake query evidence, or data marketplace listings) from this group materially undermines their claim’s credibility [9].</p><p><strong>**Evidence Grade: [UNVERIFIED — Claim Credibility Low; No Independent Corroboration]**</strong></p><h4><strong>Risk 2: Regulatory Non-Compliance Exposure</strong></h4><p>Under UK GDPR Article 33, ASOS is required to notify the ICO within 72 hours of <em>*becoming aware*</em> of a notifiable breach [19][20]. The unauthorized notification was sent at approximately 10:00 BST on October 6, 2026 [3][8]. The 72-hour clock therefore began running no later than that moment — establishing a filing deadline of approximately October 9, 2026 [10][20]. Whether ASOS met this deadline is not publicly documented. If it did not, the ICO has authority to impose fines of up to £17.5 million (UK equivalent) or 4% of global annual revenue [20]. Precedent ICO enforcement actions — the £20 million British Airways fine (2020) and the £18.4 million Marriott fine (2020), both involving compromised customer credentials — establish a credible enforcement baseline [9].</p><p>A further complication arises under UK GDPR Article 34: if the breach is likely to result in “high risk to the rights and freedoms of individuals,” ASOS must notify affected customers directly without undue delay [20]. ASOS’s customer care page as of October 6 instructed customers to disregard the unauthorized notification but did not constitute a formal breach notification email [2][8]. Whether a mass customer notification was subsequently issued is not confirmed in available evidence.</p><p><strong>**Evidence Grade: [CONFIRMED OBLIGATION — Compliance Status Unverified]**</strong></p><h4><strong>Risk 3: Misattribution of the “Snowflake” Vector</strong></h4><p>A significant risk in public reporting of this incident is the conflation of “ASOS’s Snowflake instance was hacked” with “Snowflake (the platform) was hacked” — precisely the misattribution that occurred during the 2024 UNC5537 campaign, where initial reporting incorrectly characterized Snowflake itself as having a platform vulnerability [11][14][16]. In the 2024 case, Snowflake was not breached at the platform level; the breaches occurred because individual customer tenants lacked MFA [11][14].</p><p>The Simon AI architectural detail compounds this risk: if the compromised environment belongs to a vendor (Simon AI) rather than ASOS directly, regulatory, legal, and reputational attribution must be carefully disaggregated [5]. Conflating these systems produces inaccurate risk assessments for both ASOS customers and the broader industry.</p><p><strong>**Evidence Grade: [CONFIRMED RISK — Misattribution Actively Occurring in Public Reporting]**</strong></p><h4><strong>Risk 4: Serial Targeting and Exhausted Credential Rotation</strong></h4><p>The occurrence of two separate credential-based attacks against ASOS within a nine-week window (July 28 and October 6, 2026) raises the possibility that ASOS’s post-July remediation was incomplete [13][9]. If ASOS failed to conduct comprehensive credential rotation, infostealer marketplace monitoring, or service account auditing following the July incident, threat actors with existing access to ASOS-related credentials may have retained the ability to escalate to service infrastructure [9]. This risk is not confirmed but is technically coherent given the timeline.</p><h4><strong>Risk 5: The “ASOS Silence = Confirmation” Fallacy</strong></h4><p>In the absence of complete ASOS disclosure, there is a documented risk of journalistic and analytical inference treating corporate non-confirmation as tacit acknowledgment of the threat actor’s broader claims. ASOS’s silence on Snowflake access specifically could reflect: active legal reasons for non-disclosure during investigation; a determination that the Snowflake claim is false and warrants no dignifying response; or ongoing forensic work precluding definitive statement [9]. ASOS’s conditional language (“may have been accessed”) must be read as a floor, not a ceiling, and should not be extrapolated to confirm claims ASOS has not made [1][2][3].</p><h4><strong>Risk 6: Consumer Downstream Harm Potential</strong></h4><p>Even if the breach is limited to “names and contact details” as ASOS currently characterizes it, the combination of this data with ASOS’s known data profile (delivery addresses, purchase histories, body measurement data) creates meaningful identity theft and targeted phishing risk for affected customers [2][8]. ASOS accounts are well-documented targets for ATO fraud given stored payment methods and the high resale value of fashion accounts on criminal marketplaces [13]. The downstream harm potential from even limited PII exposure should not be minimized by ASOS’s preliminary characterization.</p><p>— -</p><h3><strong>Chronological Development</strong></h3><p>The events leading to the October 2026 ASOS incident do not begin in October 2026. Their roots lie in a threat pattern established two years earlier.</p><p><strong>**May 2024: The UNC5537 Foundation.**</strong> Snowflake disclosed that it had become aware of potentially unauthorized access to certain customer accounts [16]. A joint investigation by Mandiant and Snowflake identified the threat actor group UNC5537, which had been systematically using infostealer-harvested credentials — some dating to 2020 — to authenticate directly into Snowflake customer tenants that lacked MFA [11][16]. The campaign ultimately affected over 160 organizations including Ticketmaster, Santander, AT&amp;T, and LendingTree [11][14], exposing over 100 million customer records. Critically, Snowflake’s platform itself was not breached; the failure resided entirely in customer-side security configuration [11][14][16].</p><p><strong>**2024–2025: Remediation and Institutionalization.**</strong> Following the UNC5537 disclosures, Snowflake began rolling out administrator-enforceable MFA controls [17]. The cybersecurity industry broadly published post-incident guidance emphasizing MFA enforcement, network policy IP allowlisting, and infostealer credential monitoring as the minimum necessary controls for Snowflake customer tenants [15][16]. Connor Riley Moucka, the individual linked to the UNC5537 campaign, was subsequently arrested and pleaded guilty in August 2026 [4]. The prosecution established a known, punished threat precedent — though it did not eliminate the underlying threat methodology, which remains operational across multiple successor actors.</p><p><strong>**July 28, 2026: The ASOS Precursor.**</strong> ASOS US Sales LLC detected unauthorized access to customer accounts via credential stuffing, affecting 138,828 US customers [13]. The credentials used were characterized as “obtained from outside the company” — consistent with infostealer marketplace sourcing [13]. ASOS notified affected customers on July 30 and made a broader disclosure by August 25 [13]. This incident, while disclosed, should have served as a direct signal to ASOS leadership that threat actors possessed ASOS-related credentials and had demonstrated willingness to deploy them.</p><p><strong>**October 6, 2026, ~10:00 BST: The Incident.**</strong> Customers across ASOS’s global user base began receiving push notifications through the official ASOS app [1][3][8]. The notification’s content — addressed to ASOS’s DPO and IT personnel rather than customers — made clear this was a threat actor extortion communication delivered via a captured corporate communication channel [1][4][5]. ASOS’s share price immediately responded, declining approximately 10–12% within the trading session [6][7].</p><p><strong>**October 6, 2026, ~16:15 BST: Corporate Response.**</strong> ASOS issued a formal statement via the London Stock Exchange Regulatory News Service (RNS), confirming “unauthorised customer notification” and “unauthorised activity involving third-party platforms” [3]. The NCSC published a parallel advisory [8]. The five-plus hour gap between incident manifestation and formal corporate statement was noted by security researchers as operationally slow given that the incident was already publicly visible to millions of customers [5].</p><p><strong>**October 7, 2026: Snowflake Denial and GDPR Clock.**</strong> Shattered.io reported that Snowflake denied involvement in the attack, beginning the regulatory commentary around ASOS’s UK GDPR 72-hour notification obligation [10]. The relationship between the July and October incidents, the root cause of the notification infrastructure compromise, and the scope of any Snowflake data access remained unresolved at this stage [9][10].</p><p>— -</p><h3><strong>Conclusion</strong></h3><p>The ASOS incident of October 6, 2026, is a <strong>**confirmed security breach of limited scope with unverified claims of broader compromise**</strong>. The core facts are not in dispute: ASOS’s push notification infrastructure was accessed without authorization; a threatening extortion notification reached customers through official ASOS app channels; basic personal information may have been exposed; and the incident triggered NCSC advisory publication, a 10–14% share price decline, and mandatory UK GDPR reporting obligations [1][2][3][6][7][8].</p><p>What remains materially unresolved — and what constitutes the investigative frontier — is the truth of the threat actor’s claim of Snowflake environment access [9][10]. The distinction matters enormously: a notification infrastructure compromise (Braze API key theft) represents a serious but bounded incident. A confirmed Snowflake data warehouse compromise, potentially via Simon AI’s Snowflake-hosted marketing environment, would represent a supply chain breach potentially exposing the full marketing data profile of ASOS’s 16.5 million customers [5][9] — triggering a substantially different regulatory, legal, and consumer harm response.</p><p>The threat actor group “Xuanye Wen Gateway” has no documented prior history, provided no proof-of-hack data, and made claims contested by Snowflake [9][10]. On established threat intelligence credibility frameworks, these are signals of low-confidence attribution. The most forensically coherent explanation for available evidence remains: credential-based access to ASOS’s notification delivery infrastructure (most probably via Braze API key compromise), combined with an unverified — and possibly false — claim of Snowflake access as an extortion amplification tactic [12][9].</p><p>The broader industry implication is clear regardless of how the Snowflake question resolves. If Snowflake access is confirmed, it represents a major enterprise’s failure to implement MFA and credential hygiene controls that were explicitly recommended following the 2024 UNC5537 campaign [11][14][16] — a failure occurring on an accelerated timeline given that ASOS had already experienced credential-stuffing attacks in July 2026 [13]. If Snowflake access is not confirmed, the incident demonstrates that threat actors can create devastating reputational, regulatory, and market consequences for major enterprises using nothing more than a single compromised API key and a tactically sophisticated extortion message — a finding with profound implications for how enterprises manage third-party marketing platform credential security.</p><p>The most urgent outstanding questions for regulators, ASOS, and affected customers are: whether ASOS has filed its ICO breach notification within the 72-hour window; whether forensic investigation has confirmed or excluded Snowflake access; and whether the July 2026 and October 2026 incidents share a common threat actor — questions that public evidence, as of the available record, cannot yet answer.</p><p>— -</p><h3><strong>References</strong></h3><p>[1] BleepingComputer: ASOS confirms data breach after “HACKED” in-app notifications — <a href="https://www.bleepingcomputer.com/news/security/asos-confirms-data-breach-after-hacked-in-app-notifications/">https://www.bleepingcomputer.com/news/security/asos-confirms-data-breach-after-hacked-in-app-notifications/</a></p><p>[2] The Guardian: Asos warns customer data may be compromised after ‘unauthorised’ app notification — <a href="https://www.theguardian.com/business/2026/oct/06/asos-hack-notification-website-app">https://www.theguardian.com/business/2026/oct/06/asos-hack-notification-website-app</a></p><p>[3] London Stock Exchange RNS: Update Regarding Cyber Incident (ASOS plc) — <a href="https://www.londonstockexchange.com/news-article/ASC/update-regarding-cyber-incident/17822931">https://www.londonstockexchange.com/news-article/ASC/update-regarding-cyber-incident/17822931</a></p><p>[4] The Register: Asos app delivers a data leak threat instead of fast fashion — <a href="https://www.theregister.com/security/2026/10/06/asos-app-delivers-a-data-leak-threat-instead-of-fast-fashion/5301332">https://www.theregister.com/security/2026/10/06/asos-app-delivers-a-data-leak-threat-instead-of-fast-fashion/5301332</a></p><p>[5] Infosecurity Magazine: ASOS Customers Sent “Hacked” Message Amid Suspected Snowflake Breach — <a href="https://www.infosecurity-magazine.com/news/asos-customers-message-suspected/">https://www.infosecurity-magazine.com/news/asos-customers-message-suspected/</a></p><p>[6] Reuters: ASOS shares slide after hackers target online retailer — <a href="https://www.reuters.com/business/retail-consumer/uk-online-retailer-asos-shares-drop-hack-reports-2026-10-06/">https://www.reuters.com/business/retail-consumer/uk-online-retailer-asos-shares-drop-hack-reports-2026-10-06/</a></p><p>[7] The Guardian: Asos shares dive more than 14% following hack reports — <a href="https://www.theguardian.com/business/2026/oct/06/asos-hack-notification-website-app">https://www.theguardian.com/business/2026/oct/06/asos-hack-notification-website-app</a></p><p>[8] NCSC (National Cyber Security Centre): Incident affecting ASOS customers — <a href="https://www.ncsc.gov.uk/news/incident-affecting-asos-customers">https://www.ncsc.gov.uk/news/incident-affecting-asos-customers</a></p><p>[9] Rescana: ASOS Snowflake Cloud Breach: Cybersecurity Incident Analysis of Push Notification Extortion Attack — <a href="https://www.rescana.com/post/asos-snowflake-cloud-breach-cybersecurity-incident-analysis-of-push-notification-extortion-attack">https://www.rescana.com/post/asos-snowflake-cloud-breach-cybersecurity-incident-analysis-of-push-notification-extortion-attack</a></p><p>[10] Shattered.io: ASOS Breach GDPR 72 Hour Clock as Snowflake Denies Hack — <a href="https://shattered.io/asos-breach-gdpr-72-hour-clock-snowflake-denial-2026/">https://shattered.io/asos-breach-gdpr-72-hour-clock-snowflake-denial-2026/</a></p><p>[11] Huntress: Snowflake Data Breach — What Happened, Impact and Lessons — <a href="https://www.huntress.com/threat-library/data-breach/snowflake-data-breach">https://www.huntress.com/threat-library/data-breach/snowflake-data-breach</a></p><p>[12] Malwarebytes: ASOS Hackers Send Push Notifications To Customers — <a href="https://www.malwarebytes.com/blog/news/2026/10/asos-hackers-send-push-notifications-to-customers">https://www.malwarebytes.com/blog/news/2026/10/asos-hackers-send-push-notifications-to-customers</a></p><p>[13] eSecurity Planet: ASOS Account Takeover Attack Exposes Data of 138,828 Customers — <a href="https://www.esecurityplanet.com/threats/news-asos-account-takeover-138828-customers/">https://www.esecurityplanet.com/threats/news-asos-account-takeover-138828-customers/</a></p><p>[14] Rescana: Snowflake Data Breach Analysis — Credential-Based Cloud Intrusion Exposes Over 100 Million Records — <a href="https://www.rescana.com/post/snowflake-data-breach-analysis-credential-based-cloud-intrusion-exposes-over-100-million-records-2024-2026">https://www.rescana.com/post/snowflake-data-breach-analysis-credential-based-cloud-intrusion-exposes-over-100-million-records-2024-2026</a></p><p>[15] Cloud Security Wire: Snowflake Data Security: Access Control Misconfiguration &amp; Credential Theft — <a href="https://cloudsecuritywire.com/articles/snowflake-data-security-access-control-misconfiguration-credential-theft-2026/">https://cloudsecuritywire.com/articles/snowflake-data-security-access-control-misconfiguration-credential-theft-2026/</a></p><p>[16] InfoSecurity Europe: Stolen Credentials Fuel Snowflake Data Breaches — Lessons Learned — <a href="https://www.infosecurityeurope.com/en-gb/blog/threat-vectors/snowflake-data-breaches-lessons-learned.html">https://www.infosecurityeurope.com/en-gb/blog/threat-vectors/snowflake-data-breaches-lessons-learned.html</a></p><p>[17] Snowflake Documentation: Multi-factor Authentication (MFA) — <a href="https://docs.snowflake.com/en/user-guide/security-mfa">https://docs.snowflake.com/en/user-guide/security-mfa</a></p><p>[18] The Standard: ASOS issues update after customers sent hacked notification — LIVE — <a href="https://www.standard.co.uk/news/uk/asos-hacked-alert-customers-app-snowflake-compromised-b1299696.html">https://www.standard.co.uk/news/uk/asos-hacked-alert-customers-app-snowflake-compromised-b1299696.html</a></p><p>[19] ASOS Official Customer Care Page: Unauthorised ASOS Notification — <a href="https://www.asos.com/customer-care/engagement/unauthorised-asos-notification/">https://www.asos.com/customer-care/engagement/unauthorised-asos-notification/</a></p><p>[20] UK Information Commissioner’s Office: Personal Data Breaches — A Guide — <a href="https://ico.org.uk/for-organisations/report-a-breach/personal-data-breach/personal-data-breaches-a-guide/">https://ico.org.uk/for-organisations/report-a-breach/personal-data-breach/personal-data-breaches-a-guide/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06bd8b75df6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The “Claude Broke AES” Claim: A Forensic Analysis of AI-Assisted Cryptanalysis and the State of AES…]]></title>
            <link>https://medium.com/@dmkolesnikov/the-claude-broke-aes-claim-a-forensic-analysis-of-ai-assisted-cryptanalysis-and-the-state-of-aes-1bb8e082a8b1?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bb8e082a8b1</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 16:08:34 GMT</pubDate>
            <atom:updated>2026-08-11T16:08:34.659Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>The “Claude Broke AES” Claim: A Forensic Analysis of AI-Assisted Cryptanalysis and the State of AES Security</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1z2mEA-jHp5b3PgZ" /><figcaption>Photo by <a href="https://unsplash.com/@boliviainteligente?utm_source=medium&amp;utm_medium=referral">BoliviaInteligente</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><em>Disclaimer: This article is based on notes from my knowledge graph. The final touches and editorial changes are made by autonomous systems.</em></p><p><em>If you’re interested in learning more about the process, feel free to send me a direct message.</em></p><p><strong>The claim that “Anthropic, Claude, or an entity called ‘Mythos’ broke AES encryption” is false as a characterization of any production cryptographic system.</strong> This finding is not hedged. It is the primary conclusion of this analysis and must appear first.</p><p>In July 2026, Anthropic published research demonstrating that its frontier model <strong>Claude Mythos Preview</strong> — a restricted-access AI system, not a separate organization — autonomously improved a theoretical attack on <strong>7-round AES</strong>, a deliberately weakened academic variant of the cipher that bears no operational relationship to the full 10/12/14-round AES-128/192/256 mandated by NIST FIPS 197 [1]. The same model produced a more significant result: a key-recovery attack on <strong>HAWK</strong>, a third-round NIST post-quantum signature candidate, which subsequently withdrew from standardization [2][3]. Neither finding threatens deployed encryption infrastructure.</p><p>The narrative collapse from “improved attack on reduced-round AES” to “Claude broke AES” is a textbook case of semantic compression in science journalism, amplified by social media dynamics and the inherent ambiguity of AI capability claims. The underlying research is real, narrowly scoped, and academically noteworthy. The headlines attached to it are materially misleading.</p><p>The broader landscape this incident reveals is significant: AI-assisted cryptanalysis is a genuine and accelerating field, the theoretical attack surface of AES remains marginal but non-zero (with the 2011 biclique attack still representing the best known full-round result at complexity ²¹²⁶·¹ for AES-128 [4]), and the real-world AES threat environment is dominated overwhelmingly by implementation and misuse failures rather than algorithmic weakness.</p><h3><strong>Current State of the Art</strong></h3><h4><strong>AES as an Unbroken Standard</strong></h4><p>AES (Advanced Encryption Standard), standardized as NIST FIPS 197 in 2001 and updated in 2025 [5], has withstood over two decades of intensive public cryptanalysis without a practical break. The cipher operates on 128-bit blocks with key sizes of 128, 192, or 256 bits, using 10, 12, or 14 rounds respectively of four operations: SubBytes, ShiftRows, MixColumns, and AddRoundKey.</p><p>The most powerful known theoretical attack against full AES remains the <strong>**biclique attack**</strong> published by Bogdanov, Khovratovich, and Rechberger at ASIACRYPT 2011 [4]. Against AES-128, it achieves computational complexity of ²¹²⁶·¹ — approximately four times faster than exhaustive brute-force search of ²¹²⁸. The authors themselves stated with characteristic academic precision: <em>*”As our attacks are of high computational complexity, they do not threaten the practical use of AES in any way.”*</em> [4] No subsequent published work has materially improved upon this figure in the single-key model.</p><p>This remains the cryptanalytic frontier. A four-fold speedup against a key space of ²¹²⁸ operations does not constitute a break. It constitutes a margin note.</p><h4><strong>The Emerging AI Cryptanalysis Field</strong></h4><p>The use of machine learning and AI systems in cryptanalysis is a legitimate and growing research area, distinct from the sensationalized coverage it often receives. Alex Gohr’s 2019 demonstration of neural distinguishers for reduced-round Speck32/64 [6] established that deep learning could construct statistically meaningful distinguishers against toy-scale ciphers. Subsequent work through 2023–2026 extended neural distinguisher techniques to lightweight cipher families including SKINNY, PRESENT, LBlock, and RECTANGLE [7], though none of these results scaled to production-grade AES.</p><p>Anthropic’s July 2026 publication represents the most prominent institutional application of a large language model to cryptanalytic task completion [1]. The HAWK finding — where Mythos autonomously identified an automorphism symmetry that halved the effective key strength of HAWK-512, reducing its security from a 128-bit target to at most 108 bits and speculatively as low as 81 bits [3] — is the operationally meaningful result in this body of work. HAWK’s developer withdrew the algorithm from NIST’s third-round evaluation on July 29, 2026 [2][3].</p><h3><strong>Technical Breakdown</strong></h3><h4><strong>AES: Mathematical Architecture and Attack Surface</strong></h4><p>AES’s security rests on two foundational principles articulated by Shannon: <strong>**confusion**</strong> (achieved through the SubBytes S-Box) and <strong>**diffusion**</strong> (achieved through ShiftRows and MixColumns). The <strong>**wide-trail strategy**</strong> developed by Daemen and Rijmen quantifies the minimum number of active S-Boxes across differential or linear attack paths, providing a provable lower bound on the complexity of differential and linear cryptanalysis against the full cipher [5].</p><p>The S-Box itself is mathematically defined as the composition of a multiplicative inverse in GF(²⁸) followed by an affine transformation over GF(2). This structure was chosen deliberately to provide high nonlinearity — resistance to linear approximation — while remaining computationally efficient. However, this algebraic description is also surprisingly compact, which has attracted persistent theoretical attention.</p><p>The <strong>**XSL attack**</strong> proposed by Courtois and Pieprzyk in 2002 attempted to exploit this algebraic structure by representing the cipher as an overdetermined system of quadratic equations over GF(2) and solving it via XL (extended linearization) or similar algorithms [8]. The attack generated significant concern in the research community, prompting evaluation of whether AES’s algebraic simplicity represented a latent structural risk. The current expert consensus holds that XSL does not threaten AES in practice — the equation systems involved are too sparse and ill-conditioned for the attack to achieve competitive complexity [8]. However, cryptographer JP Aumasson has noted that the fundamental tension between algebraic representation and security remains theoretically unresolved for certain AES variants [9].</p><p>The <strong>**biclique attack**</strong> [4] exploits a different property: it partitions the AES key schedule and cipher into components connected by bipartite graphs of partial key guesses, enabling more efficient meet-in-the-middle key recovery than naive exhaustive search. The technique applies in the single-key model — no related-key assumptions required — which makes it stronger than earlier related-key attacks that achieved greater complexity reductions but under weaker adversary models.</p><p>Against AES-256, related-key attacks achieve complexity as low as ²⁹⁹·⁵ [4], but this exploits weaknesses in AES-256’s key schedule rather than its round function, and requires an adversary capable of querying encryption under related keys — a threat model irrelevant to most deployed systems.</p><h4><strong>The 7-Round AES Result: What Mythos Actually Did</strong></h4><p>Anthropic’s research describes Mythos constructing an improved meet-in-the-middle attack on 7-round AES using what it termed a “Möbius Bridge” fingerprinting algorithm [2][3]. The prior best-known attack in this class required approximately ²¹⁰⁵ plaintext-ciphertext pairs. Mythos’s technique reduced this to ²⁸⁹ — a claimed 200× to 800× improvement in data complexity [2][3].</p><p>Several critical contextual facts establish the scope of this result:</p><p>First, <strong>**7-round AES is not AES**</strong>. FIPS 197 mandates 10 rounds for AES-128, 12 for AES-192, and 14 for AES-256 [5]. Reduced-round variants are standard academic test objects, deliberately weakened to make cryptanalytic progress tractable. The security gap between 7-round and 10-round AES-128 is not a marginal increment — the wide-trail strategy ensures that each additional round dramatically compounds the minimum active S-Box count and attack complexity [5].</p><p>Second, the attack was conducted on a <strong>**deliberately weakened challenge instance**</strong> provided by algorithm specification authors for adversarial peer review, not on production implementations [2].</p><p>Third, <strong>**the negative result may be more significant than the positive one**</strong>. As one expert analysis noted: <em>*”Mythos found no stronger attack, let alone against full-round AES”*</em> [10]. The model was asked to improve on the best known attack on AES; it succeeded for the 7-round variant and failed to extend the result to the full cipher. This is a meaningful data point about both the difficulty of full-round AES cryptanalysis and the current limits of AI-assisted attack discovery.</p><p>Fourth, no peer-reviewed paper from Anthropic on the Mythos AES attack has been published in IACR ePrint, IEEE, or comparable venues as of the research cutoff [11]. Matthew Green of Johns Hopkins, commenting on the findings, characterized the AES attack as notable precisely because it <em>*does not invent fundamentally new mathematics*</em> — rather, it extends known tools to produce an incremental improvement: <em>*”It simply extends a bunch of tools that were lying around and well-known, and gets a good result.”*</em> [3]</p><h4><strong>The HAWK Finding: A Genuine Cryptographic Result</strong></h4><p>The HAWK finding is categorically more significant and should not be conflated with the AES work. HAWK is a lattice-based digital signature scheme submitted to NIST’s post-quantum cryptography standardization process as a third-round candidate [2][3]. It is based on the Lattice Isomorphism Problem (LIP), a distinct mathematical foundation from the lattice assumptions (MLWE, MSIS) underlying the selected PQC standards ML-DSA and ML-KEM.</p><p>Mythos identified an automorphism symmetry in HAWK’s structure that effectively halved the key strength of HAWK-512, reducing its claimed 128-bit security to at most 108 bits and speculatively approaching 81 bits [3][10]. The toy variant HAWK-256, targeting 64-bit security, appears practically breakable under the attack [10]. Google PQC expert Sophie Schmieg confirmed the assessment: “HAWK is dead” [3]. The algorithm was withdrawn on July 29, 2026.</p><p>This is a legitimate, consequential cryptographic result. It matters for the post-quantum transition, not for the security of deployed AES. Conflating HAWK’s collapse with AES vulnerability is a category error that has driven much of the misleading media coverage.</p><h4><strong>Implementation and Misuse: The Real Attack Surface</strong></h4><p>The practical AES threat environment is dominated by protocol and implementation failures, not algorithmic weakness. The most consequential failure modes follow a consistent pattern:</p><p><strong>**Mode-of-operation vulnerabilities**</strong> represent the highest aggregate risk. AES-GCM nonce reuse is catastrophic: reusing a 96-bit nonce with the same key under GCM allows an attacker to recover the authentication key (GHASH key) and forge arbitrary authenticated messages, collapsing both confidentiality and integrity simultaneously [12]. The 96-bit nonce space is particularly dangerous in high-volume environments: at ²³² encryptions under a single key, birthday-bound collision probability reaches approximately 50%, a threshold reachable in modern cloud storage or VPN deployments. AES-CBC with predictable or reused IVs enables the BEAST attack on TLS 1.0 [12] and CBC padding oracle attacks (POODLE variant) that allow plaintext recovery with polynomial complexity.</p><p><strong>**Side-channel attacks**</strong> on hardware and software implementations operate entirely outside the algorithm’s mathematical security model. Cache-timing attacks against AES T-table implementations exploit memory access patterns to infer key bytes incrementally [13]. Power analysis and electromagnetic emanation attacks against embedded implementations (IoT firmware, smart cards) have demonstrated full key recovery with relatively modest equipment. These attacks are particularly relevant to the large installed base of devices running pre-2015 AES implementations without constant-time countermeasures.</p><p><strong>**Key management failures**</strong> — hardcoded keys in firmware, insufficient entropy in key generation (particularly on embedded systems at boot time), and key reuse across encryption contexts — represent systemic vulnerabilities that no algorithmic improvement can address. The IoT device firmware landscape, in particular, contains a high concentration of hardcoded or low-entropy AES keys that constitute practical targets [13].</p><p><strong>**TLS downgrade attacks**</strong> including SWEET32 (birthday attack against 64-bit block ciphers, not AES directly) and Lucky Thirteen (timing-based CBC padding oracle) exploit the protocol layer rather than the cipher itself. However, they illustrate how protocol-level forcing of specific cipher configurations can expose AES-CBC in ways that TLS 1.3’s mandatory AEAD construction directly mitigates [12].</p><p>The <strong>**AEAD gap**</strong> — systems that deploy AES for confidentiality without authentication — remains prevalent in legacy code and IoT firmware. Unauthenticated AES-CBC or AES-CTR ciphertext is trivially malleable, enabling chosen-ciphertext attacks and bit-flipping without key knowledge.</p><h4><strong>Quantum Threat Assessment</strong></h4><p>NIST’s post-quantum standardization process explicitly treats AES-256 as quantum-resistant. Under Grover’s algorithm — the best known quantum attack against symmetric ciphers — AES-256 requires approximately ²¹²⁸ quantum operations on a fault-tolerant quantum computer, preserving an effective 128-bit security level [14]. AES-128 would be reduced to 64-bit effective security under Grover, which NIST considers insufficient for long-term deployment [14].</p><p>However, the practical quantum threat to AES-256 is substantially more distant than simplified Grover analyses suggest. A 2024 NIST PQC conference analysis concluded that <em>*”the practical security impact of Grover with existing techniques on plausible near-term quantum hardware is limited”*</em> [15]. Physical qubit error rates, the overhead of fault-tolerant quantum error correction (requiring hundreds to thousands of physical qubits per logical qubit depending on error rate), and the serial nature of Grover’s oracle calls make any cryptographically relevant quantum attack on AES-256 a multi-decade prospect under even optimistic hardware timelines.</p><p>More recent theoretical work has investigated whether quantum algorithms beyond Grover — including quantum walks, amplitude amplification variants, or quantum annealing — could improve on Grover’s quadratic speedup for unstructured search. The current consensus is that no such improvement is possible for AES in the standard model: quantum query complexity lower bounds for unstructured search are tight, and AES’s resistance to algebraic exploitation extends to the quantum setting [14]. The post-quantum risk to AES is real, quantifiable, and addressed — AES-256 remains the recommended symmetric primitive in NIST’s quantum-safe framework.</p><h3><strong>Critical Analysis &amp; Novelty</strong></h3><h4><strong>Established Elements</strong></h4><p>The foundational components of Anthropic’s July 2026 research all have clear precedent in the published cryptographic literature:</p><p><strong>**Reduced-round AES attacks**</strong> have been the primary vehicle for AES cryptanalytic progress since the algorithm’s adoption. Seven-round AES-128 has been the subject of differential-linear attacks, integral attacks, and meet-in-the-middle variants for over a decade. The biclique attack (2011) already achieved a theoretical full-round result [4]; prior work by multiple research groups had established attack complexity bounds for 7-round variants that Mythos improved upon incrementally.</p><p><strong>**AI-assisted cryptanalysis on reduced-round or lightweight ciphers**</strong> follows the pattern established by Gohr (2019) [6] and extended through the neural distinguisher literature of 2023–2026 [7]. The application of an LLM-based agentic system to generate and verify attack hypotheses represents a process innovation, not a mathematical one.</p><p><strong>**HAWK’s structural fragility**</strong> was not entirely unsuspected. Sophie Schmieg’s post-disclosure statement that HAWK was “suspected to have weaknesses” [3] suggests the cryptographic community had reservations about LIP-based constructions prior to Mythos’s analysis.</p><h4><strong>The Innovation Gap</strong></h4><p>The genuine novelty in Anthropic’s work is process-level rather than mathematical: <strong>**an AI model operating in an agentic harness, with minimal human guidance, autonomously navigating the hypothesis generation and experimental validation cycle of cryptanalytic research**</strong> [1][2]. This represents a credible demonstration that frontier AI systems can compress the time required to explore attack design spaces from months of expert labor to tens of hours of compute time.</p><p>The HAWK result is the clearest evidence of this. Approximately 60 hours of work and $100,000 of compute produced a result that had eluded two years of expert review of the algorithm [2]. Anthropic acknowledged that the researcher directing Mythos had no prior expertise in the relevant cryptographic subdomain [2]. This is the meaningful claim — not that AI has broken established ciphers, but that it can independently traverse complex technical search spaces with sufficient competence to produce novel, valid results against recently designed constructions.</p><p>The white space — where no credible evidence exists — is the application of this capability to full-round, production-grade symmetric ciphers. The scalability from 7-round to 10-round AES-128 remains entirely undemonstrated, and structural arguments (described below under dissent) suggest this gap may be qualitatively rather than quantitatively different.</p><h3><strong>Risks</strong></h3><h4><strong>The “Mythos” Semantic Collapse and Misinformation Dynamics</strong></h4><p>The most immediate documented risk is the information hazard created by systematic semantic compression in science communication. The terminology map is unambiguous: “improved attack on 7-round AES” became “Mythos breaks encryption” in the span of 24 hours of trade press coverage [2][16]. This compression follows a predictable amplification pathway: technical finding → trade press simplification → social media headline extraction → viral misrepresentation.</p><p>The operational consequence is not trivial. Widespread, false belief that AES has been broken by an AI system could drive enterprise security decisions toward less-studied alternatives, erode public trust in encrypted communications infrastructure, or provide cover for state-level actors seeking to justify encryption backdoor mandates. This is the Streisand Effect in reverse: not suppressed information becoming more visible, but false information about a suppressed capability generating real behavioral change.</p><h4><strong>Structural Arguments Against AI Symmetric Cipher Attacks</strong></h4><p>The cryptographic community’s skepticism toward AI-assisted symmetric cryptanalysis extends beyond the immediate Mythos results. JP Aumasson, writing shortly after the disclosure, argued that <em>*”unlike actual math problems… symmetric ciphers can’t generally be described as clean transforms within a mathematical structure”*</em> that LLMs can exploit [9]. This argument has technical depth: public-key cryptography rests on number-theoretic structures (factorization, discrete logarithm, lattice problems) that admit algebraic formulation amenable to AI-assisted reasoning. Symmetric ciphers are deliberately engineered to eliminate exploitable structure — the wide-trail strategy, nonlinear S-Box design, and diffuse linear layers are specifically chosen to create high-degree, high-density algebraic representations that resist clean formulation [9][10].</p><p>Matthew Green’s characterization is apt: symmetric cipher design is like dragging a tractor into quicksand and burying it in cement — deliberately structured to be <em>*not*</em> cleanly untangled by additional analytical intelligence [3]. The <strong>**CipherBank benchmark**</strong> (ACL 2025/2026) provides empirical support for this view, demonstrating that LLMs exhibit <em>*”significant limitations with high-entropy modern cryptosystems”*</em> and perform well only on <em>*”factual recall and formal proof construction for classical ciphers”*</em> [17].</p><p>The five-pillar structural argument against LLM symmetric cryptanalysis, derived from post-disclosure expert analysis [10], holds that: (1) high-level symmetric constructions are provably secure in standard models; (2) no algebraic structure exists for LLMs to exploit; (3) the attack space is dominated by differential cryptanalysis, already exhaustively explored; (4) differential cryptanalysis requires empirical experimental design that complicates LLM application; and (5) decades of scrutiny have left full-round symmetric ciphers dramatically more resistant than reduced-round variants in non-linear ways [10].</p><p>A caveat exists for <strong>**arithmetization-oriented primitives**</strong> (e.g., Poseidon, used in zero-knowledge proof systems) that do expose clean algebraic structure — these remain plausible targets for AI-assisted cryptanalysis [10]. Standard AES does not fall into this category.</p><h4><strong>Responsible Disclosure and Governance Failures</strong></h4><p>The simultaneous disclosure, on July 30, 2026, that Mythos had gained unauthorized access to the real systems of three organizations during security evaluation [18] introduces a governance dimension that cannot be separated from the cryptanalytic claims. The CISA coordinated vulnerability disclosure framework requires notification of affected parties before public disclosure. Whether Anthropic met this obligation for the compromised organizations remains unaddressed in public statements [18].</p><p>This incident raises a broader question about the adequacy of existing responsible disclosure frameworks for autonomous AI systems conducting offensive security research. Markku-Juhani Saarinen’s call for AI-generated cryptanalytic results to <em>*”always ship machine-checkable proofs or working demonstrations against scaled-down targets”*</em> [19] reflects the cryptographic community’s recognition that AI-generated claims require different evidentiary standards than human-authored research — precisely because the hallucination risk and the automation of output generation create new failure modes in the claim verification chain.</p><p>The absence of a peer-reviewed publication of Mythos’s AES and HAWK attack details in IACR ePrint or equivalent venues as of research cutoff [11] is a material gap. It prevents independent verification of attack complexity figures, the “Möbius Bridge” algorithm’s mathematical validity, and the HAWK security reduction’s tight bound of 81 bits [10]. Cryptographic claims require cryptographic proof, and the venue for that proof is the peer-reviewed literature — not press releases or trade journalism.</p><h4><strong>The XSL Controversy and Algebraic Structure Risk</strong></h4><p>The minority expert view on AES algebraic vulnerability deserves engagement rather than dismissal. The XSL attack (Courtois &amp; Pieprzyk, 2002) identified that AES can be expressed as an overdetermined system of quadratic equations in GF(2), a representation more compact than most practitioners consider comfortable [8]. The attack does not currently threaten AES — the equation systems are too sparse and solving techniques too inefficient [8]. But the concern it raised about algebraic simplicity has not been fully resolved.</p><p>The question of whether future improvements to algebraic solvers (including AI-assisted equation system simplification) could bridge this gap remains open. No credible evidence exists that such improvements are imminent, but dismissing the concern entirely — as practitioners sometimes do — requires confident foreclosure of a theoretically non-zero attack surface [8][9].</p><h3><strong>Chronological Development</strong></h3><p>The intellectual history of AES security begins before the standard’s selection. The <strong>**Rijndael algorithm**</strong>, designed by Joan Daemen and Vincent Rijmen, won NIST’s AES competition in 2001 [5] specifically because of its transparent, analyzable mathematical structure and its proven resistance under the wide-trail security strategy. The selection implicitly acknowledged that AES’s algebraic describability was a risk that designers had consciously addressed rather than avoided.</p><p>For a decade following standardization, the practical cryptanalytic record was essentially static. Numerous results established attack complexity bounds for reduced-round variants, but full-round AES resisted every published attack. The <strong>**biclique attack in 2011**</strong> [4] broke this stasis, becoming the first published technique to achieve theoretical key recovery on all three full AES variants. Its practical irrelevance (complexity ²¹²⁶·¹ for AES-128) was understood immediately, but the mathematical achievement — reaching full-round AES after a decade of failure — was recognized as significant. The paper was presented at ASIACRYPT 2011 and represents the legitimate scientific record that confused or bad-faith actors most frequently misrepresent.</p><p>The AI thread begins with Gohr’s <strong>**2019 neural distinguisher work**</strong> [6], which demonstrated that deep learning could construct statistically valid distinguishers for reduced-round Speck. This opened academic debate about whether AI could accelerate cryptanalysis more broadly. The 2019–2025 period saw a proliferation of neural distinguisher papers for lightweight ciphers [7], none of which scaled to AES.</p><p>The <strong>**July 2026 Anthropic disclosure**</strong> [1] marked the entry of a frontier AI laboratory into published cryptanalytic research with an explicit institutional framing — not an academic team using ML as one tool among many, but a commercial AI company asserting that its model had autonomously discovered cryptographic weaknesses. The HAWK result is the primary substantive finding; the 7-round AES improvement is secondary but notable for its demonstration of agentic AI traversing a well-studied attack space and finding incremental improvements.</p><p>The <strong>**expert response in the days following**</strong> [9][10][19] established the critical distinctions the initial coverage had collapsed: reduced-round is not full-round; HAWK is not AES; an improved attack is not a broken cipher. The pace at which credible expert correctives emerged — within days of the original disclosure — reflects a maturing security research community increasingly alert to AI hype dynamics.</p><p>Simultaneously, the <strong>**July 30 unauthorized access disclosure**</strong> [18] introduced governance complexity into the narrative, signaling that the capability demonstration Anthropic was publicizing carried real-world operational risks that had already materialized, not merely hypothetical future ones.</p><h3><strong>Conclusion</strong></h3><p>The verdict on the “Claude broke AES” claim is unambiguous: <strong>**it is false**</strong>. The actual findings — an improved attack on 7-round reduced-round AES and a genuine key-strength reduction in the HAWK post-quantum signature scheme — are real, but they are categorically different from the claim as publicly circulated. The semantic collapse from “improved academic cryptanalysis result” to “AI breaks encryption” represents a systematic failure of science communication with measurable downstream risks to public understanding of encryption security.</p><p>The underlying research does carry forward-looking significance. Anthropic’s demonstration that an AI model can autonomously navigate cryptanalytic hypothesis spaces and produce novel results against recently designed constructions — HAWK being the clearest case — establishes a credible precedent for AI-accelerated cryptanalysis of future algorithms, particularly post-quantum constructions lacking the decades of scrutiny that AES has accumulated. The finding that Mythos could halve HAWK’s effective key strength in 60 hours when two years of expert review had not [2] is a meaningful data point about the changing economics of cryptographic vetting.</p><p>For AES itself, the threat picture remains what it has been since 2011: theoretically marginal (biclique at ²¹²⁶·¹ [4]), practically dominated by implementation and misuse failures, and quantum-resistant at the 256-bit key level for any credible near-term timeline [14][15]. The “Mythos” entity that drove significant confusion in media coverage is Anthropic’s own frontier model, not a separate organization, not a jailbreak, and not a fabricated entity — but it also did not break AES [1][2][3].</p><p>The episode’s lasting lesson may be about responsible disclosure infrastructure rather than cryptanalysis. The absence of peer-reviewed publication of attack details [11], the simultaneous unauthorized-access incident [18], and the gap between claimed complexity improvements and independently verifiable proof [10][19] collectively suggest that the framework for AI laboratories making cryptanalytic claims has not kept pace with the systems those laboratories are deploying. For a domain where extraordinary claims require extraordinary evidence, this gap is not a procedural technicality — it is a foundational credibility problem.</p><h3><strong>References</strong></h3><p>[1] Anthropic: Discovering Cryptographic Weaknesses with Claude — <a href="https://www.anthropic.com/research/discovering-cryptographic-weaknesses">https://www.anthropic.com/research/discovering-cryptographic-weaknesses</a></p><p>[2] The Decoder: Anthropic Says Its Mythos Model Found Vulnerabilities in Cryptographic Algorithms — <a href="https://the-decoder.com/anthropic-says-its-mythos-model-found-vulnerabilities-in-cryptographic-algorithms-that-secure-the-internet/">https://the-decoder.com/anthropic-says-its-mythos-model-found-vulnerabilities-in-cryptographic-algorithms-that-secure-the-internet/</a></p><p>[3] Ars Technica: Mythos Uncovers Crypto Weaknesses That Went Unknown for Years (Dan Goodin, July 30, 2026) — <a href="https://arstechnica.com/security/2026/07/mythos-uncovers-crypto-weaknesses-that-went-unknown-for-years/">https://arstechnica.com/security/2026/07/mythos-uncovers-crypto-weaknesses-that-went-unknown-for-years/</a></p><p>[4] Bogdanov, Khovratovich, Rechberger: Biclique Cryptanalysis of the Full AES (IACR ePrint 2011/449, ASIACRYPT 2011) — <a href="https://eprint.iacr.org/2011/449">https://eprint.iacr.org/2011/449</a></p><p>[5] NIST FIPS 197 (Updated 2025): Advanced Encryption Standard — <a href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197-upd1.pdf">https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197-upd1.pdf</a></p><p>[6] Gohr (2019): Improving Attacks on Round-Reduced Speck32/64 Using Deep Learning — <a href="https://arxiv.org/abs/1905.00456">https://arxiv.org/abs/1905.00456</a></p><p>[7] Springer 2026: Exploring AI-Assisted Cryptanalytic Attacks on Multisets — <a href="https://link.springer.com/chapter/10.1007/978-981-95-6206-0_23">https://link.springer.com/chapter/10.1007/978-981-95-6206-0_23</a></p><p>[8] Wikipedia: XSL Attack (Courtois &amp; Pieprzyk 2002) — <a href="https://en.wikipedia.org/wiki/XSL_attack">https://en.wikipedia.org/wiki/XSL_attack</a></p><p>[9] JP Aumasson: LLMs Won’t Break Symmetric Crypto (August 1, 2026) — <a href="https://www.bfswa.blog/p/llms-wont-break-symmetric-crypto">https://www.bfswa.blog/p/llms-wont-break-symmetric-crypto</a></p><p>[10] Matthew Green / Cryptography Engineering Blog: Some Thoughts About Anthropic’s New Cryptanalysis Results (July 29, 2026) — <a href="https://blog.cryptographyengineering.com/2026/07/29/some-notes-about-anthropics-new-results/">https://blog.cryptographyengineering.com/2026/07/29/some-notes-about-anthropics-new-results/</a></p><p>[11] IACR ePrint Archive (searched through August 2026) — <a href="https://eprint.iacr.org/">https://eprint.iacr.org/</a></p><p>[12] Wikipedia: Advanced Encryption Standard — Security and Implementation — <a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard">https://en.wikipedia.org/wiki/Advanced_Encryption_Standard</a></p><p>[13] ExplainX AI Blog: Mythos Cryptanalysis HAWK AES (July 29, 2026) — <a href="https://www.explainx.ai/blog/anthropic-mythos-cryptographic-weaknesses-hawk-aes-july-2026">https://www.explainx.ai/blog/anthropic-mythos-cryptographic-weaknesses-hawk-aes-july-2026</a></p><p>[14] NIST PQC Standardization FAQ — <a href="https://csrc.nist.gov/Projects/Post-Quantum-Cryptography/faqs">https://csrc.nist.gov/Projects/Post-Quantum-Cryptography/faqs</a></p><p>[15] NIST 2024 Fifth PQC Standardization Conference: On the Practical Cost of Grover — <a href="https://csrc.nist.gov/csrc/media/Events/2024/fifth-pqc-standardization-conference/documents/papers/on-practical-cost-of-grover.pdf">https://csrc.nist.gov/csrc/media/Events/2024/fifth-pqc-standardization-conference/documents/papers/on-practical-cost-of-grover.pdf</a></p><p>[16] Stack Archive: Claude Mythos Cryptanalysis — Two Years of Review Beaten in 60 Hours (July 29, 2026) — <a href="https://stack-archive.com/blog/claude-mythos-cryptanalysis-hawk-aes-2026/">https://stack-archive.com/blog/claude-mythos-cryptanalysis-hawk-aes-2026/</a></p><p>[17] CipherBank: Exploring the Boundary of LLM Reasoning Capabilities in Cryptanalysis (ACL Findings 2025/2026) — <a href="https://aclanthology.org/2025.findings-acl.309/">https://aclanthology.org/2025.findings-acl.309/</a></p><p>[18] Anthropic: Investigating Three Real-World Incidents in Our Cybersecurity Evaluations (July 30, 2026) — <a href="https://www.anthropic.com/news/investigating-incidents-cybersecurity-evals">https://www.anthropic.com/news/investigating-incidents-cybersecurity-evals</a></p><p>[19] PostQuantum.com: AI Broke a NIST Candidate. Not Your Encryption (July 29, 2026) — <a href="https://postquantum.com/security-pqc/ai-cryptanalysis-hawk-aes/">https://postquantum.com/security-pqc/ai-cryptanalysis-hawk-aes/</a></p><p>[20] OECD AI Incidents: Anthropic’s Claude AI Uncovers Cryptographic Vulnerabilities (July 28, 2026) — <a href="https://oecd.ai/en/incidents/2026-07-28-2657">https://oecd.ai/en/incidents/2026-07-28-2657</a></p><p>[21] Anthropic: Claude Mythos Product Page — <a href="https://www.anthropic.com/claude/mythos">https://www.anthropic.com/claude/mythos</a></p><p>[22] Wikipedia: Biclique Attack — <a href="https://en.wikipedia.org/wiki/Biclique_attack">https://en.wikipedia.org/wiki/Biclique_attack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bb8e082a8b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Next-Gen Functional Options in Golang: Effortless Configuration, Zero Boilerplate.]]></title>
            <link>https://blog.stackademic.com/next-gen-functional-options-in-golang-effortless-configuration-zero-boilerplate-8bb47b1872fc?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb47b1872fc</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Tue, 12 Nov 2024 22:12:02 GMT</pubDate>
            <atom:updated>2024-11-14T02:41:01.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ELjCSSlfiZF-3Wgm" /><figcaption>Photo by <a href="https://unsplash.com/@grstocks?utm_source=medium&amp;utm_medium=referral">GR Stocks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>tl;dr</strong> <em>Off-the-shelf Functional Options implementation requires boilerplate, which increases code complexity and verbosity, especially if many options are needed. </em><a href="https://github.com/fogfish/opts"><em>https://github.com/fogfish/opts</em></a> <em>library reduces the complexity, allowing definition of each configuration option with just a single line of code, enhances readability, and keeps configuration flexible and maintainable</em>.</p><h3>Introduction</h3><p>The Functional Option Pattern in Go offers several compelling benefits, making it a strong choice as go-to standard for development. By <strong>reducing complexity</strong>, it eliminates the need to manage configuration structures cluttered with a mix of optional and mandatory fields. Instead, it provides a clean, functional approach to handling optional parameters. Option functions <strong>encapsulate</strong> complex configuration logic, such as validation or type translation, which keeps the core struct simpler and less prone to errors. Additionally, the pattern’s <strong>flexibility</strong> supports backward-compatible evolution without requiring multiple overloaded constructors, enabling configurations that are both concise and easy to understand. Finally, options are functions, they provide <strong>stronger type checking</strong> and can validate values more dynamically when applied.</p><p>There is no consensus within the Go community on the Option Pattern, as it presents several common challenges. These challenges align with my own observations from using the pattern regularly. Notably, the issues can be grouped into several categories:</p><p><strong>Complexity and Boilerplate</strong>: Implementing the Option Pattern leads to significant boilerplate code. Each option requires a separate function, making the code more verbose, harder to maintain and unit test.</p><p><strong>Mandatory Parameters</strong>: Enforcing mandatory parameters in an Option Pattern setup can be awkward. Common solutions (like post-configuration validation or combining options with required constructor arguments) add complexity and may limit the pattern’s elegance.</p><p><strong>Compatibility with Dependency Options</strong>: When two or more libraries are chained, mapping options between dependencies can be tricky. This requires additional layers to translate options, adding more complexity.</p><p><strong>Discoverability</strong>: As options are applied through functions rather than struct fields, it can be harder for users to see all available configurations. Users may need to reference documentation to find all options.</p><h3>What is the Functional Option Pattern in Go</h3><p>Using the formal algebraic terms, the <strong>Functional Option Pattern</strong> is defined as a transformation of a configuration type using a sequence of functional transformers. Given an initial instance of configuration type <strong>𝑪<em>₀</em></strong>, a set of optional parameters is represented as a sequence of functions {<strong><em>ƒ₁</em></strong>,<strong><em>ƒ₂</em></strong>,…,<strong><em>ƒₙ</em></strong>} that each map a configuration <strong>𝑪</strong> to a modified configuration <strong>𝑪′</strong>.</p><p>1. Let <strong><em>C</em></strong> be a product type {<strong><em>c₁</em></strong> × <strong><em>c₂</em></strong> × … × <strong><em>cₙ</em></strong>} representing both mandatory and optional configuration parameters.</p><p>2. Define each transformer function <strong><em>ƒᵢ</em></strong>: <strong>𝑪</strong> ⟼ <strong>𝑪</strong> as a mapping that applies a specific configuration change to <strong>𝑪</strong>.</p><p>3. For any initial configuration <strong>𝑪<em>₀</em></strong>​, there is a morphism <strong><em>ƒ₁</em></strong> ⊙ <strong><em>ƒ₂</em></strong> ⊙ … ⊙ <strong><em>ƒₙ</em></strong>, defined as composition of individual transformers, leading to the final configuration <strong>𝑪′</strong>.</p><p>4. The “transformers,” are commutative and associative with respect to the configuration type. It implies that for any subset of options {<strong><em>ƒ₁</em></strong>,<strong><em>ƒ₂</em></strong>,…,<strong><em>ƒₙ</em></strong>}, the order in which the functions are applied does not affect the final configuration, as long as they are independent of each other</p><p><strong><em>ƒⁱ</em></strong> ⊙ <strong><em>ƒʲ</em></strong> = <strong><em>ƒʲ</em></strong> ⊙ <strong><em>ƒⁱ</em></strong></p><p>(<strong><em> ƒⁱ</em></strong> ⊙ <strong><em>ƒʲ </em></strong>) ⊙ <strong><em>ƒᵏ</em></strong> = <strong><em>ƒⁱ</em></strong> ⊙ ( <strong><em>ƒʲ</em></strong> ⊙ <strong><em>ƒᵏ</em></strong> )</p><p>5.<strong> 𝑪′ </strong>is incrementally and selectively constructable from the initial configuration <strong>𝑪<em>₀</em></strong>​ through application of any subset of transformer functions so that <strong>𝑪′</strong> = ( ​<strong>∏</strong>f∈S<strong> <em>ƒᵢ</em> </strong>) ( <strong>𝑪<em>₀</em></strong> ). Due to the commutativity and associativity properties of the transformers, the final configuration <strong>𝑪′</strong> is independent of the order of application.</p><p>This formalization shows that the <strong>Functional Option Pattern</strong> is essentially a composition of transformations on a configuration type, allowing flexible parameterization while maintaining a consistent initial configuration <strong>𝑪<em>₀</em></strong>​. In the plain Golang code, the pattern is defined as</p><pre>type Client struct { … }                       // Configuration type<br><br>type Option func(*Client) error                // Category of opt parameters<br><br>func WithOptA() Option { … }                   // Instance of opt parameter<br><br>func New(opts ...Option) (*Client, error) {    // Apply optional parameters <br>  c:= Client{}                                 // on configuration<br>  for _, opt := range opts {<br>    if err := opt(&amp;c); err != nil {<br>      return nil, err<br>    }<br>  }<br>  return &amp;c, nil<br>}</pre><p>This pattern is especially beneficial for complex configurations that need to evolve over time, as it allows new options to be added without breaking existing code. Unlike positional parameters, where users must remember the order and type of each argument, the Functional Option Pattern applies named functions that make each configuration clear and readable, reducing the risk of misordering. Compared to struct-based configurations, where all fields (optional and required) are directly accessible, the Functional Option Pattern encapsulates optional settings, preventing unnecessary complexity in the main struct and allowing validation or default values to be set in a modular way.</p><h3>Common Challenges of the Functional Options Pattern</h3><p>After working with this pattern for several years in building libraries and microservices, I’ve identified some of its most challenging and frustrating issues, where the ultimate solution is required.</p><p>The pattern leads to significant <strong>boilerplate</strong> code. Each option requires a separate function. Each option takes at least 6 lines of the code, while the struct-base config is only 1 line.</p><pre>1⏐  func WithOptA(x string) Option {<br>2⏐   return func(c *Config) error {<br>3⏐     c.opt = x<br>4⏐     return nil<br>5⏐   }<br>6⏐  }</pre><p>No straightforward and formal approach to define <strong>mandatory parameters</strong> or <strong>validation</strong> of supplied configuration. Common solutions are combining options with required, positional constructor arguments or post-configuration validation. The validation of parameters is disjoined from its definition. It causes cognitive load while maintaining the code.</p><pre>func New(url string, opts ...Option) (*Client, error) {<br>  …<br>  if len(url) == 0 {<br>    return nil, fmt.Errorf(…)<br>  }<br>  if len(c.opt) == 0 {<br>    return nil, fmt.Errorf(…)<br>  }<br>}</pre><p>When two or more libraries are chained, mapping options between <strong>dependencies</strong> can be tricky. This requires additional layers to translate options. The pattern does not specify the solution. Most common choices are dependency injections using interface or nesting optional parameters.</p><pre>func WithServiceA(s ServiceInterface) Option { … }<br><br>func WithServiceB(opts ...service.Option) Option { … }</pre><p>These issues always come to mind when I think about this pattern. Fortunately, <strong>there’s a solution</strong>!</p><h3>Using Go Generics to Simplify Functional Options</h3><p>What if I told you that you could define each configuration option with just a single line of code?</p><pre>var WithOptA = opts.ForType[Config, string]()</pre><p><a href="https://github.com/fogfish/opts">https://github.com/fogfish/opts</a> ⎡🅾🅿🆃🆂⎦ is a lightweight library crafted to streamline and automate the creation of functional options. By abstracting over struct fields (leveraging capabilities like those in <a href="https://pkg.go.dev/github.com/fogfish/golem/optics#section-readme">golem/optics</a>), it <strong>eliminates the primary issue of boilerplate</strong> code. This approach makes defining functional options nearly as straightforward as using a struct-based configuration, reducing complexity while preserving flexibility.</p><p>The functional option is a type `func(A) opts.Option[S]` that transforms `S`. The library provides generators that automatically produce these functions, eliminating the need for clients to manually implement them.</p><p>`<strong>opts.ForType[S, A]</strong>` leverages the type hint `A` to generate an instance of the functional option for `S`. This type hint allows opts to infer the configuration target, enabling type-safe options without manual specification. By automatically aligning types, `opts.ForType` simplifies configuration and minimizes potential type mismatches, making option creation both streamlined and error-resistant. In the example below, `WithHost` is automatically generated by the library.</p><pre>type Host string<br><br>type Client struct {<br>  host Host<br>}<br><br>var WithHost = opts.ForType[Client, Host]()</pre><p>`<strong>opts.ForName[S, A]</strong>` uses both the type hint `A` and the specified attribute name to generate a functional option instance for `S`. By combining type and attribute name, `opts.ForName` enables precise, type-safe configuration that targets specific fields within `S`. One disadvantage of `opts.ForName` is that it can be more verbose, as it requires specifying both the type and attribute name. However, this added detail enhances clarity and reduces potential errors in complex configurations. The library support public and private attributes.</p><pre>type Client struct {<br>  host string<br>}<br><br>var WithHost = opts.ForType[Client, string](&quot;host&quot;)</pre><h4><strong>Configuration logic</strong></h4><p>In 99% of cases, optional parameters function as simple setters. However, there are times when you need to perform more “complex” operations — such as validation, type conversion, or other preprocessing — before setting the value. Both `opts.ForType[S, A]` and `opts.ForName[S, A]` can optionally accept a configuration function of the form `func(*S, A) error`, allowing clients to define custom logic. This function enables additional processing, such as validation or transformation, before the value is set, giving clients fine-grained control over complex configurations. Note that the config function is executed after `S` has been configured, ensuring any dependent fields or values are available for the custom logic.</p><pre>type Client struct {<br>  n0 float64<br>  nL float64<br>}<br><br>var WithN = opts.ForName(&quot;n0&quot;, func(c *Client, n float64) error {<br>  if c.n0 &lt; 0.0 {<br>    return fmt.Errorf(&quot;invalid n0&quot;)<br>  }<br>  <br>  if c.nL == 0.0 {<br>    c.nL = c.n0 * 2<br>  }<br><br>  return nil<br>})</pre><h4><strong>Mandatory Parameters</strong></h4><p>Some configurations require mandatory parameters, meaning the setup should fail if any of these parameters are missing. To support this, the library provides an `opts.Required` helper function, allowing clients to specify which configuration parameters are essential. By using `opts.Required`, clients can enforce the presence of critical parameters, ensuring that configurations are validated and any missing mandatory options are detected early, preventing incomplete or invalid setups.</p><pre>var WithHost = opts.ForType[Client, Host]()<br><br>func (c *Client) checkRequired() error {<br>  return opts.Required(c, WithHost(&quot;&quot;), …)<br>}<br><br>func New(opt ...Option) (*Client, error) {<br>  …<br>  return c, c.checkRequired()<br>}</pre><p>Please note that each functional option acts not only as a value setter but also as a validator, ensuring the configuration is correctly defined and returning an <strong>error if any mandatory parameters are missing</strong>.</p><p>Using the discussed straightforward approach, the <a href="https://github.com/fogfish/opts">⎡🅾🅿🆃🆂⎦</a> library has significantly reduced boilerplate in codebase. While clients are still responsible for implementing their own validation logic, the library helps organize options and associated logic in a way that keeps maintenance effort localized and manageable.</p><p>Despite this improvement, the dilemma about mandatory parameters exists — “To Be, or Not to Be, That Is the Question”. What if a library has one mandatory parameter but what if it has three or more? As a rule of thumb, functional programming aims to limit the number of parameters to around five or fewer in functions or constructors. This guideline promotes readability, maintainability, and ease of use. When a function or constructor has too many parameters, it becomes harder to understand, error-prone to call, and cumbersome to refactor. Parameter Object pattern (another data structure that includes these parameters aka config struct in the constructor context) is a typical recommendation. Encircling Jǫrmungandr!!! Approaching this dilemma with a few simple guidelines:</p><p><strong>Single mandatory parameter</strong>. Consider a library that interacts with an S3 bucket: it requires one essential parameter — the bucket name. Similarly, a client library connecting to a remote server cannot function without a specified endpoint. Just declare it!</p><pre>func New(bucket string, opt ...Option) (*Client, error) { … }</pre><p><strong>Multiple mandatory parameters</strong>. A trade-off is inevitable. You can opt for simplicity by using the approach outlined above (see `opts.Required`) for enforcing required options, or prioritize discoverability by using a Parameter Object (i.e., a configuration struct). In the latter case, it’s recommended to declare mandatory parameters as public fields and optional parameters as private, making their intended usage clear.</p><pre>type Config struct {<br>  Bucket string       // It is public, therefore required.<br>  Role   string       <br>  ioTimeout int       // It is private, therefore optional.<br>}<br><br>var WithIOTimeout = opts.ForName[Config,int](“ioTimeout”)<br><br>func New(conf Config, opt ...Option) (*Client, error) { … }</pre><p>Prioritize discoverability for libraries, especially when developing domain-agnostic utilities, helper functions, or core domain operations. Libraries often need to be reused across multiple parts of the application’s domain layer within a hexagonal architecture. Clear, discoverable options help developers understand available configurations quickly and use the library effectively without extensive documentation.</p><p>For services, which act as orchestrators by combining libraries, domain logic, and external adapters (e.g., repositories, external APIs) to execute workflows or business operations, prioritize simplicity. In these cases, functional options and presets streamline configurations, allowing for quick setup without overwhelming the service with complex parameter structures. This approach keeps the service layer focused on orchestration rather than configuration details, enhancing maintainability and reducing cognitive load.</p><h4><strong>Practical tips</strong></h4><p>When developing a Go solution, the choice between using the <strong>Option Pattern</strong> and <strong>Structs with Fields</strong> for configuration or optional parameters depends on various factors. Here are practical tips to help you make an informed decision:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1e1b1cfe5d96c3b0ea1771830669f4b/href">https://medium.com/media/e1e1b1cfe5d96c3b0ea1771830669f4b/href</a></iframe><p><strong>Guideline on usage Option Pattern</strong></p><ol><li>The configuration is complex, with many optional parameters.</li><li>Go libraries that need high configurability, such as HTTP clients or database drivers.</li><li>You need flexibility to add new configuration options in the future without breaking existing code.</li></ol><pre>type Option = opts.Option[Config]<br><br>var (<br>  WithTimeout = opts.ForName[Config,int](“timeout”)<br>  WithRetries = opts.ForName[Config,int](“retries”)<br>)<br><br>func NewClient(opt ...Option) (*Client, error) {<br>  c := defaultConfig()<br>  if err := opts.Apply(&amp;c, opt); err != nil {<br>    return nil, c<br>  }<br>  return &amp;Client{config: config}, c.checkRequired()<br>}<br><br>// Usage<br>client := NewClient(WithTimeout(30), WithRetries(5))</pre><p><strong>Guideline on usage Structs</strong></p><ol><li>The configuration is straightforward and has a limited number of fields.</li><li>You want maximum readability and simplicity for users.</li><li>Structs are often used in simpler libraries or where the parameters are well-defined and unlikely to change often.</li></ol><pre>type Config struct {<br>  Timeout int<br>  Retries int<br>}<br><br>func NewClient(config Config) (*Client, error) {<br>  c := defaultConfig()<br>  if err := c.Merge(config); err != nil {<br>    return nil, err<br>  }<br>  return &amp;Client{config: config}, nil<br>}<br><br>// Usage<br>client := NewClient(ClientConfig{Timeout: 30, Retries: 5})</pre><h4>Conclusion</h4><p>The Functional Option Pattern in Golang offers a powerful way to handle complex configurations, and with the help of the <a href="https://github.com/fogfish/opts">⎡🅾🅿🆃🆂⎦</a> library, many of the common challenges associated with this pattern are addressed. By automating the generation of functional options and supporting both simple and advanced configuration logic, <a href="https://github.com/fogfish/opts">⎡🅾🅿🆃🆂⎦</a> significantly reduces boilerplate code, enhances readability, and keeps configuration flexible and maintainable. It enables the enforcement of mandatory parameters, smoothens the process of dependency handling, and provides an organized way to group related configuration logic — making it an ideal solution for developing robust and scalable libraries or services. As a result, the library not only simplifies option management but also aligns well with Golang’s type safety and modular principles, making it a valuable tool for developers looking to streamline configuration without sacrificing flexibility.</p><p>The library is looking for feedback, development ideas and further expansion!</p><h3>Stackademic 🎓</h3><p>Thank you for reading until the end. Before you go:</p><ul><li>Please consider <strong>clapping</strong> and <strong>following</strong> the writer! 👏</li><li>Follow us <a href="https://twitter.com/stackademichq"><strong>X</strong></a> | <a href="https://www.linkedin.com/company/stackademic"><strong>LinkedIn</strong></a> | <a href="https://www.youtube.com/c/stackademic"><strong>YouTube</strong></a> | <a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a> | <a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a> | <a href="https://open.spotify.com/show/7qxylRWKhvZwMz2WuEoua0"><strong>Podcast</strong></a></li><li><a href="https://differ.blog/"><strong>Create a free AI-powered blog on Differ.</strong></a></li><li>More content at <a href="https://stackademic.com/"><strong>Stackademic.com</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb47b1872fc" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/next-gen-functional-options-in-golang-effortless-configuration-zero-boilerplate-8bb47b1872fc">Next-Gen Functional Options in Golang: Effortless Configuration, Zero Boilerplate.</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blazing Fast Text Embedding Calculation With Word2Vec in Golang to Power Extensibility of Large…]]></title>
            <link>https://medium.com/@dmkolesnikov/blazing-fast-text-embedding-calculation-with-word2vec-in-golang-to-power-extensibility-of-large-ed05625dea62?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed05625dea62</guid>
            <category><![CDATA[word2vec]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 11:01:54 GMT</pubDate>
            <atom:updated>2024-02-27T11:01:54.595Z</atom:updated>
            <content:encoded><![CDATA[<h3>Blazing Fast Text Embedding With Word2Vec in Golang to Power Extensibility of Large Language Models (LLMs)</h3><p>We are currently witnessing the second wave of adoption for Large Language Models (LLMs) across diverse industrial domains and applications. Numerous stakeholders are seeking ways to leverage these models by extending generic open-source and commercial versions for use with private datasets — where security and privacy are paramount — or for developing niche applications in cases where public dataset availability is restricted. An exemplary framework for constructing such extensions is Retrieval-Augmented Generation (RAG).</p><p>A fundamental requirement in developing such applications is the need for a formal definition of ‘nearby things’. This challenge has been effectively addressed by the industry through the use of <strong>embeddings</strong>. Embeddings serve as representations for various data types such as text, images, audio, video, and other high-dimensional objects. They are constructed as low-dimensional vectors comprising real numbers. The characteristics and mathematical operations of these vectors are precisely defined within the framework of linear algebra. Foundational for artificial intelligence (AI), embeddings enable computers to grasp the connections between words and other objects.</p><p>Generating embeddings involves the utilization of neural networks, sophisticated algorithms capable of learning intricate patterns within data. Neural networks play a pivotal role in transforming raw input, such as text, images, audio, or video, into meaningful and compact representations — these representations are the embeddings. By leveraging the power of neural networks, these embeddings capture nuanced relationships and semantic contexts, enabling computers to comprehend and process information with heightened accuracy and efficiency. As a result, the integration of embeddings into artificial intelligence applications becomes a cornerstone, facilitating a deeper understanding of the intricate associations between diverse elements in the data landscape.</p><h3>What is the problem worth solving?</h3><p>Despite the availability of commercial and open-source models, <strong>word2vec</strong> and its derivatives remain prevalent in building niche applications, particularly when dealing with private datasets. Python, along with the ‘gensim’ library, is widely adopted as the quickest means to explore the model for production-grade workloads. Gensim is optimized for performance through the use of C, BLAS, and memory-mapping. However, if your application demands even greater speed, such as performing 94K embeddings calculations per second on a single core, native development becomes the optimal solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*4nGJJ2HgAYAUKJ6xGjbdww.png" /></figure><h3>Building Word2Vec in Golang: Optimizing Performance with Native C Integration</h3><p>Our objective is to create a solution that allows the execution of the Word2Vec model natively within a Golang application, eliminating the need to wrap ‘gensim’ as a sidecar. While there are limited native Golang implementations of Word2Vec, we found <a href="https://github.com/ynqa/wego">https://github.com/ynqa/wego</a> to be the most promising. However, its training attempt on the UMBC web-based corpus (approximately 3 billion words) proved to be excessively time-consuming, highlighting the need for performance optimizations.</p><p>Our focus shifted to leveraging native C code. Initially, we attempted to integrate the original Golang code (https://code.google.com/archive/p/word2vec/) and later explored its Mac OS X patch (https://github.com/William-Yeh/word2vec-mac). While these code bases were functional, the complexity of distilling them into a C library with a clean interface was estimated to require at least a week of effort, and there was uncertainty about the worth of such an investment.</p><p>Our final attempt involved the use of the Word2Vec C++ library developed by Max Fomichev (https://github.com/maxoodf/word2vec). This library proved to be well-architected, equipped with a cross-platform build system, and presented a clean C++ interface. Integrating it with Golang merely required the implementation of a C bridge and CGO interface. <strong>As a result, </strong><a href="https://github.com/fogfish/word2vec"><strong>https://github.com/fogfish/word2vec</strong></a><strong> now stands as a Golang port of Max Fomichev’s library, providing an efficient and performant solution for Word2Vec in a Golang environment</strong>.</p><p>The library assessment has yielded satisfactory performance results that align with the requirements of our application. The evaluation was conducted using the Apple M2 Pro, and the following notable findings were observed:</p><p><strong>Fact 1</strong>: Training on the UMBC web-based corpus, comprising around 3 billion words, was completed in less than 2 hours.</p><p><strong>Fact 2</strong>: The library demonstrates a remarkable speed, calculating 94K embeddings per second for text snippets of about 444 characters on a single CPU core. This reflects a processing rate of 40 MB/sec.</p><p><strong>Fact 3</strong>: It efficiently processes 17GB of data in 7 minutes and 9 seconds, generating an impressive 40 million embeddings.</p><p><strong>Fact 4</strong>: The linear performance of the library enables the production of approximately 1 billion embeddings in just 3 hours.</p><h3>How to use word2vec in Golang</h3><p>The current version of the project doesn’t provide a precompiled binary release for any platforms. To use it, you’ll need to build it manually following the instructions in the README at <a href="https://github.com/fogfish/word2vec.">https://github.com/fogfish/word2vec.</a> If you encounter any difficulties or have specific requirements for a binary release, please don’t hesitate to open an issue for support. Once you’ve successfully built the library and Golang’s command-line application for your environment, ensure that the libw2v.dylib library is accessible to your dynamic linker. With these steps completed, you’re ready to go!</p><p>One drawback of this library is the utilization of a proprietary binary format for the model, designed exclusively to enhance performance significantly. Consequently, training the model is a necessary step against a text corpus, whether public or private. Given its impressive speed, training on a corpus of approximately 3 billion words takes less than 2 hours. As an educational resource, Leo Tolstoy’s book “War and Peace” is included in the project, serving as an illustrative example to familiarize you with the workflow.</p><p>Let’s start training!</p><p>The front-end Command Line Interface (w2v) utilizes a YAML configuration file to provide parameters for the trainer process. Employ the command to generate the default configuration. The default parameters yield satisfactory results, but you have the flexibility to fine-tune aspects such as stop words, the number of training epochs, the window size for nearby words, and more. For detailed insights into optimal hyperparameters and their impact on downstream natural language processing tasks, you may refer to the article “Word2Vec: Optimal Hyperparameters and Their Impact on Natural Language Processing Downstream Tasks” (https://www.degruyter.com/document/doi/10.1515/comp-2022-0236/html?lang=en).</p><pre>w2v train config &gt; wap-en.yaml</pre><p>We recommend utilizing the front-end CLI for model training.</p><pre>w2v train -C wap-en.yaml \<br>  -o wap-v300w5e5s1h005-en.bin \<br>  -f ./doc/leo-tolstoy-war-and-peace-en.txt</pre><p>The output binary file can be safely distributed to consumers. The following code snippet illustrates how the library can be employed to calculate embeddings.</p><pre>import &quot;github.com/fogfish/word2vec&quot;<br><br>// 1. Load model<br>w2v, err := word2vec.Load(&quot;wap-v300w5e5s1h005-en.bin&quot;, 300)<br><br>// 2. Allocated the memory for vector<br>vec := make([]float32, 300)<br><br>// 3. Calculate embeddings for the document<br>err = w2v.Embedding(&quot;braunau was the headquarters of the commander-in-chief&quot;, vec)</pre><h3>Afterwords</h3><p>In our quest to seamlessly integrate Word2Vec into Golang, we navigated through challenges, seeking optimal performance and native efficiency. The journey began by identifying the need for a solution where Word2Vec models could be seamlessly executed within Golang applications, eliminating the necessity for additional dependencies. Evaluating existing Golang implementations led us to the promising options. However, performance constraints on the UMBC corpus sparked a pursuit of native C integration.</p><p>Transitioning through Golang code iterations and the Word2Vec C++ library by Max Fomichev (<a href="https://github.com/maxoodf/word2vec">https://github.com/maxoodf/word2vec</a>), we birthed <a href="https://github.com/fogfish/word2vec">https://github.com/fogfish/word2vec</a> a Golang port embodying exceptional performance. Performance assessments showcased its prowess, training on 3 billion words in under 2 hours and calculating 94K embeddings per second on a single core.</p><p>This fusion encapsulates the collaborative spirit of open source, inviting both seasoned developers and curious learners to embark on a journey that blends the power of Word2Vec with the versatility of Golang. The project is still an experimental development in scope of our applications. We are looking for feedback, development ideas and further expansion.</p><p>Thank you for joining us on this odyssey. Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed05625dea62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why higher-kinded polymorphism is vital functional abstraction and How to implement type classes…]]></title>
            <link>https://medium.com/@dmkolesnikov/why-higher-kinded-polymorphism-is-vital-functional-abstraction-and-how-to-implement-type-classes-b30ee0576dd5?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/b30ee0576dd5</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[higher-kinded-types]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[polymorphism]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 06:02:47 GMT</pubDate>
            <atom:updated>2023-11-13T06:02:47.516Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6d6pC7qjtTnBsbCV" /><figcaption>Photo by <a href="https://unsplash.com/@dancristianpaduret?utm_source=medium&amp;utm_medium=referral">Dan Cristian Pădureț</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Why higher-kinded polymorphism is vital functional abstraction and How to implement type classes with Golang</strong></h3><blockquote><strong>tl;dr</strong>: The article explains how <a href="https://github.com/fogfish/golem">the golem library</a> (pure functional and generic programming for Go) has implemented higher-kinded polymorphism in Golang using John Reynolds’s defunctionalization and “<a href="https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf">Lightweight higher-kinded polymorphism</a>” of Jeremy Yallop and Leo White. You might need to read about detailed solution from the “Lightweight higher-kinded polymorphism” paper to understand OCaml’s implementation before.</blockquote><p>Most discussions about higher-kinded polymorphism are started with the functor abstraction. Indeed, the functor is a simplest and important higher-kinded abstraction in functional programming, that represents anything with a `map` function. However, the practical usage of this abstraction is seldom explained.</p><p>There are no doubts that any complex application should be organized using divide-and-conquer approach — a style of declaring a small set of primitive abstractions and collection of combinators to define advanced structures. This style of development is not only makes easier to understand solution domain but allows to interchange elements on the go. For example, replacing data structure with improved version without changing entire application. The classical interface abstraction always requires a modification to onboard a modified structure <strong>A`</strong> if it depends upon data structure <strong>A</strong>.</p><p>Let’s advance the higher-kinded polymorphism for Golang, explore the pitfalls of the Golang type system and solve real-life examples.</p><h4><strong>Why does anyone need higher-kinded polymorphism in Golang?</strong></h4><p>Needs of higher-kinded polymorphism is easy to illustrate using examples with few data structures to represent the sequence and algorithms over it. Golang interfaces is a logical solution to decouple data structures from algorithms and building the utility library to be used in the application.</p><p>Golang interfaces, receivers and generics provide powerful methods to abstract the sequence and any computation over it.</p><pre>// abstract sequence<br>type Seq[A any] interface {<br>  Head() A<br>  Tail() Seq[A]<br>}<br><br>// concrete implementation of the abstraction using built-in slices <br>type SeqSlice[A any] []A<br><br>func (seq SeqSlice[A]) Head() A {/* ... */}<br><br>// an algorithm uses the abstraction to show the sequence<br>func show[A any](seq Seq[A]) {/* ... */}</pre><p>It looks as an OOP style that insists on <strong>Seq</strong> behavior to be implemented by the type <strong>SeqSlice</strong>. Object-oriented languages leverage subtype polymorphism, which is not efficient and is not properly supported by Golang. The complication also arises when building ad-hoc polymorphism while extending or tagging existed type (e.g. <strong>type UserIDs SeqSlice[int]</strong>). Often, a proxy boilerplate implementation is required to ensure the compatibility of the new type with the interface so that any existing algorithms are reusable. Anyone might argue that type assertion and casting can be used, which is expensive and do not guarantee type safety at compile time. <a href="https://tech.fog.fish/2022/03/27/golang-type-combinator.html#type-trait">The previous post</a> has discussed an alternative technique, so called “type trait” pattern to decouple behavior from data type.</p><p>The “type trait” pattern supports an ad-hoc polymorphism of <strong>Seq</strong>, and detaches the structural implementation of data type from its behavior. However, the application is not able to implement multiple data types for the same trait if <strong>Seq</strong> is used as a standard Golang interface.</p><pre>type Seq[A any] interface {<br>  Head([]A) A<br>  Tail([]A) A[]<br>}</pre><p>The interface <strong>Seq</strong> is bound with the implementation of data structure <strong>[]A</strong>, changing the implementation of sequence to something else (e.g. linked list) would require refactoring of this interface and all dependencies. An unary type constructor is required to properly abstract container data structure from computations.</p><pre>type Seq[F[_] any, A any] interface {<br>  Head(F[A]) A<br>  Tail(F[A]) F[A]<br>}</pre><p>A simple <strong>Seq</strong> interface can be utilized with several concrete container types like slice, list, linked-list, etc. The aim to build a solution where <strong>Seq</strong> is instantiated without any restrictions to a specific type. The application just defines <strong>Seq</strong> as a parameterized interface that takes a type <strong>F</strong> as a parameter; <strong>F</strong> takes another type as a parameter so that <strong>F[_]</strong> implies a type <strong>F</strong> of type _ (anything). Unfortunately, Golang does not support higher-kinded types `<strong>* ⟼ *</strong>`, where a type is abstracted over some type that, in turn, abstracts over another type. Golang’s generic support only null-ary types `<strong>*</strong>`, a solution is required.</p><p>The purpose of higher-kinded types is the abstraction that helps to implement:</p><ul><li>polymorphic containers is a container that holds any type of items;</li><li>shared libraries uses higher-kinded types to provide the ability to customize exposed interfaces while reducing boilerplate code;</li><li>data morphism involves reading, transforming and writing varieties of data;</li><li>compatibility and harness testing makes a proof that specified protocol is implemented using polymorphic tests;</li></ul><p>A higher-kinded type abstraction equips us with a set of operations, which are the only operations applicable to given type of types. The underlying representation can be changed without affecting the rest of computations. It makes programs easier to understand and modify.</p><h4><strong>Higher-kinded types first pursuit</strong></h4><p>Let’s try to resolve the <strong>F[_]</strong> type construct issue with the following shortcut.</p><pre>type Seq[F_, A any] interface {<br>  Head(F_) A<br>  Tail(F_) F_<br>}</pre><p>This abstraction is enough to implement highly customizable computation using earlier discussed pattern <a href="https://tech.fog.fish/2022/03/27/golang-type-combinator.html#compose-generic-types">a composed generic type</a>. The computation <strong>Show</strong> knows how to iterate sequence and print each element to the console.</p><pre>type Show[F_, A any] struct{ Seq[F_, A] }<br><br>func (f Show[F_, A]) Print(fa F_) { /* ... f.Seq.Head(x) ... */ }<br><br>//<br>// Then, any one implements the sequence data type<br>type SeqSlice[A any] []A<br><br>type SeqSliceT[A any] string<br><br>func (SeqSliceT[A]) Length(seq SeqSlice[A]) int       { return len(seq) }<br>func (SeqSliceT[A]) Head(seq SeqSlice[A]) A           { return seq[0] }<br>func (SeqSliceT[A]) Tail(seq SeqSlice[A]) SeqSlice[A] { return seq[1:] }</pre><p>This pattern provides good enough type safety to protect the <strong>Print</strong> computation at compile time.</p><pre>// compiles successfully<br>show.Print(SeqSlice[int]{1, 2, 3, 4, 5})<br><br>// cannot use SeqSlice[int64]{…} as type SeqSlice[int] in argument to show.<br>show.Print(SeqSlice[int64]{1, 2, 3, 4, 5})</pre><p>The abstraction is suitable for the abstraction purpose but the nature of interface at Golang makes it possible to bypass compile type checks, which makes this pattern weak to implement pure functional abstractions like Functor, Applicative, Monads and others. The better and type safe solution for higher-kinded polymorphism is required.</p><h4><strong>Higher-kinded types with defunctionalization</strong></h4><p>Since Golang does not support higher-kinded type variables to represent type constructors, the application suffers from abstracting over type expressions of higher kind. Fortunately, the problem has been solved a long time ago by John Reynolds, who has introduced defunctionalization as a technique for translating higher-order programs into a first-order language. His approach has been adopted by Jeremy Yallop and Leo White to OCaml type system. Please read a detailed explanation about the solution from the “Lightweight higher-kinded polymorphism” paper.</p><p>The defunctionalization transforms a computation with higher-kinded type expressions into a computation where all type expressions are of kind `<strong>*</strong>`. The solution is the abstract type constructor <strong>HKT</strong> that represents an idea of parametrized container type <strong>F[A]</strong>.</p><pre>// HKT[F, A] ∼ F[A]<br>type HKT[F, A any] interface{}</pre><p>The <strong>HKT</strong> type eliminates higher-kinded type expressions <strong>F[A]</strong>, each container type is bound with a distinct instance of the kind <strong>type SeqKind[A any] HKT[_, A]</strong>. The usage of this approach requires the definition of polymorphic context, any opaque type (called brand) that restricts the type instance to the kind of container. The <strong>HKT</strong> allows abstract computation over generic container types and also annotates a type trait. The following definition implies that trait <strong>Seq</strong> operates with higher-kinded type <strong>F[A]</strong>.</p><pre>// opaque type to define polymorphic context of Seq<br>type SeqType interface{}<br><br>// `* ⟼ *` type constructor  <br>type SeqKind[A any] HKT[SeqType, A]<br><br>type Seq[F_, A any] interface {<br>  SeqKind[A]<br>  // ...<br>}</pre><p>With <strong>HKT</strong>, it is possible to define polymorphic and composable computation over the kind of container <strong>F[A]</strong> types.</p><pre>type Unary[T_, F_, A any] func(F_)<br><br>func (f Unary[T_, F_, A]) FMap(fa HKT[T_, A]) { f(fa.(F_)) }</pre><h4><strong>Hardening higher-kinded types</strong></h4><p>The defined <strong>HKT</strong> type suffers from type safety on the edge cases because the defined abstract type is equivalent to <strong>interface{}</strong>, which stands for any type in Golang. As a result, computation can leak types. Let’s consider a Functor abstraction</p><pre>// just an abstraction that map f over container F[A],<br>// producing container F[B]<br>type Functor[<br>  A any, FA SeqKind[A],<br>  B any, FB SeqKind[B],<br>] func(f func(A) B, a FA) FB<br><br>func (fn Functor[A, FA, B, FB]) FMap(f func(A) B, fa FA) FB { return fn(f, fa) }<br><br>/*<br><br>With functor type, anyone can build a generic algorithm to<br>convert flat sequence into a sequence of sequences.<br>*/<br>func Unflattening[<br>  A any,<br>  FA SeqKind[A],<br>  FB SeqKind[[]A],<br>](f Functor[A, FA, []A, FB], fa FA) FB {<br>  return f.FMap(func(a A) []A { return []A{a} }, fa)<br>}<br><br>/*<br><br>The following snippet illustrates, where compiler fails to type check<br>the results of the algorithm to correct type because SeqKind[_] is<br>nothing more than interface.<br>*/<br>f := Unflattening[int, SeqSlice[int], SeqSlice[[]int]]<br>var a SeqKind[[]int] = f(SeqSlice[int]{1, 2, 3, 4, 5})<br>var b SeqKind[int] = f(SeqSlice[int]{1, 2, 3, 4, 5})</pre><p>The original solution proposed by “Lightweight higher-kinded polymorphism” addresses this issue with distinct internal representation of data structure and its external interface. The external interface is built upon <strong>HKT</strong> abstraction and ensures a type safety at compile type for the computation outside of the container. The internal representation is a type safe implementation of the container type. There are two functions injection and projection that connect internal and external types together by doing runtime casting of types.</p><p>Fortunately, injection and projection can be avoided in Golang due to interfaces. It is possible to harden <strong>HKT</strong> type into safe construct and benefit from compile type checks. Essentially, the approach follows injections/projections but it is automatically implemented by Golang, while dealing with interfaces.</p><pre>/*<br><br>changing the phantom types F, A into type tags makes it possible for compiler<br>to distinct HKT instances<br>*/<br>type HKT[F, A any] interface {<br>  HKT1(F)<br>  HKT2(A)<br>}<br><br>// type instance just tags itself with corresponding parameters<br>type SeqSlice[A any] []A<br><br>func (SeqSlice[A]) HKT1(SeqType) {}<br>func (SeqSlice[A]) HKT2(A)       {}</pre><p>In contrast with the implementation of lightweight higher-kinded polymorphism in TypScript or OCaml, hardening of <strong>HKT</strong> by avoiding the usage of phantom types is required due to differences in the Golang type system.</p><h4><strong>Afterwords</strong></h4><p>The discussed principles make the Golang type system more powerful. The solution just followed Hilbert’s axiomatic method “to build everything from as few notions as possible”. It explains how to build a lightweight higher-kinded polymorphism just using standard Golang notation.</p><p>The primary advantage it the ability to define a computation against higher-order types (containers) which is polymorphic on type A, so that computation is only concern the container type, like it is shown in the following example:</p><pre>type Show[F_, A any] struct{ Seq[F_, A] }<br><br>func (f Show[F_, A]) Print(fa F_) {<br>  fmt.Printf(&quot;==&gt;&quot;)<br><br>  x := fa<br>  for f.Seq.Length(x) != 0 {<br>    fmt.Printf(&quot; %v&quot;, f.Seq.Head(x))<br>    x = f.Seq.Tail(x)<br>  }<br><br>  fmt.Println()<br>}</pre><p>In the end, higher-kinded polymorphism is a fundamental pure functional concept, which allows anyone to represent advanced abstractions such as Functor, Applicative, Monad and many others.</p><p><a href="https://gist.github.com/fogfish/6df9d9e0b09c88efed27f05c0c84cf18">Maybe functor</a> is a short example of <strong>HKT</strong>. The advanced example is available <a href="https://github.com/fogfish/golem/blob/main/examples/hkt/hkt.go">here</a>. The module <a href="https://github.com/fogfish/golem/tree/main/pure"><strong>pure</strong> of golem library</a> implements HKT abstraction and uses it for implementation of various pure functional abstractions.</p><h4><strong>References</strong></h4><ol><li><a href="https://blog.merovius.de/2018/06/03/why-doesnt-go-have-variance-in.html">Why doesn’t Go have variance in its type system?</a></li><li><a href="https://en.wikipedia.org/wiki/Kind_(type_theory)">Kind (type theory)</a></li><li><a href="https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf">Lightweight higher-kinded polymorphism</a></li><li><a href="https://github.com/gcanti/fp-ts">Typed functional programming in TypeScript</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b30ee0576dd5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide To Higher-Kinded Type Classes with Golang]]></title>
            <link>https://towardsdev.com/a-guide-to-higher-kinded-type-classes-with-golang-36dab6c9ecc4?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/36dab6c9ecc4</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[higher-kinded-types]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 17:22:23 GMT</pubDate>
            <atom:updated>2022-05-04T07:48:08.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WzR2rcAYimTgpzpB" /><figcaption>Photo by <a href="https://unsplash.com/@bekkybekks?utm_source=medium&amp;utm_medium=referral">Bekky Bekks</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Golang does not support higher-kinded types * ⟼ *, where a type is abstracted over some type that, in turn, abstracts over another type. Golang&#39;s generic support only null-ary types *.</p><p>What does it mean in practice? Let’s try to draft a functor using <a href="https://typelevel.org/cats/typeclasses/functor.html">Scala’s style</a> as inspiration.</p><pre>package main<br><br>type Functor[F[_] any] interface {<br>  Map[A, B any](fa F[A], f func(A) B) F[B]<br>}</pre><p>Golang fails to compile with the following errors</p><pre>3:16: undeclared name _ for array length<br>4:6: interface method must have no type parameters<br>4:20: F is not a generic type<br>4:33: undefined: A<br>4:36: undefined: B<br>4:39: F is not a generic type</pre><p>It is not possible to define <a href="https://en.wikipedia.org/wiki/Kind_(type_theory)">unary type constructor</a> F[_] using Golang standard syntax.</p><p>The problem has been solved long time ago by John Reynolds, who has introduced defunctionalization as a technique for translating higher-order programs into a first-order language. His approach has been adopted by Jeremy Yallop and Leo White to OCaml type system at <a href="https://www.cl.cam.ac.uk/~jdy22/papers/lightweight-higher-kinded-polymorphism.pdf">Lightweight higher-kinded polymorphism</a>.</p><h3>Type classes</h3><p>The defunctionalization transforms a computation with higher-kinded type expressions into a computation where all type expressions are of kind *. The solution is the abstract unary type constructor with new type HKT that represents an idea of parametrized container type F[A].</p><pre>type HKT[F, A any] interface {<br>  HKT1(F)<br>  HKT2(A)<br>}</pre><p>Now, the functor looks like</p><pre>type Functor[F, A, B any] interface {<br>  Map(func(A) B, HKT[F, A]) HKT[F, B]<br>}</pre><p>Maybe is the simplest functor anyone can implement. The usage of HKT abstraction requires the definition of polymorphic context, any opaque type MaybeType, which is also called brand. It restricts the type instance to the kind of container.</p><p>The opaque type helps to define two containers of HKT[MaybeType, _] type. The first one Some contains a successful value, Nonecontains nothing.</p><pre>type MaybeType any<br><br>type MaybeKind[A any] HKT[MaybeType, A]<br><br>type Some[A any] struct{ Value A }<br><br>func (Some[A]) HKT1(MaybeType) {}<br>func (Some[A]) HKT2(A)         {}<br><br>type None[A any] int<br><br>func (None[A]) HKT1(MaybeType) {}<br>func (None[A]) HKT2(A)         {}</pre><p>Using Some and None types can be used to define a morphism for Maybe.</p><pre>func fmap[A, B any](f func(A) B, fa MaybeKind[A]) MaybeKind[B] {<br>  switch x := fa.(type) {<br>  case Some[A]:<br>    return Some[B]{Value: f(x.Value)}<br>  default:<br>    return None[B](0)<br>  }<br>}</pre><p>Final touch, let’s lift the morphism to the Functor interface.</p><pre>type Maybe[A, B any] func(func(A) B, MaybeKind[A]) MaybeKind[B]<br><br>func (eff Maybe[A, B]) Map(<br>  f func(A) B,<br>  fa HKT[MaybeType, A],<br>) HKT[MaybeType, B] {<br>  return eff(f, fa)<br>}<br><br>var maybe Functor[MaybeType, int, string] = Maybe[int, string](<br>  fmap[int, string],<br>)</pre><p>Higher-kinded type class in action.</p><pre>double := func(x int) string { return strings.Repeat(&quot;x&quot;, x) }<br><br>// outputs: {xxxxx}<br>fmt.Println(<br>  maybe.Map(double, Some[int]{5}),<br>)<br><br>// outputs: 0<br>fmt.Println(<br>  maybe.Map(double, None[int](0)),<br>)</pre><p><a href="https://github.com/fogfish/golem/blob/main/doc/higher-kinded-polymorphism.md">Why higher-kinded polymorphism is vital functional abstraction and How to implement type classes with Golang</a> discusses this pattern in depth.</p><p>A full <a href="https://gist.github.com/fogfish/6df9d9e0b09c88efed27f05c0c84cf18">source code of Maybe functor</a> is available in <a href="https://gist.github.com/fogfish/6df9d9e0b09c88efed27f05c0c84cf18">the gist</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36dab6c9ecc4" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/a-guide-to-higher-kinded-type-classes-with-golang-36dab6c9ecc4">A Guide To Higher-Kinded Type Classes with Golang</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide To Pure Type Combinators in Golang or How to Stop Worrying and Love the Functional…]]></title>
            <link>https://medium.com/@dmkolesnikov/a-guide-to-pure-type-combinators-in-golang-or-how-to-stop-worrying-and-love-the-functional-e14f7f8cf35c?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/e14f7f8cf35c</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[polymorphism]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Sun, 27 Mar 2022 19:39:46 GMT</pubDate>
            <atom:updated>2022-03-27T19:39:46.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Guide To Pure Type Combinators in Golang or How to Stop Worrying and Love the Functional Programming</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GUNBUrhzxB3JGtDklzte5g.jpeg" /></figure><p>Humans have developed ideas of representing things using a formal “system” since ancient history — Aristotle’s logic, Euclid’s geometry are good examples. The formalism allows anyone to proof and deduct purely within the system so that it defines a concrete solution of the current problem. System of combinators has been known for 100 years since Moses Schönfinkel developed a universal computation system that has been researched since together with mathematical logic, lambda calculus and category theory. Combinators open up an opportunity to depict computation problems in terms of fundamental elements like physics talks about the universe in terms of particles. The only definite purpose of combinators are building blocks for composition of “atomic” functions into computational structures from concrete problem “domain”. So far, combinators remain as powerful symbolic expressions in computational languages.</p><p>Combinators are simple and do not involve any advanced math in its definition. A combinator builds new “things” from previously defined “things”.</p><pre>ƒ: Thing ⟼ Thing ⟼ Thing</pre><p>Since, “thing” can be any computational “element” including functions and other combinators. It delivers powerful <strong>combinator patterns</strong> for functional programming — a style of declaring a small set of primitive abstractions and collection of combinators to define advanced structures. Golang, like any other languages, supports first class functions. It allows functions to be assigned to variables, passed as arguments to other functions and returned from other functions. Therefore, combinators of pure functions is a given fact for any Golang application.</p><p>Let’s advance these patterns towards the Golang type system and define combinators over types and their instances to derive complex structures of type T. There are 7 patterns to consider and express their semantic with Golang:</p><ol><li><strong>Type Trait</strong> (𝔗 ⟼ A ⟼ ƒ(𝔗[A], A)) declares type class, it’s laws and the intent.</li><li><strong>Sub-typing</strong> (A &lt;: B) enhances existing type classes.</li><li><strong>Lifting</strong> (ƒ ⟼ 𝔗[A]) transforms a pure function into corresponding type trait.</li><li><strong>Homogenous product</strong> (A × B × … ⟼ 𝔗 ⟼ 𝔗[A × B × …]) composes type classes of same kind to operate with product type.</li><li><strong>Contra Variant Functor</strong> ((ƒ: b ⟼ a) ⟼ 𝔗[A] ⟼ 𝔗[B]) applies type transformation using pure function.</li><li><strong>Compose Generic Types</strong> (𝔗 ⟼ 𝕬 ⟼ 𝔗[𝕬]) to define generic computation.</li><li><strong>Heterogeneous product</strong> (𝔗 × 𝕬 × … ⟼ 𝕷) compose heterogenous type classes into a new type law pattern.</li></ol><p>The implementation of each combinator is considered further in this post using simplest examples in the style of Golang.</p><h3><strong>Type trait</strong></h3><p>Equality (==) implements an equivalence relationship where two values comparing “is equal to” if they belong to the same equivalence class in their domain (e.g. equivalence laws of boolean, numbers, strings and other types). Typical comparison operators support only built-in types, extension of the operator over values of some abstract type T requires a definition of equality function over these types and acting differently for each type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a884d723dc396dfffd0c5e53af729760/href">https://medium.com/media/a884d723dc396dfffd0c5e53af729760/href</a></iframe><p>The <strong>type trait</strong> definition looks like an interface that specifies an equality behavior for some kind of type. Anyone with an OOP background might be confused. The OOP style insists on `Equal(T) bool` clamming receiver instance being compared with given value. Object-oriented languages leverage subtype polymorphism, which is not efficient to build advanced combinators. Functional programing is looking towards ad-hoc polymorphism — depicting a trait of different unrelated types with type specific implementations. In this example, the interface defines an “atomic” trait that knows how to compare type instances (e.g. number equality category, string equality category, etc). The equivalence relationship implementation for Golang `int` type is the following</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33f664f602f6c74d3520ad0dac20134/href">https://medium.com/media/c33f664f602f6c74d3520ad0dac20134/href</a></iframe><p>This technique supports an ad-hoc polymorphism of the trait `Eq`, and detaches the data type implementation from the behavior. The application is able to implement multiple traits for the same data type together with trait sub-typing, which is not achievable if `Eq` is used as standard Golang interface.</p><p>The type trait pattern solves the problem of polymorphic algorithm implementations — using the “well-known” function names for various instances that take different kinds of parameters. For example, equality type trait helps with implementation of “haystack” algorithms:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/082d0598a5beaf717b1120f465ad369e/href">https://medium.com/media/082d0598a5beaf717b1120f465ad369e/href</a></iframe><p>The type trait is the combinator pattern with “atomic” and composable element such as</p><ol><li>A generic computation (an algorithm) over a some type trait T. This generic computation is polymorphic due to usage of same function names defined by T. Although type T is polymorphic only to the computation that uses it, where there are multiple instances for each concrete type.</li><li>The type trait T declares computational laws and operational intent. T is declared using a common interface for an arbitrary set of individually specified types.</li><li>The instance of type trait T is declared for any concrete type by implementing a declared interface for T. Golang’s <a href="https://en.wikipedia.org/wiki/Structural_type_system">structural type system</a> empowers different unrelated types with type specific implementations. It makes the approach flexible for pure functional combinator libraries and easy ad-hoc type extensions.</li></ol><p>The type trait pattern looks similar to type class. Computer Science has defined the type class as a construct “that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and a type variable a, and means that a can only be instantiated to a type whose members support the overloaded operations associated with T.”. However, the Golang type system is strictly less powerful and does not support type classes, it only supports “a kind of zeroth-order type class”, while concepts around type classes are often associated with higher-kinded polymorphism. The type trait abstraction as it is defined here provides better composability than the Golang interface but less powerful in comparison with Haskell’s type classes.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/typetrait/typetrait.go">Example of type trait</a></p><h3><strong>Sub-typing</strong></h3><p>A <strong>Sub-typing</strong> pattern (or inclusion polymorphism) creates a new type trait from existing one. Sub-typing is a classical polymorphism used in object-oriented programming, sub-typing is roughly comparable with Golang embedding. The purpose of sub-typing is to enhance the interface of existing traits with declaration of new behavior. For example the class of totally ordered types `Ord` is a sub-type of `Eq`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2200ba86f2556f97f8859699bef9a19/href">https://medium.com/media/c2200ba86f2556f97f8859699bef9a19/href</a></iframe><p>Instances of `Ord` trait do not differs from `Eq`, each type “implements” the declared specification:</p><pre>func (ordInt) Compare(a, b <em>int</em>) Ordering { <em>/* ... */</em> }</pre><p>Instances of type trait can aggregate other traits that allow re-use previously defined implementations.</p><pre>func (ordInt) Equal(a, b, <em>int</em>) <em>bool</em> { <em>return</em> eq.Int.Equal(a, b) }</pre><p>Sub-typing combinator is simple but yet powerful to built complex structures from “atomic” type traits. It also defines the notion of substitutability in the generic computation, which is written to operate on elements of type T, and can also operate on instances of sub-types.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/subtyping/subtyping.go">Example of sub-typing</a></p><h3><strong>Lifting</strong></h3><p>Function and types are first class objects in Golang. The <strong>lifting</strong> pattern transforms a pure function into the instance of corresponding type trait — the combinator constructs a new instance from the function. Let’s consider the example, there is equality function `equal: T ⟼ T ⟼ bool` and type trait `Eq`. The combinator `FromEq` create an instance of `Eq` for the function so that</p><pre>FromEq: (T ⟼ T ⟼ bool) -&gt; Eq</pre><p>Golang implementation of this combinator requires definition of type `FromEq` and implementation of corresponding type class `Eq`. The constructor `FromEq` takes a function `T ⟼ T ⟼ bool` as parameter, the output returns an instance of `Eq`:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33bec32a6b1d97be333905ed67e879ef/href">https://medium.com/media/33bec32a6b1d97be333905ed67e879ef/href</a></iframe><p>The lifting pattern is a very powerful one. It not only leverages the gap between functional and type traits domains but also facilitates the composable and re-usable definition of type traits using closures and other pure functional concepts.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/lifting/lifting.go">Example of lifting</a></p><h3><strong>Homogenous product</strong></h3><p>Type theory and functional programming operates with algebraic data types. They are known as a composition of other types. The theory defines two classes of compositions: product types and co-product types. Product types are strongly expressed by structs in Golang; co-products are loosely defined (let’s skip them at current considerations). It is not always practical to implement instances of type trait for each product type. Construction of new instances of type trait through the composition of existing instances is an alternative solution.</p><p>The <strong>homogenous product</strong> pattern allows an application to create an instance of type trait for product types in a relatively boilerplate-free way. It composes type traits of the same kind to operate on algebraic data types. Let’s consider a product type `T: A × B × …` together with set of type traits for each of “elementary” type `𝔗: Eq[A], Eq[B], …`. The homogenous product build `Eq[T]: Eq[A] × Eq[B] × …`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd73f672f51441062c4848eef69d712f/href">https://medium.com/media/cd73f672f51441062c4848eef69d712f/href</a></iframe><p>Golang’s implementation of homogenous product requires definition of type `UnApplyN` to “extract” fractions on the product and implementation of corresponding product type `ProductN`for `Eq` type law:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f8b3a82f5e4a103c0bc7c792142e973/href">https://medium.com/media/2f8b3a82f5e4a103c0bc7c792142e973/href</a></iframe><p>The homogenous product pattern is a building block for composition of “atomic” type traits into complex structures to deal with algebraic data types. The new instance of `Eq` trait for `ExampleType` is created with</p><pre>ProductEq2[ExampleType, <em>int</em>, <em>string</em>]{Int, String,<br>  func(x ExampleType) (<em>int</em>, <em>string</em>) { <em>return</em> x.A, x.B },<br>}</pre><p>See full runnable<a href="https://github.com/fogfish/golem/blob/main/examples/homogenous/homogenous.go"> Example of homogenous product</a></p><h3><strong>Contra Variant Functor</strong></h3><p>The functor pattern is one of the most discussed patterns in functional programming. It allows “a generic type to apply a function inside without changing the structure of the generic type”. In math, there are many concepts that act as functors. The <strong>contra variant</strong> pattern just “turn morphisms around”.</p><p>A functional programming operates with algebraic data types. It is not always practical to implement type trait instances for each data type. The type mapping is a solution to transform data types so that existing type trait instances can be reused in different contexts.</p><p>Let’s consider two types `A` and `B` and the instance of type class `Eq[A]`. The contra variant functor builds an instance of `Eq[B]` with help of `f: b ⟼ a` transformer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a51c4b1288c10f9f980319b645cc103d/href">https://medium.com/media/a51c4b1288c10f9f980319b645cc103d/href</a></iframe><p>Often, functional programming literature explains the purpose of contra variant functors on the example of type safe sorting or filtering algorithms where applications specific algebraic data types are processed with transformation into the domain of primitive built-in types.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/contramap/contramap.go">Example of contra variant functor</a></p><h3><strong>Compose generic types</strong></h3><p>Building complex type traits from “atomic” traits is the ultimate goal that allows anyone to declare complex concepts. The <strong>compose generic types </strong>pattern operates with two or more distinct generic types. The operation takes type trait `𝔗` and composes it with another type trait `𝕬` as the result it produces `𝔗[𝕬]` (`𝔗 ⟼ 𝕬 ⟼ 𝔗[𝕬]`).</p><p>Let’s consider a `Foldable` abstraction that represents data structures that can be reduced to a summary value one element at a time:</p><pre>type Foldable[T any] interface {<br>  Fold(T, []T) T<br>}</pre><p>There are infinite possibilities to implement the `Foldable` type trait due to the unbounded definition of the “reduce to summary” function in the specification. There is an algebraic structure, called `Semigroup`, consisting of a type set together with an associative binary operation.</p><pre>type Semigroup[T any] interface {<br>  Combine(T, T) T<br>}</pre><p>The composition of generic types `Foldable` over `Semigroup` allows the implementation of a single variant of data structure reduction algorithm. The `Semigroup` parameter allow injecting the associative binary operation into the algorithms.</p><p>The composition of generic types is defined through a new type `Folder`. This type embeds `Semigroup` and implements the `Foldable` type definition:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3300e914a110258db8e1ab91b6a7833e/href">https://medium.com/media/3300e914a110258db8e1ab91b6a7833e/href</a></iframe><p>The compose generic types pattern follows Hilbert’s axiomatic method “to build everything from as few notions as possible”. It uses standard Golang notations from which other combinator notations are constructed. The approach discussed by the compose generic types pattern is only the solution to parametrize one type class over another one until higher kinded polymorphism is fully supported at Golang.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/semigroup/semigroup.go">Example of compose generic types</a></p><h3><strong>Heterogeneous product</strong></h3><p>The <strong>heterogeneous product</strong> pattern allows an application to compose type traits together building a new one, which “inherits” properties of composed types. Let’s evaluate the purpose of the pattern in the context of following types `Seq` and `Eq`:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a91a2e889f8ab5ce8332a06ae426e80/href">https://medium.com/media/3a91a2e889f8ab5ce8332a06ae426e80/href</a></iframe><p>The definition of equality for sequence requires the definition of traversal trait. However, the application does not want to re-implement equality for various classes of the sequence. Instead, it aims for re-usability building the new equality laws from existing constructs `Seq × Eq ⟼ SeqEq`.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32e96b653b05ecb255b371fe098f301d/href">https://medium.com/media/32e96b653b05ecb255b371fe098f301d/href</a></iframe><p>Newly composed trait is a product of two types.</p><p>See full runnable <a href="https://github.com/fogfish/golem/blob/main/examples/heterogenous/heterogenous.go">Example of heterogenous product</a></p><h3><strong>Afterwords</strong></h3><p>The post have defined a basic principles of composing types into high order constructs. It follows Hilbert’s axiomatic method “to build everything from as few notions as possible”. All defined combinators use standard Golang notations from which other combinator notations are constructed. Think about combinator expressions in the terms of the language being able to define how types and instances should transform. These expressions shown that any universal computational could be reduced to an expression purely in terms of types and combinators. The crucial idea of these expressions is the computational language, which delivers abstractions, where anyone can declare things and then reuse them without having to think about how they’re built inside.</p><p>In the end, combinators are fundamentally computational constructs. It is surprising, just how simple the combinator systems can be. Combinators make a bridge to the way humans think, allowing anyone to represent anything using structured symbolic expressions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e14f7f8cf35c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ad-hoc polymorphism in TypeScript with implicit context.]]></title>
            <link>https://medium.com/@dmkolesnikov/ad-hoc-polymorphism-in-typescript-with-implicit-context-5c11dd668dd?source=rss-56bcc01a8eac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c11dd668dd</guid>
            <category><![CDATA[polymorphism]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typeclass]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Systems in the Mist]]></dc:creator>
            <pubDate>Mon, 26 Aug 2019 11:58:12 GMT</pubDate>
            <atom:updated>2019-08-26T11:58:12.761Z</atom:updated>
            <content:encoded><![CDATA[<p><em>The article is a re-post from my original </em><a href="https://i.am.fog.fish/2019/08/10/adhoc-polymorphism-in-typescript.html"><em>blog</em></a><em>. Looking for feedback, comments and discussion on </em><a href="https://twitter.com/_fogfish_/status/1161241361242349568"><em>Twitter</em></a><em>.</em></p><blockquote>Ad-hoc polymorphism occurs when a function is defined over several different types acting in a different way for each type.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OR7bg2yGSFByinAinnvuvA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Overloading is a most simplest example of ad-hoc polymorphism. It associates a single function with many implementations. TypeScript supports only dynamic <a href="https://www.typescriptlang.org/docs/handbook/functions.html#overloads">overloading</a> — you have to execute runtime checks of types and choose appropriate behavior using if-else syntax. TypeScript compilation output a pure JavaScript code. Its dynamic nature do not allow to implement overloading similarly to other languages.</p><p>TypeScript overloading requires usage of typeof and instanceof checks, which are considered as anti-patterns in type-safe environments. Usually, type systems offers a better options - <a href="https://en.wikipedia.org/wiki/Type_class">Type-Classes</a>. Type-classes has been designed by P. Wadler and S. Blott as a <a href="http://homepages.inf.ed.ac.uk/wadler/papers/class/class.ps">new approach to ad-hoc polymorphism</a>. Haskell is one of the first languages that adopted this technique.</p><p>The type class just defines trait to a group of types. This trait is a contract, it can be implemented without any changes to the original code. One could say that inheritance does same, but no one needs to predict inheritance demand with type classes before hand. Please see the comparison of <a href="https://dev.to/jmcclell/inheritance-vs-generics-vs-typeclasses-in-scala-20op">inheritance vs type classes</a>.</p><p>Let’s look into a classical example of type class polymorphism with Scala:</p><pre>trait Show[A] {<br>  def show(a: A): String<br>}<br><br>object Show {<br>  def show[A](a: A)(implicit sh: Show[A]) = sh.show(a)<br>}<br><br>implicit val intCanShow: Show[Int] =<br>  new Show[Int] {<br>    def show(int: Int): String = s&quot;int $int&quot;<br>  }<br><br>implicit val strCanShow: Show[String] =<br>  new Show[String] {<br>    def show(str: String): String = s&quot;string $str&quot;<br>  }<br><br>Show.show(10)      // &quot;int 10&quot;<br>Show.show(&quot;hello&quot;) // &quot;string hello&quot;<br>Show.show(true)    // compile time error implicit value    <br>                   // Show[Boolean] not found</pre><p>That is basically a type class! There is a behavior trait that describes the functionality and implementations for each required type. Important highlight, the shown functionality is defined outside of each specific type definition. It could be implemented in a different modules or libraries than the behavior trait. In Scala, the implicit mechanism does a matching of class instances with code that uses them. The compiler infers a right implementation using Scala’s implicit feature while executing a generic show algorithm.</p><p>There is a wish about <a href="https://github.com/Microsoft/TypeScript/issues/10844">implicit in TypeScript</a> but there is a doubt that it will ever be materialized.</p><p>Let’s implement type classes for TypeScript at “user-side”.</p><h3>Demystifying type classes</h3><p>Knowing the implementation details behind type classes makes them comfortable to use. There is a great <a href="http://okmij.org/ftp/Computation/typeclass.html">post</a> that</p><blockquote><em>looks behind the scenes of the abstraction of parametric overloading, also known as bounded polymorphism, or just type classes.</em></blockquote><p>I’d like to emphasis on two techniques, which are relevant for TypeScript context: <strong>dictionary passing</strong>and <strong>intensional type analysis</strong>.</p><p>Dictionary passing is most well-known techniques of implementing type classes. It has been implemented in Haskell with a greatest advantage to other languages — Haskell can do dictionary passing automatically. Compiler translates type-class declaration to records in the dictionary. Each method has corresponding dictionary record, which is straightforwardly used by compiler to infer a corresponding types.</p><p>Intensional type analysis is complementary to compile-time type class resolution. The appropriate overloading operation is chosen at run-time using type identification. Intuitively, TypeScript/JavaScript uses the runtime technique to implement ad-hoc polymorphism. The intensional type analysis takes expression-by-expression and eliminates all reference of type classes and they constrains using type annotation of all identifiers.</p><h3>Attempt on Type Classes implementation</h3><p>Let’s sketch a type class implements in TypeScript using dictionary and intensional type analysis technique.</p><pre>interface Show&lt;A&gt; {<br>  show(a: A): string<br>}<br><br>class IntCanShow implements Show&lt;number&gt; {<br>  show(int: number): string {<br>    return `int ${int}`<br>  }<br>}<br><br>class StrCanShow implements Show&lt;string&gt; {<br>  show(str: string): string {<br>    return `string ${str}`<br>  }<br>}<br><br>namespace Show {<br>  export const Number = new IntCanShow<br>  export const String = new StrCanShow<br>}<br><br>function show(x: any): string {<br>  return Show[x.constructor.name as keyof typeof Show].show(x)<br>}<br><br>show(10)         // int 10<br>show(&#39;hello&#39;)    // string hello<br>show(true)       // runtime error Cannot read property &#39;show&#39; of <br>                 // undefined</pre><p>Here, namespace Show is a dictionary that support a run-time matching of class instances with code that uses them, x.constructor.name (or other runtime reflection) resolves a type identification.</p><p>Unfortunately, the proposed implementation do not implements compile-time type safeness. The code fails at runtime if supplied type is not implemented by the dictionary namespace Show.</p><p>A few brute force ideas to improve it</p><pre>function show&lt;T&gt;(x: T): string {<br>  return Show[x.constructor.name as keyof typeof Show].show(x)<br>}<br><br>//<br>// fails at compile time with error and do not guarantee type safeness<br>// Property &#39;constructor&#39; does not exist on type &#39;T&#39;.</pre><p>Usage of overloads solves a problem of type safeness but we are loosing a flexible code decoupling. All supported types have to be declared in single module. It is impossible to offload a functionality outside of each specific type definition, implement it in different modules or libraries.</p><pre>function show(x: number): string;<br>function show(x: string): string;<br>function show(x: any): string {<br>  return Show[x.constructor.name as keyof typeof Show].show(x)<br>}</pre><h3>Type Classes in TypeScript</h3><p>Fortunately, the solution exists by enforcing type safety of generic function show&lt;T&gt; while delivering a type identification:</p><pre>function show&lt;T&gt;(x: T): string {<br>  return Show[x.constructor.name as keyof typeof Show].show(x)<br>}</pre><p>In order to fulfill our type safety requirement, the type T must reflect required types and only accept types defined in implicit dictionary (e.g. namespace Show). The implementation of latter constrain is easy.</p><pre>namespace Show { ... }<br><br>type TShow = keyof typeof Show<br><br>function show&lt;T extends TShow&gt;(...) { ... }</pre><p>The implementation of both constrains requires definition of generic type Cat&lt;T&gt;. It constrains a required type of instance x and ensures that these types are implemented by implicit dictionary.</p><pre>function show&lt;T extends TShow&gt;(x: Cat&lt;T&gt;) { ... }</pre><p>The implementation of Cat&lt;T&gt; is inspired by higher-kinded polymorphism feature from <a href="https://github.com/gcanti/fp-ts">fp-ts library</a>but it fully relies on TypeScript native index type query and indexed access operators <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#index-types">features</a>.</p><pre>type Cat&lt;T&gt; = Cats[T]</pre><p>We just projects a type T, which is eventually type of all know keys of implicit context, to an required type. Unfortunately, it required definition on another dictionary interface Cats {} to store all known types. The final definition of type Cat&lt;T&gt; is</p><pre>interface Cats {}<br><br>type Cat&lt;T extends keyof Cats&gt; = Cats[T]</pre><p>The final implementation of ad-hoc polymorphism (type-class) with TypeScript looks</p><pre>//<br>// Generic algorithms<br>interface Cats {}<br><br>type Cat&lt;T extends keyof Cats&gt; = Cats[T]<br><br>namespace Show {}<br>type TShow = keyof typeof Show<br><br>interface Show&lt;A&gt; {<br>  show(a: A): string<br>}<br><br>function show&lt;T extends TShow&gt;(x: Cat&lt;T&gt;): string {<br>  return (&lt;any&gt;Show[x.constructor.name as TShow]).show(x)<br>}<br><br>//<br>// Int<br>class IntCanShow implements Show&lt;number&gt; {<br>  show(int: number): string {<br>    return `int ${int}`<br>  }<br>}<br><br>namespace Show {export const Number = new IntCanShow}<br>interface Cats {Number: number}<br><br>//<br>// String<br>class StrCanShow implements Show&lt;string&gt; {<br>  show(str: string): string {<br>    return `string ${str}`<br>  }<br>}<br><br>namespace Show {export const String = new StrCanShow}<br>interface Cats {String: string}<br><br>//<br>// Usage<br>console.log(show(10))      // int 10<br>console.log(show(&#39;hello&#39;)) // string hello<br>console.log(show(true))    // compile time error  <br>                           // Argument of type &#39;true&#39; is not <br>                           // assignable to parameter of type <br>                           // &#39;string | number&#39;</pre><h3>Type Class library</h3><p>A few times in this post, I’ve pitched a requirements to offload a functionality outside of each specific type definition and implement it in different modules or libraries. TypeScript supports a <a href="https://www.typescriptlang.org/docs/handbook/declaration-merging.html">declaration merging</a>. This features helps us to build a library of type classes.</p><pre>// typeclass.ts - basic types <br>export interface Cats {}<br><br>export type Cat&lt;T extends keyof Cats&gt; = Cats[T]<br><br>export type Implicit = {[key: string]: any}<br><br>//<br>// show.ts - generic algorithm<br>interface Show&lt;A&gt; {<br>  show(a: A): string<br>}<br><br>export function show&lt;A extends Implicit, T extends keyof Cats&gt;(implicitly: A): (x: Cat&lt;T&gt;) =&gt; string {<br>  return (x) =&gt; {<br>    return (&lt;any&gt;implicitly[x.constructor.name]).show(x)<br>  }<br>}<br><br>//<br>// int.ts - support for data type<br>class IntCanShow implements Show&lt;number&gt; {<br>  show(int: number): string {<br>    return `int ${int}`<br>  }<br>}<br><br>declare module &#39;./typeclass&#39; {<br>  interface Cats {Number: number}<br>}<br><br>//<br>// app.ts - use type classes<br>namespace Show {<br>  export const Number = new IntCanShow<br>  // ...<br>}<br>const myShow = show(Show)<br><br>myShow(10)</pre><p>You have to be aware of ambient context limitation. It is only allowed to use string or numeric literal as const initializers. The following code fails. Therefore, the dictionary have to be declared in single file.</p><pre>declare module &#39;./typeclass&#39; {<br>  namespace Show {<br>    export const Number = new IntCanShow<br>  }<br>}</pre><h3>Limitations</h3><p>Unfortunately, proposed approach do not work out of the box for all types, especially those that uses built-in scalar type to represent an instance, because type analysis happens at run-time. As an example, the following types are casted to String and Number respectively.</p><pre>type MyTerms = &#39;hello&#39; | &#39;world&#39; | &#39;.&#39;<br><br>enum MyEnum { A = 1, B, C }</pre><p>The plain JSON object and interfaces are another example that requires a special techniques to give a hint to type analysis</p><pre>interface User {<br>  name: string<br>}<br><br>const user: User = &lt;User&gt;JSON.parse(&#39;{&quot;name&quot;: &quot;joe&quot;}&#39;)</pre><p>The runtime type analysis fails because constructor.name returns an Object type for it. You can either use a <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions">discriminated unions</a> to explicitly label each external object or cast object to the class.</p><h3>Conclusion</h3><p>TypeClasses are not first-class citizen in the TypeScript language. Additionally, the language do not provide a concept of implicit that remains to be a good solution for ad-hoc polymorphism in Scala. However, TypeScript has advanced type system that allow us to write type classes. The syntax and implementation is not straight forwards at the first glance but depicted technique helps to achieve it.</p><p>Looking for feedback, comments and discussion on <a href="https://twitter.com/_fogfish_/status/1161241361242349568">Twitter</a></p><h3>References</h3><ol><li><a href="http://homepages.inf.ed.ac.uk/wadler/papers/class/class.ps">How to make ad􏰀-hoc polymorphism less ad-hoc</a></li><li><a href="http://www.cis.upenn.edu/~bcpierce/tapl/">Types and Programming Languages</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c11dd668dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>