Inside Pi

Appendix A

Computer science concepts, by field

10 min read · checked against pi@4954d76 on 2026-10-16

Every concept the book teaches, grouped by the university course it belongs to, with a one-line definition and the chapters where Pi uses it. Use it three ways: as a revision sheet after each part, as an index when a term reappears, and as a syllabus map. If a row feels unfamiliar, go back to the chapter and do its exercises.

A.1 Programming languages and type systems

ConceptThe idea in one lineChapters
Discriminated (tagged) unionA union whose members share a literal tag field, so checking the tag narrows the type.1, 3, 16
Branded (nominal) typesA structural type made distinct by a phantom field, so two number ids cannot be mixed up.3, 13
Runtime schemas (JSON Schema, TypeBox)One value that is both a validator at runtime and a type at compile time.1, 3, 17
Type stripping / erasable syntaxRunning TypeScript by deleting the types, which works only if no syntax needs code generation.2
Result typesExpected failures returned as values the compiler forces you to check.16
VarianceArguments may accept more (contravariant), results may return more (covariant); the rule for safe API evolution.17
Ownership and move semanticsWho may mutate a value, and when that right transfers; documented when the language cannot check it.14, 17
Async/await and promisesSyntax over continuation-passing; an await yields to the event loop.3, 6
Proxies and metaprogrammingIntercepting property access to record writes (drafts) without copying.17
Macros vs evaluationPrompt templates substitute text and never evaluate it.10

A.2 Data structures

ConceptThe idea in one lineChapters
Queue from two stacksAmortised O(1) FIFO; the EventStream buffer.3
Trees with parent pointersAppend-only nodes that each name a parent; branches without rewriting.9
Lowest common ancestorWhere two paths in a tree meet; used to summarise an abandoned branch.9
Persistent data / structural sharingNew versions share unchanged subtrees with old ones.13, 17
Piece tableA sequence as runs over an original buffer and an insert buffer; edits never copy the original.17
Treap / implicit-key treeA BST with random heap priorities; expected O(log n) split, merge and index.17
Ring and stack buffersBounded history for undo and the kill ring.12
Weak mapsCaches keyed by objects that do not keep their keys alive.3
Bounded queuesFixed-capacity buffers that drop, conflate or block when full.15, 17
Snapshots plus logsPeriodic full bases plus deltas, bounding replay time.9, 13, 14

A.3 Algorithms

ConceptThe idea in one lineChapters
Topological sortOrder a DAG so dependencies come first; the monorepo build order.2
Incremental parsingParse a stream that arrives in arbitrary chunks (SSE, JSON lines, frames, partial JSON).3, 4, 7, 16
Partial JSON repairClose open strings and brackets to read arguments that are still streaming.3
Fuzzy matchingTolerant matching for edits and for picker search, with scored candidates.8, 12
Longest common subsequenceO(n·m) dynamic programming; the base of diff.17
Longest increasing subsequencePatience sorting with binary search, O(k log k); identity-anchored diffs.17
Okapi BM25IDF × saturated term frequency × length normalisation.10, 16
Exponential backoff with jitterWait base · 2^n, capped, randomised, so clients do not retry in lockstep.4, 7, 18
Pseudo-random generatorsXorshift and seeded PRNGs for determinism.17, 18
Line-diff renderingRedraw only from the first to the last changed line.12
Grapheme segmentationMeasure terminal width by user-perceived characters, not code units.12
Perceptual colour spacesBlend colours in OKLab so steps look even to the eye.12

A.4 Concurrency

ConceptThe idea in one lineChapters
Event loopOne thread runs callbacks to completion; long CPU work blocks everything.3, 18
Cooperative cancellationAbortSignal checked at every await; nothing can be killed from outside.6, 17
Explicit contextCancellation and request values passed as an immutable parameter.16, 17
Structured concurrencyChild work never outlives its parent; a parent finishes only after its children.15
Mutual exclusion by promise chainingA per-key FIFO lock built from then.8, 14
Double-checked lockingCheck, lock, check again; avoids duplicate token refreshes.5
Single-flightConcurrent callers share one in-flight operation.18
Optimistic concurrency controlWork on a snapshot; the first commit wins and others go stale.17
BackpressureA producer slows when the consumer's buffer is full.16, 17
ConflationUnder pressure, keep only the newest state value.15, 17
Debounce and throttleCollapse bursts into one action; cap the rate of actions.12, 16, 17
Quiescence detectionFinish a wait after a period of silence when no clean end signal exists.16

A.5 Durability and distributed systems

ConceptThe idea in one lineChapters
Write-ahead loggingAppend the change durably before acknowledging it.14
Durability levels (fsync, synchronous=NORMAL)How much a power cut can lose, traded against speed.14
Torn writes and commit markersDetect a half-written record and ignore it on recovery.9, 14
Fail-stopOn an unexpected storage error, stop rather than continue in an unknown state.14
Idempotency keysA request id that makes a retried submission a no-op.13
Effects vs transactionsCommit intent, run the effect, commit the outcome (the effect sandwich).15
Deterministic replayRe-execute code with recorded inputs to rebuild lost in-memory state.15, 18
Event sourcing and projectionsThe log is the truth; views are computed from it.9, 13, 15
Operation shippingReplicate state by sending deltas, with snapshots as recovery points.15, 17
Two-phase commitPrepare everywhere, decide, then apply.14, 17
Heartbeats and leasesSilence beyond a timeout means failure; remote work dies with its lease.16, 18
The Two Generals problemA lost reply leaves the outcome unknown; only idempotency or replay policy resolves it.15, 16
Content addressingName data by its hash; versions never collide and integrity is checkable.2, 16
Hot code swappingRun old and new code side by side; migrate state at a safe point.15, 17

A.6 Operating systems

ConceptThe idea in one lineChapters
Processes, groups and signalsSpawn detached, kill -pgid; exit code 128 + n for a signal.8, 16, 18
File descriptors and inodesA handle names a file, not a path; closes TOCTOU races.16
File watchinginotify, FSEvents and polling, made reliable by snapshot diffs.15, 16
TerminalsRaw mode, escape sequences, synchronised output, bracketed paste, keyboard protocols.12
Pseudo-terminalsA fake terminal so interactive programs run under a controller.16
Standard streamsWho owns stdout, and why a protocol must take it over.7
WebAssembly isolationA separate engine and memory behind a narrow import surface.18

A.7 Networking and protocols

ConceptThe idea in one lineChapters
Server-Sent Eventsdata: lines over a long HTTP response; resumable with event ids.4, 18
Newline-delimited JSONOne record per \n, careful with U+2028 and split UTF-8.7, 9, 18
Length-prefixed binary framingBig-endian length, header, payload; corrupt frames end the connection.16
Request/response correlationIds match replies to requests; many in flight on one connection.7, 16, 18
JSON-RPC 2.0Requests, notifications and responses, in both directions.18
Version negotiationAgree on a protocol version in the handshake.17, 18
Flow control and head-of-line blockingWindows and priorities so bulk data does not delay replies.16, 17
HTTP caching (ETag, TTL)Conditional requests and freshness windows.5
OAuth 2.0Authorization code with PKCE, device grant, discovery, dynamic registration, refresh, step-up.5, 18
SSHBatch mode, pinned host keys, no forwarding.16

A.8 Security

ConceptThe idea in one lineChapters
Supply-chain hardeningPinned versions, lockfiles, review of install scripts.2, 8, 10
Object capabilitiesAuthority only through references you were given.10, 16, 18
SandboxingRun untrusted code where it can reach nothing else.10, 18
Shell injectionPass argv, not strings, when data becomes a command.8, 16
Prototype pollutionNever let data choose __proto__ as a key.17
Trust on first useVerify a key once out of band, then pin it.16
Least privilegeDrop privileges; hide graders and secrets from the agent.18
Hooks are not boundariesA check inside the same process can be bypassed by that process.8, 10

A.9 Software engineering

ConceptThe idea in one lineChapters
Monorepos and dependency DAGsMany packages, one repo, acyclic dependencies.2
Layered architectureEach layer depends only on the ones below.2, 13, 17
Dependency injectionHand components their capabilities instead of letting them reach for globals.6, 16
Adapter and strategy patternsOne interface, many providers; one behaviour, many placements.4, 16, 18
ReducersState changes as a pure function of state and event.6
Null object and bracket patternsA do-nothing default; a resource scoped to a callback.18
Plugin systemsExtension points, event buses, isolation, versioned contracts.10, 17
Progressive disclosureShow summaries, load detail on demand (skills, deferred tools).10, 16
Test doubles and fakesA faux provider and memory storage as strict as production.5, 14
Conformance suitesOne test suite every implementation of an interface must pass.14, 16, 18
Differential and property-based testingRandom inputs, compared against a reference implementation.16
ObservabilitySpans, attributes and events that can never change outcomes.18
Experimental designPaired, counterbalanced, pre-registered evals; honest missing data.18

A.10 Machine learning and LLM systems

ConceptThe idea in one lineChapters
Tokens and context windowsModels read token sequences of bounded length; everything competes for space.1, 3, 9
The ReAct loopReason, call a tool, observe, repeat.1, 6
Tool callingModels emit structured calls that a runtime validates and executes.1, 6, 8
Streaming generationPartial outputs as an event protocol.3, 4
Prompt cachingReuse computation for an unchanged prefix; append, don't rewrite.4, 6, 16
Constrained decodingMask tokens so output must match a schema or grammar.5, 18
Context compactionSummarise old turns into a structured summary when the window fills.9, 15
Code as actionThe model writes a program that calls tools, keeping intermediate results out of context.10, 15, 18
Retrieval for toolsRank tool descriptions to load only what a task needs.16
Evals and reward hackingMeasure behaviour statistically; keep graders out of reach.18