Posts in Tutorial (20 found)
The Coder Cafe 4 days ago

Building Barista—Part 2: Formal Verification and TLA+

☕ Welcome to The Coder Cafe! Part 1 of Building Barista covered the architecture. Today, we explore formal verification through a real bug my tests missed. You’ll learn what model checking is, how to read a bit of TLA+, and why it catches the bugs we never think about. I spent a lot of time on formal verification at Google; this time, I pointed it at my own system. Get cozy, grab a coffee, and let’s begin! One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. Now the worst-case scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. How do you prevent that? I picked my email provider for it: Plunk. Why Plunk? Because it accepts an idempotency key. When calling Plunk, I pass a key like : the user and the day. If Plunk receives the same key again, it doesn’t send anything; it replies with a 409. My code reads that 409 as “these posts were already sent” and marks them as sent. No duplicate. It was a conscious decision. Plunk is 10x more expensive per email than AWS SES, which has no idempotency key. I was happy to pay for it. So here was the state: A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Great mental model of the code. Pure intellectual control . Now, what if I told you my code had a bug? One that none of my tests caught. I only managed to find it with something called formal verification. Let’s see how. Formal Verification Before becoming an SRE, I worked in Air Traffic Management (I talked about it in Reliability Explained ). It’s a so-called safety-critical domain. You can easily imagine why. In a safety-critical system, green tests aren’t enough. That’s the blind spot of intellectual control: tests only check the scenarios we thought about. And the bugs that hurt are, by definition, the ones we didn’t think about. In domains like this, green tests aren’t the end of the conversation. Some teams go further and prove that certain bugs can’t happen. Airbus, for example, used a static analyzer called Astrée to prove that the flight control software of the A340 and A380 is free of a whole class of runtime errors. So instead of picking scenarios one by one, what if we could check all of them? That’s the idea behind formal verification: describe the system precisely, write down the properties it must respect, and let a tool check that no possible execution breaks them. Note the word: verification . It answers “did we build the thing right?”, meaning does the design respect our properties. Not to be confused with validation : “did we build the right thing?”, meaning are these the properties we actually need. A tool can do the first. The second stays on us. There are several ways to verify a system, from mathematical proofs to running real code on generated inputs. The one I used is model checking . A model checker sees a system as states (a value for every variable) and actions (a step from one state to the next). It starts from the initial state, tries every possible action, then every possible action from each new state, and so on, until it has visited every reachable state. A test follows one path. A model checker walks all of them. That’s why it finds bugs nobody writes a test for. AWS described it in 2015, in a paper on how they use formal methods: one of their DynamoDB bugs had survived design reviews, code reviews, and testing. The shortest sequence of events to trigger it was 35 steps long. At each state, the model checker checks our properties. They come in two flavors: Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) When a property breaks, we get a counterexample : the exact sequence of steps that led there. The model checker I used is TLC. It reads models written in TLA+, a language created by Leslie Lamport to describe a system as states and actions. In other words: we describe the system in TLA+, and TLC explores every state it can reach. A TLA+ spec doesn’t look like code. There are no instructions executed one after the other. Instead, each action is a formula that says two things: when the step is allowed (a condition on the current state), and what the state looks like after it (the values in the next state). TLC then tries every allowed action, in every possible order. A few symbols are enough to follow the examples below: means “is defined as” is the value of in the next state and mean “for all” and “there exists” Let’s see it on a simple example. Imagine a cafe with one croissant left and two baristas. When a customer asks for a croissant, a barista does two things: first, they check the display case to see if there’s one left; then, they sell it. The property we want is a safety one (something bad never happens): the cafe never sells a croissant it doesn’t have. In other words, the stock never goes below zero. To model this cafe, we need two variables: : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . Now, the two actions. The first one is checking the display case: The first two lines are conditions: can only happen if barista is idle and there’s a croissant left. The last two lines describe the next state: is now selling ( means “every other barista stays where they are”), and the stock stays the same. The second action is selling: And the property, written as an invariant that must hold in every state: That’s the whole model. TLC starts from the initial state (one croissant, two idle baristas) and tries every action, in every possible order. In most orders, everything is fine. For example, barista 1 checks and sells, then barista 2 can’t check anymore because the stock is zero. But TLC finds one order that breaks the invariant: Both baristas looked at the display case before either one sold. Both saw a croissant. Both sold it. That’s how to read a counterexample: find the step where it broke (5), then walk back to the decision that made it inevitable (3). The fix is to make checking and selling a single action, so nobody can slip in between. Re-run TLC, and it explores every state without finding a violation. In a cafe, we can merge two steps. Across a network call and a database write, we can’t, and that’s exactly why idempotency keys exist. Now, let’s do the same with Barista. Back to Barista. Years after leaving Air Traffic Management, I wondered: what if I applied the same rigor here? So I wrote a TLA+ spec of the stage. The model was tiny: one user, two posts, a clock with eight slots per day, and two days. The key idea is that it tracks two things separately: what was really delivered to the user, and what Barista believes was delivered. If Barista works, both always agree. The full spec also has a few actions I’m leaving out here: the clock ticks, Rank picks new posts, and moves the next send time forward. Here are the variables (simplified): : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. And a simplified version of the action at the time: A few new pieces: defines a local name (here, the key). is a pair, our . adds to a set, and adds to the end of a list. And is a record: an email to containing these posts. Read it line by line. can only run once the send time has passed. If Plunk already knows the key, it replies with a 409 and nothing is delivered. Otherwise, the email goes out. Either way, Plunk remembers the key, and Barista marks the posts as sent. That last line is the one to watch. The real action can also end badly: Plunk delivers the email, then Barista crashes before recording anything. TLC tries that outcome too. Now the property, in the same spirit as the cafe’s : In plain English: Barista’s belief must match the truth. If a post is marked as sent, an email really contained it. I ran TLC. Guess what? Despite all the tests, despite the idempotency key I was paying 10x for, it failed on the first run . Every configuration failed, even the simplest one: no crash, no settings change. Here’s one of the counterexamples, in real times. Alice gets her email at 22:00 UTC: An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog One Email a Day A quick summary of Barista : it’s a system I built that fetches hundreds of sources, gets a unique prompt per user, and sends that user one email per day with the best sources for them. Making sure Barista sends a single email per user per day is something important to me. If Alice receives the same email twice on a random day, that’s a terrible user experience. As discussed in Part 1 , Barista is a set of independent stages coordinating through Postgres. The last one, , runs every 5 minutes, looks for the users whose send time has passed, and emails each of them the posts picked by the stage. The nominal scenario: The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ✅ Barista writes back in Postgres that the email to Alice was sent that day. The stage starts and notices an email has to be sent to Alice. Barista calls the email provider and receives an ACK. ❌ Before writing back in Postgres that the email was sent, Barista crashes. The stage starts again and notices an email has to be sent to Alice. Barista calls the email provider again and receives an ACK. ← Duplicate email ✅ Barista writes back in Postgres that the email to Alice was sent that day. A business decision: no duplicates, even if it costs more. A sound design, with an email provider deduplicating for me. Unit tests, integration tests, end-to-end tests. All green. Safety : Something bad never happens (e.g., Alice never receives the same email twice) Liveness : Something good eventually happens (e.g., Alice eventually receives her daily email) means “is defined as” is the value of in the next state and mean “for all” and “there exists” : how many croissants are left. It starts at 1. : where each barista is. Each one starts , moves to after checking, and ends . : the clock. : when user ’s next email is due. : the posts picked for ’s next email. : the idempotency keys Plunk has already seen. : the list of emails really delivered. The truth. : the posts Barista has marked as sent to . What Barista believes. An outage on May 20 eats Alice’s May 21 email. The catch-up send at 01:00 UTC uses key , so the regular send at 22:00 gets a 409, and its posts are marked as sent without being delivered. Alice never gets her May 21 email. Its posts are marked as sent, so Barista will never offer them again. No error, no alert. And it happens 21 hours after everything recovered. The fun part is that I never modeled an outage. Nothing in the spec says Barista can be down. But nothing forces to run on time either: in TLA+, the clock is just another action, and TLC is free to let it tick while waits. An outage, a slow deploy, a job stuck behind another one: for the model, it’s all the same. TLC tried every possible delay and found the one crossing midnight. So what went wrong? Plunk did exactly what it promised. A 409 doesn’t mean “these posts were sent.” It means “something was already sent under this key.” My key was the day of the attempt, not the day the email was for. As long as a send ran on the day it was due, it didn’t matter. The moment one slipped past midnight, it did. Should Barista skip the catch-up, then? No. Alice should still get her May 20 email. The catch-up was right; my reading of the 409 was wrong. Ironically, I was obsessed with sending too many emails, and the very thing I was paying 10x for made me send too few, silently. Would my tests have caught it? Honestly, no. I tested a crash after the ACK, and the idempotency key handled it. I would never have written a test where runs late, past midnight UTC, followed by a regular send the next evening. And that was exactly my fear in the first place. The fix? One key per email instead of one per day. I re-ran TLC. Green. The Future of Software Engineering? In December 2025, Martin Kleppmann, the author of Designing Data-Intensive Applications , published a post with a bold prediction: AI will make formal verification go mainstream . His argument is mostly about cost. Formal verification has always been expensive. Proving that seL4, an OS kernel of about 8,700 lines of C, was correct took around 20 person-years. For most systems, a bug was cheaper than the proof that would have prevented it. But coding agents are getting good at writing proofs. And a wrong proof isn’t dangerous: the checker rejects it, and the agent tries again. One of the issues with TLA+ has always been making sure the spec is accurate. A TLA+ spec is a model, and a model is only as good as its abstraction. TLC checks the spec, not the code. The hard part is making sure the spec describes what the code actually does. But with the rise of coding agents, especially over the last few months, I feel like this gap is shrinking. An agent can read the code and draft the spec, keep both in sync when the code changes, and turn a counterexample into a failing test against the real code. At Google, I spent a lot of time exploring formal verification, especially on convoluted logic: loops with several paths, retries, error codes. On many occasions, I found bugs despite significant test coverage. Back then, though, writing and maintaining a spec was a real investment, so it was reserved for the parts that truly justified it. That’s what’s changing. When a spec costs an afternoon instead of weeks, the question is no longer “is this part critical enough to deserve a spec?” It becomes “why not?” Does it mean software will be bug-free? No. As Kleppmann also points out, the hard part moves to the specification itself: are we checking the properties we actually care about? That’s the validation question from earlier. But think about what it took to find Barista’s bug: a property of a few lines, and a tool patient enough to try every delay, every order, every midnight. Now extend that. Maybe that’s what software engineering becomes: less time on how the code achieves something, more time on what must hold no matter what. Alice never receives the same email twice. Alice eventually receives her daily email. We write those down; agents write the code and the spec; tools check that the properties hold. Kleppmann compares it to compilers: we don’t read the machine code they produce, and maybe one day, we won’t read the code agents produce either. Will we get there? I don’t know. But it might be worth exploring in your own system: write down its invariants, and see whether a model can show you where they break. If you want to see what this pipeline picks for you, give Barista a try. Describe what you like to read, and your first email lands in your inbox in seconds. It’s free (one post a day), and every new account gets 7 days of the paid plan to try more. Resources Sources How Amazon Web Services Uses Formal Methods, Newcombe et al., CACM, 2015 Systems Correctness Practices at AWS, Brooker and Desai, ACM Queue, 2024 The Astrée Static Analyzer Prediction: AI will make formal verification go mainstream How we continuously validate formal specifications in production - Datadog

0 views

Monads in Lean

This post demonstrates how to use monads in the Lean programming language (Lean 4, to be specific). If you're not familiar with Lean, this part of the language is very similar to other functional programming languages, like Haskell or OCaml. Suppose we want to write a simple numerical expression evaluator that supports numbers with addition and division: What happens when we encounter a division by zero? We'll want our evaluator to report this as a failure, which will be represented explicitly using the the Option type: With this in hand, the eval function can be written as follows: safeDiv returns an Option ; to propagate that possible failure to its caller, eval also returns an Option , and - moreover - has to perform lots of tedious checking for the possibility of a none value. Is there a better way? Note a common code pattern repeated here: We can extract it into a helper function: And rewrite our eval using this helper: This is already much better; we can make it even cleaner using operator overloading: Congratulations - we've pretty much invented monads! In simplified form, the Monad type class in Lean is defined as: In our code, pure is equivalent to some , and bind is equivalent to withSome ; in fact, the Monad instance for Option is something like: An operator akin to >>? for monads is already defined in Lean; it's called >>= , and picks up the bind method of the Monad type class. So we can rewrite our evaluator using the standard Monad instance, without defining withSome or the >>? operator [1] : We can go even further with the do notation, which is syntactic sugar around >>= that lets us rewrite the evaluator as: This notation should be familiar if you've seen Lean code dealing with I/O; we'll revisit I/O later in the post. Functional programming languages place a lot of emphasis on pure functions that are free of side effects. There's no question that such functions are easier to reason about, debug, and even optimize (by memoization). That said, the real world is messy and sometimes side effects are inescapable; monads help encapsulate side effects in functional programs. The core idea is: side effects are encapsulated inside a Monad , which wraps the value returned from a computation. The bind method (or the equivalent >>= operator) lets us take a wrapped value and push it into the next computation in the sequence. This may look familiar from continuation-passing style (CPS). Continuations themselves can also be modeled with a monad [2] . The definition of bind is: Here's a mental model to think about it: Chaining multiple bind s together is essentially a sequence of computations while keeping track of the side effects. A monad decouples what computations do from how they are sequenced . The programmer describes the sequence of computations and their dependencies, while the monad's bind implementation handles the bookkeeping necessary to combine their side effects. Our evaluator case study shows one example of side effects: early return from a computation with a none value. Let's see another idiomatic way of doing that, with the Except type that contains either a successful result or an error value (very similar to the Result type in Rust). We'll begin by writing an exception-returning version of safeDiv : Instead of writing a whole new eval variant for Except , we'll create a generic one that works with any Monad [3] : Now evalM can be used with safeDivExc to implement an evaluator where division returns Except ; used with safeDiv , it would be equivalent to the Option -specific evalDo we've written before. Let's look at a more advanced example: an evaluator that also logs the computation it executes in a linear log of strings. The challenge here is that we still have to combine that with Option to support the divide-by-zero case, so we'll start by creating a new structure to carry the state of the computation: This will be the result of one eval call; it produces an optional value, along with a list of strings (the log). Here's the Monad implementation for this type: The main idea is combining the stored log with the log of the next computation by appending them (thus accumulating a linear log). Here's our evaluator: Note how the code of evalLogged doesn't have to deal with the mechanics of logging too much (other than adding new log entries). All of that is hidden within the monad instance. LoggedOption is an example of the writer monad , which is a write-only version of the state monad . One of the most important use cases of monads in functional programming languages is modeling mutable state through a computation. A stateful computation is modeled as a function that takes an initial state and returns a tuple containing the result value and a new, updated state. In Lean notation: To demonstrate this in action, let's enhance our evaluator to support variable assignments and lookups. Our state is going to be an association list of name, value pairs: And we'll augment our expression enum with additional operations: This is going to be our state monad: Note the correspondence of the run function to the State signature above: This is its Monad class implementation: And finally, the evaluator: Operations that don't deal with variables directly (like .num and .add ) just do their work as before. .div only has to deal with the actual monad type to ensure that none is propagated in case of division by zero. Note also that this evaluator supports stores as expressions, since they separately return a value and the updated state; therefore, computations like this one will work: Producing the result some (16, [("x", 12)]) . In a language with mutable state, modeling side effects is easy - just assign some state (like a struct field or class member). In a functional language like Lean, however, we have to carry this state across the computations explicitly; monads help us do this with elegance - by hiding most of the mechanics of actually carrying the state around, the majority of the code remains free of bookkeeping. Perhaps the most well known example of a monad in functional programming languages like Lean and Haskell is IO . To anyone who's written a "real" program that interacts with the outer world, IO is very familiar. Here's a customized "Hello" program that's typically taught in the first 15 minutes of learning a new programming language: Note the do notation here, suggesting monads. As mentioned before, do is syntactic sugar for the monad's bind method, or the >>= operator; we can rewrite this code more explicitly as: In essence, IO is a state monad, where the state carried around represents the "outside world". IO operations like println act on that world, and its state is carried over using bind , like other state monads. Here's a version of our expression evaluator that logs directly to standard out, instead of collecting the log as a list of strings: The only unusual construct here is OptionT , which is a monad transformer that helps us compose Option (for propagating failure from safe division) with the IO Monad [4] . The IO monad also supports throw for Python-like exception behavior, but in this example we use Option explicitly; exceptions are a matter of programming preference, and using them inside library functions like eval doesn't feel right to me. Just like in Haskell, monads in Lean should obey certain laws . Those are: Left identity : wrapping a value in pure and immediately passing it to f with bind should be equivalent to just calling f on the value: Right identity : extracting a value from a computation and immediately wrapping it with pure again should not change the computation: Associativity : the grouping of operations doesn't matter, as long as their order remains the same: Let's see how Option obeys these laws. For left identity, pure v is some v and the bind implementation matches some x to next x , which is equivalent to f v . For right identity, m >>= pure just rewraps a some value in pure , leaving none alone - this is equivalent to keeping things as they are. For associativity, if m is none then both sides are none . If m is some v , the left side is f v >>= g , and the right side reduces to the same, so again they are equivalent. While Lean doesn't enforce that a Monad instance obeys these laws, it has a separate type class called LawfulMonad which does require Lean proofs; this is useful for Lean's main use case - proving theorems about programs, expressed through its powerful type system. But this is a topic for another day. Examine the value of an Option If it's none , return none without proceeding Otherwise if it's some result , continue the computation with result Take a value wrapped with potential side effects Take a computation that takes this value and may produce additional side effects Combine the results into a final wrapped value It takes the current state, which for our use cases is an association list carrying values for all defined variables. It returns an optional result which is a pair of some value (in our case, the result of the computation) and an updated state.

0 views

Claude Code token cost explorer

I am experimenting with involving subagents more in my LLM coding agent workflow. I discovered that subagents make it more difficult to diagnose token usage in Claude Code, because the regular command only breaks down context usage for the main conversation, not for the subagents. I tried some existing tools like and , but they weren’t able to give me the sort of breakdown into specifics I needed to optimise my usage. Thus, I shamelessly had Claude Code whip up a tool that gives me a better view of its token usage. This is vibecoded in the true sense of the word – I have barely looked at the code – but I’m okay with that becuase it is not critical infrastructure and it does what I need it to. If you want to know how to get more out of your Claude Code sessions without paying more for it, here’s how you can find out. First, open the context cost explorer in your browser. Everything happens locally on your machine, so none of your transcript data leaves your computer. If you’re the paranoid kind, you can verify by opening the network tab in your browser and reading in a non-sensitive session and seeing that nothing funny happens. Then follow the steps below, or use your own analytical ability. (Continue reading the full article on the web.)

0 views
James Stanley 1 weeks ago

How to make a CNC plasma cutter with high-frequency start

The issue with high-frequency start ("HF start") on plasma cutters is that igniting the pilot arc creates an enormous amount of electromagnetic interference which causes problems for nearby electronics, in particular tending to disconnect the USB connection to your CNC motion controller. You can solve this by talking to the motion controller over WiFi. This is my machine in its temporary location on the workbench: If you still need to acquire a plasma cutter then I obviously recommend trying to get one with "blowback start" instead of "HF start" so that you don't have to worry about it. In acquiring a machine with HF start I made an error. But I got it to work anyway, so if you already have an HF start machine and you want to use it for CNC, you might be able to do the same thing. I kind of wanted a CNC plasma cutter because I have recently spent lots of time and end mills making planar parts like this for my cyclecar at excruciatingly low feed rates and depths of cut: So I started placing some bids on eBay and accidentally won a Parkside PPS 30 B2 for £80: The seller stated that he bought it from Lidl on a whim but then realised it needed a compressor and he didn't have one. If I had done my research I would not have bid on a machine without blowback start, but here we are. So when it arrived I set it up on the garage floor and tried to run my 6040 CNC router while lighting the plasma arc. As you might predict, I couldn't get it to work. Most of the time lighting the arc would disconnect UGS from Grbl. But serendipitously I was running a test program that had a small number of very long and very slow movements, which meant I had several minutes of motion left in Grbl's buffer, and I noticed that even though UGS got disconnected from Grbl and was totally broken... Grbl was still moving the machine! It was still following my gcode perfectly. So the issue isn't that the HF start actually prevents Grbl from working, it's just that it disconnects the USB serial connection . Solution: use FluidNC on an ESP32 board and talk to it over WiFi. FluidNC is Grbl-compatible but suitable for more modern microcontrollers. Charlie suggested talking to the controller over fibre optic, which would probably work even better than WiFi but is more faff to set up. Annoyingly, ESP32 outputs are 3.3v instead of 5v. I made up a breakout board for an Arduino Nano ESP32 on a piece of stripboard with a 74HCT245 abused as a level-shifter on the outputs and this was sufficient to provide 5v output from 3.3v input, unsure how legit this is. You can see my custom breakout board in here: I initially experimented with some small stepper motors with A4988 drivers, left over from when I dismantled my i3 clone 3d printer , and I think these would have been fine. But I also had some spare Leadshine easy servos from the unfinished CNC mini mill project I bought years ago. I didn't think the Leadshine servos would work because I thought the interference would confuse the encoder input, but I tested them and they seemed fine. And they're more powerful and better so I used them. But for a plasma cutter I really don't think fancy servos are necessary, the cutting load is basically zero, it's just a glorified pen plotter. The Leadshine documentation says they need at least 18v, but I only had a 12v power supply lying around so I tried it and it seems fine. I did subsequently connect the alarm output from the servo to an input on FluidNC and it kept falsely triggering every time the arc started (sigh) so I am running the servos without the alarm input. That's no worse a position than I would have been in using open-loop stepper motors anyway. My motion platform is made out of box section steel and 3d printed parts: With GT2 belts left over from the same 3d printer, and printed pulleys. The bigger of the two orange parts was a 36-hour print and used 700g of material, that's my biggest ever 3d print. All printed in ABS-GF on Bambu Studio "strength" setting. The "linear rails" consist of 608 bearings riding directly on the steel box section. I didn't make any of them adjustable but I should have done because it has slightly more play in it than I would prefer. Again this would be nowhere near adequate for a router but for a plasma cutter I think it should be fine. (The aluminium foil wrapped around the torch lead was a shielding experiment from before I was using FluidNC, it didn't help, I just haven't taken it off yet). I need to get a larger water tray. To fire the arc on the plasma cutter, it has a 2-pin GX16 connector which you normally connect to the torch trigger. I connected it to a relay operated by FluidNC so that I can turn it on/off with M3/M5. (But note you need to give FluidNC a non-zero "spindle speed" else M3 won't do anything, so get used to "M3 S1"). So at this point I have a working CNC motion system, with an HF start plasma cutter that I can fire from CNC control. Time to cut something out? Unfortunately I have no plasma cutting experience and (story of my life) it's harder than it looks. I messed around with the air pressure, current setting, and feed rate, and I just couldn't get a clean cut in 4mm steel. That's disappointing because the machine documentation says it can cut through up to 12mm steel. But I tried a piece of 3mm steel and my first test cuts worked a lot better, so I tried to cut out a heart shape. (I got ChatGPT to write the gcode for this). It blew the fuse in the extension lead 3/4 of the way through because I foolishly had the compressor and plasma cutter plugged into the same one. D'oh! I moved the compressor to a different extension lead and then it worked first time, albeit with a lot of slag on the underside of the cut: I cleaned this off with the angle grinder and you can see that along one axis my machine is cutting nice straight sides but on the other axis it is quite badly bevelled: I am going to replace the consumables in the torch when they arrive, and failing that I am going to make the torch clamp angle adjustable, and I expect I will be able to get rid of the bevel, but I don't know if the combination of the excessive bevel and the poor cutting performance are evidence that my machine is actually faulty. This may be the real reason it was sold on eBay after hardly any use. I have subsequently had my 16 amp breaker trip a few times while cutting so I may want to either find a way to run the compressor on a different circuit or else upgrade the circuit I have. These are the switches and lights on my control cabinet: Though the "alarm" light is now surplus as the servo drives can no longer trigger it. The "torch" light comes on when FluidNC is asking for the relay to turn on, but the relay doesn't actually turn on unless the switch is set to "enable". This is so I can ensure that even when I'm fumbling the gcode the torch can't light unexpectedly. And btw I obviously don't have an emergency stop button on this machine, but I can still toggle the torch off, or switch the power off, and there's no world in which I'm running a plasma cutter unattended, so I'm not very worried about it. I also don't have limit switches. I don't really understand why people bother putting limit switches on DIY machines (unless they have an automatic tool changer or whatever). What's the benefit to having a global coordinate system? You need to set up work coordinates for every job anyway. I don't have limit switches on any of my machines, but on this one in particular I expect limit switches would falsely trigger whenever the HF arc starts. So what have we learnt about making CNC plasma cutters? you can use a HF start machine if you talk to the motion controller over WiFi you don't want any inputs to the microcontroller, including limit switches, emergency stop, alarm inputs, USB serial if you make linear rails out of box section and ball bearings then make some of them adjustable so that you can take out the play GT2 belts are adequate 3d-printed structure is adequate getting correct cutting parameters is not any easier than it is with milling unfortunately, so still lots to learn Leadshine easy servos appear to work with 12v supply even though the documentation says they need at least 18v I made a custom gcode sender to talk to FluidNC because I wanted it to work differently to any existing ones and coding agents make software cheap, but I'm pretty sure UGS can talk over WiFi so it is not necessary to make your own sender. If you make a CNC plasma cutter using information from this post then please email me and show me, I'd love to hear from you. you can use a HF start machine if you talk to the motion controller over WiFi you don't want any inputs to the microcontroller, including limit switches, emergency stop, alarm inputs, USB serial if you make linear rails out of box section and ball bearings then make some of them adjustable so that you can take out the play GT2 belts are adequate 3d-printed structure is adequate getting correct cutting parameters is not any easier than it is with milling unfortunately, so still lots to learn Leadshine easy servos appear to work with 12v supply even though the documentation says they need at least 18v

0 views
neilzone 1 weeks ago

Automating renewal of Let's Encrypt certificates with Home Assistant OS

I had an alert from my monitoring tool that the Let’s Encrypt TLS certificate for my Home Assistant OS installation had expired. The answer lay in the documentation for the Let’s Encrypt app : Certificates are not renewed automatically by the plugin. The app has to be started again to renew certificates. If the app is started again, it checks if the certificates are due for renewal. This is usually the case 30 days before the certificates’ due date. If the certificates are not due for renewal, the app terminates without changes. If the certificates are due for renewal, new certificates will be created. There are multiple ways how the app can be started to check/renew the certificates. One way to automate the certificate renewal is to configure a Home Assistant automation to restart this app every night via the Supervisor app restart action. My automation looks like this: I can see in the log for the Let’s Encrypt app, and the log for the automation, that it ran as expected so, fingers crossed, no more TLS certificate issues…

0 views
Nelson Figueroa 1 weeks ago

How to Serve Your Hugo Site on a Local Network

Sometimes it’s useful to check how a Hugo site looks on a real mobile device before deploying. That requires serving the site on a local network so other devices on that network can access it. Here’s the command to serve a Hugo site on a local network: Then open on your phone. The site should load and work as expected. The option is necessary because Hugo binds itself to by default, which means no other devices except the one serving the site would be able to reach said site. The option is needed so that links generated in the Hugo site all point to the local IP address the site is being served from. Otherwise, the links will be generated with . Note that if you’re on public wifi this command may not work due to client isolation! If you need to get your local IP address, here are a few methods depending on your operating system. On macOS, try running: If it returns nothing, try instead. On Linux, try this command. The first address is usually the one you need: On Windows, try this command. Look for “IPv4 Address”: I felt the need to write this post because I tried this command that worked for loading the home page on my phone, but everything else was broken. I couldn’t tell if I was doing something wrong or if there was something wrong with Hugo. With this command, the home page loaded on my mobile device on the same local network, but clicking on any links to other pages of the site resulted in a connection error. That’s because the links are all generated with , which means the device tries to connect to itself and the Hugo server is running on a separate device. Using is necessary to get past this.

0 views
Takuya Matsuyama 1 weeks ago

Effective Neovim setup for agentic coding towards 2027

Hey, what's up? It's Takuya here. In this article, I'm going to share my new Neovim setup, which I built from scratch with an AI agent. Watch the video tutorial on YouTube: My Dotfiles is here: In the previous setup I shared in 2023 , I used LazyVim to avoid maintaining plugins, and it's been working great. Thanks to the LazyVim community, I could easily keep my plugins up to date and tweak the settings. But the more I customized it, the more unstable it got. Fixing errors after every LazyVim update was kind of annoying. Meanwhile, recent Neovim releases have added a lot of built-in features that used to need plugins: So I decided to build a fresh setup on top of them. The agentic coding paradigm shift has arrived, and I've adapted to an agentic workflow . These days, I mainly use Neovim to review code , rather than to write it by hand. To be honest, I don't know how long I'll keep using it, since workflows are changing so fast. But I thought it would be interesting to share my current setup. Tweaking a Neovim config is super easy now, because you just tell your agent what you want. So instead of writing Lua, I wrote a spec of my config in English on Inkdrop , and fed it to my agent step by step via the MCP server . The spec describes what I want and why , not how . The agent figures out the Lua. I gave the agent these rules: I mapped to . Below is the whole spec, step by step. Feel free to copy it and feed it to your own agent, and tweak it to your taste. I started by telling the agent where the spec lives: Neovim 0.12's experimental ui2 handles messages. It's turned on at the end of . tiny-cmdline.nvim shows the command line as a floating box, centered left to right, 20% from the top. It's set up in . A custom tabline in , with no plugin. lualine , one global bar, theme . snacks.nvim provides the notifier, indent guides, statuscolumn, and word highlighting. Later steps turn on more of it, like the picker and the lazygit integration. The snacks.nvim picker. oil.nvim replaces netrw and shows hidden files. nvim-treesitter , main branch. Mason + mason-tool-installer install on start, and never auto-update: nvim-lspconfig supplies defaults. For example, typing in a TSX file: Per-server settings live in . Neovim 0.12 merges these automatically, so there's no setup boilerplate. blink.cmp , version , preset: Enter accepts. conform.nvim formats on save with a 1000 ms timeout, falling back to the LSP. Since I mostly review code written by my agent now, this is the part of the setup I use the most. gitsigns.nvim with defaults. mini.diff from my fork ( , branch ). codediff.nvim for side-by-side diffs and history. I use it when my agent makes a lot of changes in the codebase. opens lazygit in a float through snacks.nvim , with the theme synced and the active border in the WarningMsg color. Pressing on a file closes lazygit and opens the file in the window it was launched from, through and . Lazygit's own config lives in , outside the Neovim config. snacks.nvim loads it together with the synced theme. It holds: copilot.lua with auto-trigger on, enabled in Markdown and help too. The keys work in insert mode: These are small helpers for passing context from Neovim to an agent. To try the setup in a real agentic workflow, I built a keymap cheat sheet website with Vite+ and my agent. To show how I use this setup day to day, I built a tiny app with it: a one-page cheat sheet of every keymap in this config. I followed Inkdrop's note-driven agentic coding workflow. Each task gets one note, which works as a shared place for me and the agent. I write the requirements, and the agent fills in the rest of the plan. I created a Waku app in : I created a new note and applied the built-in Implementation plan note template with . My requirements were just two lines, plus a link to the spec note: I copied the note link and passed it to Claude Code: Claude Code reads and updates the note through the Inkdrop MCP server, using the skill. Before writing the plan, it read both the spec note and my actual Lua config. Then it asked me about the decisions only I could make: It recorded my answers in Decisions Needed and broke the work into three phases: Reviewing a plan is much cheaper than reviewing code, so this is where I spend my attention. I told Claude Code to work on it, and it implemented all three phases in 1 minute 18 seconds . It checked off each phase in the note's Status section as it went. The cheat sheet has 7 sections and 59 keys, with dark mode. This is where the Git part of my setup comes in: After the review, I switched the project to pnpm and committed it. Finally, I pasted a screenshot of the working page into Claude Code. It filled out the note's Outcome and Follow-up sections. Now the note records what was built and why, including the follow-up to fix the typo in my spec. The finished note: Create a keymap cheatsheet for Neovim setup Writing code is very cheap now, so writing the config as a spec in a natural language felt natural. It's English and Japanese for me. The spec is readable, it keeps the why next to each setting, and I can rebuild or tweak the setup any time by just telling my agent what I want. The full spec is above, so feel free to copy it and make it your own. I hope it's helpful for your Neovim setup. Thanks for reading/watching! : a built-in plugin manager and : LSP setup with almost no boilerplate ui2: a new message UI : reloads Neovim and restores the session Write a step of the spec. Ask the agent to implement only that step. Reload Neovim with and check the behavior myself. Review the diff and commit. Read the spec and implement only the step I name. Add nothing beyond it. Check your work lightly: Neovim starts without errors: New keymaps exist: Don't build test projects or drive the UI. I check the behavior myself after the restart. Neovim restarts in the same terminal and restores the windows, tabs, and buffers. Save first with . Unsaved buffers block the restart. Or use to discard them. After a step that adds a plugin, shows an install prompt. Confirm it. Run the agent in a separate terminal split, not in a inside Neovim, since the restart kills it. Neovim 0.12 or newer. The config relies on built-ins that landed in 0.12: , , and the ui2 message UI. A Nerd Font. I use PlemolJP Console NF. Icons appear in the tabline, statusline, completion menu, and file explorer, so a plain font shows boxes. The config folder is a git repository. : the config root folder : enables for faster startup, then requires these files directly, in order: , assigned to the global : my config lives here : shared helpers : returns a table of helper modules, empty for now. Later steps add modules like , exposed as . : plain Neovim settings, one file per name above : installs every plugin in one call, then requires each group file Each plugin group gets its own file next to it (e.g. ), which configures its plugins with . : every keymap that uses a plugin, required last so all plugins are set up first. Group files hold no keymaps. Lua files are indented with tabs, formatted by stylua with its defaults. Leader and local leader are Space . Mouse is off . Keyboard-only. Clipboard is , so yank and paste go through the system clipboard. Indent is 2 spaces : , , and are all 2 and are on counts as part of a word, so is one word. Fits CSS classes and kebab-case names. Hybrid line numbers: + on , so the cursor line shows its real number. on . No wrap, 10 , 8 . always on . Text doesn't jump when git or diagnostic marks appear. 0 and one global statusline ( 3 ). Maximizes vertical space. Rounded borders on every float ( ). Popup menu: at most 10 rows, slightly see-through ( 10 , 10 ). Matching brackets flash briefly ( on , 2 ). on , so the terminal tab shows the file name. Diagonal fill in empty diff areas. + on : case-insensitive until a capital letter is typed. adds , so searches subfolders. completion: is skips , , , , , and off . Persistent undo ( on ) lives in . Undo survives closing the file. Swap files only get in the way. Snappier timing: 300 , 500 , 0 . Faster CursorHold events, and key sequences resolve without lag. Edit , , reopen it, then New splits open below and to the right . Folds come from Treesitter , with 99 . Everything starts unfolded, and folds can still be closed by syntax. , then / inside a function Short messages: corner popup up to 30% of the screen tall, gone after 5 seconds . Long output (errors, , , shell commands, progress): a scrollable pager up to half the screen. Search count, search pattern, completion, completion list, and confirm prompts stay in the command line. Output of a command I type goes to the command line too, whatever its kind. It expands over the bottom of the screen until the next key. moves it into the pager. With 0, the command line needs somewhere to appear, and near the top is where the eyes already are. Yanked text flashes briefly. Only the active window shows the cursorline. closes every hidden buffer, except unsaved ones. solarized-osaka , style, transparent background. The terminal's blur shows through, and the palette matches the Ghostty theme. mini.icons , also mocking nvim-web-devicons . One icon source for every plugin. Shown only when there are 2 or more tabs. Each tab shows the active window's file name with its icon, padded with 3 spaces, between slanted separators. Both edges slant outward going down, so each tab is a trapezoid, wider at the bottom: Colors from the solarized-osaka palette: Active tab: bold base4 text on yellow Inactive tab: base0 on base02 The icon takes the tab's text color. The separators take the tab's color on a transparent background, and so does the empty area after the last tab. Names longer than 20 characters are cut to 17 plus . Unsaved tabs show before the icon. Terminals show and empty buffers , with no icon. The project root is found by searching upward for , , , , , , or . Refreshes on cursor move and macro start/stop. The recording indicator replaces the hidden command line. The result would look like: incline.nvim shows a filename tag with an icon in the top-right corner of each window, plus when unsaved. With a single global statusline, each split still needs to say which file it holds. The tag hides when the cursor reaches its line. Words : the word under the cursor is highlighted everywhere. / jump between occurrences. It needs a language server, so it works after step 5.1. Smooth scroll is off . Scrolling should feel instant. The directory is a buffer, so renaming, moving, and deleting files is plain text editing followed by . Columns: icon, permissions, size, modified time. Renaming a file asks the LSP to update imports and saves those edits automatically. In the tabline (2.3), an oil tab shows its directory ( ) with no icon. Paths longer than 20 characters are cut from the left to plus the last 17 . Ensures 38 parsers: astro, bash, c, cmake, cpp, css, diff, fish, gitignore, go, graphql, html, http, java, javascript, jsdoc, json, lua, luadoc, luap, markdown, markdown_inline, php, printf, python, query, regex, rust, scss, sql, svelte, toml, tsx, typescript, vim, vimdoc, xml, yaml A FileType autocmd starts highlighting and Treesitter indent whenever a parser exists. runs on the event. Parsers stay in sync with the plugin version. todo-comments.nvim highlights , , and the like, with defaults. nvim-highlight-colors paints hex, rgb, hsl, ANSI, and CSS variable colors as backgrounds. Tailwind is off. Neovim's LSP document colors are turned off, so colors aren't painted twice. Servers: lua-language-server, vtsls, eslint-lsp, oxlint, tailwindcss-language-server, css-lsp, rust-analyzer, copilot-language-server Formatters: prettier, prettierd, oxfmt, stylua, shfmt Servers are turned on with : eslint, oxlint, lua_ls, cssls, vtsls, tailwindcss, rust_analyzer. Every server gets file-rename support ( / ). Underlined, not updated while typing, sorted by severity. Inline text: , with the source only when there are several. Gutter icons come from the shared icon set. The error is underlined, with inline and an icon in the gutter. The line also has a "never read" hint, but the gutter shows the error icon, since they are sorted by severity. oxlint flags the unused too, so each message shows its source ( , ). vtsls : Uses the workspace TypeScript and updates imports on file move. Server-side fuzzy matching and function-call completion. Inlay hints are short: no variable types, 30 characters max. lua_ls : knows the Neovim runtime, shows param-type hints, silences a few noisy checks. cssls : ignores empty rules. oxlint : starts with . Every language server from 5.1 also gets blink.cmp 's completion capabilities. Auto-brackets after functions. Docs pop up after 200 ms . Menu items are colorized by Treesitter, with kind icons from the shared icon set. Ghost text is off . Copilot already shows inline suggestions, and two ghost texts would clash. In the command line, the menu opens by itself for commands only, with nothing preselected. mini.pairs with defaults, in insert and command mode. oxfmt runs only when the project has an oxfmt config, like or a Vite+ . Projects using prettier keep their own formatter. turns format-on-save off or back on for the current buffer, with a notification. The command lives in . The fork groups changes into whole hunks, the way shows them. Explorer: tree view, 50 columns wide, opens files as the cursor moves, shows +/- line stats. Compact mode: only changes plus 8 context lines, with folds synced across panes. remembers the current window. quits lazygit, focuses that window with , then opens the file, so the cursor ends up in the file. Not a new tab and not a nested Neovim. Outside Neovim, it just runs . The edit command is written in fish syntax. Diffs render with . Mouse events are off and auto-fetch is off. in the files panel commits with commitizen ( ). gitlinker.nvim : copies a GitHub URL for the current line, or the selected range. Notes and docs benefit from suggestions as much as code does. Requires once. On macOS, the terminal needs Option as Alt. Both show the copied text in a notification. Pasting the path into an agent's prompt points it at the exact line. The template starts with Requirements and Related notes sections for me to write. The rest is a skeleton for the agent: requirements restatement, current state, decisions, phases, risks, status, and outcome. Instructions for the agent live in and blocks. Inkdrop strips them from the created note, and the agent reads them from the source template. It listed where every keymap is defined, with references. It found mismatches between the spec and the config. e.g. the spec had a typo, instead of , for finding files. It decided to trust the config over the spec. Keymap data Page and table component Remove starter leftovers : lazygit, to skim the whole diff : codediff, to walk through each changed file side by side : the mini.diff overlay, to see the changes inside a file

0 views
Maggie Appleton 1 weeks ago

Fortune Telling and Speculative Design

Practical tools for design engineers to explore possible futures through speculative design

0 views
Kev Quirk 2 weeks ago

How I Customised Pure Blog for This Site

A few people have reached out to me to ask how I did X, or Y with my site, so I thought I'd talk about the customisations I've made to this site, and how they work. Firstly, this site runs on Pure Blog , a CMS that I've been building over the last year or so. As it's matured, I've added features that allow more advanced users to do clever things without having to fiddle with the core platform. This means that people generally shouldn't have to fork the project and should continue to get all the new goodness as I release it. This site is no different. I haven't done anything clever that Pure Blog can't do out of the box - everything is documented so by reading the docs and using a bit of creativity, you can do quite a lot with this plucky little CMS. I'll link out to the appropriate docs as we go through this post. Ok, so what customisations have I made? This is going to be a fairly long post, so I'll list them here with links to each header so you can jump around and read the parts that interest you. If you want to see specific code examples for any of these customisations, feel free to contact me . I have three custom post types on this site - notes , links , and books . Notes are used as short-form social media type posts, links are links to other blog posts that I've enjoyed, and books are short reviews of the books I read. Each has their own layout and in the case of notes, they have a different view on the homepage too. To do this I've created a custom partial, but we will come to that later. I could just use the default post type for all these posts, but I prefer to have a customised UI at the back-end for each. Here's what books and links look like in my editor: Notes are a little different as I use a custom page for them that only I can access. This looks more like a social media post window than a blog post window: Read the custom post layout docs ➡ I like to think of hooks as little tripwires that are set to go off when certain conditions are met. For example, something happens when an image is uploaded, or a new post is published. They're extremely useful and I have a number of them on this site: Read the hooks docs ➡ Beyond custom post types, Pure Blog lets you drop PHP files into . These can either override default pieces of the site (like navigation or post footers), or serve as entirely bespoke standalone pages, like my quick-publish notes screen, or the terminal 404 page . Here's a full list of the templates and partials used on this site: Read the layout partials docs ➡ I've replaced the default feed with one that allows for filtering on post type. So one feed file, 5 feeds - one for each post type, and a fifth for everything. My custom feed template allows you to visit for everything, or (e.g. ) for the posts of that particular type. This custom feed file lives in and I then used redirects to redirect the default URL to . All the feed URLs are available here . I use a self-hosted instance of Sendy to send out email "newsletters" whenever I publish a new post. These emails always contain the entire post, so people can read my content from their inbox if they wish. Because I write notes much more frequently than long-form posts, I let readers choose what they receive: everything, long-form content only, or notes only. To make that work without sending people through clunky third-party forms, I wrote a custom server-side handler ( ). When someone submits the form on the subscribe page , the handler: This not only helps segregate the emails people receive, but it has also had a dramatic effect on spammy sign ups. Which, if you've ever run a newsletter, you will know is a common problem. Pure Blog allows you to add your own PHP helper functions for all kinds of things. On my site, I only have 1 function defined: which transforms fractional score strings in my book posts (e.g. ) into accessible star glyph strings (e.g. ). I just think that looks far nicer in a post than . But how is this star rating accessible? Well, it's rendered on the front-end like this so screen readers can parse it: Read the custom functions docs ➡ I don't do anything magical with the design on this site. I use the Victor Mono font , and around 850 lines of CSS, which I've added to the custom CSS field within settings. Combined with the custom , and files above, it gives me everything I need to customise the site from the default look to what you see now. I have a custom theme palette that I've defined too, also in settings. The colours used can be found at the bottom of my colophon . Read the design customisation docs ➡ One of the most powerful things about using a static site generator is the ability to use data files. With data files you can have a structure data file, like YAML, that contains repeated data, which can then be looped through on the front-end to render content. I really wanted Pure Blog to be able to support data files, so I added support very early on. Personally, I use two data files on this site: Data files are fantastic as they reduce the amount of repetitive code you have to write. Instead of typing , after , after manually, you write your once, then loop through it with a data file and Pure Blog does the rest. Read the data files docs ➡ The final thing I customise is my file. There's a number of things I do to the standard Pure Blog file to either redirect URLs, or protect various locations: This ended up being an even longer post than I anticipated, but hopefully it shows just how much you can bend Pure Blog to your will, by design . None of this requires hacks to the core code, or maintaining your own fork. Everything you see here is achieved using Pure Blog as designed: settings, custom CSS, hooks, custom layouts, and partials. Because all these files live inside , , and , I can upgrade Pure Blog the moment a new release drops without worrying about overwriting my site's bespoke features. That was always my goal with Pure Blog - a super simple, distraction-free blogging platform out of the box, with enough flexibility under the hood for tinkerers (like me!) to build whatever they want. If you're running Pure Blog and have built your own customisations, or if this post inspired you to try something new with your setup, hit the reply button below, or find me on Mastodon. I'd love to see what you've done with it. Thanks for reading this post via RSS. RSS is ace, and so are you. ❤️ You can reply to this post by email , or leave a comment . Post layouts Hooks and automations Templates and partials RSS feed enhancements Newsletter subscriptions Functions and helpers Design and typography Data driven pages .htaccess rules Final thoughts Email Obfuscation ( ) : Scans rendered content and encodes the site email address into hexadecimal HTML entities to protect against scrapers. This has been pretty effective at reducing spam - I wrote more about this feature in this post . Post Sanitisation & Metadata Preservation ( ) : Automatically generates date/time titles for new notes. Normalises layout values by stripping quotes (turning layout: "notes" into layout: notes), ensuring posts written in external editors like Obsidian don't break layout checks. Preserves in post frontmatter when saving via the admin interface so the Mastodon card at the bottom of every post continues to work. Image Optimisation ( ) : Automatically resizes images exceeding 2560px width whilst maintaining aspect ratio, also converts them to lossless WebP, and cleans up original unoptimised files. Mastodon Cross-Posting & Syndication ( ) : Automatically crossposts all published post types to Fosstodon via the Mastodon API. Notes posts are cross-posted with full body text and media attachments (uploaded to Mastodon's media endpoint). Articles, links, and books are crossposted with their description and permalink URL. Captures the returned Mastodon status URL and automatically persists into the post's frontmatter which is then used for the Mastodon card at the bottom of every post. Custom Font for Open Graph Images ( ) : Makes dynamic Open Graph image generation to use my custom font. (partial) : This replaces the default and adds post-type filter buttons, preserving query parameters across pagination. It also displays notes in full, while other post types show only the title and excerpt. (partial) : A customised version of the default file from Pure Blog. On top of the default tag list and post pagination, this version adds the obfuscated "Reply by email" button, a client-side Mastodon conversation card displaying live stats (favourites, boosts, replies) as well as a link to the post on Fosstodon, Pure Comments integration, and a subscription call-to-action. (template) : Dedicated discovery hub combining Pure Blog's full-text search with an alphabetical, weighted tag cloud showing post frequencies. (template) : An interactive metro map that lists all of the pages on this site. There's also an option to see the pages as a list. (template) : My quick-publish admin screen for composing and publishing short-form note posts. (template) : Dashboard for tracking the 100 Days to Offload challenge streaks in batches of 100 posts. (partial) : This replaces the default template in Pure Blog. It adds a custom layout, as well as 404 handoff ( ) to render the custom template without modifying core Pure Blog files. (template) : A fun interactive terminal-styled 404 page with custom commands that include goats! (template) : Endpoint that resolves and redirects visitors to a randomly chosen published post . Checks a simple verification question ("What is Kev's surname?") to keep bots at bay. Silently discards submissions that trigger a honeypot field, or exceed IP rate limits. Subscribes the user to the correct Sendy list(s) via Sendy's API in a single click. which is then used to render my blogroll page . which is used for my projects . Admin Access Restriction : I restricts access to specific allowed IP addresses. Legacy URL & Feed Redirects : 301 redirects mapping historical and URLs to clean root and routes that Pure Blog uses. Redirects for legacy feed and social endpoints ( , , , , , etc.) to or to make sure the feed URLs from various versions of this site don't break. Route Rewrites : clean URL routing for all my RSS feeds so they have simple to share URLs.

0 views
Abhinav Sarkar 2 weeks ago

An LC-3 Disassembler in Haskell

LC-3 assembly is an educational programming language. It is simple enough that complex programs can be written directly in it without needing a compiler, and thus it is often used in teaching assembly. An LC-3 textual assembly program is compiled to a binary object file by an assembler, and then executed by a virtual machine . Writing a virtual machine for LC-3 is a fun little exercise. However, in this post, we implement a disassembler for compiled LC-3 binaries back to textual assembly programs. This post was originally published on abhinavsarkar.net . LC-3 has a simple instruction set with only 18 instructions. It works with eight 16-bit registers (numbered from 0 to 7), and 16-bit addressable memory. LC-3 instructions are also 16-bit, with first four bits used for opcodes, and the rest for instruction arguments. There are instructions for doing arithmetic and bitwise logical operations, conditional branching, executing subroutines, loading from and storing to memory, handling interrupts and doing system calls. Some of them take source, destination, and base registers as arguments ( , , and respectively in the diagram above). Some other take integer immediate values, program counter, and address offsets ( , , and respectively in the diagram above). The instruction take a code for the syscall to execute. Notice that we count the bits from right to left, zero-indexed. When written in the textual assembly format, we use mnemonics for the opcodes and syscalls. The eight registers are written as to . The instructions can be labeled and referred from other instructions using them. Let’s start by looking at a simple LC-3 assembly file: As seen above, the assembly file can also contain assembler directives such as , , , , and . Quoting the docs: We assemble the program with the assembler, and then execute the resultant binary with the VM 1 : It works as expected! As much fun as it would be to write an assembler and a VM, in this post, we don’t assemble or run LC-3 programs, we disassemble them. We don’t care what the instructions do, only how they are encoded. Unlike an object file generated from X86 or Arm assembly, an LC-3 object file does not contain section tables separating code from data, symbol tables indicating function and variable names, relocation information, or debug symbols 2 . It contains only raw binary instructions and data that are freely intermixed in a single address space. This is made necessary by the fact that LC-3 has only 16-bit addressable memory. So data blocks and read-write memory addressed from code has to be within \(2^{16}\) bits or 8192 bytes of the code addressing it. Consider these bytes: A disassembler looking only at binary code has no context. A 16-bit word that decodes perfectly as a legal instruction may actually be a character, a part of a packed string, a number/byte literal, or a memory address. We need context to decode correctly, so the disassembler works in multiple passes: Let’s go over the disassembler part-by-part. First, the imports: We use the vector library for instruction lists, and the monad for manipulating them mutably. We also use bytestring for doing binary IO. Here are the data types we use: The type enumerates the eight LC-3 registers. The type represents the condition codes used for conditional jumping, which are negative, zero and positive. The type enumerates the eight standard LC-3 trap codes used for doing IO and halting the programs: The type is the heart of the disassembler. It doesn’t represent only the real LC-3 instructions, but also adds more constructors that are useful for disassembling: This representation lets us handle ambiguous data. Also note that we capture the raw bytes in some instructions like and . Finally, represents entire 16-bit binary code, and is the type for representing an LC-3 object file with an origin address and the binary code. Since we work a lot with bits here, we define some patterns to make it easier and less error-prone: Each LC-3 instruction has a 4-bit opcode, and many have 3-bit register or flag fields. So, we define two new types: (3-bit) and (4-bit), with pattern synonyms for exhaustive pattern matching. By defining patterns through , we map directly to the ISA specification. For example, visually shows the bit pattern for the opcode. GHC’s pragma enforces exhaustiveness, so no fallback cases are needed. The smart constructor functions and take the least significant 3 or 4 bits of the passed 16-bit parameter respectively, and return respective typed bits. First, we decode the registers and trap routines: We see the bit patterns in action here. The trap routines codes are as defined in the ISA. Next, the function extracts the opcode nibble (the most significant four bits), and decodes the arguments by calling , which dispatches on the opcodes: Now, we go over decoding of each instruction one-by-one. has two variations: one that takes two source registers, and another that takes one source register and one immediate value. First, we extract and decode the destination and first source register. Then depending on the sixth bit, we either decode the second source register or the value. The value is sign extended by calling the helper function . When decoding the second register, if we find that the forth and fifth bits are not , that means this is not a valid instruction. In that case, we return the raw bytes wrapped in the constructor, because the malformed instructions are far more likely to be data that happens to have an opcode prefix. Capturing them as lets us treat them as data in the later steps. This same pattern is used in decoding other instructions as well: extract and decode registers, flags, and values, and check fixed bits for validity. If valid, return the decoded instruction, or else the raw bytes. The instruction has exactly same format as the instruction, except for the different opcode. To decode the instruction, we decode the registers and check for the fixed bits. Decoding the instruction requires us to decode the condition flags, which is a straightforward mapping from their bit patterns. In case no flags are set, the instruction is likely to be an ASCII character instead with the high byte set to , so we add a special check for that. Note that we capture the raw byte in the output instruction, to be used later. The and instructions have same opcode, but differ in the bits 7–9, which are set to for . Note that the function also checks for the fixed bits, failing which it returns a instruction. The and instructions have the same opcode, differing in the 12th bit. Decoding the , and instructions is a straightforward matter of decoding their registers and offsets. Notice that the and instructions also capture the raw bytes. Decoding the , and instructions is similar to the , and instructions. Again, straightforward decoding of register and offset: The instruction is a constant byte pattern. Decoding the instruction requires us to decode the trap routines. We don’t care about the rest of the bytes if the opcode is for the instruction. That’s it for decoding the bytes to instructions. But that was the easy part. Up next, we get into the heuristic operations. , the function below, is our main entry point to disassembling the binary code. It runs in the monad so that we can work with a mutable vector of instructions. First we allocate the mutable vector, and then we do a basic disassembly of the binary code into it by calling . After that, we go over the disassembled instructions in , and use heuristics to guess better ones. Finally, we clean up by combining the character data and inserting the labels, and return the final immutable vector of instructions. is where our first heuristic is applied. We go over the binary code vector element-by-element, decoding each raw word using the function we wrote earlier. But we don’t stop there, we do an additional check. If a freshly decoded instruction is one of some instructions, preceded by some particular instructions, we use it to further disassemble some data. We recognize these three patterns: These patterns are very common and almost standard, so we can confidently use them for detecting character and string data. Also, note the checks in the beginning of that prevent already disassembled char/string data from being overwritten. At this point, we have decoded the instructions and char/string data. But there are more possibilities of improving the disassembly quality. In this pass, we revisit the decoded instructions and correct them based on their targets and neighbours: runs till a fixed-point is reached, that is to say, till the instructions stop changing. It does a backward sweep with the function, then a forward sweep, then repeats until no changes occur. We do this because a rewrite can create conditions for another rewrite. Doing this till fixed-point is safe because of the way is written: it only changes code-like instructions to data-like instructions, and never the other way. That makes the whole pass monotonic, causing it to eventually terminate. We do the sweep in both directions to make the changes order-independent. Next up is : The idea behind is that, certain instructions that point to other instructions are likely to be data. Different instructions have different confidence levels for their target addresses, encoded as : below carries out the actual rewrites: The two helper predicates distinguish definite data and speculative data: checks for , , , and the original side of . checks for the speculative data alternative. Note how speculative data can cause neighbouring instructions to become data, but cannot alone cause a branch/call instruction to change, thus limiting speculation from spreading. After the previous pass the instructions become stable. We now process them to do some cleanups. First, we merge consecutive characters into strings: uses to walk the instruction list and combine: If a run is not -terminated, we revert the characters in it to . Finally, we insert the labels before the instructions that other instructions point to: We also change the pointing instructions to use the labels instead of offsets. This concludes the entire disassembly of LC-3 binary code. To finish off, we need functions to print the instructions and to read the binary files. is our top-level function that takes an object file and returns the disassembly as text: simply pretty prints each disassembled instruction and wraps the result with and directives from LC-3 assembler format. Here is the pretty printer: The instructions are rendered in the LC-3 assembly syntax. words become directives. values become with proper escape sequences. instructions are rendered with both interpretations: the speculated data form followed by the original instruction as a comment. This preserves ambiguity for human review. The helper pretty-printers: The registers are printed as – . Numeric values are prefixed with , and the escape sequences ( , , etc.) are properly encoded in strings. The trap routines are looked up by their standard codes and output as their names. After all we’ve been through, this is a piece of cake: Only important thing to note is to combine the byte pairs in the big-endian order. The function reads a binary file from STDIN, parses it, and disassembles it to STDOUT: Error messages are printed and the program exits with status 1 on failure. And, we are done! Let’s test it on the “Hello World!” program : Amazing! We assembled the disassembled program and ran it, and it produced the same output. The assembly is also pretty much the same. To make sure the disassembler works correctly, let’s run it on a the binary code for a larger program: lc3-fizzbuzz.asm that output the solution for the Fizzbuzz problem. It works perfectly. You can also see the word-wise diff between original and disassembled assembly below: Except for the data section at the end, the assembly is pretty much same other than the label names. Perfect! Building a disassembler for a format without metadata is a fun exercise. You have to find the patterns in the data, come up with heuristics, and use them to write your disassembler. You may need to go over the output multiple times to refine it. While the approach here is specific to LC-3, the principles generalize to other code/data separation problems in binary analysis and reverse engineering. The full code for this disassembler is available here . If you have any questions or comments, please leave a comment below. If you liked this post, please share it. Thanks for reading! I patched the VM to not print when halting. ↩︎ Most LC-3 assemblers produce .sym files containing the debug symbols. But we don’t use them for disassembling the binaries in this post. ↩︎ Actually, the ISA defines opcode as reserved for future use. ↩︎ Thanks for reading this post via feed. Feeds are great, and you're great for using them. ♥ This post was originally published on abhinavsarkar.net . Read more of my posts and notes . Introduction to LC-3 Problem in Disassembling LC-3 Decoding Instructions Basic Disassembly Fixed-Point Cleanup Postprocessing Pretty-Printing Reading the Binary Finishing Up First, we decode instructions that are unambiguous. Then, we use the context of the decoded instructions to speculatively decode the rest of the instructions/data. We repeat this till a fix-point is reached. Next, we clean up the data by combining bytes. Finally, we insert labels at the right places. to are the real LC-3 instructions. represents the one reserved opcode that the ISA defines as invalid 3 . is for capturing raw encoded binary data. represents a single character. represents a string, that is a sequence of characters. is a textual label used to annotate instructions that other instructions may jump to. It doesn’t exist in binary data, and is inserted by the disassembler. is a speculated instruction. It holds both the original instruction decoded from the binary data, and the guessed instruction depending on the context. followed by : This pattern loads a character at the relative into the registers and prints it. If we see this pattern, we know that the instruction at current index plus is a character. So we disassemble it immediately as a character in . followed by : This signals that the data at the relative is a null-terminated one-character-per-word string. So we disassemble it character-by-character till we reach the null bit in . followed by : This pattern is for a null-terminated two-characters-per-word string, so we disassemble accordingly in . , used for , : If the target is known to be data or does not exist, this instruction must be wrong, because these instructions are for jumping to code. Rewrite the instruction to . , used for : may or may not point to data. But if the instruction is in a neighbourhood that mostly has data, it is very likely to be data itself. Rewrite such instruction as , capturing both the data and instruction forms. , used for , , : The target doesn’t strongly indicate code or data. However, if is as well, the instruction is likely to be data if present in a data-heavy neighbourhood. In such case, rewrite as , otherwise ignore. a run of s followed by to become a single with the terminator, and a run of two-character entries followed by to become a single combined . I patched the VM to not print when halting. ↩︎ Most LC-3 assemblers produce .sym files containing the debug symbols. But we don’t use them for disassembling the binaries in this post. ↩︎ Actually, the ISA defines opcode as reserved for future use. ↩︎

0 views
Nelson Figueroa 2 weeks ago

Enums Can Be Enforced at the Database Level in PostgreSQL

PostgreSQL databases support having enumerated type (enum) columns so that the column only accepts one of a predefined set of values. I’ve worked with ORMs like Active Record from Ruby on Rails . Using Active Record, I could work with database columns that only allowed a certain set of values. I always thought that was only possible due to the ORM layer abstracting away these things, but that’s not the case. Enums can be enforced at the database level (at least with PostgreSQL). I’ll demonstrate on a PostgreSQL container with a simple table. I’ll be using Podman. You can also use Docker to follow along, just replace with in the commands. Make sure Podman/Docker is running, then run the following to get a running PostgreSQL container locally: Then exec into the running container: Now we can start setting up the table to try out enums. First, we’ll create the enum type itself. It’s going to be a type just like or are types in a database. I’m thinking of CI/CD pipelines to use as an example, so the enum will be called and it’ll only accept the values , , , and . Run this SQL query in the container: PostgreSQL should return: Now let’s create a simple table that makes use of the enum. The table will be called and it’ll have two columns: of type , and which uses our enum type . Run this in the container: PostgreSQL should return: Now let’s try inserting a row. This SQL query inserts a row where is and is one of the four predefined enum values ( ). PostgreSQL replies: We can check for the newly created row: You should see: Now let’s try inserting a row with an enum value that is not a part of the values we defined. We’ll try inserting for the column. We should get an error. PostgreSQL should say: The value isn’t one of , so PostgreSQL gives us an error. PostgreSQL itself is enforcing enums! No ORMs here. Note that the values in the enum are case sensitive. So inserting instead of will fail: PostgreSQL returns the error: Another caveat is that inserting as the value for is still allowed unless the column is also created with . Let’s say we actually want to be a part of the enum. We can modify the enum like so: PostgreSQL responds with: Now that is a valid value, we can try inserting again and we won’t get an error: PostgreSQL responds with: We should have two rows total now. We can double check: You should see: We successfully added a value to the enum and used it in a new row. One final note: there isn’t a clean way to remove a value from an enum. You can add values, but you would need to rebuild the enum if you want to remove any values. Plan ahead! Now that the demo is over, exit the PostgreSQL prompt by running: Then clean up the container and, optionally, the image: We created an enum type with predefined values, tried inserting both valid and invalid values, and it was all enforced at the database level with no abstractions from an ORM!

0 views
neilzone 2 weeks ago

Fixing the unavailability of Tasmota devices after HomeAssistant restarts

Earlier this year, I moved from running HomeAssistant in Python venvs to HomeAssistantOS . After an initial challenge with proxying , it has been working fine. I still don’t like using HAOS, but I can live with it. It seems to need updating a lot , and there is no - at least, not that I have found - automated way of doing this. So I am using an automation based on this template to automate updates . This works fine, but I have noticed that my Tasmota devices - of which I have quite a lot - are unavailable after HomeAssistant Core restarts. There are a lot of search results about this, so I am not the only one with this problem. I looked into a couple of the options ( to 0, and to 0), but I already had these set. Reloading the Tasmota integration did not do anything either. What seems to have worked, though, is an automation which tells all the Tasmota devices to restart, once HomeAssistant restarts . Mine looks like this: This seems - a bit more testing needed - to preserve the state of the device, so if it is off when it restarts, it remains off, and vice versa. I imagine that, because the Tasmota devices are restarting, if HomeAssistant tried to send a command to one or more devices during this restart window, the command would fail. Probably not an issue for me, but perhaps something to bear in mind.

0 views
Jeff Geerling 2 weeks ago

Noctua Fan Swap on a Calnex Rb/GPS Frequency Reference

Since this will be the only source of this process on the Internet 1 , I figured I'd document a quick fan swap I did on a piece of test/reference equipment I'm running in my Atomic Clock Tower . I took my Torx T10 screwdriver and popped off the top cover. The screws required some force to loosen, as they were all secured with Loctite. The inside is simple and serviceable. There's a SpectraTime GRClok-1500 , with an integrated timing-grade GPS module, and a stabilized 10 MHz output 2 .

0 views
neilzone 2 weeks ago

LibreOffice Writer, changing text styles, and accepting formatting changes

Hello, future Neil. Here are the two things that you often want to do with formatting and LibreOffice Writer, but do not always remember how to do them. You can use the “Find and Replace” function to change all instances of text in one style to another style. Ctrl + H to open “Find and Replace”. Under “Other options”, select “Paragraph Styles”. In “Find”, select the style that you want to replace. In “Replace”, select the style with which you want to replace it. Often, I want to tidy up tracked changes in a document, to remove formatting changes. From the menu bar, select Edit / Track changes / Manage … Select the “Filter” tab, and, under “Actions” select “Formats”. Go back to the “List” tab, and then “Accept All”.

0 views
neilzone 3 weeks ago

Fixing my LocalBytes Tasmota smart bulb which had lost its Tasmota template

I have used a LocalBytes smart bulb in our porch light for ages . It is controlled by Home Assistant, so that it comes on a few minutes before sunset, and goes off later in the evening. For some reason, it reverted to Tasmota’s default settings - without the LocalBytes bulb functionality - a while ago. Now that the clocks have changed, and it is darker earlier, fixing it moved up my priority list. Fortunately, it was pretty straightforward, thanks to the LocalBytes documentation . The key bit is the Tasmota template for the bulb: With this, and the Tasmota instructions for importing templates , I have a working bulb again.

0 views

Unleashing agents inside the workshop

I recently learned of Ubuntu Workshops . In short, Workshops allow you to create an isolated development environment to safely work with AI agents. You get a configured (via YAML) sandbox where you can safely run an agent without the need for permission checks and guardrails. Workshops allow you to expose or block certain parts of your system as needed (for example, you can expose your GPU for local models or block access to your webcam). As an example, let's build a simple Rust app that converts images from the HEIC format (bane of my existence) to JPEG. We'll use Iced to provide a simple GUI that supports drag and drop. First, install the Workshops Snap from the Ubuntu App Store. I also had to install the LXD subsystem for virtualization : To setup the workshop, create an empty directory and run the following commands: This will give a workshop named "dev" with Codex and Rust ready to go. On first run, we'll need to login to Codex using the following: Next, we want to define an "auto-mode" for Codex so we don't have to deal with permission check prompts. We'll do this by defining an "action" in the file. We've added two actions, to define a non-interactive session, and for an interactive one. Both have the flag which bypasses permission checks. As an added benefit, actions make it easy to standardize how we pass instructions to agents. We could easily define a Claude action that accepts the same arguments as Codex. Now let's define our prompt, instructing the agent to build our Rust application. This could of course also be done interactively via the Codex TUI inside the workshop, or through a a AI software factory . For now, we'll create a file and add the following: Finally, we'll setup Git for version controlling. Time for the fun part! We'll use the command to build the application in the folder without needing any input from the user. The agent will now run completely autonomously with no need to press "enter" on permission checks. Our host system remains protected as the agent is sandboxed away from our filesystem and devices. In fact, you'll notice in the prompt we specified that the agent should not try running the application. This is because we didn't provide access to a Wayland or X11 display server, so the agent cannot run a GUI application. Here's what I got as a result: The UI isn't great, but it works and successfully converted some photos from my iPhone! After putting together this article and testing out workshops, I'd say it's definitely a tool worth using. Workshops add minimal overhead, provide a composable/reusable environment for development and safeguard your host system from agents going rogue. Between this and Myna , Canonical is doing a lot to support the new development workflows that are becoming common

0 views

Static Analysis for the Uninitialized

I really enjoy learning new things in my free time. Lately I’ve been studying this book on Static Program Analysis . The book is very good, but some of the formulas are quite dense so I like to try writing them out in code. The chapter I’m currently reading (chapter 9) has a section on finding possibly-uninitialized variables using bipartite graphs. I’ve found it to be quite enjoyable, so in this post I would like to describe, in my own words, how to do it. We’ll start by analyzing some code from a toy programming language the book uses called “TIP”, and then we’ll use the techniques we developed to analyze some Ruby code. In other words, we’re going to write a program to analyze programs. We’re really going to be meta-programmers today! The TIP programming language is like a very very simplified version of JavaScript. Below is the code we’ll be analyzing: This example is taken straight from the chapter. In TIP, you declare variables with the keyword kind of like in JavaScript. In chapter 9 of the book, the TIP language only has integers; later chapters add pointers. In TIP, 0 is considered false, and there is a special function that returns an integer input from the user. Each line in the above code has a comment indicating which variables are possibly uninitialized. I keep saying “possibly”, and I’ll explain why later. The first line declares the variables with , and all variables start as “uninitialized” when they are declared. The second line gets input and assigns it to , so now only and are uninitialized. The third line adds and and assigns it to . On this line, is still considered to be “uninitialized” because is uninitialized, and the value of depends on the values of and . The fourth line is an if statement, and whether we take the if statement depends on input from the user. In other words, we can’t statically determine whether this statement is taken or not. The if statement doesn’t impact the “initializedness” of any variables, so all variables maintain their state ( and are uninitialized). If we take the branch, the 5th line will assign a value to , so at that line only is uninitialized. On the 6th line, we can’t know whether the if statement branch executed, so we have to say that and are possibly uninitialized. This is why our analysis is only giving us a “possibly uninitialized” result. If the branch is taken, then will be initialized, otherwise it won’t. But since we can’t know whether the branch will be taken, we have to be conservative and say that may be uninitialized on line 6. These two states, and , form a two element lattice, with on top. The top is the “safe” answer: it’s never wrong to say a variable might be uninitialized, it’s just less precise. When two paths in the code meet, like at the end of the if statement on line 6, we take the higher of the two states (because the less precise decision is also the “safe” one). On one path is initialized, on the other it’s possibly uninitialized, so after the if statement it’s possibly uninitialized. The rules for each line in uninitialized variable analysis are so-called “distributive functions”. For example, take the rule for line 3, . If we feed it the set , we get the same answer as feeding it and separately and then taking the union of the results: . This is just like in math class where we could say . In the case of a two element lattice and an analysis that uses a distributive function, we can represent the variable states using a bipartite graph. The book works out the proof for this, but I’m going to omit it (because I want to get to the coding part). But if you want to see the proof, check chapter 9! A bipartite graph is just a graph with “two sides”. Nodes on one side of the graph will connect with nodes on the other side of the graph, but never with their own side. I imagine it like two football teams tackling each other, each player is a node, and tackling someone else is an edge in the graph. Hopefully the players don’t tackle people on their own team, and they form a bipartite tackle graph! In our case, each node in our graph will represent a variable in the program, and we’ll have one extra node that represents “uninitialized”. For one graph, we’ll double those nodes, and use the edges to represent the flow of data through the code. For example, let’s look at the bipartite graph for the first line, : The node on the left represents the value “uninitialized”. On the line, the “uninitialized” value flows from to the , , and nodes. Next let’s look at the graph for line 2, : In this graph, the uninitialized node flows to itself. The variables and haven’t changed, so whatever value was in and just flow to the other side of the graph. The variable got initialized from , so no value flows to the other side of the graph. The reason no value flows is because we’re tracking “uninitializedness”, and on this line becomes initialized, so the absence of an edge means we got a value. If we repeat this value flow process and then line each graph up next to each other, we’ll end up with a graph like this: A black dot in the variable’s column indicates that the variable is possibly uninitialized at that point. Grey dots and lines indicate paths that don’t occur because the link was severed earlier. The dotted lines indicate alternate paths the code can take; an if statement has two outgoing paths. Looking at the graph we can see that (obviously) uninitialized ( ) is always uninitialized (we don’t bother to print that out because it’s not very helpful). We can also see that the black dots correspond to the “uninitialized variable” comments from the example code. For example, right after , the and variable have a black dot indicating that they are possibly uninitialized. If we assign each variable a number (and reserve 0 as the number for “uninitialized”), we can represent this bipartite graph in Ruby using a bit matrix. The graph needs to store a connection between any of the variables, and an “on” bit represents an “uninitialized” state from our lattice flowing from one variable to another. Since we need to be able to record an edge from any variable to any variable (plus the uninitialized value), the number of bits required is . Our example case has 3 variables, plus the extra variable for “uninitialized”, so we can do it in 16 bits. In practice though, to make accessing the data easier, we’ll align on a byte: The way we use this class is by assigning numbers to variables and then calling with the edges we need. For example, to represent , we need to connect “uninitialized” to the , , and variables. If we’ve assigned them numbers, we can do it as follows: Now we can represent the data flow rules for any line in the program. The next step is we need a way to connect graphs together. To do this, we’ll add another method that takes as input a list of “possibly uninitialized variables” (these are also known as “facts”) and returns a new list of “possibly uninitialized variables” based on the data flow rules for that graph. Since the input variables are just numbers, we can use each one as a row index into our bit matrix. Practically speaking, this means we bitwise OR together the rows for each input variable, and then get the position of the “on” bits in the output. Here is the code for the function: Let’s add a second rule for : In the above rule, just as in the visualization above, we connect the uninitialized nodes, then we connect to itself and to itself. These “self” connections mean “whatever value was in as input, we’re going to pass that along as output”. Now we can use the method and chain the two graphs together: At the start of the program nothing has been declared yet, so the only fact is “uninitialized” itself ( ). If we apply that to the first line, we see that all of the variables are “possibly uninitialized” (as expected). We can take the output of the application and feed it as the input to the next graph, and we see that the uninitialized variables are 2 and 3 (or , and ). Now all we need to do is define the rules for each line of code and apply them, and we’ll be able to calculate which variables are possibly uninitialized! Next we’re going to create a class that lets us record rules for each part of the program. The example code we wrote above works well for straight-line code since we can just apply the data flow rules from each line to the previous line. But the example program we have contains control flow and we’ll need a way to model the “dotted line” from the visualization above. To do that, we’re going to construct a simple control flow graph. A control flow graph (or CFG), is constructed from “basic blocks” where each block contains “straight line code” and ends in either a jump or a return. Each block has up to two outgoing edges, and those edges connect to possible jump targets. There are other ways to define a basic block, but this is my blog, so my rules! First we’ll define a class and a class. The class just holds on to the source line (a string for printing), and a graph representing the rules at that line. The class holds the list of objects that make up the block. It also contains a list of successors (jump targets) as well as predecessors (basic blocks whose jump target is the current block): Next we’ll define a class that has a bunch of helper methods that let us construct a CFG along with a graph for each line. I’m not going to explain all of the lines of the class because I think using the class is a better way to explain it. However, the full source is below. Let’s use the class to define all of the data flow rules for the sample TIP program: First we define a new program class. Then we ask the program class to record a source line of TIP along with the data flow rules for that line of code. I added lots of comments to explain the code, but let’s revisit one excerpt just to make double sure: Here we’re asking the program to record the TIP source code , and the data flow rule for this line is that “uninitialized” flows into , , and . This is exactly the same as the bipartite graph we created above, but this time we’re just recording that graph alongside the TIP source code. After we’ve recorded all of the rules, we call on the program so that it can calculate and set predecessor edges. We’ve got multiple graphs going on here. We’ve got a control flow graph that represents the program overall, and a bipartite graph representing data flow at each line. Our goal is to walk the CFG, and for each block calculate variable definedness at each line. The input state for each block is the union of the output state for that block’s predecessors. In other words, in order to analyze the whole CFG, we only really need to record the final state at the end of each block. Also, each calculation cares what happened in the past . For example, the definedness of the variables at line 2 care about what happened at line 1. This means we have a forward dataflow analysis . Any time the facts we derive depend on what happened in the past, it means we need to move forward through the code. So we define a strategy class that lets us analyze the CFG by moving forward through the code: In the above class, the method takes a basic block, looks up the predecessors for the block, then unions the output of those blocks. The function takes a block and some input (which happens to be the return value of ), and for each line of code in that block computes output facts based on the input. Those output facts are the “possibly uninitialized variables” at that line. Since we really only care about the state of the world at the end of the block, we just use an (a left fold for scheme people) over the code in the block. If, after analyzing all lines in the block, the facts are the same as what we had recorded previously, will return false. Otherwise, it saves the facts for that block and returns true. The method returns all blocks in reverse post-order (the traditional order for doing forward analysis that my grandparents used), and the method returns the successors for a block. We’ve got our CFG, and we’ve got a strategy for iterating the graph and analyzing it. Now we need to actually do the analysis. We discussed earlier that this problem is a two element lattice with a monotonic function (it moves up the lattice, never down). That means it’s perfect for a worklist algorithm. Our worklist algorithm is actually quite simple, it’s just this: Given an iteration strategy, ask for a list of blocks to process. While we have blocks to process, get a block. Ask the strategy for the input facts for that block, then ask the strategy to record output facts for that block given the input. If we learned something new ( returns true), then ask the strategy for children of that block and add the children to the worklist (if they aren’t in the worklist already). After this processing finishes, the hash inside the object will contain possibly-uninitialized variable information for each block. We can iterate over the blocks in the analysis and print out the possibly uninitialized variables for each line: Since we only recorded output information for each block, we have to do some extra processing at the end to print out the facts at each line, but if we run this code we finally get this output: Whew. That was a ton of work. But the good news is that we can reuse this framework for other languages too. I’m not going to explain the intricate details of this code, but we can use Prism to parse Ruby and feed that into our class. The function walks the Prism AST and records a rule for each statement, using the same kinds of rules we wrote by hand for TIP. Just to emphasize this, we wrote all of the data flow rules by hand for TIP, but our Prism code does it automatically based on assignments in the Ruby code. Once we get this into the program class, we can perform the same analysis on this code: (The curly braces are just how our class prints if statements, even for Ruby.) If you actually run this Ruby code, will raise a , because hasn’t been assigned yet so Ruby thinks it’s a method call. That’s exactly the kind of bug this analysis is meant to catch! You can find the full source for this program here . I feel like finding uninitialized variables isn’t that impressive. But the power in the technique here is that we can do any kind of analysis using this framework as long as the facts we track are a finite set, and the transfer functions are distributive (as I mentioned earlier). (The book calls this framework the IFDS framework, though I’ve omitted part of the full framework in this post). For example, we could use this same code to do “taint” analysis: “does this variable hold untrusted data?” If we were to number expressions and perform a backward analysis, we could discover what the book calls “very busy expressions”. A “very busy expression” is an expression that will definitely be evaluated no matter which path the code takes, before any of its variables change. For example: In the above example is considered “very busy” because we calculate it regardless of which branch the if statement takes. That means it is a candidate for hoisting above the if statement. Anyway, I’m having a lot of fun reading this book and I just wanted to share the stuff I’ve learned so far. Have a good day!

0 views
Martin Fowler 1 months ago

Build your slide template

Building a slide template starts with three foundational choices — colours, fonts and layouts. Sumeet Gayathri Moghe covers the basics of color theory and how to build a reusable palette, the essentials of typography, including serif, sans-serif, handwritten and monospace fonts, plus the finer points of kerning and leading, and why a near-blank layout might serve you better than the prescribed layouts that ship with your slideware.

0 views
neilzone 1 months ago

Blurring part of a video using ffmpeg

Hello, future Neil! You are probably trying to remember how you blurred part of a video. You blurred the bottom left portion of a circus video, using . : this is the size of the boxblur, 440px wide, 80px high : this is the position of the boxblur, starting from left top. i.e. 0 pixels from the left, 370 pixels from the top : this is how dense the blurring is. 2 is quite weak; 10 is strong : this needs to match the position of the boxblur

0 views