Hello World
Welcome to my blog – a space for sharing notes on CS, ML, and engineering.
Welcome to my blog – a space for sharing notes on CS, ML, and engineering.
When members connect to external MCP servers, their OAuth tokens are stored in the database. They used to be encrypted with one app-wide Fernet key, so a ciphertext copied to another row decrypted as that row’s token. Now each write uses a fresh AES-256-GCM data key, wrapped by Cloud KMS, with AAD naming the environment, workspace, connection, member, and token kind. The KMS work happens before the refresh token is rotated.
When agents run on an EC2 host, their processes can reach 169.254.169.254 too. Only the host’s management processes should be able to fetch instance role credentials from IMDS. An nftables output hook allows them by socket owner UID. Packets forwarded from another network namespace carry no UID, so a forward hook rejects them by destination alone.
Resizing an EC2 instance means stopping it, changing the instance type, and starting it again. Once, AWS refused the change after the stop and the host stayed down. I now split AWS errors into “definitely not changed” and “unknown”. A second problem was that the AWS call was made while holding row locks and a global lock. The call now runs outside any transaction, and the reply is only used if the state read again afterwards matches the state before the call.
A shared host keeps HOME on a separate EBS volume. When the VM fails, I want to attach that volume to a new VM. The first-boot helper formatted an empty disk and refused one with an existing filesystem. Relaxing that to “mount if it is ext4” risks mounting the wrong disk or a snapshot copy. The helper now identifies the disk by its NVMe serial and admits it without formatting only when its ext4 UUID matches the one recorded at creation.
Waking a stopped EC2 host took 77 seconds before work started. Most of it was waiting for the admission gate closed by the previous stop to reopen, plus a process restart after a failed boot authentication. I moved the decision to reopen admission from a VM lifecycle worker outside the ALB to the host itself, which only asks the control plane whether the current boot differs from the one before the stop. The ALB target group switched from instance to ip targets so a wake no longer waits for re-registration.
I added a cache that skips opening about 8,000 JSON records at startup when their stat matches the previous run. A same-size rewrite within one timestamp tick produced an identical stat and returned stale bytes. Stopping and starting the EC2 host changed st_dev and turned every entry into a miss. The fix caches only files whose ctime is at least two seconds old, and on ext4 rebinds st_dev only when the UUID-derived f_fsid matches.
Two Sessions on the same Task both minted task-77-1, and one died with branch_in_use. Git does not lock branch selection across worktree add. The fix holds one preparation lock from branch pick through worktree creation. Separately, an idle AWS work area is archived to S3 only after the daemon and its executor children are quiet, with size and SHA-256 checked before the original is retired, and restore never overwrites an existing path.
A shared EC2 host used to run one daemon per member. That matched personal machines, but on one VM it multiplied processes, credentials, and upgrade paths. The design that replaced it keeps a single ownerless daemon on the host, stores each member’s provider login in the host agent’s vault, and hands the daemon a signed proof scoped to one Run so it can fetch only that member’s execution credential.
A shared EC2 host should cost almost nothing while nobody needs it, and still accept work within about a minute. Always-on is simple but expensive. Stop-on-idle is cheap but races with new work. The design that stuck starts from four hard constraints: keep waiting jobs in the database, distinguish auto-stop from manual stop, seal admission on the host before StopInstances, and never replay an engine write while the VM is waking.
Opening a long conversation on the phone became extremely slow. The latest 500 history items were 19MB, nearly all tool results and arguments. Responses kept failing the relay’s 8MB limit, and the client retried with half as many items each time. After comparing a higher limit, compression and truncation, the history list now leaves tool results out, and the phone fetches the one item a user opens.
To run a background process on a Mac from boot, you register a LaunchDaemon as root. I split just that step into a root helper, so admins could allow only that helper in sudoers. But the helper wrote the run-as user from its arguments straight into the plist. Pass root, and any binary would run as root at every boot. This post shows how the helper now checks its input against SUDO_UID and the account database.
A migration that only dropped an old table deadlocked in production twice and rolled back. DROP TABLE also takes the strongest lock on the tables its foreign keys reference, and a running worker read those tables in the opposite order. After comparing lock_timeout and plain reruns, I left the applied migration untouched and took all the needed locks up front with NOWAIT in a Flyway beforeEachMigrate callback.
My Tauri desktop app used CPU every few seconds while idle. React Query’s focusManager only listens to visibilitychange, so polling kept running in a window hidden behind others. This post covers stopping it with Tauri’s focus events, a spread of the whole query result that doubled re-renders, and freezing a streaming Markdown answer block by block once each block is complete.
Inside a container, a tool the agent calls can read the engine token and tell its internal API that work was saved, and unsaved work is deleted. Tokens and file modes cannot stop a tool running as the same UID. The fix reads SO_PEERCRED per connection in Go ConnContext and returns 403 before the token is checked when the peer UID is wrong.
A batch of containers booted all at once, their start deadlines expired, and many failed. Auto-recovery only fires when work is waiting, so it skipped them and the failures stayed. This post covers the causes and how failed boots are now split into waiting work, leftover running work, and nothing at all, compared with Kubernetes CrashLoopBackOff.
I am moving the environment that runs agents from per-workspace VMs to Cloudflare Containers that start per job and stop afterwards. Following one job from start to stop, this post covers fencing off old containers (boot_id and CAS), work ownership, committing saves to R2, and draining before stopping, each compared with the common approach.
A Monte Carlo estimate of the volume of a cone rotated a second time. A million points are placed in a box, in a cylinder, and on a uniform grid, and each estimate is compared with the exact value.
Understanding WebRTC by comparing it with WebSocket. This article covers signaling, connection establishment with ICE, STUN, and TURN, and data transport through DataChannel and Media.

Revisiting Masaya Chiba’s Introduction to Contemporary Thought and exploring Michel Foucault’s philosophy. Where does power come from, and how are our notions of normality constructed?
When writers save by replacing a whole document, last-write-wins causes lost updates, and an optimistic-locking conflict error pushes the merge onto every caller. This post does a line-level 3-way merge on the server, using an immutable base snapshot and SELECT … FOR UPDATE.
After a deploy removed a content-hashed chunk, requests for it fell through to the SPA fallback index.html and were cached as immutable. This post covers a route that returns 404 no-store for missing assets and a recovery bootstrap that cannot reload-loop.
A machine with Wi-Fi, a VPN and a container bridge has several addresses, and a hostname lookup can return the wrong one. Connecting a UDP socket to a destination makes the kernel pick the source address it would use, and getsockname() reads it back without a single packet being sent. Checked on Linux with three interfaces: five destinations, five answers, no IPv4 or ARP frames on the wire.
A runbook for replacing a running daemon without dropping requests, tested on a small TCP server under real systemd. A plain restart refused or reset connections every time; starting the new version beside the old one avoided refusals but still reset a connection in some runs, and a kernel setting made those resets go away; socket activation produced no errors. Also covered: draining in-flight work against TimeoutStopSec, and a release swap that checks the new version and rolls back.
A self-updating daemon that starts an update helper detached with setsid and then restarts its own service loses the helper too, because systemd decides what belongs to a service by cgroup. In the same way, launchd cleans up by process group, and Go’s exec.CommandContext only kills the direct child on cancel. Results and fixes from four trials on a real systemd 257 and a Go experiment with a grandchild process.
A Durable Object has one alarm, a failing alarm is retried up to six times, and then nothing wakes the object. This post builds lease expiry in about 35 lines and checks retry exhaustion and recovery on local workerd.
Cloudflare’s docs say hibernation keeps WebSocket connections open and discards in-memory state. This post runs a small Durable Object under local workerd and watches exactly what that means: the socket stays OPEN, the constructor runs again on the next message, class fields reset, attachments survive only if you serialize them, and a pending timer or the standard WebSocket API quietly turns hibernation off. Production behaviour and billing are not tested.
A request deadline fired on a connection that carries many requests at once. Do you close the connection, or only the request? In a small Node lab, closing the HTTP/2 session failed two innocent requests, while cancelling only the stream let them finish on the same TCP connection. The same lab shows the one case where cancelling is not enough: a lost packet stalls every stream on a TCP connection, and a connection-level PING is the right way to tell.
WebSocket send() never waits, and bufferedAmount only sees the part of the path that is in your own process. In a small lab, a sender that politely waited for bufferedAmount to drain still let a slow consumer queue nearly all 400 messages in its own memory, while a credit window of 8 kept the backlog at 8. This post goes through four common beliefs about send(), bufferedAmount, message size and backpressure, tests each one, and ends with a table for choosing between them.
How a client catches up after a reconnect without losing state, without duplicates, and without re-reading history. Built in steps (versions 0 to 4), from “read everything again” to a bounded log with a snapshot fallback, with what a real browser’s EventSource does on reconnect and on a non-200 response, a snapshot-ordering bug, and a decision tree.
Send a header and a body as two small write() calls, then wait for a reply, and every round trip can stall for about 40 ms on an idle machine with an idle network. Neither Nagle’s algorithm nor delayed ACK is a bug; together they deadlock until a timer fires. This post predicts the stall, reproduces it with a 50-line script, reads it off a packet trace, and compares the four ways out.
When a request times out, the client cannot tell whether the request or only its acknowledgement was lost. This is why exactly-once delivery cannot be built, and why effectively-once processing is at-least-once delivery plus a receiver that deduplicates. A runnable experiment with a flaky network, the bug that still duplicates 89 of 200 requests, an atomic dedupe store, and a jitter simulation.
TCP never tells you that the peer is gone. A reader blocks forever, a writer keeps retransmitting for a quarter of an hour, and SO_KEEPALIVE does nothing while data is unacknowledged. This post builds a one-file Linux lab with no root, climbs a ladder of mechanisms (nothing, keepalive, TCP_USER_TIMEOUT, an application heartbeat), measures how long each takes to notice, and shows where NAT and the RFCs fit in.
A WebSocket carries credentials once, at the handshake, and afterwards the server holds only a verdict. When the token expires or is revoked, the open socket does not change. The Origin header checked at the handshake is the browser’s statement about which page opened the socket, not proof of who is connecting. A small server that enforces expiry itself, accepts renewals under four rules, and checks Origin by exact match while always requiring a separate credential, with tests and a headless Chrome check.
On Cloudflare Durable Objects, incoming WebSocket messages are billed and outgoing ones are not. On a relay like that, the number of messages is something you design. Three ways, with working code and tests: batch events into one frame by time, count and bytes; replace timer polling with change subscriptions and keep the poll as a fallback; and have an idle host drop its connection when nobody needs it.
A client that waited for its own socket’s close event before cleaning up stopped silently when the event never arrived. A WebSocket’s close event and readyState only tell you what the socket last reported. Three habits follow, each with working code and tests: clean up the moment you decide to close, probe only a quiet connection with an application-level ping, and on returning to the foreground, check, rebuild and catch up.
Designing collaborative document editing with conflict-free synchronization, saved snapshots, and safeguards against overwriting content before initial sync.
When an agent lives on a machine that cannot open an inbound port, the server never connects to it. The machine reports liveness over short outbound HTTPS requests and fetches work with a separate one. Silence is kept apart from a stop, and the destination of a piece of work is fixed when it is submitted, so silence never moves it to another machine. Includes a minimal PostgreSQL version with a partial unique index and FOR NO KEY UPDATE.
In a backend that writes SQL by hand, retry idempotency and double-claim prevention live inside ON CONFLICT and FOR UPDATE SKIP LOCKED, where a mocked database never looks. This post starts the production PostgreSQL version with testcontainers, applies the real migrations, isolates tests with TRUNCATE, and splits pytest into unit and integration lanes in CI.
Why I built an AI agent platform in Go instead of using LangChain, and how Clean Architecture made model, memory, tool, and streaming concerns independently replaceable.
Welcome to my blog – a space for sharing notes on CS, ML, and engineering.