Technical Notes

Browse technical notes, course breakdowns, and debugging writeups organized by topic.

All tags
accessibilityACIDAgent SkillsagentsAIAI agentsAI harnessAI toolsalgorithmsAPIAPI designarrayarraysAstroasyncB-treebackupBlind 75browser APIsbucket sortcachingcallbackscapability securitycardinalityCDNClaude Codeclosurescloud deploymentCloudflareCloudflare WorkersCodexcomplexity analysisconcurrencyconnection poolingconstraintsContainersContent Security Policycontext engineeringcontext windowcookiesCORSCSPCSSCSS Overflow 5data modelingdatabasedeploymentdisaster recoverydistributed systemsdynamic programmingDynamic Workersexecution contextFetch APIfrequency countingfunctionsGithash tablehigher-order functionsHouse RobberHTMLHTTPhydrationidempotencyindexindexingIntersectionObserverintervalsinterview preparationJavaScriptjob queueJOINJSONlearninglearning notesLeetCodeLLMmachine learningMapMCPMCP Appsmergemulti-tenancyNext.jsnormalizationobservabilitypaginationperformancePgBouncerPITRPostgreSQLprefix productprefix sumprerenderingprimary keyproduction observabilityprogressive enhancementprompt engineeringpythonqueryquery designquery performancequery plannerReactReact Server ComponentsrebaserecursionResizeObserverretriesrolling stateRow-Level Securitysamplingschema migrationscopesecuritysecurity headersSELECTserverlessSetsliding windowsortingSPASQLSSRstandard promptingstatic sitestringsuffix productSupabasetestingtoken efficiencytokenstransactiontwo pointersTypeScriptUIUI SDKUUIDv7validationverificationversion controlView Transitionsweb developmentweb performanceweb securityWorkersworkflowXSSzero downtime

Introducing UI SDK: composable interactions and an interface agents can use

A practical introduction to UI SDK behaviors, primitives, framework adapters, and the agent bridge, with React requirements, benchmark limits, and a small Astro integration to evaluate.

JavaScript Closures: How Functions Remember Outer Variables

Use counters to explore closures and lexical scope, shared and independent state, and memory cleanup.

JavaScript Callbacks and Higher-Order Functions: Passing Behavior as an Argument

Build a reusable array transformation to understand callbacks, higher-order functions, map, arrow functions, mutation, and shallow copies.

What Happens When a JavaScript Function Runs? Execution Context and Local Memory

Trace JavaScript function calls, parameters, return values, and local variables with original examples, then see how closures preserve state.

What Is an AI Harness? From Answering Questions to Executing Tasks

Follow a bug fix to understand AI harnesses: instructions, tools, the agent loop, context, and model adapters—and how they differ from Agent Skills, MCP, and sandboxes.

Structured Output: The AI Returned JSON. Now What?

Compare format prompts, JSON mode, and schema constraints. Use metadata checks, timestamps, and a token-estimation counterexample to see what the application still needs to validate.

Context Placement: Where Should the Important Bits Go?

You supplied the context, but the answer missed it. Explore information placement, long documents, conversation summaries, and ways to test each change separately.

Core Prompting Techniques: When Should I Add Examples?

When one instruction isn't enough, should you add rules or examples? Compare standard, zero-shot, one-shot, and few-shot prompts using GitHub issues.

Standard Prompts: Start with a Clear Request

A short Practical Prompt Engineering note: improve a newsletter-form request with context, constraints, targeted clarification, and concrete checks.

Temperature and Top P: How a Model Selects the Next Token

Practical Prompt Engineering notes: use a five-token probability example to understand temperature, nucleus sampling, Top P 0.5, and the limits of consistent output.

Token Limits and Context Windows: What Can the Model See in This Turn?

Practical Prompt Engineering notes: distinguish tokens from words, context from output limits, and conversation history from memory, with a worked token budget.

What Is Prompt Engineering? Turning a Question into a Testable Task

Notes from Practical Prompt Engineering: use a JavaScript closure example to understand prompts, context, output requirements, and repeatable checks.

ResizeObserver basics: element sizes, boxes, and update boundaries

An element can shrink without the viewport changing. Use a runnable JavaScript example to understand ResizeObserver, content and border boxes, logical axes, hidden elements, cleanup, and resize feedback loops.

IntersectionObserver: visibility, loading, and virtualization are separate jobs

Learn root, rootMargin, threshold, initial notifications, and observer cleanup with small JavaScript examples. Separate infinite-scroll request control from virtualization and its DOM budget.

CORS from scratch: separate request delivery, cookies, and response access

A practical guide to origins, OPTIONS preflights, fetch credentials, cookies, Allow and Expose headers, and browser debugging. Understand why an API can finish while JavaScript cannot read its response.

PostgreSQL backups: what pg_dump, WAL, and PITR actually do

Use an accidental order deletion to understand RPO and RTO, SQL versus custom archive restore tools, forward WAL replay, and PITR stopping points and restore checks.

Supabase RLS Beyond the Policy UI: Make Authorization SQL Testable

Keep Supabase RLS, least-privilege grants, operation-specific policies, and allow-or-deny SQL tests in migrations so every environment can replay and review them.

PostgreSQL RLS is not an automatic WHERE clause: four boundaries for multi-tenant data

Use PostgreSQL Row-Level Security for a shared table by separating GRANTs from policies, existing rows from proposed rows, and caller identity from view or function ownership.

PgBouncer does not make PostgreSQL infinite: budget connections before choosing a pool mode

Use the boundaries between connections, sessions, and transactions to reason about PostgreSQL connection budgets, PgBouncer modes, session-state compatibility, and `pg_stat_activity`.

LeetCode 198: House Robber with take-or-skip rolling states

My House Robber solution, why its p1 and p2 updates work, and a clearer O(n)-time, O(1)-extra-space rolling-state version.

LeetCode 70: Climbing stairs from repeated recursion to two rolling states

My Climbing Stairs path from a factorial dead end and exponential recursion to an O(n)-time, O(1)-extra-space rolling-state solution.

A retry is not a second attempt: the real boundaries of API idempotency keys

A timeout is not proof of failure. Use operation keys, parameter binding, atomic records, bounded retries, and an outbox to prevent duplicate side effects.

LeetCode 152: Why maximum product subarray needs both extremes

My Maximum Product Subarray attempt, the counterexample that broke it, and the final O(n) maximum-and-minimum state solution with an invariant and brute-force checks.

LeetCode 53: Maximum subarray without rescanning every starting point

My O(n²) backward scan and final O(n) solution, with the distinction between endingHere and best, all-negative inputs, loop invariants, and executable tests.

LeetCode 238: Product of array except self with prefix and suffix products

My division-based solution and prefix/suffix version, with zero handling, loop invariants, executable tests, and the difference between extra and output space.

Why does the next page repeat a row? OFFSET and keyset pagination

Trace five rows through OFFSET and keyset pagination, then connect compound cursors to B-tree indexes, NULL handling, and the limits of changing data.

ArtInt Reading Notes: Intelligent Agents and the AI Basics I Mixed Up

Notes on ArtInt 3e sections 1.1–1.2: agents, computability, and corrections to my understanding of decision trees, reinforcement learning, early language systems, and text generation.

The site is deployed. Why am I still seeing the old version?

Follow a response through browser and CDN caches, understand s-maxage and validators, and connect fingerprinted JavaScript to the HTML that actually requests it.

LeetCode 15: 3Sum in TypeScript, Why Skipping Duplicates Does Not Lose Answers

My progression from a global Set that loses answers to two pointers, with an explanation of all three duplicate checks, complexity, and executable assertions.

LeetCode 11: Container With Most Water in TypeScript, Why Move the Shorter Side?

My two-pointer solution, with a brute-force comparison, a proof for discarding the shorter side, and executable checks for O(n) time and O(1) extra space.

LeetCode 125: Valid Palindrome in TypeScript, From Cleaning to In-Place Two Pointers

Keep the submitted cleaned-string solution, then explain an in-place charCodeAt-based two-pointer alternative.

Don't block first: use CSP Report-Only to find real dependencies, then tighten safely

CSP Report-Only is not a pause in security. It reveals real dependencies, noise, and legacy code patterns before a nonce-, hash-, and least-privilege policy reaches production.

LeetCode 424: Longest Repeating Character Replacement in TypeScript

Keep the submitted frequency-counting sliding-window solution and explain why maxFreq can retain its historical maximum.

LeetCode 3: Longest Substring Without Repeating Characters in TypeScript

Keep an initial reset-and-rescan attempt, explain its O(n²) limit, then use a one-pass Map sliding window.

A schema migration is not one SQL statement: expand, backfill, and observe before you contract

A PostgreSQL schema migration must account for existing rows, older workers, and newly deployed code. Use expand, repeatable backfills, and evidence about locks, indexes, and constraints before removing an old path.

LeetCode 49: Group Anagrams in TypeScript, From Sorting Keys to Count Signatures

Work through a sorting-based Group Anagrams solution, its repeated-array-copy cost, and a count signature for the fixed lowercase alphabet.

LeetCode 347: Top K Frequent Elements in TypeScript, From Frequency Sorting to Buckets

Start with Map frequency counting and sorting, then remove the O(n log n) sort with frequency buckets.

LeetCode 242: Valid Anagram in TypeScript, From Sorting to Character Counts

Compare sorting, Map-based frequency differences, and a fixed-size count array for Valid Anagram, including correctness, invariants, and complexity.

Do not add an index first: use EXPLAIN, statistics, and ANALYZE to see what PostgreSQL is guessing

PostgreSQL chooses query plans from estimated costs. Compare EXPLAIN estimates with real execution before deciding whether statistics, query design, or an index needs to change.

LeetCode 1: Two Sum in TypeScript with a Map

Replace nested pair checks with a Map of earlier values and indices, then explain complement lookup, the loop invariant, and expected O(n) time.

LeetCode 217: Contains Duplicate in TypeScript with a Set

Compare a Set's size with the array length, or stop early during one scan, while explaining the Set solution's correctness and expected O(n) complexity.

LeetCode 121: Best Time to Buy and Sell Stock in TypeScript

Replace nested transaction checks with one scan that tracks the lowest purchase price, including the correctness argument for a two-pointer solution and its O(n) cost.

Indexes follow query shape, not a column checklist

A PostgreSQL index earns its cost only when a real query's filters, ordering, result size, and write workload justify another maintained data structure.

Transaction Boundaries for Orders, Inventory, and ACID

An order can touch inventory, orders, and payment records. A transaction keeps database changes all-or-nothing; it cannot unsend an email or replace constraints and concurrency design.

LeetCode 2574: Left and Right Sum Differences in TypeScript

Compare stored left and right sums with a single scan, including output space, auxiliary space, and the loop invariant.

LeetCode 724: Find a Pivot Index in TypeScript

Find the leftmost pivot index with a total sum and one running left sum, then make the loop invariant and O(n) analysis explicit.

LeetCode 1732: Find the Highest Altitude in TypeScript

Track current altitude and the highest altitude so far in one scan with O(n) time and O(1) auxiliary space.

LeetCode 1480: Running Sum in TypeScript

Use each completed array position as state for one linear scan, with an honest discussion of in-place mutation, the loop invariant, and O(n) time.

Before JOIN Syntax, Count the Relationship

Decide what one result row means and whether unmatched data stays first. Then choose INNER JOIN or LEFT JOIN without mistaking normal fanout for duplicates.

LeetCode 128: Longest Consecutive Sequence in TypeScript

Move from sorting to a Set, expand only sequence starts, and give a rigorous expected O(n) analysis for the longest consecutive sequence problem.

LeetCode 56: Merge Intervals in TypeScript

Derive a TypeScript merge-intervals solution through sorting, one linear scan, input immutability, and an honest O(n log n) complexity analysis.

A SELECT Needs Four Decisions: Columns, Rows, Order, Limit

A reliable SQL query does more than retrieve data: name the columns, filter with WHERE, define an order with ORDER BY, then cap the result with LIMIT.

A Database Is Not a JSON Blob: Let Constraints Protect Data

Tables, keys, and constraints form a shared data contract. Frontend validation improves UX; the database must reject impossible writes.

AbortController: Cancel Stale Work, Not Every Error

AbortController stops work a person has superseded, but cancellation, timeouts, HTTP failures, and server-side effects need different handling. Put controller ownership in the right place first.

Navigation API: A Router Primitive, Not an SPA Mandate

The Navigation API centralises SPA navigation, but only intercept same-origin GETs your app can safely finish. Leave forms, downloads, hash links, external destinations, and unsupported browsers to ordinary navigation.

Speculation Rules: Faster Navigation Must Not Do Things Early

Speculation Rules can speed up the next MPA navigation, but prefetch and prerender have very different costs. Exclude side-effecting URLs, preserve ordinary navigation, then use activation and hit rate to decide whether to expand.

Browser Scheduler: Classify Work Before You Queue It

Scheduler gives the browser a priority hint; it is not a background thread. Keep short UI work synchronous, then choose postTask, yield, or a Web Worker from measured evidence.

MCP Tool Results: Decisions, Not API Dumps

An MCP tool should return decision-ready summaries, verifiable fields, and a path to drill down—not a raw REST response poured into the context window.

<details> Is Disclosure, Not an Accordion System

Native details already handles toggling and keyboard interaction. name can create exclusive panels, but only when that matches content semantics and safe fallback behavior.

Popover API: Less UI State, Not Free Accessibility

Native Popover can replace some toggle, click-outside, and z-index code. It remains non-modal UI, so it cannot choose semantics, content, or product flow for you.

PostgreSQL SKIP LOCKED: Job Queue, Not Magic Broker

SKIP LOCKED can claim jobs without worker contention, but reliable delivery still needs short transactions, leases, retries, idempotency, and an exit plan.

Native CSS Carousels Are an Enhancement, Not a Rewrite

CSS Overflow 5 can generate carousel buttons and markers, but it is not Baseline yet. Start with a semantic list, scroll snap, and progressive enhancement before removing JavaScript.

Cloudflare OS: Sandboxes Are Not the Security Model

Cloudflare OS offers a useful pattern for agent-built apps: isolate generated code, remove ambient authority, grant narrow capabilities, and review side effects separately.

PostgreSQL 18 Skip Scan: The Leftmost Rule, Revisited

PostgreSQL 18 can reuse a multicolumn B-tree when the leftmost column is not filtered. The win is real, but cardinality and query plans still decide.

A Green Build Is Not a Live Release

A field note from this Astro blog: what local checks prove, what they do not, and how static assets reach a Cloudflare Worker.

MCP Apps Put UI in Chat, Not in Every Tool

MCP Apps can render dashboards, forms, and visual tools inside AI conversations. The useful boundary is simple: tools execute, views present, and hosts control trust.

Your SSR Data Is Part of the Page Weight

SSR can improve first paint and SEO, but hydration JSON and RSC payloads still travel and parse. Here is a practical Next.js measurement and reduction order.

View Transitions Make MPAs Smoother, Not SPAs

The View Transition API now covers same-document state changes and page navigation. Here is the minimal approach to fallbacks, shared elements, and reduced motion.

Cloudflare Containers: When a Worker Is Not Enough

Cloudflare Containers is generally available. Here is a practical guide to its cold starts, pricing, ephemeral disks, scaling, and division of labor with Workers.

UUIDv7 for Primary Keys: Better, Not Universal

UUIDv7 improves index locality in SQLite and PostgreSQL, but 128-bit keys still cost more than bigint. Use it when distributed ID generation is required.

Agent Skills: Build Verifiable Workflows

Use hch-log.com's Astro release workflow to build a downloadable SKILL.md with existing checks and an ads.txt failure case, separating command validation from agent activation tests.

Caveman: Shorter Release Reports Without Losing Evidence

Compare two edits of a real hch-log.com audit record, checking dates, scope, negation, and next steps without treating shorter prose as a token or accuracy experiment.

Git Merge vs Rebase: Which Should You Use?

Learn how Git merge and rebase change commit history, when each workflow fits, and how to avoid rewriting shared branches or creating needless conflicts.