<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>wendaining</title>
    <link>https://blog.wendain.ing/en/</link>
    <description>wendaining's Blog</description>
    <language>en</language>
    <copyright>All rights reserved 2026, wendaining</copyright>
    <lastBuildDate>Tue, 17 Nov 2026 02:40:00 GMT</lastBuildDate>
    <generator>Hexo</generator>
    <atom:link href="https://blog.wendain.ing/en/rss.xml" rel="self" type="application/rss+xml"/>
    <item>
      <title>Learning Kubernetes from a High-Level Mental Model</title>
      <link>https://blog.wendain.ing/en/posts/learn-k8s-from-a-higher-perspective/</link>
      <description>Starting from my perspective on git, re-understanding k8s in a similar way</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E4%BA%91%E5%8E%9F%E7%94%9F/">Cloud Native</category>
      <category domain="https://blog.wendain.ing/en/tags/Infra/">Infra</category>
      <pubDate>Mon, 16 Nov 2026 11:39:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/learn-k8s-from-a-higher-perspective/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>Although this title and the term (<em>mental model</em>) look very AI-ish, I actually think it summarizes things quite well, so I used it as the title.</p><p>Let me try to go through the fundamentals of K8S again from this perspective.</p><h2 id="The-So-Called-High-Level-Mental-Model">The So-Called "High-Level Mental Model"</h2><p>Actually, I was inspired by my understanding of git to try re-understanding k8s from this perspective, so let me first explain my understanding of git:</p><div class="note note-info"><p>I'd like to think I understand git reasonably well, but that doesn't mean I'm familiar with all kinds of git commands</p><ul><li>In fact, I only know the basic ones, at most with a few extensions</li></ul><p>What I mean is that I know git's underlying structure, and I can look at git from a high-level perspective:</p><ul><li>git can be understood as a DAG (directed acyclic graph)</li><li>Each node in this graph is a commit, and a commit is a complete snapshot of a version</li><li>The parent commit (previous version) always points to the child commit (next version), and the incremental changes in the process are the version changes (<strong>state machine transitions</strong>)</li><li>Inside a commit there are blobs, and <strong>logically</strong> a blob is the content of each file tracked by git in that version</li><li>A so-called branch is just a pointer; the branch's name (a string) points to some commit; when commits are updated, the branch moves along the DAG accordingly</li><li>There is a staging area, which controls which files need to be migrated during the state machine transition</li></ul><p>I can consider that git consists of roughly just these things, and this can be called my <strong>mental model</strong> of git. In theory, I can now perform <strong>any</strong> git operation.</p><p>For example, I don't necessarily need to know what the command for some operation is; I can describe it to an agent, for instance:</p><ul><li>I want to move the part of the commit tree from commit A to commit B onto commit D, essentially a grafting operation.</li><li>Then the agent can help me execute a rebase (or possibly a cherry pick, or directly call some plumbing commands I don't know about)</li></ul><p>As long as I understand git's underlying structure, I can operate it from a high-level perspective.</p></div><p>So I want to build a similar mental model for k8s, with roughly these key points:</p><p>(Actually, I think the answer Gemini 4 Hydrogen gave me was pretty good, but for the sake of review, I'll type it out myself)</p><p>Understanding it from the highest level of abstraction:</p><ul><li>k8s has a giant central bulletin board (etcd)</li><li>All components <strong>do only two things</strong>: 1. Modify the requests on the bulletin board 2. Watch the requests on the bulletin board and do the work</li></ul><p>Going one level down:</p><p>etcd is the <strong>sole state store</strong>; any component such as Pod, Deployment, etc., is essentially just structured YAML data in etcd.</p><p>The structured data can be divided into two parts:</p><ul><li>Spec: declares what state is desired</li><li>Status: the actual current state</li></ul><p>The API Server is the <strong>sole communication bus</strong>; all communication between components goes through the API Server. The API Server is essentially just a <strong>RESTful API Server</strong> + <strong>Watch mechanism</strong> (long-lived connection listening). <strong>Any <code>kubectl</code> operation is merely sending an HTTP request to the API Server</strong>, either returning read-only data or modifying the spec's content (modifying some field in etcd).</p><p>The part that is actually responsible for managing state is called the <strong>Controller</strong>; they <strong>do not communicate with each other and run independently</strong>. The core of a Controller is called the <strong>Reconcile Loop</strong>, roughly pseudocode like this:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">for</span> {  desired := watchSpecFromAPIServer()  actual := watchStatusFromAPIServer()  <span class="hljs-keyword">if</span> desired != actual {    doSomethingToAlignThem()  }}</code></pre></div><p>However, Controllers work at a certain granularity, and since they cannot communicate directly with each other, they must communicate through the <strong>Watch mechanism</strong> and the <strong>etcd database</strong>, forming a <strong>chained relay</strong>. For example:</p><div class="note note-info"><ul><li>The user modifies the Deployment's spec via <code>kubectl</code>, declaring that the desired number of Pods changes from 3 to 5</li><li>After the Deployment Controller detects the change, it modifies the ReplicaSet's Spec to 5</li><li>After the ReplicaSet Controller detects the change, it writes two additional new Pod objects into etcd.<ul><li>Note that these Pod objects are only <strong>declared</strong>; there is no corresponding actual runtime, and <code>Spec.nodeName</code> is empty</li></ul></li><li>The Scheduler (also a Controller) watches all Pods with an empty <code>Spec.nodeName</code>; once it finds one, it computes resources to find an idle node, then fills <code>nodeName</code> into the corresponding field. <strong>Note that at this point it has only modified the spec and has not actually started the runtime</strong>.</li><li>Each node has a kubelet component, which watches for Pods whose <code>Spec.nodeName</code> is itself; once it detects a new one, it actually pulls the image and runs the runtime in its own VM</li><li>Meanwhile, the node also contains CNI and kube-proxy, which work together with the Service component to manage the local machine's network forwarding and rules, etc.</li></ul></div><p>At the same time, this architecture is <strong>extensible</strong>, reflected in these two features:</p><ul><li>CRD (Custom Resource Definition) is essentially defining a custom YAML format, telling the API Server that a self-defined kind of object exists</li><li>An Operator is a program you write yourself and deploy into the cluster, using the API Server's Watch mechanism to manage CRDs; in essence, it is a Custom Controller</li></ul><p>We can easily notice one of k8s's inherent flaws:</p><ol><li>Declaration != implementation; the corresponding expectation is expressed, but it doesn't mean the state machine has completed the transition, so there are naturally issues like latency</li><li>Some others to be added TODO</li></ol><h2 id="Kubernetes-Tutorials"><a href="https://kubernetes.io/zh-cn/docs/tutorials/">Kubernetes Tutorials</a></h2><p>With this perspective in hand, let's try re-reading the official k8s tutorial documentation.</p><p><a href="https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/create-cluster/cluster-intro/">The first article</a> says that a k8s cluster can consist of two parts: the Control Plane and Nodes</p><ul><li>The Control Plane contains kube-api-server, etcd, kube-scheduler, kube-controller-manager</li><li>A Node contains kubelet, container runtime</li></ul><p><a href="https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/deploy-app/deploy-intro/">The second article</a> mainly introduces what a Deployment is.</p><p>In short, it packages all the requirements for running pods into a single API Object, such as Pod creation rules, the desired number of replicas, and the update strategy.</p><p>Specifically, three fields:</p><ul><li><code>replicas</code> describes the desired number of pods to run</li><li><code>template</code> describes how this Pod should be created, such as where to pull the image from, environment variable settings...</li><li><code>selector</code> describes which pods to manage and how to identify them; you can think of this as a CSS selector—it needs specific labels to identify the scope under its jurisdiction</li></ul><p><a href="https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/explore/explore-intro/">The third article</a> mainly goes deeper into Nodes and Pods.</p><p>A Pod is the smallest unit of scheduling in k8s and can contain <strong>several containers</strong>; a pod has these characteristics:</p><ul><li>Shared network namespace, e.g., all containers can access each other via localhost</li><li>A Pod has Volumes, and containers within the pod can mount the volume to different places</li><li>The scheduler's smallest unit of scheduling is the pod</li></ul><div class="note note-info"><p><strong>Why do we need Pods instead of directly managing Containers?</strong></p><p>You can understand this from a concrete scenario.</p><p>Suppose there is a Web Server that needs a log collector to continuously read the log files it generates.</p><p>If the two containers were completely independent, you would need to additionally solve:</p><ul><li>How to let the two containers share files?</li><li>How to make them deploy on the same machine?</li><li>How to make them use a common network address?</li><li>How to make them have the same lifecycle?</li></ul><p>A Pod organizes these related resources into a whole. This forms a very natural abstraction: <strong>A Pod = a group of containers that need to be scheduled together and share part of the runtime environment.</strong></p></div><p>A Node can be understood as a <strong>worker machine</strong> in the k8s cluster (it can be a physical machine or a virtual machine).</p><p>A Node consists of:</p><ul><li>At least one pod</li><li>kubelet, which manages pods and containers, and registers the node with the api server</li><li>container runtime</li></ul><p>If a node goes down, the pods inside it have their nodeName field removed, and then wait to be reassigned.</p><div class="note note-info"><p>Regarding persistence, it involves concepts like StatefulSet, PersistentVolume, etc.—more on that later.</p></div><p><a href="https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/expose/expose-intro/">The fourth article</a> is mainly about Services.</p><p>Roughly speaking:</p><ul><li><p>To solve the problem that Pods may repeatedly go offline causing their IPs to keep changing, while Pods need to communicate with each other, a Service can provide something like DNS</p></li><li><p>Each Pod has a Label, like this:</p><div class="code-wrapper"><pre><code class="hljs yaml"><span class="hljs-comment"># Pod A</span><span class="hljs-attr">metadata:</span>  <span class="hljs-attr">labels:</span>    <span class="hljs-attr">app:</span> <span class="hljs-string">backend</span>    <span class="hljs-attr">version:</span> <span class="hljs-string">v1</span></code></pre></div></li><li><p>A Service can select Pods with specific Labels (by defining the <code>spec.Selector</code> field) and give it a name (similar to DNS), say <code>backend</code>, so that other Pods can access it via <code>backend:80</code></p></li><li><p>Note that port forwarding can also be configured yourself; omitted here</p></li></ul><p>The implementation behind this relies on the EndpointSlice component, which can be understood as a DNS table, maintained by watching state.</p><div class="note note-info"><p>You can think of it as the chained relationship between Deployment and ReplicaSet.</p></div><p>Traffic forwarding is implemented by the kube-proxy component in the control plane using Linux kernel forwarding (configuring network forwarding rules such as iptables or nftables).</p><ul><li><strong>Note this has nothing to do with the API Server</strong>; the API Server is only responsible for resource-management-related requests</li></ul><p><a href="https://kubernetes.io/zh-cn/docs/tutorials/kubernetes-basics/update/update-intro/">The last article</a> mainly covers how k8s performs rolling updates; in one sentence, it modifies the Pod Template in a Deployment, then triggers a Rollout, gradually creating new Pods and deleting old ones.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>kagent, acp, agent substrate and other concepts</title>
      <link>https://blog.wendain.ing/en/posts/kagent-acp-and-other-concepts/</link>
      <description>As the title suggests, but it's mainly some technical understanding and research, written as thoughts come to mind.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/Agent/">Agent</category>
      <category domain="https://blog.wendain.ing/en/tags/AI/">AI</category>
      <category domain="https://blog.wendain.ing/en/tags/Agent/">Agent</category>
      <pubDate>Tue, 10 Nov 2026 06:40:10 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/kagent-acp-and-other-concepts/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="About-kagent">About kagent</h2><p>Upstream: <a href="https://github.com/kagent-dev/kagent">https://github.com/kagent-dev/kagent</a></p><p>Let me write a tldr of the core elements:</p><ul><li>One agent runtime runs inside a pod</li><li>k8s is responsible for managing the agents' execution</li><li>Rather than being a coding agent, it's more like consolidating the previous dashboard-like functionality onto a single platform by exposing interfaces to the agent, because the platform can <strong>share</strong> agents</li></ul><p>The upstream is more like a distributed system (referring to kagent as a whole), while the secondary development part is deployed in a centralized manner.</p><p>The Agent's Runtime and the Agent's definition are decoupled; an Agent is defined in a declarative-like way (model, system prompt, mcp, tool lists, etc.).</p><div class="note note-info"><p>I feel that kagent, rather than being the coding agent everyone understands it to be, is more like — or at least what I currently believe — its ultimate form is something like ChatGPT Web</p><p>Because right now it already feels more like consolidating the previous dashboard-like functionality onto a single platform by exposing interfaces to the agent, since the platform can <strong>share</strong> agents</p><p>ChatGPT Web also has a virtual machine for each session where things can run, and it can be resumed and continued at any time — behind the scenes it must be a similar approach</p></div><h2 id="ACP">ACP</h2><p>(For now) the secondary development part uses Agent Runtimes built with Google ADK</p><div class="note note-info"><p>It's an Agent development framework fairly similar to Langchain, providing interfaces such as Agent definitions, Tool Schemas, and so on.</p></div><p>But the upstream has implemented the so-called "<strong>decoupling of Harness and Agent Runtime</strong>" — in short, you can use things like Codex, Pi, etc. as the Harness, without having to build it with Google ADK.</p><p>When thinking about this requirement, the first thing that came to my mind was <strong>ACP</strong>, i.e. the <strong>Agent-Client Protocol</strong>. This protocol is mainly used in the <strong>Zed</strong> editor. Without going into technical details, purely in terms of UX: the editor provides an agent panel, and this panel can invoke a local agent and use it directly and normally. Behind the scenes, simply put, it's a unified protocol — once an Agent implements the ACP Client, the client can use any Agent Runtime under a single Interface.</p><blockquote><p>Suppose Zed wants to support Claude Code. Zed needs to do the following:</p><ol><li>Launch the Claude Code process.</li><li>Create an Agent Session.</li><li>Send user input to the Agent.</li><li>Receive the Agent's streaming output.</li><li>Display which tools the Agent is calling.</li><li>Handle the Agent's permission requests.</li><li>Notify the Agent when the user cancels a task.</li></ol><p>By implementing the ACP Client once, Zed can integrate with all ACP-compatible Agents.</p></blockquote><p>Specifically, ACP specifies the following:</p><ol><li><code>initialize</code>, the "<strong>handshake</strong>" step for establishing a connection;</li><li>Management of the session lifecycle: creation, loading, resuming, closing;</li><li>Session interaction: prompt, cancel, update;</li><li>Bidirectional interaction, e.g. agent request persmission from user</li></ol><p>But clearly this set of things seems a bit lacking... The various agents on the market have far too many proprietary features, so the upstream first introduced ACP, then later removed it and switched to writing their own Runtime interface.</p><div class="note note-info"><p>ACP can't be that bad, right? Otherwise why would Zed still be using it? Besides, I think once the core functionality is supported, the rest can just be a panel in the dialog box that simply implements slash commands — I can't think of any feature that couldn't be supported that way. It's like the QQ Bot interface: through Slash Commands you can do a lot of things, yet the user is just interacting with it in a simple chat box.</p></div><h2 id="Agent-Substrate">Agent Substrate</h2><p>A feature integrated into kagent upstream, developed by Google. It works like this:</p><ul><li>Previously, spinning up an agent meant one pod</li><li>With the traditional Kubernetes Deployment approach, each Agent is assigned a Pod, so even if the Agent is idle 99% of the time, the corresponding Pod resources are still continuously occupied.</li></ul><p>For Agent Substrate:</p><ul><li>There is a Worker Pool<ul><li>A Worker is <strong>one</strong> pre-started <strong>Pod</strong> that hosts Actors</li></ul></li><li>One Worker can host <strong>multiple</strong> isolated Actors<ul><li>An Actor is an independent Agent running instance, with its own process, memory, filesystem, and running state</li></ul></li><li>One Agent Session corresponds to <strong>one</strong> Actor<ul><li>When a session is created, the actor is in a suspended state, and is only resumed when a message is sent</li></ul></li><li>When an Actor is idle, its state snapshot is saved to OSS and compute resources are released</li><li>On resume, the snapshot is restored</li></ul><p>From this mechanism, it's easy to think of Cloudflare's <a href="https://developers.cloudflare.com/durable-objects/concepts/what-are-durable-objects/">Durable Objects</a> and <a href="https://developers.cloudflare.com/agents/harnesses/container/">Containers</a> — the only difference is that the Container here runs an Agent.</p><p>Regarding Snapshots: you need to consider whether it's <strong>simply restoring persisted data</strong> or <strong>restoring the entire runtime state</strong>:</p><ul><li>For the former, consider creating subvolumes based on the BTRFS filesystem — snapshots are very convenient with this</li><li>The latter is a bit more troublesome, but honestly I don't think it matters much — after all, in everyday computer use, shutting things down and letting the Agent continue later isn't really a big hassle<ul><li>That said, there are two implementation technologies for a full process Sandbox: gVisor and microVM, which I won't go into here for now.</li></ul></li></ul><h2 id="Benchmarking-Against-ChatGPT-Chat-Web">Benchmarking Against ChatGPT Chat (Web)</h2><p>kagent's ultimate goal is certainly not client-distribution level, but rather a centrally deployed, service-providing SaaS-like product, with the following characteristics:</p><ul><li>Generally, it <strong>cannot read</strong> the user's local environment, and the user <strong>cannot freely operate</strong> the environment the agent belongs to<ul><li>The former distinguishes it from ordinary Coding Agents; the latter distinguishes it from the likes of Dot or Grok Bot</li></ul></li><li>The tools available to the agent are restricted, or rather, there is fairly heavy permission management</li><li>From a UX perspective, it mainly provides interfaces to intranet services for a general-purpose LLM, so users can conveniently have the Agent use these services</li></ul><p>So no matter how you look at it, it's very similar to ChatGPT Web:</p><ul><li>Each ChatGPT Web Session has an Agent, and the Agent Runtime necessarily depends on a virtual machine</li><li>It's impossible for the VM behind every Session to exist all the time — it must be dynamically released according to compute resource allocation<ul><li>Isn't this exactly Agent Substrate?</li></ul></li><li>Sessions need to be resumed, and the degree of restoration upon resume is limited<ul><li>For OpenAI, there's also the question of the model's own KV Cache (perhaps), but we don't need to worry about that here</li></ul></li></ul><p>But honestly, having said all this, it's basically just reinventing the wheel — just with some specialization, such as exposing permissions for different Agents based on the user or the organization the user belongs to. But these are higher-level concerns that can be layered on later; there doesn't seem to be anything particularly novel about it.</p><div class="note note-info"><p>In fact, the wheel doesn't even need to be reinvented... it feels like there are plenty of truly open-source options out there. I previously saw that Tencent, Alibaba, and others have open-sourced their own Agent sandboxes, but I haven't seen their orchestration strategies — worth investigating later.</p></div><p>Once the lowest-level functionality is all built, what remains here is simply integrating various internal tools — this has little to do with kagent itself, and is instead a matter of each responsible department developing the corresponding CLI Tool / Skill / MCP etc.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>Some Blogs I've Collected</title>
      <link>https://blog.wendain.ing/en/posts/my-bookmarked-blogs/</link>
      <description>&quot;WIP&quot; A collection of blogs I've bookmarked along with brief content summaries. Since blogroll links are often mutual, I plan to compile everything into one post, which may also serve as a kind of recommendation list.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%9D%82%E8%B0%88%E4%B8%8E%E9%9A%8F%E6%83%B3/">Essays and Reflections</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%9D%82%E8%B0%88/">Essays</category>
      <category domain="https://blog.wendain.ing/en/tags/%E9%9A%8F%E6%83%B3/">Reflections</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%8D%9A%E5%AE%A2/">Blog</category>
      <pubDate>Sun, 08 Nov 2026 11:23:23 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/my-bookmarked-blogs/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h4 id="Preface">Preface</h4><p>This article is mainly a collection of the blogs I've saved along with brief summaries of their content. Since friend links are usually a mutual thing, I plan to compile everything into a single post, which also serves as a kind of recommendation list.</p><p>I'll update it whenever I have time.</p><div class="note note-primary"><p>If any blogger does not wish to be featured here, please contact me at me@wendain.ing</p></div><h4 id="RawWeb"><a href="https://rawweb.org/">RawWeb</a></h4><p>Not a blog, but a search engine for blogs. It's quite useful, although nowadays it feels like GPT could replace it.</p><h4 id="wendaining"><a href="https://blog.wendain.ing/">wendaining</a></h4><p>This site</p><h4 id="Kisechan-s-Blog"><a href="https://blog.kisechan.space/">Kisechan's Blog</a></h4><p>A CSer, with very interesting technical essays and very helpful course notes, as well as some rather interesting life records and random musings.</p><p>My favorites are the <strong><a href="https://blog.kisechan.space/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases series</a></strong>, the <strong><a href="https://blog.kisechan.space/2025/notes-ptms/">Crash Course Notes on Probability Theory</a></strong>, and some useful little essays such as the <strong><a href="https://blog.kisechan.space/2026/esim/">eSIM Tinkering Log</a></strong></p><h4 id="Palind-s-Blog"><a href="https://blog.palind-rome.top/">Palind's Blog</a></h4><p>An LLM expert whose technical notes are all quite deep (<s>though I can't understand them</s>)</p><p>You can also browse his Zhihu, which has <strong>lots of interesting content</strong>.</p><h4 id="指针的轨迹-The-Pointer-s-Trail"><a href="https://blog.xialing.icu/">指针的轨迹 (The Pointer's Trail)</a></h4><p>A <strong>very, very interesting</strong> senior CS student, although I've somewhat forgotten how I discovered this site.</p><p>The posts range from courses and technical notes to personal deep reflections and records. The former shows the blogger's strong curiosity about technology and "tinkering spirit," which can also be seen from the PRs and issues under the <a href="https://github.com/XiaLing233/tongji-course-scheduler">Tongji Course Scheduler</a>. The latter combines quality of thought, fun, and depth — a rare, high-quality blog.</p><h4 id="Ashitemaru"><a href="https://ashitemaru.github.io/">Ashitemaru</a></h4><p>A PhD student at Tsinghua University, although it hasn't been updated in a long time.</p><p>The blogger's interests are extremely broad, covering everything. Some of the everyday records are also worth reading.</p><h4 id="arctanp"><a href="https://blog.arctanp.top/">arctanp</a></h4><h4 id="Lyc8503-s-blog"><a href="https://blog.lyc8503.net/">Lyc8503's blog</a></h4><p>An undergraduate graduate in Software Engineering from Nanjing University, a <strong>technical wizard whose skill has reached another realm</strong>, with a breathtaking depth of understanding of systems.</p><p>Needless to say more — just read <strong><a href="https://blog.lyc8503.net/post/4-years-at-nju/">this post</a></strong>.</p><h4 id="独角恋歌-Unrequited-Love-Song"><a href="https://revival-of-hope.github.io/">独角恋歌 (Unrequited Love Song)</a></h4><h4 id="Jambity-s-Blog"><a href="https://blog.jambity.top/">Jambity's Blog</a></h4><h4 id="Fries-on-the-pier"><a href="https://nozom1466.github.io/">Fries on the pier</a></h4><h4 id="MinmusLin-s-sBlog"><a href="https://www.minmuslin.cn/">MinmusLin's ßBlog</a></h4><h4 id="Lanxinmob-Old-and-Lanxinmob-New"><a href="https://lanxinmob.github.io/">Lanxinmob Old</a> and <a href="https://lanxinmob.dev">Lanxinmob New</a></h4><p>A classmate</p><p>The former is dead (although I don't understand how a static blog framework where every file is present can die — could it be that only the compiled artifacts remain without the source files?)</p><p>The latter is mainly technical content, and the frontend was recently overhauled — quite interesting.</p><h4 id="muji"><a href="https://muji2007.github.io/">muji</a></h4><p>Will there be interesting content just getting started?</p><h4 id="Arthals-ink"><a href="https://arthals.ink/">Arthals' ink</a></h4><h4 id="Axi-s-Blog"><a href="https://axi404.top/blog">Axi's Blog</a></h4><h4 id="LinhoNotes"><a href="https://notes.linho.cc/">LinhoNotes</a></h4><h4 id="Actinium-s-Blog"><a href="https://blog.actinium233.com/">Actinium's Blog</a></h4><h4 id="tugumineko"><a href="https://tugumineko.github.io/">tugumineko</a></h4><h4 id="溴化锂的笔记本-Lithium-Bromide-s-Notebook"><a href="https://www.nvme0n1p.dev/">溴化锂的笔记本 (Lithium Bromide's Notebook)</a></h4><h4 id="Chesszyh-s-Blog"><a href="https://blog.chesszyh.xyz/">Chesszyh's Blog</a></h4><h4 id="Ezra-Yang"><a href="https://ezrablake2006.github.io/">Ezra Yang</a></h4><h4 id="Samuel-Hu-s-Blog"><a href="https://www.hjw-aihub.cn/">Samuel Hu's Blog</a></h4><h4 id="Ayanami-s-Cave"><a href="https://ayanami1314.github.io/">Ayanami's Cave</a></h4><h4 id="nzooherd-s-blog"><a href="https://nzooherd.github.io/">nzooherd's blog</a></h4><h4 id="ShinN-s-Blog"><a href="https://sh1nn.top/">ShinN's Blog</a></h4><h4 id="Candlest"><a href="https://blog.candlest.cc/">Candlest</a></h4><h4 id="新月潮汐摄动流形-New-Moon-Tide-Perturbation-Manifold"><a href="https://b.ryusel.com/">新月潮汐摄动流形 (New Moon Tide Perturbation Manifold)</a></h4><h4 id="idealclover"><a href="https://idealclover.top/">idealclover</a></h4><h4 id="Tilnel-s-Blog"><a href="https://tilnel.github.io/">Tilnel's Blog</a></h4><h4 id="茶栗栗屋-Cha-Riri-s-House"><a href="https://chariri.moe/">茶栗栗屋 (Cha Riri's House)</a></h4><h4 id="Caraway-Kong"><a href="https://carawaykong.github.io/">Caraway Kong</a></h4><h4 id="ErinwithBMQ-s-Blog"><a href="https://www.erinwithbmq.xin/">ErinwithBMQ's Blog</a></h4><h4 id="Azure-Zeng-Blog"><a href="https://blog.azurezeng.com/">Azure Zeng Blog</a></h4><h4 id="riba2534-s-Blog"><a href="https://blog.riba2534.cn/blog/">riba2534's Blog</a></h4><h4 id="新的原野-New-Wilderness"><a href="https://sinyalee.com/blog/">新的原野 (New Wilderness)</a></h4><h4 id="换功臣的个人博客-Huangongchen-s-Personal-Blog"><a href="https://www.flowertea.xyz/">换功臣的个人博客 (Huangongchen's Personal Blog)</a></h4><h4 id="ddadaal-me"><a href="https://ddadaal.me/">ddadaal.me</a></h4><h4 id="sbwcwso-s-CSStudy"><a href="https://sbwcwso.github.io/CSStudy/#/page/readme">sbwcwso's CSStudy</a></h4><h4 id="iPotato"><a href="https://ipotato.me/">iPotato</a></h4><h4 id="Piglei"><a href="https://www.piglei.com/">Piglei</a></h4><h4 id="TTAWDTT"><a href="https://ttawdtt.github.io/">TTAWDTT</a></h4><h4 id="imaginary"><a href="https://justimaginary.github.io/">imaginary</a></h4><h4 id="Rinai-s-Private-Garden"><a href="https://blog.g-rinai.cn/">Rinai's Private Garden</a></h4><h4 id="Hexo-Fluid-User-Manual"><a href="https://fluid-dev.github.io/hexo-fluid-docs/start/">Hexo Fluid User Manual</a></h4><h4 id="Ch3nyang-s-blog"><a href="https://blog.ch3nyang.top/">Ch3nyang's blog</a></h4><h4 id="ykiko-s-blog"><a href="https://ykiko.me/zh-cn/">ykiko's blog</a></h4><h4 id="yzxoi-s-Personal-Corner"><a href="https://yzxoi.github.io/">yzxoi's Personal Corner</a></h4><h4 id="层间札记-Between-Layers"><a href="https://unik-lif.github.io/blog/">层间札记 (Between Layers)</a></h4><h4 id="Alex-Chi-Z"><a href="https://www.skyzh.dev/">Alex Chi Z.</a></h4><h4 id="roife"><a href="https://roife.github.io/">roife</a></h4><h4 id="W3nYui-s-Blog"><a href="https://w3nyui.github.io/">W3nYui's Blog</a></h4><h4 id="Sukka-s-Blog"><a href="https://blog.skk.moe/">Sukka's Blog</a></h4><h4 id="Xiyuan-Yang-s-Blog"><a href="https://xiyuanyang-code.github.io/">Xiyuan Yang's Blog</a></h4><h4 id="GaleInk-s-blog"><a href="https://twj-ink.github.io/">GaleInk's blog</a></h4><h4 id="Ri-Nai-s-Blog"><a href="https://ri-nai.github.io/astro-blog/">Ri-Nai's Blog</a></h4><h4 id="Ramsey-s-Blog"><a href="https://zncu-photo.pages.dev/">Ramsey's Blog</a></h4><h4 id="AceSheep"><a href="https://blog.acesheep.com/">AceSheep</a></h4><h4 id="AM-s-Personal-Little-Site"><a href="https://amroute.black/">AM's Personal Little Site</a></h4><h4 id="滑滑蛋的个人博客-Slipegg-s-Personal-Blog"><a href="https://slipegg.github.io/">滑滑蛋的个人博客 (Slipegg's Personal Blog)</a></h4><h4 id="shiquda"><a href="https://shiquda.link/">shiquda</a></h4><h4 id="Zongjian-s-blog"><a href="https://hezongjian.com/">Zongjian's blog</a></h4><h4 id="imbAnt-s-blog"><a href="https://imbant.github.io/blog/">imbAnt's blog</a></h4><h4 id="supdriver-s-Blog"><a href="https://www.supdriver.top/">supdriver's Blog</a></h4><h4 id="Cinea-Cnblogs"><a href="https://www.cnblogs.com/cinea">Cinea (Cnblogs)</a></h4><h4 id="isSeymour-细水长流-Slow-and-Steady"><a href="https://isseymour.github.io/butterflyblog/">isSeymour - 细水长流 (Slow and Steady)</a></h4><h4 id="Fernweh"><a href="https://blog.wohin.me/">Fernweh</a></h4><h4 id="码一地闲言，蕴一段岁月-Coding-Idle-Words-Cherishing-a-Stretch-of-Years"><a href="https://alvachien.github.io/">码一地闲言，蕴一段岁月 (Coding Idle Words, Cherishing a Stretch of Years)</a></h4><h4 id="bisucrose-s-Island"><a href="https://bisucrose.github.io/">bisucrose's Island</a></h4><h4 id="芝士雾汐-Cheese-Wuxi"><a href="https://wuxio.top/">芝士雾汐 (Cheese Wuxi)</a></h4><h4 id="Jinyan-Su"><a href="https://jinyansu1.github.io/">Jinyan Su</a></h4><h4 id="skywt-blog"><a href="https://skywt.cn/blog">skywt blog</a></h4><h4 id="纸鹿摸鱼处-Paper-Deer-s-Slacking-Spot"><a href="https://blog.zhilu.site/">纸鹿摸鱼处 (Paper Deer's Slacking Spot)</a></h4><h4 id="Rain-s-Essays"><a href="https://blog.yfycloud.site/">Rain's Essays</a></h4><h4 id="DGideas-Blog"><a href="https://dgideas.net/">DGideas' Blog</a></h4><h4 id="Morethan-s-Little-Site"><a href="https://morethan987.github.io/">Morethan's Little Site</a></h4><h4 id="Warren-s-Blog"><a href="https://wz.anoms.top/">Warren's Blog</a></h4><h4 id="HikariLan-s-Blog"><a href="https://blog.hikarilan.life/">HikariLan's Blog</a></h4><h4 id="CAICAIIs"><a href="https://caicaiis.cc/">CAICAIIs</a></h4><h4 id="Ylin"><a href="https://ylin07.github.io/">Ylin</a></h4><h4 id="二月木的个人博客-Eryuemu-s-Personal-Blog"><a href="https://eryuemu.com/">二月木的个人博客 (Eryuemu's Personal Blog)</a></h4>]]>
      </content:encoded>
    </item>
    <item>
      <title>CMU 15-445 Bustub Project 4 - Concurrency Control - Note</title>
      <link>https://blog.wendain.ing/en/posts/cmu-15-445-bustub-proj4/</link>
      <description>A brief note on Project 4 of the CMU 15-445 course - Concurrency Control</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/bustub/">Bustub</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <pubDate>Tue, 20 Oct 2026 02:39:58 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/cmu-15-445-bustub-proj4/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>This time I'm opening a document to record things before writing, so that I won't forget everything later)</p><p>After all, a quick glance shows that the spec for P4 is quite long — if I don't take notes, I'll definitely end up writing the later parts while forgetting the earlier ones.</p><p>Actually, I haven't watched the corresponding lectures yet, so I'll also record some notes on the knowledge here.</p><p>This time I tried using an LLM purely, but combined with the course's high-quality resources, giving it this prompt:</p><blockquote><p>I'm a bit too lazy to watch the videos, so please help me speedrun it like this:</p><ol><li>Learn unit by unit, with each section within each lecture as the unit, using the slides and notes as the main thread to assist my learning</li><li>For the original text above, try to translate it verbatim; add as little embellishment of your own as possible</li><li>However, you are encouraged to use intelligent UI diagrams to help me understand</li><li>After learning each chunk of knowledge, use the corresponding problems from the homework to build a Q&amp;A system paired with intelligent UI for me to practice with</li></ol><p>That's it. Start with Lecture 17 first — try outputting how you would divide up Lecture 17. Once you've divided it, I'll say "start," and then we'll begin learning bit by bit.</p><p>There are quite a few files you need to read, so be a bit careful with reading them.</p></blockquote><p>Let's see how it works.</p><div class="note note-info"><p>Second edit: the result was <strong>really good</strong>.</p></div><h3 id="Lec-17-Concurrency-Control-Theory">Lec 17 Concurrency Control Theory</h3><p>Why we need concurrency control and Recovery:</p><ul><li>Lost Update Problem (Concurrency Control): when two or more transactions try to update the same data simultaneously, how should we handle it?</li><li>Durability Problem (Recovery): when a power outage occurs, how do we ensure the database is in a correct state?</li></ul><p>The basic requirement of a Transaction: either complete all steps, or execute none of them.</p><p>A simple way to handle transactions:</p><ul><li>Serialize everything, with a single worker thread executing one transaction at a time.</li><li>Before a transaction begins, the DBMS copies the entire database to a new file and makes all modifications on that file.</li><li>If the transaction succeeds, the new file becomes the current database file; if the transaction fails, the DBMS discards the modified copy and none of the transaction's changes are saved.</li></ul><p>This approach is called The Strawman System or Shadow Paging; it gives up all concurrency and doesn't work well.</p><p>If concurrent execution is needed, we must guarantee:</p><ul><li>Correctness: ensure execution meets requirements without errors</li><li>Fairness: ensure no transaction starves</li></ul><p>Moreover, transactions can only constrain things within the DBMS. Suppose a transaction modifies the database and sends an email to an external mailbox, and then the transaction aborts — the DBMS has no way to recall the email.</p><p>Therefore, we need Formal Correctness Criteria to judge whether a certain interleaved execution is valid. Specifically:</p><div class="note note-primary"><p>Formally, a database can be represented as a fixed set of named data objects (A, B, C, ...).</p><p>These objects can be Attributes, Tuples, Pages, Tables, or even the entire database.</p><p>The algorithms we will discuss apply to any type of object, but all objects must be of the same type.</p><p>A Transaction is a series of read/write operations performed on these objects, such as <code>R(A)</code>, <code>W(B)</code>. This is the DBMS's abstract view of the user program.</p><p>The boundaries of a transaction are defined by the client.</p></div><p>In SQL, a new transaction begins with the <code>BEGIN</code> command and ends with <code>COMMIT</code> or <code>ABORT</code> / <code>ROLLBACK</code>.</p><p>For <code>COMMIT</code>, either all of the transaction's modifications are saved to the database, or the DBMS overrides this decision and aborts the transaction instead.</p><p>For <code>ABORT</code>, all of the transaction's modifications are undone, making it as if the transaction never happened.</p><p>A transaction's abort can be initiated proactively by the transaction itself, or caused by the DBMS.</p><p>Correctness specification: <strong>ACID</strong></p><h4 id="Atomic">Atomic</h4><p>The possible outcomes of a transaction's commit:</p><ul><li>Commit</li><li>Abort / Rollback</li></ul><p>Methods to guarantee Atomicity:</p><ul><li>Logging: the DBMS records all operations in a log in order, maintaining undo logs on both disk and in memory</li><li>Shadow Paging: mentioned above. Runtime performance is worse than logging</li></ul><p>The key difference between the two approaches:</p><p>Logging: allows modifying data, then undoing the modifications using the recorded information.</p><p>Shadow Paging: keeps the original pages, makes modifications on a copy, and only adopts the new pages after commit.</p><p>Two concurrent transactions interfere with each other, causing the final database state to not correspond to the result of any serial execution. Which property is primarily violated?: Isolation.</p><h4 id="Consistency">Consistency</h4><h5 id="Integrity-Constraints">Integrity Constraints</h5><p>Constraints at the SQL level, such as a certain field not being allowed to be negative.</p><h5 id="Eventual-Consistency">Eventual Consistency</h5><p>Eventual consistency: a committed transaction may see inconsistent results</p><p>For example, a committed transaction may not immediately see the updates made by an earlier committed transaction.</p><p>So, eventual consistency isn't great.</p><h4 id="Isolation">Isolation</h4><p>Isolation of Transactions: the DBMS provides transactions with the illusion that "each transaction is the only one running in the system," unable to see the effects of other transactions.</p><p>This is equivalent to: transactions running serially. But truly serial execution is impossible. So we need a way to let transactions execute interleaved while still appearing to execute one at a time.</p><h4 id="Concurrency-Control-Protocol">Concurrency Control Protocol</h4><p>A concurrency control protocol is the method by which the DBMS decides at runtime how to correctly interleave the operations of multiple transactions.</p><p>It falls into two categories:</p><ul><li>Pessimistic concurrency control: the DBMS assumes transactions will conflict, so it prevents problems from the start;</li><li>Optimistic concurrency control: the DBMS optimistically assumes conflicts between transactions are rare, so it chooses to handle them after they occur.</li></ul><h4 id="Execution-Schedule">Execution Schedule</h4><p>The order in which the DBMS executes transactions is called the execution schedule.</p><p>Goal: interleave transactions to <strong>maximize concurrency</strong> while remaining <strong>equivalent to some serial execution</strong>.</p><h4 id="Formal-Properties-of-Schedules">Formal Properties of Schedules</h4><p>We can think of before and after execution as state transitions, with the entire database being a state machine.</p><ul><li>Serial schedule: literally what it says</li><li>Equivalent schedules: two schedules that produce exactly the same final state</li><li>Serializable schedule: if a schedule is equivalent to some serial execution of these transactions, then it is a serializable schedule</li></ul><h4 id="Conflicting-Operations">Conflicting Operations</h4><p>Let's define a few concepts.</p><p>Two operations are said to conflict if they satisfy the following conditions:</p><ol><li>They belong to different transactions.</li><li>They act on the same data object.</li><li>At least one of the operations is a write.</li></ol><p>Different types of <strong>conflicts</strong> lead to different types of <strong>anomalies</strong>, such as:</p><p>Read-write conflicts lead to <strong>unrepeatable reads</strong>, i.e., a transaction reads the same data object multiple times but cannot get the same value. A simple example: transaction T1 has two read tasks, with a complete transaction T2 sandwiched between them, which has an RW conflict with T1.</p><p>Write-read conflicts lead to <strong>dirty reads</strong>, i.e., a transaction reads data written by another transaction that has not yet been committed.</p><img src="https://image.wendaining.top/image-20261021083912282.png" style="zoom: 50%;"><p>Write-write conflicts lead to <strong>lost updates</strong>, i.e., one transaction overwrites data written by another transaction that has not yet committed. Essentially, T1 writes first, and T2 writes later, overwriting T1's write.</p><p>There is one more anomaly, the <strong>phantom read</strong>, which we'll discuss later.</p><div class="note note-warning"><p>Distinguish between <strong>conflicts</strong> and <strong>anomalies</strong>:</p><p>A conflict is a relationship between operations; an anomaly is an abnormal phenomenon that appears during execution.</p></div><h4 id="Conflict-Serializability">Conflict Serializability</h4><p>Two schedules are <strong>conflict equivalent</strong> if and only if both of these conditions hold:</p><ol><li>They contain the same operations of the same transactions.</li><li>In both schedules, every pair of conflicting operations has the same relative order.</li></ol><p>If a schedule S is conflict equivalent to some serial schedule, then S is <strong>conflict serializable</strong>.</p><p>Intuitively, this means schedule S can be transformed into a serial schedule by swapping adjacent, non-conflicting operations between different transactions.</p><p>Example:</p><img src="https://image.wendaining.top/image-20261021090842747.png" style="zoom:50%;"><h4 id="Dependency-Graph">Dependency Graph</h4><p>Use a dependency graph to verify whether a schedule is conflict serializable.</p><p>In the dependency graph:</p><ul><li>Each transaction is a node in the graph</li><li>There is a directed edge from $T_i$ to $O_i$ if and only if operation $T_j$ of transaction $O_j$ conflicts with operation $O_i$ of transaction $O_j$, and $T_i$ appears before $T_j$ in the schedule</li></ul><p>A schedule is conflict serializable <strong>if and only if its dependency graph is acyclic</strong>.</p><p>Understanding: if the dependency graph has no cycles, we can find a topological ordering and execute the transactions serially in that order, while satisfying the ordering constraints between all conflicting operations.</p><h4 id="View-Serializability">View Serializability</h4><p><strong>View serializability</strong> is a <strong>weaker</strong> definition of serializability than conflict serializability.</p><div class="note note-info"><p>View serializability is difficult to enforce efficiently, because the DBMS does not know how the application will interpret these values. Therefore, real systems do not adopt this approach.</p></div><p>So I was too lazy to read it; skipping.</p><h4 id="Durability">Durability</h4><p>Transaction durability: all modifications of committed transactions must be durable after a system crash or restart, i.e., the following two situations are not allowed:</p><ul><li>Incomplete updates are not allowed: after crash recovery, only part of a transaction's modifications must not remain.</li><li>Modifications of failed transactions must not be retained: the modifications of a transaction that did not successfully commit must not become part of the database's valid state after recovery.</li></ul><p>This is achieved through appropriate redo logs.</p><p>An example problem:</p><img src="https://image.wendaining.top/image-20261021093404730.png" style="zoom:67%;"><h3 id="Lec-18-Two-Phase-Locking">Lec 18 Two-Phase Locking</h3><h4 id="Transaction-Locks">Transaction Locks</h4><p>Serializability and its related theory carry an assumption: at scheduling time, all read and write operations are known.</p><p>But in practice, we need a method that maintains correctness dynamically during execution.</p><p>Therefore, the DBMS uses locks to dynamically produce serializable transaction execution schedules, with an internal <strong>lock manager</strong> responsible for deciding whether a transaction can acquire a lock on a particular object.</p><div class="note note-info"><p>That sentence above is a bit convoluted. A simple example: suppose Ta and Tb want to access the same object — the Lock Manager coordinates the lock requests.</p></div><div class="note note-info"><p>The difference between Locks and Latches:</p><ul><li>Lock: protects the database's data values (<strong>isolates transactions</strong>), avoiding conflicts between concurrent transactions</li><li>Latch: protects the DBMS's internal data structures (<strong>isolates threads</strong>), avoiding errors caused by multi-threaded concurrent access</li></ul><p>Locks are usually held for the entire transaction, while Latches are only held for short critical sections.</p></div><p>Two basic kinds of locks:</p><ul><li>Shared Lock: allows multiple transactions to read the same object simultaneously</li><li>Exclusive Lock: while held, no other transaction may hold a lock on that object</li></ul><div class="note note-info"><p>It's basically just a reader-writer lock, right?</p></div><p>How the Lock Manager works: it maintains an internal Lock Table, recording which transactions hold which locks, and which transactions are waiting to acquire locks.</p><h4 id="Basic-Two-Phase-Locking">Basic Two-Phase Locking</h4><p>Two-Phase Locking: a <strong>pessimistic concurrency control protocol</strong> that uses locks to dynamically decide whether a transaction is allowed to access objects in the database.</p><p>Phase 1: Growing — each transaction requests the locks it needs from the DBMS's Lock Manager. The Lock Manager grants or denies these requests.</p><p>Phase 2: Shrinking — after a transaction releases its first lock, it immediately enters the shrinking phase. In this phase, the transaction can only release previously acquired locks and cannot acquire new ones.</p><p>Core rule: <strong>once you start releasing locks, you cannot acquire new locks, nor upgrade existing locks</strong>.</p><p>2PL <strong>guarantees conflict serializability</strong>, because the dependency graph produced by the schedule contains no cycles.</p><div class="note note-info"><p>Simple explanation: under 2PL, the conflict ordering between transactions must be consistent with the order of their last successful lock acquisitions; a cycle is impossible because locks cannot be re-acquired.</p></div><p>2PL has the Cascading Abort problem: after one transaction aborts, other transactions must also roll back, wasting already-completed computation work.</p><p>A simple example: T1 finishes its writes and enters the shrink phase; T2 acquires the lock but then something goes wrong and it aborts — then T1's completed work must also abort.</p><p>2PL can also produce dirty reads.</p><h4 id="Strong-Strict-2PL">Strong Strict 2PL</h4><p>Definition of a Strict Schedule: a schedule is Strict if any value written by a transaction is not read or overwritten by another transaction until that transaction commits.</p><p>So SS2PL: a variant of 2PL in which a transaction must finish (Commit or Abort) before it can release locks.</p><p>Advantages:</p><ul><li>No cascading aborts</li><li>The DBMS can undo an aborted transaction's modifications by restoring the dependent values of the recovered tuples.</li><li>Avoids dirty reads</li></ul><p>Disadvantages:</p><ul><li>Poor concurrency performance</li><li>Cannot prevent deadlocks</li></ul><p>Strict 2PL: must hold all X-Locks until the transaction ends, but allows releasing S-Locks early (provided the 2PL phase restrictions are still respected).</p><h4 id="Deadlock">Deadlock</h4><p>Two approaches 2PL uses to handle deadlocks: detection and prevention</p><h5 id="Detection">Detection</h5><p>The DBMS can build a Waits-for Graph to track which locks each transaction is waiting to acquire.</p><p>The graph is defined as follows:</p><ol><li>Nodes represent transactions.</li><li>If transaction $T_i$ is waiting for transaction $T_j$ to release some lock, there is a directed edge $T_i\rightarrow T_j$ (<strong>waiter -&gt; holder</strong>)</li><li>The system periodically checks the wait-for graph for cycles and decides how to break them.</li></ol><p>The system usually uses a background thread to periodically check the Waits-for Graph for cycles. If one check misses a deadlock, subsequent checks still have a chance to find it, so there are trade-offs in detection frequency.</p><h5 id="Handling">Handling</h5><p>When the DBMS detects a deadlock, it selects a Victim Transaction, rolls it back, and thereby breaks the wait-for cycle.</p><p>There are many selection strategies, such as age, proportion of execution, etc.</p><h5 id="Prevention">Prevention</h5><p>Unlike Detection, deadlock prevention stops any transaction from entering a deadlock before it happens.</p><p>That is: when a transaction tries to acquire a lock held by another transaction, the DBMS can abort one of them.</p><p>To achieve this, the DBMS assigns priorities to transactions; for example, one scheme is "the older, the higher the priority."</p><p>For example, Wait-Die:</p><ul><li>An old transaction requests a new transaction's lock: the old transaction waits</li><li>A new transaction requests an old transaction's lock: the old transaction dies</li></ul><p>Wound-Die:</p><ul><li>An old transaction requests a new transaction's lock: the new transaction dies</li><li>A new transaction requests an old transaction's lock: the new transaction waits</li></ul><p>Both protocols guarantee no deadlocks; both schemes only allow transactions to wait for locks <strong>in one direction</strong>, so cycles are impossible in the graph.</p><div class="note note-info"><p>If a transaction is restarted after being aborted, the DBMS lets it keep using its original timestamp rather than assigning a new one.</p><p>This avoids the transaction becoming ever younger and lower in priority, being repeatedly aborted, and thus causing Starvation.</p><p>Note: this is a measure to avoid starvation; it does not mean starvation is absolutely impossible under any scheduling conditions.</p></div><h4 id="Lock-Hierarchy">Lock Hierarchy</h4><p>This is essentially about distinguishing lock granularity.</p><p>Trade-offs:</p><ul><li><strong>Coarse-grained locks</strong> reduce lock management overhead, but limit concurrency;</li><li><strong>Fine-grained locks</strong> improve potential concurrency, but require managing more locks.</li></ul><h5 id="Database-Lock-Hierarchy">Database Lock Hierarchy</h5><table><thead><tr><th>Level</th><th>Frequency of Use</th></tr></thead><tbody><tr><td>Database</td><td>Slightly Rare</td></tr><tr><td>Table</td><td>Very Common</td></tr><tr><td>Page</td><td>Common</td></tr><tr><td>Tuple</td><td>Very Common</td></tr><tr><td>Attribute</td><td>Rare</td></tr></tbody></table><h5 id="Intention-Locks">Intention Locks</h5><p>Suppose T1 already holds an exclusive lock on some tuple in table P. If T2 wants to acquire a shared lock on the entire table, the DBMS must know that a finer-grained exclusive lock exists on this table; otherwise it might incorrectly approve the request.</p><p>Checking tuple by tuple is too expensive.</p><p>Hence <strong>intention locks</strong> are introduced, allowing the system to determine whether a lock can be granted to a higher-level node without checking all lower-level nodes.</p><p>If a node has an intention lock on it, it means some transaction is locking at that lower level.</p><p>So, for the example above, T1 would add an IX(TableP) to the table; since S(TableP) conflicts with IX, the lock cannot be acquired.</p><div class="note note-info"><p><code>IX(Table P)</code> means the transaction intends to use exclusive locks at a lower level of P; it is not itself equivalent to <code>X(Table P)</code>.</p></div><p>Three kinds of intention locks:</p><ul><li>Intention Shared: indicates the transaction is currently or about to explicitly acquire an S-Lock at a lower level.</li><li>Intention-Exclusive: indicates the transaction is currently or about to explicitly acquire an X-Lock at a lower level.</li><li>Shared + Intention-Exclusive: the entire subtree rooted at this node is explicitly locked in shared mode, while the transaction will also explicitly acquire exclusive locks at lower levels. (<strong>read the whole, write parts</strong>)</li></ul><div class="note note-info"><p>A counterintuitive conclusion: <strong>IX is compatible with IX</strong>. Because they only declare that there are writes at a lower level; it doesn't mean both parties will modify the same tuple. Real conflicts still need to be determined at the lower level.</p></div><h4 id="Hierarchical-Locking">Hierarchical Locking</h4><p>This subsection focuses on how transactions acquire locks along the hierarchy.</p><p>In general: acquiring S/IS or X/IX/SIX on a child node requires holding the corresponding lock on the parent node.</p><p>Therefore, one should usually <strong>acquire locks top-down and release locks bottom-up</strong>.</p><p>When is SIX needed: scanning the entire table while modifying a single tuple.</p><p>As long as locks are compatible, different transactions can concurrently access the same element.</p><h4 id="Lock-Escalation">Lock Escalation</h4><p>When a transaction holds a large number of low-level locks, the DBMS can automatically convert them to a coarser-grained lock, reducing the number of lock requests the Lock Manager needs to maintain and process.</p><h4 id="Explicit-Locking">Explicit Locking</h4><p>Most databases support explicit locking via SQL, bypassing the Lock Manager. I won't go into detail here.</p><p>A simple example: before performing a large number of writes to a table, proactively acquire an exclusive lock first, to prevent two transactions later both wanting to upgrade and causing a deadlock, forcing an abort.</p><h3 id="Lec-19-Timestamp-Ordering-Concurrency-Control">Lec 19 Timestamp Ordering Concurrency Control</h3><p>As for why Timestamp Ordering (<strong>TO</strong>) is introduced, we first need to review 2PL.</p><p>2PL is a pessimistic protocol, in that: it requires transactions to acquire locks before accessing database objects.</p><p>But if in fact conflicts between transactions are rare, an optimistic protocol is better.</p><p>TO is a class of optimistic concurrency control protocols; specifically:</p><ul><li>The DBMS uses timestamps to determine the serializability order of transactions</li><li>Each transaction $T_i$ is assigned a unique, fixed, monotonically increasing timestamp, denoted $TS(T_i)$</li><li>If $TS(T_i) &lt; TS(T_j)$, then the DBMS must ensure that <strong>the execution schedule is equivalent to the serial schedule in which $T_i$ executes before $T_j$</strong>.</li></ul><p>Timestamp allocation strategies:</p><ul><li>System clock (UNIX TIME)</li><li>Logical counter (increment +1)</li></ul><h4 id="OCC-Basic-Protocol">OCC Basic Protocol</h4><p>OCC - Optimistic Concurrency Protocol</p><div class="note note-info"><p>Optimistic Concurrency Control (OCC) is an optimistic concurrency control protocol that uses timestamps to validate transactions.</p><p>OCC works best when the number of conflicts is small. For example:</p><ol><li>All transactions are read-only.</li><li>The data subsets accessed by transactions do not overlap.</li></ol><p>If the database is large and the workload has no obvious skew, the probability of conflicts between transactions is low, so OCC is a good choice.</p></div><p>In OCC, the DBMS creates a <strong>Private Workspace</strong> for each transaction:</p><ul><li>All of a transaction's modifications are done in its own Workspace;</li><li>Objects being written are copied into the Workspace for modification;</li><li>If the isolation level needs to guarantee Repeatable Read, read objects are also copied into the Workspace.</li><li>Note that <strong>other transactions cannot read the modifications a transaction produces in its Private Workspace</strong>.</li><li>When a transaction is ready to commit, the DBMS checks whether its Write Set conflicts with other transactions.</li></ul><p>The three phases of OCC:</p><ol><li>Read Phase: the DBMS tracks the transaction's Read Set and Write Set, and stores the transaction's writes in the Private Workspace</li><li>Validation Phase: when the transaction is ready to commit, the DBMS assigns the transaction a unique timestamp (TS), then checks whether the transaction conflicts with other transactions.</li><li>Write Phase:<ul><li>If validation succeeds, the DBMS sets write timestamps (W-TS) on all modified objects in the Private Workspace and applies the modifications atomically to the global database.</li><li>If validation fails, the transaction aborts and restarts.</li></ul></li></ol><p>The Read Phase is when the transaction does its actual work; the Validation and Write Phases together form the Commit Protocol.</p><h4 id="OCC-Validation">OCC Validation</h4><p>In the Validation Phase, how do we determine whether the transaction to be committed will conflict with other transactions? It's simply a matter of validating the Read / Write Sets of other in-progress transactions; there are two methods.</p><ul><li>Forward Validation: check active transactions that have not yet committed.</li><li>Backward Validation: check transactions that have already committed.</li></ul><p>Three conditions to guarantee serializability:</p><p>Assume the timestamp order is $TS(T_i)&lt;TS(T_j)$; <strong>satisfying at least one of the three conditions is sufficient</strong>:</p><ul><li>Fully serial: $T_i$ completed its Write Phase before $T_j$ entered its Read Phase.</li><li>Overlapping read phases, ordered writes: $T_i$'s Write Phase must be earlier than $T_j$'s Write Phase, and $W_i\cap R_j=\varnothing$</li><li>Larger overlap: $T_i$'s Read Phase must end before $T_j$'s Read Phase ends, and $W_i\cap R_j=\varnothing$ and $W_i\cap W_j=\varnothing$</li></ul><h4 id="OCC-Performance-and-Limitations">OCC Performance and Limitations</h4><p>OCC's ideal scenarios:</p><ul><li>All transactions are read-only</li><li>Transactions access non-overlapping data subsets</li></ul><p>Potential problems:</p><ul><li>The Private Workspace is obviously problematic</li><li>Validation and the Write Phase's verification are bottlenecks</li><li>Aborts are wasteful</li><li>Timestamp Allocation Bottleneck</li></ul><p>Aborts are fairly serious, because with OCC, in high-conflict scenarios a large number of transactions will roll back. Moreover, aborts happen only after the transaction has already finished executing, causing a lot of waste.</p><h4 id="Phantom-Reads">Phantom Reads</h4><p>Phantom read: when a transaction scans a range multiple times, and another transaction inserts or deletes tuples belonging to that range between the two scans, the scanning transaction may get different results.</p><p>The phantom read problem arises because transactions only lock existing records, ignoring records that other transactions are creating.</p><h4 id="Phantom-Prevention">Phantom Prevention</h4><table><thead><tr><th>Method</th><th>Core Idea</th><th>Usage in the Course</th></tr></thead><tbody><tr><td>Lock Everything</td><td>Lock the entire table or all relevant pages</td><td>Common, but coarse-grained</td></tr><tr><td>Re-Execute Scans</td><td>Re-scan the predicate before commit, checking whether the results are still the same</td><td>Rarely used</td></tr><tr><td>Predicate Locking</td><td>Lock the WHERE predicate; if another transaction tries to acquire a lock on the same predicate and it conflicts with an existing predicate lock, a lock conflict occurs</td><td>Rarely used</td></tr><tr><td>Index Locking</td><td>Use index keys to lock ranges</td><td>Common</td></tr></tbody></table><p>Let's focus on the last one; it is in fact a special case of predicate locking: <strong>using Key Ranges in the index to protect the query range</strong>.</p><p>It divides into these four types:</p><table><thead><tr><th>Type</th><th>Protected Object</th></tr></thead><tbody><tr><td>Key-Value</td><td>A single Key. To protect a Key that does not yet exist, Virtual Keys need to be introduced.</td></tr><tr><td>Gap</td><td>Locks the Gap between index key values, preventing other transactions from inserting new records into the protected gap.</td></tr><tr><td>Key-Range</td><td>Locks the interval from one existing Key to the next Key, thereby protecting both existing key values and the corresponding insertion range.</td></tr><tr><td>Hierarchical</td><td>Allows transactions to hold larger Key Ranges in different lock modes, reducing the overhead of accessing the Lock Manager.</td></tr></tbody></table><h4 id="Isolation-Levels">Isolation Levels</h4><p>We've been talking about: serializability, conflict serializability, etc.</p><p>But forcibly enforcing serializability makes the system's concurrency too low and performance poor.</p><p>Therefore, the DBMS may want to use weaker consistency levels to improve scalability.</p><p>Four anomalies:</p><table><thead><tr><th>Anomaly</th><th>Original Definition</th></tr></thead><tbody><tr><td>Dirty Read</td><td>Reading data that has not yet been committed</td></tr><tr><td>Unrepeatable Read</td><td>Re-reading the same data yields different results</td></tr><tr><td>Lost Update</td><td>One transaction overwrites another concurrent transaction's update</td></tr><tr><td>Phantom Read</td><td>Inserting or deleting records causes the same range scan to yield different results</td></tr></tbody></table><p>Four isolation levels, from strongest to weakest:</p><ul><li>Serializable: phantom reads not allowed, all reads are repeatable, and dirty reads are also not allowed.</li><li>Repeatable Read: phantom reads may occur.</li><li>Read Committed: phantom reads, unrepeatable reads, and lost updates may occur.</li><li>Read Uncommitted: all of the above anomalies can occur.</li></ul><div class="note note-info"><p>Actually, the definitions corresponding to these names are easy to remember. For example, why doesn't Read Committed have dirty reads? Because the definition of a dirty read is precisely "reading uncommitted data." And Repeatable Read means multiple reads return the same data, i.e., it solves the unrepeatable read and lost update problems. Why does it solve lost updates? Because a lost update can also be seen as repeatedly reading inconsistent data.</p></div><p>How to implement different isolation levels? Taking 2PL as an example:</p><table><thead><tr><th>Isolation Level</th><th>Implementation Idea</th></tr></thead><tbody><tr><td>Serializable</td><td>Strong Strict 2PL + Phantom Protection</td></tr><tr><td>Repeatable Read</td><td>Strong Strict 2PL, but without Phantom Protection</td></tr><tr><td>Read Committed</td><td>Exclusive locks held until transaction end; shared locks released immediately after reading</td></tr><tr><td>Read Uncommitted</td><td>Exclusive locks held until transaction end; no shared locks acquired when reading</td></tr></tbody></table><h3 id="Lec-20-MVCC">Lec 20 MVCC</h3><h4 id="MVCC-Fundamentals">MVCC Fundamentals</h4><p>Multi-Version Control System MVCC is a broader concept than a mere Concurrency Control Protocol, touching every aspect of the DBMS's design and implementation.</p><p>MVCC's core idea: <strong>one logical object, multiple physical versions</strong>.</p><p>MVCC's core benefit: write transactions don't block read transactions, and read transactions don't block write transactions.</p><div class="note note-warning"><p><strong>Note</strong> that MVCC allows reads and writes to not block each other, but it does not automatically eliminate write-write conflicts.</p></div><blockquote><p>It means one transaction can modify an object while other transactions read the object's old version.</p></blockquote><p>Read-only transactions can, without using any locks, access the <strong>Consistent Snapshots</strong> provided by the DBMS.</p><h4 id="Snapshot-Isolation">Snapshot Isolation</h4><p>Snapshot Isolation: at the start of a transaction, the transaction is given a <strong>consistent snapshot</strong> of the database, where the data values in the snapshot only include values produced by transactions committed <strong>at that time</strong>. <strong>The entire complete transaction runs within this snapshot</strong>.</p><p>Solutions for Write-Write Conflicts: First Writer Wins or Last Writer Wins.</p><p>For example, with the former: if the earlier transaction writes but hasn't committed, the later transaction writing the same object will be aborted.</p><h4 id="Write-Skew-Anomaly">Write Skew Anomaly</h4><p>Under Snapshot Isolation, when two concurrent transactions modify different objects, a Write Skew Anomaly may occur, producing a non-serializable schedule.</p><p>To explain this problem, here's an example:</p><ul><li>Suppose the database initially has two marbles, one black and one white; the former is A, the latter is B.</li><li>T1 turns all black marbles white, T2 turns all white marbles black.</li><li>Serialized results:<ul><li>If the order is T1 - T2, everything ends up black;</li><li>If the order is T2 - T1, everything ends up white.</li><li>These two cases correspond to the only possibilities under serializability.</li></ul></li><li>But under snapshot isolation, both transactions execute on snapshots with the same initial conditions;</li><li>T1 only modifies A, T2 only modifies B</li><li>Since they don't write the same object, no WW conflict occurs</li><li>Then, the final result: A is white, B is black, <strong>corresponding to no serial result whatsoever</strong>.</li></ul><p>The essential reason is that <strong>there is a cycle in the dependency graph</strong>.</p><img src="https://image.wendaining.top/image-20261021191731098.png" style="zoom:50%;"><div class="note note-info"><p>Strictly speaking, this uses the Read-Write Antidependency from multi-version serialization graphs; you can't simply treat it as a single-version schedule and apply the ordinary conflict graph directly.</p></div><blockquote><p>Project 4's Snapshot Isolation only needs to check write-write conflicts, so in the marble example above, both transactions might successfully commit.</p><p>But Task 4.4's Serializable Verification also needs to check the data that was read, to determine whether concurrent transactions' writes invalidate those reads.</p><p>For example, when T1 commits, if it finds that T2 has already committed, and:</p><p>$$R_1\cap W_2\ne\varnothing$$</p><p>then T1 may need to be aborted to avoid a non-serializable execution.</p></blockquote><h4 id="Version-Chains">Version Chains</h4><p>Version storage: the DBMS uses the pointer field in a Tuple to create a <strong>Version Chain</strong> for each logical Tuple. Essentially, it is a linked list ordered by timestamp. At runtime, a transaction traverses along the version chain until it finds the correct version visible to itself.</p><h4 id="Version-Chain-Ordering">Version Chain Ordering</h4><ul><li>Oldest-to-Newest (O2N):<ul><li>New versions are appended to the end of the version chain. Lookups must traverse the version chain.</li></ul></li><li>Newest-to-Oldest (N2O):<ul><li>Each time a new version is created, the index pointer must be updated to point to the new chain head.</li><li>Reading the latest version requires no traversal of the version chain.</li><li>This is usually the better approach, because most transactions only care about the latest version.</li></ul></li></ul><div class="note note-primary"><p>Note the actual approach in the BusTub project:</p><p>BusTub does not append the complete updated Tuple to the main table on every update; instead it uses a Delta Storage-like scheme: current physical values -&gt; Undo Log chain. More on this later.</p></div><h4 id="Append-Only-Storage">Append-Only Storage</h4><p>Append-Only Storage</p><ul><li>All physical versions of a logical Tuple are kept in the same table space.</li><li>Different versions are stored mixed together in the table.</li><li>On each update, the DBMS only needs to append the Tuple's new version to free space in the table, then update the version chain.</li></ul><h4 id="Time-Travel-Storage">Time-Travel Storage</h4><p>This is the counterpart to Append-Only Storage, the second version storage scheme. Specifically:</p><ul><li>The DBMS maintains a separate table, called the Time-Travel Table, which stores old versions of Tuples.</li><li>On each update, the DBMS copies the old version to the Time-Travel Table, then overwrites the Tuple in the Main Table with the new data.</li><li>The Tuple's pointer in the Main Table points to the historical version in the Time-Travel Table.</li></ul><p><strong>It is still the pointer-linked-list logical structure</strong>; it's just that all historical versions are in the Time-Travel Table.</p><p>The direct benefit is that the main table doesn't have to mix in a large number of historical Tuples.</p><h4 id="Delta-Storage">Delta Storage</h4><p>Time-Travel Storage has this problem: if you only change one column of a tuple with many columns, you end up recording the entire historical information in full.</p><p>Delta Storage is similar to Time-Travel Storage, but the DBMS no longer stores complete historical Tuples; instead it stores only the differences or changes (Deltas) between Tuples in a Delta Storage Segment.</p><p>Afterwards, a transaction can traverse these Deltas in reverse order and apply them to recreate old versions.</p><p>Therefore, compared to Time-Travel Storage, Delta Storage writes faster but reads slower.</p><div class="note note-primary"><p><strong>A Delta stores the value before the modification, not the value after</strong>.</p></div><div class="note note-warning"><p>Note that for Tuples that have been logically deleted and are no longer needed by any active transaction, the physical records in the <strong>main table</strong> can eventually also be reclaimed.</p><p>That is the GC to be discussed below.</p></div><h4 id="Tuple-Level-Garbage-Collection">Tuple-Level Garbage Collection</h4><p>A version can be reclaimed if any of the following conditions is met:</p><ol><li>No active transaction can see this version.</li><li>This version was created by a transaction that has already Aborted.</li></ol><p>There are two main implementation approaches to garbage collection: Tuple-Level GC and Transaction-Level GC.</p><p>Regarding the first point, an example: version A0 has timestamp 10, but all currently active transactions have timestamps &gt; 10, and it has been logically deleted — then this version can be reclaimed.</p><p>Let's focus on the principle of what we call Tuple-Level GC: the DBMS discovers old versions by <strong>directly inspecting Tuples</strong>.</p><p>Two implementation schemes:</p><ul><li>Background Vacuuming<ul><li>A separate background thread periodically scans tables, looking for versions that can be reclaimed.</li><li>A simple optimization is to maintain a Dirty Page Bitmap, recording which Pages have been modified since the last scan. This way, the background thread can skip Pages that haven't changed.</li></ul></li><li>Cooperative Cleaning<ul><li>Worker Threads identify reclaimable versions while traversing version chains</li><li>Only applicable to Oldest-to-Newest (O2N) version chains, because the traversal order must be old -&gt; new so that cleanup can be done along the way</li></ul></li></ul><h4 id="Transaction-Level-Garbage-Collection">Transaction-Level Garbage Collection</h4><p>In transaction-level garbage collection, each transaction is responsible for tracking its own old versions, so the DBMS doesn't need to scan Tuples to find them.</p><ul><li>Each transaction maintains its own Read Set and Write Set.</li><li>When a transaction ends, the garbage collector can use these sets to determine which Tuples can be reclaimed.</li></ul><p>Simply put: maintain a set of Old Versions and determine whether these old versions are still needed.</p><p>However, BusTub's implementation differs greatly from this; more on that later.</p><h4 id="Logical-vs-Physical-Pointers">Logical vs. Physical Pointers</h4><p>Understanding how MVCC indexes locate version chains.</p><p>For the primary key index, which points to the head of the version chain: if a transaction modifies a Tuple's primary key attributes, that modification is treated as a DELETE followed by an INSERT. If Time-Travel or Delta Storage is used, the latest Tuple may always be kept in the same physical slot, in which case ordinary column updates don't necessarily require modifying the index pointer.</p><div class="note note-primary"><p>Updating a Tuple's contents does not necessarily mean changing the Tuple's physical address.</p></div><p>For secondary indexes, it's more complicated. There are two management schemes:</p><ol><li>Using Logical Pointers:<ul><li>The DBMS uses a fixed, unchanging identifier for each Tuple.</li><li>This requires an additional Indirection Layer to map logical IDs to the Tuple's physical location.</li><li>Afterwards, a Tuple update only needs to modify the mapping in the indirection layer.</li></ul></li><li>Physical Pointers<ul><li>The DBMS directly uses the physical address of the version chain head.</li><li>Whenever the version chain head changes, all related indexes need to be updated. This can be very expensive.</li></ul></li></ol><h4 id="MVCC-Duplicate-Key-Problem">MVCC Duplicate Key Problem</h4><p>Indexes in MVCC databases usually don't store a Tuple's version information together with the index key. The same Key in different snapshots may point to different logical Tuples. Therefore, the index needs to support duplicate Keys. This is the <strong>MVCC Duplicate Key Problem</strong>.</p><p>Three requirements are proposed:</p><ol><li>The index's underlying data structure needs to be able to store non-unique keys.</li><li>Primary key indexes and unique indexes need additional execution logic for conditional inserts. It must atomically check whether the Key exists before deciding whether to insert.</li><li>A Worker may get multiple entries from a single index query, so it needs to follow the pointers to find the correct physical version.</li></ol><div class="note note-info"><p><strong>Allowing the index's underlying layer to store duplicate Keys does not mean allowing two visible records that violate the uniqueness constraint to appear in the database</strong>.</p></div><p>However, bustub's constraint is that an index always points to the same RID.</p><h4 id="Deleted">Deleted</h4><ul><li>Logical Delete means that, for a particular snapshot, the record no longer exists.</li><li>Physical Delete means the database actually releases the storage space occupied by the record.</li></ul><p>The method of logical deletion: actually, we've already done this in the projects:</p><ol><li>Maintain an <code>is_deleted_</code> in the metadata</li><li>Set a tombstone</li></ol><h3 id="Preface-About-the-Spec">Preface About the Spec</h3><p>Recording some miscellaneous things to know.</p><ol><li>Use undo logs and undo links. The former is bound to transactions</li><li>Depends on the correct implementation of p2 and p3</li><li>Need to modify on top of this</li></ol><p>Also: this diagram is very useful:</p><img src="https://image.wendaining.top/img/2026/11/b6a5cf15b1df80cd03498841b1b659a8.png" style="zoom:67%;"><h2 id="Task-1">Task 1</h2><h3 id="Timestamp-Allocation">Timestamp Allocation</h3><p>First, understand bustub's timestamp allocation mechanism:</p><ul><li>Each transaction is assigned two timestamps: read ts and commit ts</li><li>When a transaction begins, it is assigned a read ts whose value equals <strong>the commit timestamp of the most recently committed transaction</strong></li><li>When a transaction commits, it uses <strong>the most recently committed transaction's commit timestamp + 1</strong><ul><li>Why is this OK? Because the read ts is fixed once assigned, but afterwards the last commit ts only increases monotonically</li></ul></li><li>Visible version = the latest version with (timestamp &lt;= read ts)</li><li><strong>Remember to update <code>last_commit_ts_</code></strong></li></ul><p>Here you need to implement the corresponding todo comments in <code>TransactionManager::Commit</code> and <code>TransactionManager::Begin</code>.</p><p>Actually, if you just follow what's said above, there's not much to say. Note that for this task, you only need to modify the corresponding parts.</p><h3 id="Watermark">Watermark</h3><p>The so-called watermark is:</p><ul><li>Among all transactions that have not yet been Committed or Aborted, the smallest read timestamp (<code>read_ts</code>).</li><li>If no such transaction exists, then the Watermark equals the last commit ts.</li></ul><p>The meaning of the Watermark is: <strong>current and future transactions never need to read snapshots earlier than the Watermark</strong>.</p><p>The most naive way to obtain it is obviously to traverse everything (the manager has a <code>std::unordered_map&lt;txn_id_t, std::shared_ptr&lt;Transaction&gt;&gt; txn_map_</code>, so just scan it all).</p><p>But this is too inefficient, so the spec requires us to implement a watermark algorithm that is at least $O(logN)$.</p><p>Anyway, first read the code. <code>watermark.h</code> contains these three fields:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-type">timestamp_t</span> commit_ts_;<span class="hljs-type">timestamp_t</span> watermark_;std::unordered_map&lt;<span class="hljs-type">timestamp_t</span>, <span class="hljs-type">int</span>&gt; current_reads_;</code></pre></div><table><thead><tr><th>Member</th><th>Meaning</th></tr></thead><tbody><tr><td><code>commit_ts_</code></td><td>The latest commit timestamp recorded inside Watermark</td></tr><tr><td><code>watermark_</code></td><td>The cached minimum active read timestamp</td></tr><tr><td><code>current_reads_</code></td><td>Records active read timestamps and their occurrence counts</td></tr></tbody></table><p>Then we need to implement these two functions:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">Watermark::AddTxn</span><span class="hljs-params">(<span class="hljs-type">timestamp_t</span> read_ts)</span> -&gt; <span class="hljs-type">void</span></span>;<span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">Watermark::RemoveTxn</span><span class="hljs-params">(<span class="hljs-type">timestamp_t</span> read_ts)</span> -&gt; <span class="hljs-type">void</span></span>;</code></pre></div><p>Actually, we also need to combine this with the functions in <code>TransactionManager</code>; <code>Begin()</code>, <code>Commit()</code>, and <code>Abort()</code> all need to correctly call <code>AddTxn()</code> and <code>RemoveTxn()</code>.</p><p>We can then realize that we can exploit the monotonically non-decreasing property of the watermark, using the existing hash table data structure to achieve amortized $O(1)$.</p><p>Roughly speaking:</p><ul><li>If the hash table is non-empty, then at the position keyed by the watermark there must be a value, and everything before the watermark is empty</li><li>When deleting a txn, if the value doesn't become 0, nothing happens</li><li>If the entire hash table becomes empty, set watermark = commit_ts</li><li>But if the hash table is not empty, then check whether the deleted one is exactly the one at the watermark position</li><li>If so, keep moving forward until reaching a non-empty position.</li><li>This only traverses once, amortized $O(1)$.</li></ul><h2 id="Task-2">Task 2</h2><p>The preceding introduction covers the storage mechanism for version data.</p><p>BusTub stores transaction data in three places: the Table Heap, the Transaction Manager, and each transaction's own Workspace:</p><ul><li>The Table Heap always contains the latest Tuple data.</li><li>The Transaction Manager keeps, for each Tuple, a link pointing to the latest Undo Log (<code>PageVersionInfo</code>).</li><li>Transactions keep the Undo Logs they created themselves, recording how the transaction modified the Tuple.</li></ul><p>The connections are roughly:</p><ul><li>You can get Tuple + Metadata from the TableHeap via RID</li><li>You can get an UndoLink from the Transaction Manager via RID, which is essentially <code>txn_id</code> + <code>log_idx</code>. An <code>UndoLink</code> is a link pointing to an Undo Log, used to chain together all the Undo Logs of a Tuple.<ul><li>If this txn id is invalid, then the undo link is invalid. Before obtaining undo logs, you need to first confirm validity</li></ul></li><li>Via the Undo Link you can get undo logs from the Transaction and traverse them one by one</li></ul><p>The way to obtain historical versions:</p><ul><li>First, get all modifications that occurred after this timestamp</li><li>Starting from the latest version, undo these modifications one by one</li></ul><h3 id="Tuple-Reconstruction">Tuple Reconstruction</h3><p>Goal: given the latest Tuple and a set of Undo Logs, reconstruct the historical Tuple.</p><p>(The next small task: finding the appropriate undo logs)</p><p>Implement this function:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">ReconstructTuple</span><span class="hljs-params">(</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> Schema *schema,</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> Tuple &amp;base_tuple,</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> TupleMeta &amp;base_meta,</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> std::vector&lt;UndoLog&gt; &amp;undo_logs</span></span><span class="hljs-params"><span class="hljs-function">)</span> -&gt; std::optional&lt;Tuple&gt;</span>;</code></pre></div><p>Note that the undo logs here:</p><ul><li>Are applied in order from newest to oldest</li><li>All passed-in Undo Logs should be applied; you must ensure the arguments don't pass in too many undo logs</li></ul><p>Also, if the result is deleted, return <code>std::nullopt</code>.</p><p>Another thing to note: the meanings of the fields of the undo log class are all easy to understand, except for the tuple — this tuple uses a <strong>partial schema</strong>, containing only the columns that were changed.</p><p>So we need to use <code>Schema::CopySchema()</code> to construct a partial schema, so that we can get the values we need from this tuple, and finally construct the returned tuple.</p><p>When constructing, we need an array <code>std::vector&lt;uint32_t&gt; attrs</code>, which can be obtained by iterating over the undo log's <code>modified_fields_</code> (by index).</p><h3 id="Sequential-Scan-Tuple-Retrieval">Sequential Scan (Tuple Retrieval)</h3><p>This section is essentially about collecting the undo logs that are actually needed.</p><p>We need to rewrite the <code>SeqScanExecutor</code> from Project 3 so that it can obtain the corresponding version based on the transaction's read ts. We also need to implement <code>CollectUndoLogs()</code> in <code>execution_common.cpp</code>:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">CollectUndoLogs</span><span class="hljs-params">(</span></span><span class="hljs-params"><span class="hljs-function">    RID rid,</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> TupleMeta &amp;base_meta,</span></span><span class="hljs-params"><span class="hljs-function">    <span class="hljs-type">const</span> Tuple &amp;base_tuple,</span></span><span class="hljs-params"><span class="hljs-function">    std::optional&lt;UndoLink&gt; undo_link,</span></span><span class="hljs-params"><span class="hljs-function">    Transaction *txn,</span></span><span class="hljs-params"><span class="hljs-function">    TransactionManager *txn_mgr</span></span><span class="hljs-params"><span class="hljs-function">)</span> -&gt; std::optional&lt;std::vector&lt;UndoLog&gt;&gt;</span>;</code></pre></div><p><strong>Pay attention to the return values</strong>:</p><ul><li>Returning an empty vector: there is a value but no rollback is needed; the current version can be used directly.</li><li>Returning <code>std::nullopt</code>: at the current transaction's read point in time, this Tuple does not yet exist, and there are not enough historical versions to reconstruct it.</li></ul><p>So we can divide into three cases:</p><ol><li><p>If the base tuple is new enough for the current snapshot, i.e. <code>base_meta.ts &lt; = txn.read_ts</code>, then it's case 1</p></li><li><p>If the base tuple is too new, i.e. <code>base_meta.ts &gt; txn.read_ts</code>, or the Tuple was modified by another transaction that has not yet committed, then we need to traverse the version chain and collect all undo logs after <code>txn.read_ts</code>.</p></li><li><p>If the Tuple in the Table Heap contains the current transaction's own modifications, i.e. the current transaction is reading data it previously modified itself, then special handling is needed, using a <strong>temporary timestamp</strong>.</p><div class="note note-info"><p>Even if a transaction's <code>read_ts</code> is earlier than its own modifications, the transaction should be able to read its own latest uncommitted modifications.</p></div><p>For case 3, if it's the transaction's own modification, the handling is actually the same as case 1.</p></li></ol><p>Here let me explain the temporary timestamp in detail:</p><ul><li>Both <code>timestamp_t</code> and <code>txn_id</code> are <code>int64_t</code></li><li>It is stipulated that <code>txn_id</code> starts from 1LL &lt;&lt; 62, i.e. only values with bit 62 set to 1 are transaction IDs (bit 63 is the sign bit, unused)</li><li>And it is stipulated that <code>0 &lt;= ts &lt; 1LL &lt;&lt; 62</code>, so anything with bit 62 equal to 0 is a timestamp</li><li>The temporary timestamp <strong>directly uses the current transaction's ID</strong></li><li>As long as bit 62 is 1 when scanning, it means this is a temporary timestamp</li></ul><p>However, bustub provides human-friendly interfaces:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">using</span> <span class="hljs-type">txn_id_t</span> = <span class="hljs-type">int64_t</span>;<span class="hljs-type">const</span> <span class="hljs-type">txn_id_t</span> TXN_START_ID = <span class="hljs-number">1LL</span> &lt;&lt; <span class="hljs-number">62</span>;<span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">GetTransactionTempTs</span><span class="hljs-params">()</span> <span class="hljs-type">const</span> -&gt; <span class="hljs-type">timestamp_t</span> </span>{  <span class="hljs-keyword">return</span> txn_id_;}<span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">GetTransactionIdHumanReadable</span><span class="hljs-params">()</span> <span class="hljs-type">const</span> -&gt; <span class="hljs-type">txn_id_t</span> </span>{  <span class="hljs-keyword">return</span> txn_id_ ^ TXN_START_ID;}</code></pre></div><p>You can use <code>GetTupleAndUndoLink()</code> to get the Base Tuple, TupleMeta, and the link pointing to the first Undo Log all at once.</p><div class="note note-primary"><p>When traversing the version chain, the loop termination condition is finding the <strong>first</strong> log with <code>log.ts &lt; txn.ts</code>.</p></div><div class="note note-info"><p><code>CollectUndoLogs</code> is responsible for determining the rollback path; <code>ReconstructTuple</code> is responsible for applying the logs and determining whether the target version was deleted.</p><p>The collection phase should <strong>not</strong> prematurely determine deletion.</p></div><h2 id="Task-3">Task 3</h2><blockquote><p>In this section, you will need to implement the data modification executors. This includes the insert executor, delete executor, and update executor.</p></blockquote><h3 id="Insert-Executor">Insert Executor</h3><p>Roughly these points:</p><ul><li>Create a new tuple in the table heap, correctly constructing the tuple meta</li><li>Set the timestamp in the tuple heap to the current transaction's temporary timestamp</li><li>Also add the new Tuple's RID to the Write Set via <code>AppendWriteSet()</code></li></ul><div class="note note-info"><p>For Task 4.2, when re-inserting, you need to consider reusing an existing RID.</p><p>Note the two functions <code>TableHeap::UpdateTupleInPlace()</code> and <code>TransactionManager::UpdateUndoLink()</code>:</p><ul><li>They work similarly to CAS: check first, then decide whether to execute</li><li>Use these two functions together with <code>GetTupleAndUndoLink()</code> and <code>UpdateTupleAndUndoLink()</code> to atomically update the Tuple and UndoLink. This only needs to be considered in Task 4.2; the current tests are all single-threaded.</li></ul></div><h3 id="Commit">Commit</h3><p>Convert the tuples modified by the transaction from temporary versions to committed versions.</p><p>Roughly there are six elements:</p><ol><li><p>Acquire <code>commit_mutex_</code> to ensure only one transaction performs a commit at a time</p></li><li><p>Obtain the Commit Timestamp; it is recommended to use <code>last_commit_ts_.load() + 1</code> rather than <code>fetch_add(1)</code></p><div class="note note-info"><p>Essentially, you must not update the global TS prematurely, otherwise the new read ts would be wrong</p></div></li><li><p>Update the timestamps of all base tuples in the write set</p></li><li><p>Set the transaction state to <code>COMMITTED</code></p></li><li><p>Update the transaction's own <code>commit_ts_</code></p></li><li><p>Update the global <code>last_commit_ts_</code>; here you can use <code>fetch_add(1)</code></p></li></ol><p>You also need to implement <code>TxnMgrDbg</code>, used to print the contents of the Table Heap and each Tuple's version chain. This is a bit annoying, so I had an LLM write it (after all, I'm not really good at debugging it myself).</p><h3 id="Generate-Undo-Logs">Generate Undo Logs</h3><p>The core point is: <strong>when the same transaction modifies the tuple corresponding to the same RID multiple times, only one undo log is kept in the end</strong>.</p><p>You need to implement <code>GenerateNewUndoLog()</code> and <code>GenerateUpdatedUndoLog()</code>.</p><p>Why two functions are needed:</p><ul><li>When a transaction modifies a tuple for the first time, use <code>GenerateNewUndoLog()</code></li><li>For subsequent modifications, use <code>GenerateUpdatedUndoLog()</code></li></ul><p>Three cases need to be considered:</p><ol><li><p>Update — the key point is to only update the values that weren't updated, keeping the original values from the very beginning</p></li><li><p>Delete — the complete tuple needs to be kept in the undo log. You should also consider: how to handle the case where the same transaction has already performed multiple modifications on it before.</p><div class="note note-warning"><p>Note that <code>UndoLog::is_deleted_</code> indicates whether the historical version to be restored was deleted!</p></div></li><li><p>Insert — in Task 4.2, you need to deal with the case of inserting a new tuple into the position of a previously deleted tuple</p></li></ol><p>Note that you may use two functions:</p><ul><li><code>Tuple::IsTupleContentEqual()</code>: directly compares whether the serialized values of two Tuples are equal, without comparing RIDs</li><li><code>Value::CompareExactlyEquals()</code>: compares whether two fields are equal; note this function treats two NULLs as equal. Because for an undo log, going from null to null is also no change.</li></ul><p>You must be clear about what the undo log is for:</p><ol><li>Be clear about what the undo log's <code>is_deleted_</code> is actually for — it indicates that <strong>historically</strong> this tuple did not exist, that it was deleted</li><li>If we are currently performing a delete operation, then on the contrary <code>is_deleted_</code> should be set to false, and the log's tuple should be set to the previous tuple. This represents what the tuple looked like at that time</li></ol><h3 id="Update-Delete-Executor">Update &amp; Delete Executor</h3><p>Actually wire the previously implemented undo log reading and undo log generation into the update and delete logic, so that the database can correctly modify versions.</p><p>For each rid to be modified:</p><ol><li>Check for write-write conflicts</li><li>Handle the undo log and version chain</li><li>Update the table heap</li></ol><p>Detecting write-write conflicts: mainly divided into two categories:</p><ol><li>This tuple was modified by a transaction that has not yet committed, so other transactions are forbidden from modifying this tuple, otherwise they will be aborted</li><li>This tuple was deleted and committed by a transaction, but an earlier-started transaction attempts to delete it again after that commit</li><li><strong>Note</strong>: a transaction's own modifications to itself should not be considered a write-write conflict</li></ol><p>The sole condition for detecting a write-write conflict is checking the base tuple metadata's timestamp.</p><p>When a write-write conflict is detected:</p><ul><li>Set the transaction state to <code>TAINTED</code></li><li>Throw an <code>ExecutionException</code></li></ul><p>The Update Executor should act as a pipeline breaker:</p><ul><li>First pull down and cache all tuples from the child executor, then read tuples from the cache and update them</li><li>Reason: for example, if the child executor is a seq scan executor, scanning below while modifying above would affect the scan below</li></ul><p>The core modifications needed for update and delete:</p><ul><li>Use the Generate series of functions from the previous task to generate the latest undo log</li><li>Use <code>UpdateTupleAndUndoLink()</code> to update</li></ul><p>But actually, after reading the spec above I still didn't know what to do; it took several rounds of grilling an LLM to roughly understand. To summarize:</p><ul><li><p>First, since update needs to be a pipeline breaker, i.e. caching all tuples and rids, we just do that. Although I suspect memory won't fit, the tests don't seem to check this, so whatever.</p></li><li><p>Use <code>auto [base_meta, base_tuple, undo_link] = GetTupleAndUndoLink(txn_mgr, table_info_-&gt;table_.get(), old_rid);</code> to get the base meta and base tuple; the so-called base tuple is the tuple currently pointed to by this rid</p></li><li><p>Then, check for write-write conflicts. If the write-write conflict check passes, then the base tuple should be the same as the old tuple (since currently there are only single-threaded tests); if it doesn't pass, handle it as described above</p></li><li><p>Then, as before, keep evaluating to get the new_tuple</p></li><li><p>Case analysis on the base meta:</p><ol><li>If it's the first modification, call <code>GenerateNewUndoLog()</code>, then call <code>txn-&gt;AppendUndoLog()</code> to get the new_link, which will be needed later when calling <code>UpdateTupleAndUndoLink()</code></li><li>If it was previously modified by ourselves, then use <code>GenerateUpdatedUndoLog()</code>; no need to worry about the undo link and such</li><li>In all other cases, the timestamp is our own + no previously created undo -&gt; this tuple was newly inserted within this transaction, no need to worry, just modify it directly</li></ol></li><li><p>Finally,</p>  <div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (<span class="hljs-built_in">UpdateTupleAndUndoLink</span>(txn_mgr, old_rid, new_link, table_info_-&gt;table_.<span class="hljs-built_in">get</span>(), txn, {txn-&gt;<span class="hljs-built_in">GetTransactionTempTs</span>(), <span class="hljs-literal">false</span>}, new_tuple)) {  txn-&gt;<span class="hljs-built_in">AppendWriteSet</span>(plan_-&gt;<span class="hljs-built_in">GetTableOid</span>(), old_rid);  updated_cnt += <span class="hljs-number">1</span>;}</code></pre></div></li></ul><p>Here, this <code>new_link</code> is the previous undo link if it's not the first modification.</p><p>Handling the delete executor is similar.</p><h3 id="Stop-the-world-Garbage-Collection">Stop-the-world Garbage Collection</h3><h3 id="Abort">Abort</h3><p>Implement the abort logic. The spec gives two implementation approaches, but I feel the first one is utterly baffling — it says it can be done this way to save time, but actually implementing the second one isn't much more complicated...</p><p>First, why abort is needed:</p><ul><li>When a transaction encounters a write-write conflict, it is set to the TAINTED state</li><li>It needs to be aborted to eliminate the transaction's effects on the database, so that writing can continue;</li><li>Otherwise, when other transactions try to write this tuple, checking the meta reveals it's all temp ts, always a write-write conflict, and they simply can't write</li></ul><p>The abort logic is actually not hard:</p><ul><li>Our goal is to restore the tuple to its state before this transaction modified it</li><li>Based on our earlier implementation, a transaction's modifications to a tuple result in at most one undolog, repeatedly modified on a single log; or it's newly created, or previously deleted</li><li>So, use <code>GetTupleAndUndoLink()</code> to get it</li><li>Then, check the <code>UndoLink</code>; if it doesn't exist, it's a newly inserted tuple. In this case the spec says to set the meta's ts to 0 — this is a special case — then call <code>UpdateTupleAndUndoLink()</code></li><li>If it exists, just restore accordingly; note that the meta afterwards should have parameters matching those in the log</li></ul><h2 id="Task-4">Task 4</h2><p>Task 4 requires making the current MVCC system support <strong>primary key</strong> indexes and extending it to the serializable isolation level.</p><p>The main issue is that the earlier parts didn't touch indexes at all (or rather, the parts of the update/insert/delete executors that involved indexes were removed), and now we need to implement this:</p><ul><li>The index is responsible for finding the RID</li><li>MVCC decides whether this RID exists in the current snapshot</li></ul><p>Worth noting is that the tests only test the primary key index. The primary key index can have more than one column, but in any case secondary indexes won't be tested.</p><h3 id="Index-Insert">Index Insert</h3><p>Core task: modify <code>InsertExecutor</code> so that Insert operations correctly maintain the primary key index.</p><p>Elements of the primary key index:</p><ol><li>A table has at most one primary key index</li><li>The primary key index is created automatically based on the table's schema</li><li>The primary key can be a composite primary key</li></ol><p>Operation flow:</p><ol><li>Check whether the primary key already exists in the index; if it exists, set TAINTED + throw an ExcutionException</li><li>Insert into the TableHeap</li><li>Insert into the index, mapping the new primary key to the RID; on failure, set TAINTED + throw an ExcutionException</li></ol><p>Actually, just implement it according to this. To check whether the primary key exists, use <code>tuple.KeyFromTuple()</code> to get the primary-key-related key, then use the primary key index's <code>ScanKey()</code>.</p><h3 id="Index-Scan-Delete-Update">Index Scan, Delete &amp; Update</h3><p>Solve three problems:</p><ol><li>After IndexScanExecutor finds the RID via the index, it needs to return the appropriate historical version based on the current transaction</li><li>For InsertExecutor, how to handle the case where the primary key exists in the index but the Tuple has been deleted (reuse the RID)</li><li>How UpdateExecutor / DeleteExecutor can modify tuples without breaking the index mapping</li></ol><div class="note note-primary"><p>Essence: the key in the Index always points to the same RID, and remains unchanged once created.</p><p>The tuple pointed to by the RID can change; MVCC is responsible for maintaining history.</p></div><p>So, for IndexScanExecutor, it's basically just reusing the previous handling logic for SeqScanExecutor, migrating it over with minor tweaks — not hard.</p><p>For InsertExecutor, it's a bit more complicated. Roughly these elements:</p><ol><li>Simply put, after <code>ScanKey()</code> finds something, instead of directly throwing an exception, you should reuse the original RID, i.e. modify on top of the previous sub-task (modify inside that if)</li><li>But here it's essentially an Update (though an Update of something that was originally deleted), which is actually pretty much the same as Task 3.6; just reuse the various logic</li><li>However, the difference from Task 3.6 is that concurrency needs to be considered, i.e. <code>UpdateTupleAndUndoLink()</code> needs to consider the <code>check()</code> callback. If the check fails, you also need to set TAINTED and throw an exception</li><li>It's actually a bit complicated.</li></ol><p>Then the Update and Delete Executors are basically the same as above — just add a check, and there's not much to say: just check whether the ts relative to the base meta has changed.</p><div class="note note-info"><p>Why do neither Update nor Delete need to handle the index anymore? Because the index is not bound to any specific tuple or anything like that, but only bound to the RID!</p></div><p>In the end, I found that the core logic chain in these three Executors — first get the meta tuple link, then branch based on whether it was modified by the current transaction — can be extracted into execution common as a <code>Modify</code> function.</p><h3 id="Primary-Key-Updates">Primary Key Updates</h3><p>Simply put:</p><ol><li>When the primary key is updated, the implementation is: first delete the old key, then do an insert for the new key</li><li>The execution order is: first insert the tuple with the new primary key into the table heap, then delete all the old tuples that will be updated, and finally insert the updated tuple back with the new primary key</li><li>The new key creates a new index entry; the old key is left untouched and kept.</li></ol><p>Translating this into code:</p><ul><li>Originally, when the UpdateExecutor called <code>Modify()</code>, it did so without any conditions</li><li>But in this task, you need to first determine whether the primary key's column values have changed</li><li>If they have changed, you can't go directly through Modify; instead you must split it into delete + insert</li></ul><p>First use <code>Tuple::KeyFromTuple</code> and <code>IsTupleContentEqual</code> to determine whether the primary key has changed.</p><p>Then, inserting the tuple with the new primary key into the table heap is nothing special — just pass <code>nullptr</code> as the target parameter of Modify. Actually, this can be combined with the unchanged case using a ternary expression: if changed, pass nullptr.</p><p>Afterwards, for the part of inserting back, I found it's exactly the same logic as InsertExecutor, also needing to consider RID reuse, so I extracted the logic there into a function and put it in execution common.</p><p>Up to here it's fine, but there's a problem: the spec requires <strong>deleting all the old tuples that will be updated</strong> first.</p><p>So, <code>Next()</code> uses two loops: the first loop does pure reading + deletion first, also implementing the previous logic, but keeps an array to temporarily store all the tuples that changed. Then, the second loop iterates over the just-stashed array and Inserts them one by one.</p><h3 id="Serializable-Verification">Serializable Verification</h3><p>Serializability depends on Snapshot Isolation, but the write skew problem exists; this Task is about solving that problem.</p><p>It's about performing an OCC (Optimistic Concurrency Control) Backward Validation before each transaction commits.</p><p>Simply put, it's a scan: <strong>whether the range read by the current transaction was modified by other transactions after the read and before the commit</strong>.</p><p>The so-called "<strong>range read</strong>" is essentially <strong>recording the predicates</strong>.</p><p>The spec says:</p><ul><li>Each time SeqScan or IndexScan is called, use <code>Transaction::AppendScanPredicate(table_oid, predicate)</code> to record the predicate; <code>predicate == nullptr</code> means a full table scan</li><li>Also implement <code>VerifyTxn</code>, which makes the judgment in the context of the current transaction's information.</li></ul><p>Specifically, the rules of <code>VerifyTxn</code> are:</p><ul><li>Read-only transactions don't need verification.</li><li>Collect all conflicting transactions. A conflicting transaction is one that committed after the current transaction's read ts.</li><li>Collect the RIDs from the WriteSets of all conflicting transactions, grouped by table oid</li><li>For each RID, use <code>CollectUndoLogs</code>, then <strong>restore versions one by one</strong>, as follows:<ul><li>The so-called "<strong>restoring versions one by one</strong>" means traversing the entire version chain starting from the base tuple, verifying one by one</li><li>For each version, get the before image and after image, i.e. what the row looked like before and after the change</li><li>If it's an insert, i.e. before doesn't exist but after does, abort if the after image hits the predicate</li><li>If it's a delete, abort if the before image hits the predicate</li><li>If it's an update, i.e. both exist, check both; abort if either hits</li><li>Actually I feel the division given in the spec isn't very meaningful; just compute both before and after as optionals and test them</li><li>Note that the so-called hitting the predicate is obtained via <code>GetScanPredicates() -&gt; const std::unordered_map&lt;table_oid_t, std::vector&lt;AbstractExpressionRef&gt;&gt; &amp;</code></li></ul></li></ul><p>However, there are a few edge cases:</p><ul><li>If it's insert followed by delete, just ignore it, as if nothing happened</li><li>If something was changed and then changed back, the above logic also needs to be used to judge</li><li>If tupleA and tupleB "swap", both need to be checked</li></ul><p>There are also a few points to note when coding:</p><ol><li>You need to traverse <code>txn_map_</code> to get all the conflict txns, but this step requires acquiring the shared lock of the txn map. However, if you handle other core logic inside the traversal loop, the call chain inside <code>CollectUndoLogs</code> will call <code>GetUndoLogOptional</code>, which acquires the map's shared lock again — but repeatedly acquiring the same shared lock in the same thread is UB. So the solution is to first store all the conflicting transactions.</li><li>If <code>CollectUndoLogs</code> returns no value, it actually means this is a newly inserted tuple; don't just ignore it directly.</li></ol><p>The end.</p><img src="https://image.wendaining.top/img/2026/11/4d83906fe7424944951c43adb86a4bb0.png" style="zoom:67%;"><img src="https://image.wendaining.top/img/2026/11/347669edb48bdd1aacc1300fc236eae9.png" style="zoom:67%;">]]>
      </content:encoded>
    </item>
    <item>
      <title>CMU 15-445 Bustub Project 3 - Query Execution - Note</title>
      <link>https://blog.wendain.ing/en/posts/cmu-15-445-bustub-proj3/</link>
      <description>Brief notes on Query Execution, the third project of the CMU 15-445 course</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/bustub/">Bustub</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <pubDate>Sun, 18 Oct 2026 04:31:29 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/cmu-15-445-bustub-proj3/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p><strong>Wasn't it supposed to be about the same difficulty as P1</strong>?</p><p>I worked on it on and off from October 9th to October 17th, at least 4h+ every day, and 7~8h+ when I was relatively free. When I finished, I hadn't done any Leaderboard optimizations, yet my Leaderboard ranking was pretty good (24/140+), which is a bit mysterious.</p><p>As usual, at the start I had no idea what to do, and only got a rough picture as I wrote along. Then I discovered my earlier understanding of the concepts was completely off, tore it all down and started over, again and again.</p><p>The main reason is that this project's codebase is genuinely huge—there's a lot to read. All the architectural design decisions, the meanings of various data structures and custom types—all of it needs to be crystal clear before you can write appropriate code. And even when it's all clear, you still might not write it correctly, e.g., questions like "which <code>Schema</code> exactly am I supposed to pass?"</p><p>Starting the blog post only after finishing is also a bit mysterious; I should have been writing notes as I went. That said, this time I put a lot of things into commit messages, and a commit message is usually very long, which makes it convenient for me to review how I was thinking at the time.</p><p>At the beginning I didn't know how to proceed, so I referred to these blog posts:</p><ul><li><a href="https://zhuanlan.zhihu.com/p/2058632609798923944">CMU15445-2025FALL Personal Ramblings - W3nYui's article - Zhihu</a></li><li><a href="https://zhuanlan.zhihu.com/p/587566135">Building a Database: 2022 CMU15-445 Project3 Query Execution - Shi Yi's article - Zhihu</a></li><li><a href="https://zhuanlan.zhihu.com/p/570917775">The Making of BusTub: From Course Project to SQL Database</a>, this one is by the author of this Project.</li></ul><h2 id="Understanding-the-Core-Structure">Understanding the Core Structure</h2><p>Let me just briefly go over it, since I'm a bit too lazy to write everything down—here are a few core points:</p><p>The full execution flow of a SQL statement, which all three blog posts above cover:</p><ol><li><p>Parser: with the help of PostgreSQL's third-party parsing library, produces a Postgres AST</p></li><li><p>Binder: after the AST is produced, the binder rewrites this AST into a higher-level AST that bustub can understand. For example, for <code>SELECT colA FROM test_1</code>, it resolves <code>test_1</code> to the corresponding <code>table_oid</code>.</p></li><li><p>Planner: essentially binds the information in the query statement onto various plan nodes. As for what a plan node is, you'll naturally understand as you write along. Then, it builds a query tree.</p></li><li><p>Optimizer: optimizes the plan nodes</p><div class="note note-info"><p>Another thing worth mentioning is that, generally speaking:</p><ul><li>The Planner generates Logical Plan Nodes, representing abstract Plans.</li><li>The Optimizer generates Physical Plan Nodes, representing concretely executed Plans.</li></ul><p>A typical example is Join. In the query plan generated by the Planner, a Join is just a Join. In the query plan generated by the Optimizer, the Join will be optimized into a concrete HashJoin or NestedIndexJoin, etc.</p><p>In Bustub, there is no distinction between Logical Plan Nodes and Physical Plan Nodes. The Planner directly generates Physical Plan Nodes.</p></div></li><li><p>Executor: based on the Planner's plan, generates the executor corresponding to the plan and carries out the actual execution.</p></li></ol><p>Regarding Executors: the execution models of operators can be roughly divided into three types:</p><ul><li>Iterator Model: has Init and Next, but each Next returns only one tuple</li><li>Materialization Model: one Next returns everything at once (materialization)</li><li>Vectorization Model: one Next returns a certain number of tuples (specified by yourself)</li></ul><p>Bustub uses the third one.</p><p>In addition, there are two execution directions for operators:</p><ol><li>Top-to-Bottom. Starting from the root operator, continuously pull data from the operators below.</li><li>Bottom-to-Top. Starting from the leaf operators, push your own data up to the operators above.</li></ol><p>Bustub uses Top-to-Bottom.</p><p>That's roughly what you need to know before starting, so let's begin the journey proper. Of course, if this is your first time, after hearing all of the above you're probably still confused. You really have to dig into the code to understand it.</p><h2 id="Task-1">Task 1</h2><p>Implement three relatively simple executors, though not understanding the concepts at the start is definitely quite painful.</p><p>First look at this image</p><img src="https://pica.zhimg.com/v2-9bc6214441f8ca37004ff1389114a692_1440w.jpg" style="zoom: 67%;"><p>This image is pretty good; it clarifies a lot of concepts.</p><h3 id="SeqScan">SeqScan</h3><p>So, to implement SeqScan, you just keep a TableHeap iterator and keep reading Tuples. This way the state of <code>Next</code> is also maintained. Remember to check <code>TupleMeta.is_deleted_</code>.</p><p>Note that you should <strong>not</strong> keep pulling from a child executor, because there is no child executor at all.</p><h3 id="Insert-and-Delete">Insert and Delete</h3><p>I'll discuss these two together, because the general framework is the same: keep pulling tuples from the child executor, modify the TableHeap, and then maintain the indexes on the table. Unlike SeqScan, here there really is a child executor.</p><p>But here you need to pay attention to the comment:</p><div class="note note-primary"><p><strong><em>@param</em>[out] <em>tuple_batch</em> The tuple batch with one integer indicating the number of rows inserted into the table.</strong></p><p><strong>InsertExecutor::Next() returns true with the number of inserted rows produced only once.</strong></p></div><p>For example:</p><div class="code-wrapper"><pre><code class="hljs sql"><span class="hljs-keyword">CREATE TABLE</span> t1(id <span class="hljs-type">INT</span>, val <span class="hljs-type">INT</span>);<span class="hljs-keyword">INSERT INTO</span> t1 <span class="hljs-keyword">VALUES</span> (<span class="hljs-number">1</span>, <span class="hljs-number">10</span>), (<span class="hljs-number">2</span>, <span class="hljs-number">20</span>), (<span class="hljs-number">3</span>, <span class="hljs-number">30</span>);</code></pre></div><p>The child executor provides <code>(1, 10)</code>, <code>(2, 20)</code>, <code>(3, 30)</code>, while the InsertExecutor's output is only one tuple containing a single integer <code>3</code>. Delete and Update work the same way.</p><p>So my implementation is:</p><ul><li>In the first <code>Next()</code>, keep calling the child's <code>Next()</code> until all input has been processed</li><li>Then return a count, and use <code>finished_</code> to record that execution has already happened</li><li>Subsequent <code>Next()</code> calls see <code>finished_ == true</code> and directly return <code>false</code>.</li></ul><p>The code that finally constructs the result, for example for Insert:</p><div class="code-wrapper"><pre><code class="hljs cpp">tuple_batch-&gt;<span class="hljs-built_in">emplace_back</span>(    std::vector&lt;Value&gt;{ValueFactory::<span class="hljs-built_in">GetIntegerValue</span>(insert_cnt)},    &amp;<span class="hljs-built_in">GetOutputSchema</span>());finished_ = <span class="hljs-literal">true</span>;<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;</code></pre></div><p>Note: even if not a single row was inserted, you should still return a tuple with the value <code>0</code>.</p><h3 id="Some-Notes-and-Pitfall-Records">Some Notes and Pitfall Records</h3><h4 id="Next-Must-Clear-the-Previous-Batch-s-Output"><code>Next()</code> Must Clear the Previous Batch's Output</h4><p>Here's a commit message from back then, <code>add3064</code>:</p><blockquote><p>clear batch before call Next()</p><p><strong>check <code>ExecutionEngine::PollExecutor</code> to understand why!!!</strong></p></blockquote><p>Looking at <code>ExecutionEngine::PollExecutor()</code> makes it very clear:</p><div class="code-wrapper"><pre><code class="hljs cpp">std::vector&lt;RID&gt; rids{};std::vector&lt;Tuple&gt; tuples{};<span class="hljs-keyword">while</span> (executor-&gt;<span class="hljs-built_in">Next</span>(&amp;tuples, &amp;rids, BUSTUB_BATCH_SIZE)) {  <span class="hljs-keyword">if</span> (result_set != <span class="hljs-literal">nullptr</span>) {    result_set-&gt;<span class="hljs-built_in">insert</span>(result_set-&gt;<span class="hljs-built_in">end</span>(), tuples.<span class="hljs-built_in">begin</span>(), tuples.<span class="hljs-built_in">end</span>());  }}</code></pre></div><p>The caller repeatedly reuses the same two vectors and <strong>will not clear them for the executor</strong>. So at the beginning of <code>Next()</code> you need:</p><div class="code-wrapper"><pre><code class="hljs cpp">tuple_batch-&gt;<span class="hljs-built_in">clear</span>();rid_batch-&gt;<span class="hljs-built_in">clear</span>();</code></pre></div><p>If you don't clear, the SeqScan test will behave like this: the first batch returns <code>0</code>, the second batch becomes <code>0, 1</code>, the third batch becomes <code>0, 1, 2</code>—all duplicated old results.</p><h4 id="Insert-The-Values-Have-Already-Been-Computed-by-the-Child">Insert: The Values Have Already Been Computed by the Child</h4><p>The original text of the <code>06278d7</code> commit message:</p><blockquote><p>insert doesn't need to evaluate, because its child executor is a value executor, which does the evaluation itself (you can look at the value executor's next function)</p></blockquote><p>This refers to the <code>INSERT ... VALUES ...</code> case. Looking at <code>ValuesExecutor::Next()</code>, it is already responsible for evaluating column by column and then constructing the tuple:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-type">const</span> <span class="hljs-keyword">auto</span> &amp;row_expr = plan_-&gt;<span class="hljs-built_in">GetValues</span>()[cursor_];<span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> <span class="hljs-keyword">auto</span> &amp;col : row_expr) {  values.<span class="hljs-built_in">push_back</span>(col-&gt;<span class="hljs-built_in">Evaluate</span>(<span class="hljs-literal">nullptr</span>, dummy_schema_));}tuple_batch-&gt;<span class="hljs-built_in">emplace_back</span>(values, &amp;<span class="hljs-built_in">GetOutputSchema</span>());</code></pre></div><p><code>dummy_schema_</code> is an empty Schema. For example, for <code>VALUES (1, 10 + 20)</code>, these expressions don't depend on the columns of any input tuple, so what's passed here is <code>nullptr</code> and an empty Schema.</p><p>Of course, Insert's child isn't always Values; it can also come from <code>INSERT INTO ... SELECT ...</code>. But for InsertExecutor, the handling is no different: <strong>what the child returns is already a fully evaluated tuple that can be inserted into the table</strong>.</p><p>Therefore, the main logic is:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">auto</span> table_info = exec_ctx_-&gt;<span class="hljs-built_in">GetCatalog</span>()-&gt;<span class="hljs-built_in">GetTable</span>(plan_-&gt;<span class="hljs-built_in">GetTableOid</span>());<span class="hljs-keyword">auto</span> indexes = exec_ctx_-&gt;<span class="hljs-built_in">GetCatalog</span>()-&gt;<span class="hljs-built_in">GetTableIndexes</span>(table_info-&gt;name_);<span class="hljs-comment">// 下面位于消费 child batch 的循环里面。</span>std::optional&lt;RID&gt; rid = table_info-&gt;table_-&gt;<span class="hljs-built_in">InsertTuple</span>({<span class="hljs-number">0</span>, <span class="hljs-literal">false</span>}, tuple);<span class="hljs-keyword">if</span> (rid.<span class="hljs-built_in">has_value</span>()) {  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> &amp;index_info : indexes) {    Tuple key = tuple.<span class="hljs-built_in">KeyFromTuple</span>(        table_info-&gt;schema_, index_info-&gt;key_schema_,        index_info-&gt;index_-&gt;<span class="hljs-built_in">GetKeyAttrs</span>());    index_info-&gt;index_-&gt;<span class="hljs-built_in">InsertEntry</span>(key, rid.<span class="hljs-built_in">value</span>(), exec_ctx_-&gt;<span class="hljs-built_in">GetTransaction</span>());  }  insert_cnt += <span class="hljs-number">1</span>;}</code></pre></div><p><code>{0, false}</code> is <code>TupleMeta</code>, where <code>false</code> means not deleted. <code>InsertTuple()</code> returns a <code>std::optional&lt;RID&gt;</code>, and on success you get the location of this new record in the TableHeap. <strong>Note that the RID used to insert into the index here is this new RID</strong>, not the RID returned by the child, because tuples produced by Values never had a corresponding location in the table in the first place.</p><p>One more point: updating the table does not automatically maintain the indexes for us. However many indexes the table has, you need to extract the key and insert into each one separately.</p><h4 id="Why-Is-the-Index-s-Key-Also-a-Tuple">Why Is the Index's Key Also a Tuple?</h4><p>I didn't understand this at the time either.</p><p>For example, if the table's Schema is <code>(id INT, val INT)</code>, a row is <code>(2, 20)</code>, and the index is only built on <code>id</code>:</p><ul><li>Full tuple: (2, 20)</li><li>key attrs: [0]</li><li>key schema: (id INT)</li><li>key tuple: (2)</li><li>Mapping stored in the index: (2) -&gt; the RID of this row</li></ul><p>The three parameters of <code>KeyFromTuple()</code> then correspond:</p><ul><li><code>table_info-&gt;schema_</code>: what structure to use to read the original full tuple.</li><li><code>index_info-&gt;key_schema_</code>: what structure the extracted index key has.</li><li><code>GetKeyAttrs()</code>: which columns to take from the full tuple, and in what order.</li></ul><p>Although this key is also of type Tuple, it <strong>only contains the columns the index needs</strong>.</p><p>Actually, I think designing it as <code>vector&lt;Value&gt;</code> would be more reasonable; I don't know why it's like this. In any case, keep this in mind.</p><h3 id="Delete-Logical-Deletion-and-Deleting-Index-Entries">Delete: Logical Deletion and Deleting Index Entries</h3><p>Delete's input is the records already filtered out by the child for deletion. Once you get the tuple and the corresponding RID, just delete them directly.</p><p>However, although it's called deletion, this doesn't erase the tuple's bytes from the page; it only sets <code>TupleMeta.is_deleted_</code> to <code>true</code>. Then, delete the corresponding entry in each index.</p><h3 id="Update">Update</h3><p>Although it's essentially Insert and Delete stitched together, I actually hit more pitfalls here than in both of them combined. The <a href="https://15445.courses.cs.cmu.edu/fall2025/project3/#update">Fall 2025 spec</a> requires deleting the old record first, then inserting the new record.</p><p>First, let me paste the <code>7ed57b8</code> commit message verbatim; this one basically records all the problems I had at the time:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1310 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">Refactor update_executor, lots of pitfalls You must look at the fields o...</span></summary><blockquote><p>Refactor update_executor, lots of pitfalls</p><ol><li><p>You must look at the fields of the plan and the executor; don't assume they're all the same. The update executor has <code>const TableInfo *table_info_</code>, but I didn't notice it when writing code, so I first defined a local variable <code>table_info</code>, and then later when using it, because of autocomplete, I used <code>table_info_</code> everywhere, and they were all null pointers, causing errors... Actually I think this field isn't very useful either; getting it locally is the same. But since it's given, initialize it in the constructor.</p></li><li><p>Next is another field, but this one is on the plan node: <code>std::vector&lt;AbstractExpressionRef&gt; target_expressions_;</code>. <strong>I actually didn't use this at first, which means my update updated nothing at all</strong>. Here we need to evaluate this vector one by one</p><ul><li>Note that tidy requires reserving in advance and forbids push_back inside loops, so we can refer to the reserve in value_executor</li></ul><p>Then we get new_tuple and new_rid. Then we also need to delete the old index entries and update the new index entries. Note that the index key here is very important. This key means the index's key, the key for looking up the index. Note that the key and rid used for deleting the old index entry and building the new one must each be the corresponding one; don't mix them up!</p></li></ol></blockquote></details><h4 id="target-expressions-Determines-the-Updated-Values"><code>target_expressions_</code> Determines the Updated Values</h4><p>At first, unfamiliar with the API, what I did was "delete the old tuple, then insert the same tuple back"—pulling your pants down just to put them back on.</p><p>For example:</p><div class="code-wrapper"><pre><code class="hljs sql"><span class="hljs-keyword">UPDATE</span> t1 <span class="hljs-keyword">SET</span> val <span class="hljs-operator">=</span> val <span class="hljs-operator">+</span> <span class="hljs-number">5</span> <span class="hljs-keyword">WHERE</span> id <span class="hljs-operator">=</span> <span class="hljs-number">2</span>;</code></pre></div><p>Suppose the old tuple is <code>(2, 20)</code>. The <code>target_expressions_</code> given by the Planner can be understood as an array whose length is the number of columns of the final returned tuple, where each column corresponds to a computation. For columns that weren't modified, the Planner fills in a <code>ColumnValueExpression</code> that reads the old column:</p><div class="code-wrapper"><pre><code class="hljs text">Column 0: #0.0        reads the id of the old tupleColumn 1: #0.1 + 5    reads the val of the old tuple, then adds 5</code></pre></div><p>Here <code>#0.1</code> means the 1st column of the 0th input, with indices starting from 0.</p><p>Therefore, you need to call <code>Evaluate()</code> one by one to get all the Values for constructing the new tuple:</p><div class="code-wrapper"><pre><code class="hljs cpp">std::vector&lt;Value&gt; values;values.<span class="hljs-built_in">reserve</span>(plan_-&gt;target_expressions_.<span class="hljs-built_in">size</span>());<span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> <span class="hljs-keyword">auto</span> &amp;expr : plan_-&gt;target_expressions_) {  values.<span class="hljs-built_in">push_back</span>(expr-&gt;<span class="hljs-built_in">Evaluate</span>(&amp;old_tuple, child_executor_-&gt;<span class="hljs-built_in">GetOutputSchema</span>()));}Tuple new_tuple{values, &amp;table_info_-&gt;schema_};</code></pre></div><p>What you get is <code>(2, 25)</code>. Each expression is evaluated against the same <code>old_tuple</code>; it's not "modify one column, then use the modified tuple to compute the next column."</p><h4 id="Which-Schema-Should-Actually-Be-Passed">Which Schema Should Actually Be Passed?</h4><ul><li><p>The current executor's <code>GetOutputSchema()</code> represents what the current executor outputs to its parent node, not the structure of the table it operates on</p></li><li><p>The <code>child_executor</code>'s Schema works the same way</p></li><li><p><code>plan_-&gt;output_schema_</code> is actually the same as the current executor's, mainly because this line of the function is the same:</p>  <div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">GetOutputSchema</span><span class="hljs-params">()</span> <span class="hljs-type">const</span> -&gt; <span class="hljs-type">const</span> Schema &amp; <span class="hljs-keyword">override</span> </span>{ <span class="hljs-keyword">return</span> plan_-&gt;<span class="hljs-built_in">OutputSchema</span>(); };</code></pre></div></li></ul><h4 id="Old-Key-Old-RID-and-New-Key-New-RID">Old Key, Old RID and New Key, New RID</h4><p>After computing the new values, the operations on the table are:</p><div class="code-wrapper"><pre><code class="hljs cpp">table_info_-&gt;table_-&gt;<span class="hljs-built_in">UpdateTupleMeta</span>({<span class="hljs-number">0</span>, <span class="hljs-literal">true</span>}, old_rid);std::optional&lt;RID&gt; new_rid = table_info_-&gt;table_-&gt;<span class="hljs-built_in">InsertTuple</span>({<span class="hljs-number">0</span>, <span class="hljs-literal">false</span>}, new_tuple);</code></pre></div><p>The operations on the indexes require extracting the old key and the new key separately:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (new_rid.<span class="hljs-built_in">has_value</span>()) {  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">auto</span> &amp;index_info : indexes) {    Tuple old_key = old_tuple.<span class="hljs-built_in">KeyFromTuple</span>(        table_info_-&gt;schema_, index_info-&gt;key_schema_,        index_info-&gt;index_-&gt;<span class="hljs-built_in">GetKeyAttrs</span>());    Tuple new_key = new_tuple.<span class="hljs-built_in">KeyFromTuple</span>(        table_info_-&gt;schema_, index_info-&gt;key_schema_,        index_info-&gt;index_-&gt;<span class="hljs-built_in">GetKeyAttrs</span>());    index_info-&gt;index_-&gt;<span class="hljs-built_in">DeleteEntry</span>(old_key, old_rid, exec_ctx_-&gt;<span class="hljs-built_in">GetTransaction</span>());    index_info-&gt;index_-&gt;<span class="hljs-built_in">InsertEntry</span>(new_key, new_rid.<span class="hljs-built_in">value</span>(), exec_ctx_-&gt;<span class="hljs-built_in">GetTransaction</span>());  }  updated_cnt += <span class="hljs-number">1</span>;}</code></pre></div><p>For example, if the index is built on <code>id</code>, the old record <code>(2, 20)</code> is located at the hypothetical <code>RID(10, 0)</code>, and after updating to <code>(8, 20)</code> it's located at the hypothetical <code>RID(11, 0)</code>. That means deleting <code>2 -&gt; RID(10, 0)</code> and inserting <code>8 -&gt; RID(11, 0)</code>. The key and the RID must each correspond; you can't stitch a new key together with an old RID.</p><p>Even if you only modify <code>val</code> and <code>id</code> doesn't change, the index still needs to be maintained. Because P3 here does delete-then-insert, <strong>the key can be the same, but the record's location has already changed to the new RID</strong>. If the original index still points to the old record, a lookup would find the record that has already been marked as deleted.</p><h4 id="Could-You-Update-a-Record-You-Just-Inserted-Yourself">Could You Update a Record You Just Inserted Yourself?</h4><p>This question relates to which kind of iterator SeqScan chooses: the difference between <code>MakeIterator()</code> and <code>MakeEagerIterator()</code>.</p><p>For example, with <code>UPDATE t1 SET val = val + 1</code>, if you insert new records while scanning, and the iterator keeps moving toward the new end of the table, you might end up updating the just-inserted records again. This is the Halloween problem that needs to be avoided here.</p><p><code>MakeIterator()</code> records the current end-of-table stopping position when created, so subsequent scans won't cross this boundary to chase newly inserted records.</p><h3 id="Optimizing-SeqScan-to-IndexScan">Optimizing SeqScan to IndexScan</h3><p>Although in the spec, the order is to implement IndexScan first and then this optimizer rule, the spec also says implementing the latter first helps you better understand the former, so I did it that way, and that was indeed the case.</p><p>But since this was my first encounter with an optimizer, let's first understand the basic structure of the optimizer:</p><h4 id="What-Is-the-Optimizer-Actually-Changing">What Is the Optimizer Actually Changing?</h4><blockquote><p>The BusTub optimizer is a rule-based optimizer. Most optimizer rules construct optimized plans in a bottom-up way. Because the query plan has this tree structure, before applying the optimizer rules to the current plan node, you want to first recursively apply the rules to its children.</p><p>At each plan node, you should determine if the source plan structure matches the one you are trying to optimize, and then check the attributes in that plan to see if it can be optimized into the target optimized plan structure.</p><p>In the public BusTub repository, we already provide the implementation of several optimizer rules. Please take a look at them as reference.</p></blockquote><p>The optimizer takes in an execution plan tree and returns an optimized execution plan tree.</p><div class="note note-info"><p>A trick for writing the optimizer is to notice what type the finally returned plan node actually is, then look at its constructor to determine what we need to obtain, and use that as a clue for coding.</p></div><p>For example, if table <code>t1(id INT, val INT)</code> has an index on <code>id</code>, the query <code>WHERE id = 2</code> can simplify the plan into the following transformation:</p><div class="code-wrapper"><pre><code class="hljs text">Filter(id = 2)                 SeqScan(filter = id = 2)  └── SeqScan(t1)       -&gt;              ↓                              IndexScan(key = 2)</code></pre></div><p>This is actually two rules: <code>OptimizeMergeFilterScan()</code> is responsible for merging the Filter into the SeqScan, and <code>OptimizeSeqScanAsIndexScan()</code> then tries to replace this SeqScan with a predicate.</p><p>The former's skeleton code is already implemented; only the latter is something we need to write.</p><div class="note note-info"><p>Reading the source code of <code>OptimizeMergeFilterScan()</code> is of great benefit for implementing this problem.</p></div><p>Look at <code>optimizer.cpp</code> and <code>optimizer_custom_rules.cpp</code>; they simply call these optimization functions in sequence. <strong>The order matters</strong>: our rule reads <code>SeqScanPlanNode::filter_predicate_</code>, which presupposes that <code>OptimizeMergeFilterScan()</code> has been implemented.</p><p>Then, almost every optimization rule begins with something like this:</p><div class="code-wrapper"><pre><code class="hljs cpp">std::vector&lt;AbstractPlanNodeRef&gt; children;<span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> <span class="hljs-keyword">auto</span> &amp;child : plan-&gt;<span class="hljs-built_in">GetChildren</span>()) {  children.<span class="hljs-built_in">emplace_back</span>(<span class="hljs-built_in">OptimizeSeqScanAsIndexScan</span>(child));}<span class="hljs-keyword">auto</span> optimized_plan = plan-&gt;<span class="hljs-built_in">CloneWithChildren</span>(std::<span class="hljs-built_in">move</span>(children));</code></pre></div><p>That is, first recursively optimize each child, then put the optimized children back into a new current node, and finally determine whether the current node can be optimized. For example, if the root node is a Projection with the SeqScan below it, checking only the root node would never find the SeqScan below.</p><p>The meaning of <code>CloneWithChildren()</code>: keep the current node's other information and only replace its children. It's like keeping the subtree's root node while grafting on entirely new children.</p><h4 id="So-My-SeqScan-Was-Also-Implemented-Wrong-Before">So My SeqScan Was Also Implemented Wrong Before</h4><p>Because we noticed that <code>OptimizeMergeFilterScan()</code> merges the predicate into the <code>SeqScanPlanNode</code>, but <strong>our SeqScan Executor seemingly never handled the predicate at all</strong>!</p><p>Here's the original text of the <code>3bf6908</code> commit message:</p><blockquote><p>fully refactor seq_scan_executor</p><p>SeqScanExecutor::Next() has 3 bugs.</p><ol><li>It completely fails to handle filter_predicate_: so DELETE WHERE id = 1 would delete all records it reads.</li><li>It directly returns false upon encountering a deleted Tuple: but it should skip it and continue scanning.</li><li>Each Next() returns only one Tuple: it doesn't actually read in batches according to batch_size.</li></ol><p>Mainly because I didn't understand many concepts at the very beginning, this part was completely wrong</p></blockquote><p>The first pitfall is directly related to this optimization process. <strong>The Filter node has already been merged away, so the responsibility for evaluating the condition has been handed to the SeqScan</strong>. If SeqScan doesn't handle <code>filter_predicate_</code>, it's as if the <code>WHERE</code> condition simply vanished.</p><p>Handling it like this is enough:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (plan_-&gt;filter_predicate_ != <span class="hljs-literal">nullptr</span> &amp;&amp;    !plan_-&gt;filter_predicate_-&gt;<span class="hljs-built_in">Evaluate</span>(&amp;tuple, plan_-&gt;<span class="hljs-built_in">OutputSchema</span>()).<span class="hljs-built_in">GetAs</span>&lt;<span class="hljs-type">bool</span>&gt;()) {  <span class="hljs-keyword">continue</span>;}</code></pre></div><h4 id="Parsing-the-Expression-Tree-of-the-Filter-Condition">Parsing the Expression Tree of the Filter Condition</h4><p>The key to cracking this problem is understanding what the expression tree inside <code>filter_predicate_</code> looks like. Note that this is a different thing from the execution plan tree above:</p><ul><li>The nodes in the execution plan tree are operators like SeqScan, Filter, Projection, etc.</li><li>The nodes in the expression tree are expressions like <code>LogicExpression</code>, <code>ComparisonExpression</code>, <code>ColumnValueExpression</code>, etc.</li></ul><p>For example, for <code>WHERE id = 1 OR id = 4 OR 7 = id</code>, one possible expression structure is:</p><div class="code-wrapper"><pre><code class="hljs text">        OR      /    \    OR      =   /  \    / \  =    =  7   id / \  / \id 1 id 4</code></pre></div><p>So, for the conditions specified in the spec here (conversion to IndexScan), you can understand it as:</p><ul><li>A binary tree.</li><li>Looking at each comparison condition as a whole, at the bottom they are all <code>=</code> comparisons of <code>ComparisonExpression</code>.</li><li>Above them is a bunch of possible <code>LogicExpression</code>s; as the spec says, only <code>or</code> multi-condition matching is accepted.</li><li>Below the comparison nodes are the two real kinds of leaf nodes: <strong>columns</strong> and <strong>constants</strong>.</li></ul><p>So design two handler functions: <code>handle_cmp_expr</code> handles a single comparison condition, and <code>handle_expr</code> recursively processes the whole expression tree.</p><div class="note note-info"><p>This pattern was used again later; it's very handy.</p></div><p>What <code>handle_cmp_expr</code> needs to confirm:</p><ol><li>Whether it's a <code>ComparisonExpression</code>, and the comparison type is <code>ComparisonType::Equal</code>.</li><li>Whether one side is a <code>ColumnValueExpression</code> and the other side is a <code>ConstantValueExpression</code><ul><li>The logic here is a bit annoying, because the left side could be a constant and the right side a column, so you have to go through if-else repeatedly to determine which is which. So if the first match fails, swap left and right and try again.</li></ul></li><li>For the integer indexes supported here, check that the column type is <code>INTEGER</code> and the constant is not NULL.</li></ol><p>On success, return the column index and the constant expression for the outer function to construct with; on failure, return <code>std::nullopt</code>.</p><p><code>handle_expr</code> checks whether the logic node is an OR, then recursively checks both sides:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">auto</span> handle_expr = [&amp;](<span class="hljs-keyword">auto</span> &amp;&amp;self, <span class="hljs-type">const</span> AbstractExpressionRef &amp;expr) -&gt; <span class="hljs-type">bool</span> {  <span class="hljs-keyword">if</span> (<span class="hljs-keyword">auto</span> logic_expr = <span class="hljs-built_in">dynamic_cast</span>&lt;<span class="hljs-type">const</span> LogicExpression *&gt;(expr.<span class="hljs-built_in">get</span>())) {    <span class="hljs-keyword">if</span> (logic_expr-&gt;logic_type_ != LogicType::Or) {      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;    }    <span class="hljs-keyword">return</span> <span class="hljs-built_in">self</span>(self, logic_expr-&gt;<span class="hljs-built_in">GetChildAt</span>(<span class="hljs-number">0</span>)) &amp;&amp;           <span class="hljs-built_in">self</span>(self, logic_expr-&gt;<span class="hljs-built_in">GetChildAt</span>(<span class="hljs-number">1</span>));  }  <span class="hljs-comment">// 下面调用 handle_cmp_expr，检查并收集单个比较条件。</span>  <span class="hljs-comment">// ...</span>};</code></pre></div><p>This return value determines "whether both sides can be parsed into the point-query conditions we support."</p><p>There's also a restriction: all comparisons must target the same column. <code>id = 1 OR val = 4</code> is not optimized.</p><h4 id="Deduplication-and-Index-Selection">Deduplication and Index Selection</h4><p><code>WHERE id = 1 OR id = 1</code> should only return the corresponding record once. So when collecting constants, use an <code>unordered_set&lt;int32_t&gt;</code> for deduplication, and use <code>pred_keys</code> to store the deduplicated constant expressions:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (uset.<span class="hljs-built_in">insert</span>(value).second) {  pred_keys.<span class="hljs-built_in">push_back</span>(pred_key);}</code></pre></div><div class="note note-info"><p>The <code>.second</code> in <code>insert()</code>'s return value indicates whether a new element was actually inserted this time.</p></div><p>Duplicate values are no longer added to <code>pred_keys</code>, but the whole condition is still valid; you can't return a parse failure just because of duplicates. I encountered this distinction again later with the Hash Join optimizer.</p><p>After confirming the whole expression can be handled, go look up the table's indexes in the Catalog. My implementation only selects OR conditions joined on single-column integer indexes, and requires <code>GetKeyAttrs().front()</code> to equal the column index just extracted. If not found, return the original plan; if found, construct:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">return</span> std::<span class="hljs-built_in">make_shared</span>&lt;IndexScanPlanNode&gt;(    seq_scan_plan-&gt;output_schema_, table_info-&gt;oid_, index_oid.<span class="hljs-built_in">value</span>(),    seq_scan_plan-&gt;filter_predicate_, pred_keys);</code></pre></div><p>That is, hand the output Schema, the table's OID, the index's OID, the original predicate, and the constants to query over to the IndexScan.</p><h3 id="IndexScan">IndexScan</h3><p>After finishing the optimizer above, this part actually isn't hard anymore.</p><p>There's no child executor here; the data comes from the index and the TableHeap. <strong>Note that what you find in the index is a RID, not a complete tuple</strong>; after getting the RID, you still need to go back to the table:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">auto</span> [meta, tuple] = table_info-&gt;table_-&gt;<span class="hljs-built_in">GetTuple</span>(rid);</code></pre></div><p>Then, just like SeqScan, check <code>meta.is_deleted_</code>, skip deleted records, and put valid tuples and their corresponding RIDs into the output batch.</p><h4 id="Point-Lookup-and-Ordered-Scan">Point Lookup and Ordered Scan</h4><p>The spec says two kinds of queries need to be implemented:</p><blockquote><ol><li>Point Lookup: <code>SELECT FROM &lt;table&gt; WHERE &lt;index column&gt; = &lt;val&gt;</code>. You will implement the optimizer rule to transform a <code>SeqScan</code> into an <code>IndexScan</code> in the next section.</li><li>Ordered Scan: <code>SELECT FROM &lt;table&gt; ORDER BY &lt;index column&gt;</code>. The optimizer rule to generate an <code>IndexScan</code> for queries with <code>ORDER BY</code> on an index column has been implemented for you. Your task is to handle <code>ASC</code> (or default) ordering only in <code>IndexScan</code>.</li></ol></blockquote><p>That is:</p><table><thead><tr><th>Query Type</th><th>Who Generates the IndexScan Plan</th><th>How the Executor Reads</th></tr></thead><tbody><tr><td><code>WHERE id = 1 OR id = 4</code></td><td>The <code>OptimizeSeqScanAsIndexScan()</code> implemented above</td><td>Iterate over <code>pred_keys_</code>, calling <code>ScanKey()</code> one by one</td></tr><tr><td><code>ORDER BY id ASC</code>, or ASC omitted</td><td>The existing <code>OptimizeOrderByAsIndexScan()</code></td><td>Traverse in order starting from the index's beginning iterator</td></tr></tbody></table><p>Here, <code>pred_keys_.empty()</code> distinguishes the two branches. When empty, do an ordered scan; when not empty, do point lookups. This is the convention of how these rules currently generate plans.</p><p>For point lookup, first evaluate the constant expression, then construct the key tuple using the <strong>index's key Schema</strong>:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-type">const</span> AbstractExpressionRef &amp;expr = plan_-&gt;pred_keys_[now_key_idx_];Value val = expr-&gt;<span class="hljs-built_in">Evaluate</span>(<span class="hljs-literal">nullptr</span>, <span class="hljs-built_in">Schema</span>({}));Tuple key{{val}, &amp;index_info-&gt;key_schema_};std::vector&lt;RID&gt; rids;index_info-&gt;index_-&gt;<span class="hljs-built_in">ScanKey</span>(key, &amp;rids, exec_ctx_-&gt;<span class="hljs-built_in">GetTransaction</span>());<span class="hljs-keyword">if</span> (rids.<span class="hljs-built_in">empty</span>()) {  <span class="hljs-keyword">continue</span>;}RID rid = rids.<span class="hljs-built_in">back</span>();</code></pre></div><p>What's evaluated here is a constant, so no input tuple or Schema is needed; empty arguments suffice.</p><p>When constructing the key tuple, however, you need the real <code>key_schema_</code>, for the same reason as extracting the index key during Insert earlier.</p><p>The ordered scan part is just the P2 iterator; the B+ tree is already sorted by key, so just traverse along the leaf pages.</p><p>These two branches each need to save state:</p><ul><li>The ordered scan saves <code>it_</code>, stopping at the next index entry to process when a batch is full.</li><li>The point lookup saves <code>now_key_idx_</code>, indicating which position in <code>pred_keys_</code> has been processed.</li></ul><div class="note note-info"><h4 id="LLM-The-spec-clearly-allows-the-cast-so-why-does-dynamic-cast-still-fail">[LLM] The spec clearly allows the cast, so why does <code>dynamic_cast</code> still fail?</h4><p>I also ran into a version problem here. Following the spec, I wrote:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">auto</span> tree = <span class="hljs-built_in">dynamic_cast</span>&lt;BPlusTreeIndexForTwoIntegerColumn *&gt;(    index_info-&gt;index_.<span class="hljs-built_in">get</span>());</code></pre></div><p>But the cast produced a null pointer. Here's what I asked Codex verbatim at the time:</p><blockquote><p>I don't understand the second point—doesn't the spec say this cast can be used freely?</p></blockquote><p>After investigating, I found that the local code had mixed in Spring 2026's index creation changes. Single-column integer indexes were actually created as <code>GenericKey&lt;4&gt;</code> template instantiations, while Fall 2025's <code>BPlusTreeIndexForTwoIntegerColumn</code> uses <code>GenericKey&lt;8&gt;</code>; these are different C++ types.</p><p>Although the name contains TwoIntegerColumn, it <strong>doesn't mean we're querying two integer columns</strong>; rather, it's that an 8-byte key template is fixed here. An INT column is only 4 bytes, and it can also be placed inside this 8-byte key. <code>dynamic_cast</code> won't automatically convert between two different template instantiations just because they're both called B+ trees.</p><p>In the end, I only reverted the corresponding base code and tests to Fall 2025, keeping the other implementations. The original text of the <code>b7975d8</code> commit message:</p><blockquote><p>revert(p3): restore Fall 2025 index templates and tests</p><p>This reverts commit c26d28cf07acbbdc8b5a46ae6efa1cafb4a7bed2(s26 p3: added support for composite key indexes in DDL).</p><p>Spring 2026 DDL creates <code>GenericKey&lt;4&gt;</code> indexes for single integer columns,while Fall 2025 specifies BPlusTreeIndexForTwoIntegerColumn, which uses<code>GenericKey&lt;8&gt;</code>. The mismatch makes the prescribed dynamic_cast fail.</p><p>Restore fixed 8-byte index creation for primary keys and CREATE INDEX,including the original one-or-two-column limit. Remove the Spring 2026composite-key index scan test and retain the existing Fall 2025 P3 tests.</p><p>Validation in Ubuntu with clang 15, using the current working tree:</p><ul><li>sqllogictest builds successfully.</li><li>clang-format and clang-tidy pass for bustub_ddl.cpp.</li><li>P3.01-06: 5/6 pass. P3.05 gets past the original type assertion butstill fails on index ordering after UPDATE in the executor implementation.</li></ul></blockquote><p>The 5/6 here was the intermediate result right after the revert, not the result after the later fixes. One more point: a 4-byte column doesn't mean a 4-byte index template was actually created, so you can't determine which C++ type it is just by looking at the column's size.</p></div><h2 id="Task-2">Task 2</h2><p>Task 2 includes 3 operators: Aggregation, NestedLoopJoin, and NestedIndexJoin.</p><h3 id="Aggregation">Aggregation</h3><p>The difficulty of Aggregation lies in understanding a large pile of concepts that are all coupled together, which is quite annoying. Here, let's take a single SQL query and walk through the whole process of how the input becomes the result.</p><div class="code-wrapper"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> department, <span class="hljs-built_in">COUNT</span>(<span class="hljs-operator">*</span>), <span class="hljs-built_in">SUM</span>(salary)<span class="hljs-keyword">FROM</span> employee<span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> department;</code></pre></div><p>Suppose the child executor produces <code>(CS, 5000)</code>, <code>(Math, 7000)</code>, <code>(CS, 6000)</code> in order; the final result should be two rows: CS has 2 people with a total salary of 11000, and Math has 1 person with a total salary of 7000.</p><div class="note note-primary"><p>Aggregation means <strong>one output record per group</strong>.</p></div><p>First read this diagram; it's very valuable.</p><img src="https://image.wendaining.top/20261018151622507.png" style="zoom:50%;"><div class="note note-info"><p>The prompt for this diagram was: "Referring to the diagram above that describes the logical relationships between data structures like the table heap, draw a similar-style diagram explaining the data structures and APIs related to aggregation."</p></div><h4 id="First-find-the-group-then-prepare-this-row-s-aggregate-input">First find the group, then prepare this row's aggregate input</h4><p>To complete this query, we need to maintain a headcount and a salary sum for each department.</p><p><code>SimpleAggregationHashTable</code> is internally just an <code>unordered_map</code>: the key indicates which group, and the value holds the accumulated state for that group.</p><p>Next, we need to compute the group key and the aggregate input provided by each row from every input, then update the accumulated state of the corresponding group.</p><p>Having decided to aggregate by department, first look at how the Plan describes this. It contains three groups of information:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-comment">/** The GROUP BY expressions */</span>std::vector&lt;AbstractExpressionRef&gt; group_bys_;<span class="hljs-comment">/** The aggregation expressions */</span>std::vector&lt;AbstractExpressionRef&gt; aggregates_;<span class="hljs-comment">/** The aggregation types */</span>std::vector&lt;AggregationType&gt; agg_types_;</code></pre></div><table><thead><tr><th>Method in the Plan</th><th>Content in this example</th><th>Purpose</th></tr></thead><tbody><tr><td><code>GetGroupBys()</code></td><td><code>department</code></td><td>Computes the group key, e.g. <code>[CS]</code></td></tr><tr><td><code>GetAggregates()</code></td><td>constant <code>1</code>, <code>salary</code></td><td>Computes the value each input row contributes to the aggregation, e.g. <code>[1, 5000]</code></td></tr><tr><td><code>GetAggregateTypes()</code></td><td><code>CountStarAggregate</code>, <code>SumAggregate</code></td><td>Determines how each of these two items is accumulated</td></tr></tbody></table><p><strong>The expressions <code>std::vector&lt;AbstractExpressionRef&gt; aggregates_</code> are responsible for computing this row's input values, while the aggregate types <code>std::vector&lt;AggregationType&gt; agg_types_</code> are responsible for deciding how to accumulate them</strong>.</p><p>Then the two helper functions map onto this:</p><ul><li><code>MakeAggregateKey(&amp;tuple)</code>: evaluates <code>group_bys_</code> one by one to determine which group this tuple belongs to.</li><li><code>MakeAggregateValue(&amp;tuple)</code>: evaluates <code>aggregates_</code> one by one to get this row's aggregate input.</li></ul><div class="note note-warning"><p>Note that the <code>AggregateValue</code> type can represent both <strong>the input values provided by one row</strong> and <strong>the accumulated result of a group so far</strong>.</p></div><p>With this, the hash table stores:</p><div class="code-wrapper"><pre><code class="hljs text">AggregateKey -&gt; AggregateValue[CS]         -&gt; [2, 11000][Math]       -&gt; [1, 7000]</code></pre></div><div class="note note-info"><p>If there is no GROUP BY, <code>MakeAggregateKey()</code> produces an empty group key, and all inputs go into the same group.</p><p>In other words, having no grouping columns doesn't mean there are no aggregate items.</p><p>For example, <code>select count(*) from t</code> has no <code>group by</code>.</p></div><h4 id="How-are-results-accumulated-within-the-same-group">How are results accumulated within the same group?</h4><p>The hash table provides an <code>InsertCombine()</code> method, which calls two methods we need to implement: <code>GenerateInitialAggregateValue()</code> and <code>CombineAggregateValues()</code>.</p><p>The general idea is that with the group key and this row's input values, you can call <code>InsertCombine()</code>: first find the group in the hash table; if it doesn't exist, use <code>GenerateInitialAggregateValue()</code> to create the initial value, then call <code>CombineAggregateValues()</code> to update it.</p><p>For example, CS's initial value is <code>[0, NULL]</code>. Merging the first <code>(CS, 5000)</code> gives <code>[1, 5000]</code>; merging <code>(CS, 6000)</code> then gives <code>[2, 11000]</code>. Math updates its own entry, accumulated separately from CS.</p><p><code>CombineAggregateValues()</code> updates <code>result-&gt;aggregates_[i]</code> for each aggregate item according to <code>agg_types_[i]</code>:</p><ul><li><code>COUNT(*)</code>: add one for every row, regardless of whether other columns in the row are NULL.</li><li><code>COUNT(expr)</code>: add one only if the input value is not NULL.</li><li><code>SUM</code>, <code>MIN</code>, <code>MAX</code>: skip NULLs; when the result doesn't yet have a valid value, first accept the first non-NULL input, then perform the addition or comparison.</li></ul><p>The group key may also contain NULLs; when both corresponding positions are NULL, they should be considered as belonging to the same group, so <code>AggregateKey::operator==()</code> has this special handling:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (val.<span class="hljs-built_in">IsNull</span>() &amp;&amp; other_val.<span class="hljs-built_in">IsNull</span>()) {  <span class="hljs-keyword">continue</span>;}</code></pre></div><div class="note note-info"><p>Also, here's a mistake I made at the beginning; the original text of the <code>e75f409</code> commit message:</p><blockquote><p>Fixed an error in the aggregation executor constructor</p><p>The main thing here is to clarify the difference between the plan's two <code>std::vector&lt;AbstractExpressionRef&gt;</code>:</p><ul><li><code>std::vector&lt;AbstractExpressionRef&gt; group_bys_</code> contains the group by fields; for example, if it's group by salary, then this expression is a ColumnValueExpression</li><li><code>std::vector&lt;AbstractExpressionRef&gt; aggregates_</code> contains the concrete aggregate computations, like SUM() and so on</li></ul><p>The latter is passed in here, because</p><ol><li>There may be no group by logic at all</li><li><code>SimpleAggregationHashTable</code> requires the latter, for incremental aggregation; moreover, the count of this corresponds to the number of columns to output in the Schema, so iterating over this one by one to compute is reasonable. Passing the former might give 0, and the loop wouldn't even run</li></ol></blockquote><p>The correct initialization is:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-built_in">aht_</span>(plan_-&gt;<span class="hljs-built_in">GetAggregates</span>(), plan_-&gt;<span class="hljs-built_in">GetAggregateTypes</span>())</code></pre></div><p>At the time, the first <code>SELECT COUNT(*) ...</code> returned <code>0</code>. The reason was that without GROUP BY, <code>GetGroupBys().size()</code> was 0, and my <code>CombineAggregateValues()</code> used <code>agg_exprs_.size()</code> to control the loop, so nothing was ever accumulated.</p></div><h4 id="Pipeline-Breaker">Pipeline Breaker</h4><p>Hash aggregation is a <strong>pipeline breaker</strong>: the input must be fully consumed before the final grouped results can be output; the intermediate hash table holds the accumulated state of each group.</p><p>Therefore, the build phase goes in <code>Init()</code>, and <code>Next()</code> is only responsible for fetching results.</p><p><code>Init()</code> first clears the previous hash table, initializes the child, then keeps pulling inputs:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">while</span> (child_executor_-&gt;<span class="hljs-built_in">Next</span>(    &amp;tmp_tuple_batch, &amp;tmp_rid_batch, BUSTUB_BATCH_SIZE)) {  <span class="hljs-keyword">for</span> (<span class="hljs-type">const</span> Tuple &amp;tuple : tmp_tuple_batch) {    aht_.<span class="hljs-built_in">InsertCombine</span>(        <span class="hljs-built_in">MakeAggregateKey</span>(&amp;tuple), <span class="hljs-built_in">MakeAggregateValue</span>(&amp;tuple));  }}</code></pre></div><div class="note note-warning"><p>Note an edge case; the original text of the commit message:</p><blockquote><p>Fixed an edge case</p><p>Failed test 7; took a look and it's a special case</p><p>The table is an empty table, but the input is <code>select count(*) from table</code></p><p>Because the table is empty, <code>Init()</code> inserts nothing. But actually we need to insert the initial value. Added a function to insert the initial value — even if there's nothing to do, we should still run that <code>Generate</code> once.</p><p>Worth noting is the additional condition <code>&amp;&amp; plan_-&gt;GetGroupBys().empty()</code>.</p><p>Because if we only check is_table_empty, then for SQL like this</p><div class="code-wrapper"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> v1, <span class="hljs-built_in">COUNT</span>(<span class="hljs-operator">*</span>) <span class="hljs-keyword">FROM</span> t1 <span class="hljs-keyword">GROUP</span> <span class="hljs-keyword">BY</span> v1;</code></pre></div><p>Since v1 doesn't actually appear, nothing should be output — the output should just be nothing. Without this condition, the output would be</p><div class="code-wrapper"><pre><code class="hljs 1c"><span class="hljs-literal">NULL</span> <span class="hljs-number">0</span></code></pre></div><p>which doesn't meet the requirement.</p><p>Anyway, it's a rather tricky edge case, and it involves annoying NULLs, so no need to worry too much about it.</p></blockquote><p>So the added condition is: <strong>the input is empty AND there is no GROUP BY</strong>. Without GROUP BY, the entire input forms one group; with GROUP BY, empty input produces no groups at all.</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">if</span> (is_table_empty &amp;&amp; plan_-&gt;<span class="hljs-built_in">GetGroupBys</span>().<span class="hljs-built_in">empty</span>()) {  aht_.<span class="hljs-built_in">InsertInitialValue</span>(AggregateKey{});}</code></pre></div><p>Also, this doesn't only handle a standalone <code>COUNT(*)</code>: for example, <code>SELECT COUNT(*), SUM(v1) FROM t1</code>, empty input still needs to return one row of initial values. According to this Project's initial values and the <code>p3.07</code> test, <code>COUNT(*)</code> returns 0, and the other aggregate items return <code>integer_null</code>, including <code>COUNT(v1)</code>. This is handled per the project's requirements.</p></div><p>Once the empty-input case is handled, that's mostly it; finally execute <code>aht_iterator_ = aht_.Begin()</code>.</p><h4 id="Next"><code>Next()</code></h4><p>The thing to note here is the format of the returned tuple: <strong>each time you traverse a hash table entry, create a new <code>values</code> and construct a result tuple</strong>:</p><div class="code-wrapper"><pre><code class="hljs text">A -&gt; (2, 400)    yields (A, 2, 400)B -&gt; (3, 600)    yields (B, 3, 600)</code></pre></div><p>What's generated here is an in-memory aggregation result with no corresponding TableHeap record location, so <code>rid_batch</code> gets a placeholder <code>RID{}</code>.</p><p>Also, HAVING is the job of an upper-level Filter; there's no need to implement it again inside AggregationExecutor.</p><h3 id="Nested-Loop-Join">Nested Loop Join</h3><p>So-called NLJ:</p><ul><li><p>Fix one left-table record and scan the right table from beginning to end;</p></li><li><p>Then move to the next left-table record and rescan the right table.</p></li><li><p>One left row may match multiple right rows, and every match must be output.</p><div class="note note-info"><p>Fixing either the left or the right table actually works. But fixing the right table and probing with the left table is the better choice, because it makes Left Join easier.</p></div></li></ul><p>Here the plan node provides <code>left_executor_</code> and <code>right_executor</code>, i.e., the sources for obtaining each table's tuples.</p><p>We need to support INNER JOIN and LEFT JOIN:</p><ul><li>INNER JOIN only outputs successfully matched combinations</li><li>LEFT JOIN must also keep left rows with no matches at all, filling the right-side columns with NULL</li></ul><p>Each check of a pair of left/right tuples uses <code>EvaluateJoin()</code>:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-type">const</span> Value &amp;val = filter_expr-&gt;<span class="hljs-built_in">EvaluateJoin</span>(    &amp;left_tuple, left_schema, &amp;right_tuple, right_schema);<span class="hljs-type">bool</span> has_value = !val.<span class="hljs-built_in">IsNull</span>() &amp;&amp; val.<span class="hljs-built_in">GetAs</span>&lt;<span class="hljs-type">bool</span>&gt;();</code></pre></div><p>Only a non-NULL true result is output.</p><p>If the left side has been fully scanned, no match was found, and it's a LEFT JOIN, fill the right side with NULLs according to the right table Schema's column types.</p><p>Initially, I materialized the entire right table into memory in <code>Init()</code>, and then each left row traversed this cache. But this implementation couldn't pass the tests. The original text of the <code>6c6df25</code> commit message:</p><blockquote><p>The implementation that materializes the entire right table in Init() cannot pass the tests</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-built_in">BUSTUB_ASSERT</span>(    casted_right_executor-&gt;<span class="hljs-built_in">GetInitCount</span>() + <span class="hljs-number">1</span> &gt;=        casted_left_executor-&gt;<span class="hljs-built_in">GetNextCount</span>(),    <span class="hljs-string">"nlj check failed, are you initializing the right executor every time when there is a left tuple? "</span>    <span class="hljs-string">"(off-by-one is okay)"</span>);</code></pre></div><p>It should be changed to: for each new left tuple processed, re-initialize the right table via right_executor_-&gt;Init() to rescan the right side, and in Next() read the right-side tuples in batches, rather than pre-caching everything.</p></blockquote><p>Then <code>6509c81</code> changed it to "implement partial loading of the right table", restarting the right-side scan for each new left row. The following flow needs to be followed:</p><ul><li>Take one left tuple</li><li>The right executor starts from the beginning</li><li>Read right tuples batch by batch, checking the join condition for each</li><li>When the table is exhausted, move to the next left tuple</li></ul><p>However, maintaining state here is troublesome; the state I maintained:</p><table><thead><tr><th>Member</th><th>Meaning</th></tr></thead><tbody><tr><td><code>left_tuples_</code>, <code>left_cursor_</code></td><td>The current left-table input batch, and the row currently being processed</td></tr><tr><td><code>right_tuples_</code>, <code>right_cursor_</code></td><td>The current right-table input batch, and the next position to compare</td></tr><tr><td><code>matched_</code></td><td>Whether the current left-table record ever matched during this round of right-table scanning</td></tr></tbody></table><p>Honestly, I feel this kind of trivial detail isn't very important; just have an agent or a plain chat LLM write it.</p><div class="note note-info"><p>Later, when implementing Hash Join, the same problem came up again, and it was even more complicated — maintaining variables alone was too hard. So I wrote a class to maintain this kind of state, which is much simpler. Of course, NLJ here wasn't implemented that way, probably because it wasn't hard enough yet xD</p></div><h3 id="Nested-Index-Join">Nested Index Join</h3><p>After implementing the former, it actually didn't feel that complicated anymore.</p><p>A regular NLJ takes one outer-table record and scans the entire inner table, while Nested Index Join directly uses the outer table's join key to look up the inner table's index. After finding the RID, it goes back to the table to construct the join result; for LEFT JOIN rows with no match, the right side is still filled with NULLs.</p><h2 id="Task-3">Task 3</h2><p>Implement Hash Join, Optimizing NestedLoopJoin to HashJoin.</p><p>I feel these are the two hardest problems... especially the implementation of Grace Hash Join.</p><h3 id="Hash-Join">Hash Join</h3><p>Although the task is to implement Grace Hash Join, I first implemented a version without considering Grace.</p><p>So-called Hash Join:</p><ul><li>First, based on the join predicate, compute the hash row by row<ul><li>For example, <code>table A(a, b, c), table B(e, f)</code>, and I want to <code>join A, B on A.a = B.e and A.b = B.f</code></li><li>Then I traverse table B, computing the hash of each row's combination of e and f; the value is the key, and I build a hash table mapping from key to each actual row of table B</li></ul></li><li>Then, I traverse table A row by row, computing the hash of the a and b combination; if this hash value exists in the hash table above, the join rows are found, and those rows are pulled out</li><li>The combinations of the above rows are the result</li></ul><p>This implementation isn't actually that troublesome.</p><p>First, according to:</p><blockquote><p><strong>Hint:</strong> You will need a way to hash a tuple with multiple attributes in order to construct a unique key. As a starting point, take a look at how the <code>SimpleAggregationHashTable</code> in the <code>AggregationExecutor</code> implements this functionality.</p></blockquote><p>Following this, write a hash; the key point is really writing the Key — imitate it and write a <code>HashJoinKey</code>, and the Value is just a Tuple.</p><p>Imitating it isn't troublesome; the core requirement is satisfying the hash table's required <strong>reflexivity</strong>, i.e., any key satisfies <code>k == k</code>. This really means specially handling the case where both keys are NULL — in that case <code>operator==</code> returns true, but <code>NULL = NULL</code> must not produce a JOIN result. So we also need to skip right-table rows whose join keys contain NULL during the build phase. LEFT JOIN's left-table rows must be kept; when no match is found later, a result with the right side filled with NULLs still needs to be output.</p><p>Then just write it normally; note that since Hash Join is a pipeline breaker, the entire hash table needs to be built during Init, and then you just match against the iterator.</p><p>Note that the hash table we use here is actually <code>std::unordered_multimap</code>, so one key can match multiple values. When traversing, you need to record two iterators, using <code>equal_range()</code> to get the begin and end iterators of all values for a key and traverse them.</p><div class="note note-info"><p>Although the spec says that even if the hash values are equal, you must check whether the Values are actually equal, to guard against hash collisions.</p><p>But actually, the STL requires the hashmap's key to implement <code>operator==</code>; internally it uses this operator overload to do real comparisons during lookup, thereby handling hash collisions internally, so we don't need to worry about this.</p></div><h3 id="Grace-Hash-Join">Grace Hash Join</h3><p>The previous regular Hash Join has a problem:</p><ul><li>Because table B may be very large, the hash table may not fit in memory at all</li></ul><p>The solution: partitioned hash join</p><ul><li>Set a partitioning constant, e.g., PART_COUNT = 4, effectively splitting each of the two tables into 4 parts</li><li>The partitioning principle is: at initialization, hash each of the two tables separately<ul><li>For table A, for example, hashing the first row gives 101; mod 4 gives 1, so this row's content is recorded into partition 1</li><li>Same for table B</li><li>Note that what's stored above is effectively <code>vector&lt;Row&gt;</code>, and the array's index is the partition number. Moreover, this data is stored on disk</li></ul></li><li>When traversing, go through the partitions one by one<ul><li>When traversing partition 0, first build the hash table for table B's partition 0</li><li>Then traverse all rows of table A's partition 0 and match them, just like the naive Hash Join above</li></ul></li><li>Finally, aggregate to get the result</li></ul><p>The most important point here is that <strong>both sides must use the same partitioning rule</strong>. Identical join keys produce identical hash values, so they must land in the same numbered partition. This way, processing <code>A[i]</code> and <code>B[i]</code> is enough; there's no need to look at other partitions. Of course, this is now effectively a hash with very high collision rate, so you need to check equality yourself.</p><div class="note note-info"><p>The modulo operation is the most naive, and also a rather poor, hash function</p></div><p>This way, what needs to be loaded into memory each time is smaller. After processing one partition, you can clear the hash table and continue with the next.</p><p>However, the fact that this executor is a pipeline breaker doesn't change, so we still need to compute all the hashes during Init. How do we load them? We need an <strong>Intermediate Result Page</strong>.</p><h4 id="Intermediate-Result-Page">Intermediate Result Page</h4><div class="note note-info"><p>The <code>vector&lt;Row&gt;</code> written above is just for ease of understanding; what's actually kept in memory is the page id, and the Tuples are placed in Intermediate Result Pages managed by the BufferPoolManager. Essentially, you need to (temporarily) persist the Tuples into pages.</p></div><p>First, about this <code>Intermediate Result Page</code>; the most valuable references are <code>table_page.h</code> and <code>table_page.cpp</code> — the core design is basically identical!</p><p>The spec mentions that you can go read the external merge sort section; after reading it, the most core sentence is this:</p><blockquote><p>Also, your <code>IntermediateResultPage</code> layout should be compact, i.e. as little fragmentation as possible. You should also make sure that the pages are actually deleted after the merge sort is done.</p></blockquote><p>So we need a compact implementation, meaning the previous tuple should be adjacent to the next tuple.</p><p>Referring to the source code, apart from not needing to store Meta, remove that part. The rest can be said to be exactly the same.</p><p>So designing a page really means: first make a fixed-length header storing some basic meta data, and then the dynamic part follows. At the very beginning, use a <code>char*</code> pointer to pin down the position.</p><p>Specifically here, it reuses TablePage's slotted page idea. However, intermediate results don't need <code>TupleMeta</code>, and the order of pages is managed by the outer page id array, so not even a next page id needs to be stored. In the end, only these things remain:</p><ul><li>At the beginning, <code>num_tuples_</code>, occupying 2 bytes, records how many Tuples this page has.</li><li>Following that are each Tuple's offset and size, two <code>uint16_t</code>s, 4 bytes per Tuple.</li><li>The actual Tuple data is placed from the end of the page toward the front, while the slot array at the front grows toward the back; the space between the two is the remaining space.</li></ul><p>When inserting, besides the Tuple itself, you also need to reserve space for a new slot. If the two sides collide, <code>InsertTuple()</code> returns <code>std::nullopt</code>, letting the outer executor switch to another page.</p><p>This design also satisfies the spec's requirement of supporting <code>VARCHAR</code>, obviously.</p><p>Also, regarding the <code>char*</code> mentioned above, the actual code writes <code>char page_start_[0]</code>, placed at the very beginning of the class, used to obtain the starting address of the data within the page — no pointer is actually stored in the page. This is clang's idiom, copied from the source code; I didn't really look into why it doesn't occupy space itself, but it works anyway)</p><div class="note note-info"><p>You can't stuff a <code>std::vector&lt;Tuple&gt;</code> into the page; otherwise what's stored is just an in-process pointer, and the Tuple data never gets written into the page.</p></div><h4 id="Initializing-partitions">Initializing partitions</h4><p>Then comes the core part of Grace Hash Join.</p><p>Initially I defined the constant <code>static constexpr size_t PARTITION_COUNT = 16;</code>; the value was chosen by the LLM. Later it was changed to 32, with the reason explained later.</p><p>The general purpose is that at initialization, all left and right inputs must be initialized and written to disk, and the form of persistence is through the intermediate pages just written. Manipulating pages also requires going through the context's BufferPoolManager and using some PageGuard APIs; I hadn't written it in a while and had somewhat forgotten, but the writing style is just like that anyway. The core is in the <code>initialize_partitions</code> Lambda function.</p><p>Specifically, define a data structure like this:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">using</span> Partitions = std::vector&lt;std::pair&lt;std::vector&lt;<span class="hljs-type">page_id_t</span>&gt;, std::vector&lt;<span class="hljs-type">page_id_t</span>&gt;&gt;&gt;;</code></pre></div><p>The general idea is that <code>first</code> is <code>left</code> and <code>second</code> is <code>right</code>; then for a specific <code>partition_idx</code>, which is really <code>partition_idx = std::hash&lt;bustub::HashJoinKey&gt;{}(hjk) % PARTITION_COUNT</code>, write the Tuple into a page; if the page is full, create a new page and continue writing.</p><p>So it looks like there are three layers, which is really just:</p><div class="code-wrapper"><pre><code class="hljs cpp">partitions_[分区编号].first   <span class="hljs-comment">// 这个分区的左表有哪些页</span>partitions_[分区编号].second  <span class="hljs-comment">// 这个分区的右表有哪些页</span></code></pre></div><p>Each time a Tuple is read, first compute the <code>HashJoinKey</code> using the corresponding side's key expressions from the plan, then decide the partition. Then try to write into the last page of this partition; if there's no page, or the last page can't fit it, call <code>NewPage()</code>, get a WritePageGuard, <code>Init()</code> it, and then insert.</p><p>The NULL filtering mentioned earlier also goes in this step:</p><ul><li>For INNER JOIN, rows on either side whose <strong>join keys</strong> contain NULL can be skipped;</li><li>For LEFT JOIN, only the right side's NULLs are skipped.</li></ul><div class="note note-warning"><p>Note that here you check the <strong>join keys</strong>, not any arbitrary column of the Tuple; NULLs in other columns don't affect this row's participation in the JOIN.</p></div><p>This part is fine, no big deal.</p><h4 id="Managing-traversal-with-PagesReader">Managing traversal with PagesReader</h4><p>Then, the most important thing is still <code>Next()</code>. The key is understanding the essence of Grace Hash Join. The point is that for a specific partition idx, we build (build) the right table's hash table, then use the left table to probe — remember to select the left table of the same partition — then traverse the tuples inside; for each tuple, compute its key, then find all matching right-table tuples from the hash table just built, reusing the emit logic.</p><p>But actually writing it is quite painful. Previously you only needed to manage the left table's batch and the cursor within the batch; now there's an extra layer of partitions, each partition has several pages, each page has several Tuples, and after getting a left Tuple, you still have to continue traversing all matching right Tuples. And at any time you may return because the output batch is full, and the next call must resume from the last position.</p><p>Writing this was painful for me, so I had the AI try to propose a simplified logic; unexpectedly, it proposed an intermediate-layer Class that manages reading Tuples page by page and Tuple by Tuple from a partition. This is really clever, as exquisite as the PageGuard design; learned something.</p><p>This class is <code>PagesReader</code>. The outside only needs to tell it this group of page ids, and then repeatedly call <code>Next()</code>. Implement these interfaces:</p><ul><li><code>Reset(pages)</code>: switch to a new group of pages and start reading from the beginning of this group.</li><li><code>Next()</code>: take out the next Tuple; when the current page is exhausted, move to the next page, and only return false when all pages are exhausted.</li><li><code>GetCurrentTuple()</code>: get the currently retrieved Tuple.</li><li><code>ClearCurrentTuple()</code>: when the current Tuple is done being processed, clear it, but keep the position for the next read.</li></ul><p>The purpose of the last interface is in the so-called nested fallback, i.e., when the inner side has no match and we check for left join. Because if the current left tuple has ever matched, the left join logic doesn't need to run. Executing <code>ClearCurrentTuple()</code> indicates that the current tuple has matched.</p><h4 id="Moving-from-one-partition-to-the-next">Moving from one partition to the next</h4><p>With this encapsulation, the outside only needs to consider:</p><ul><li>Whether the current left Tuple still has unmatched matches</li><li>Whether the left partition still has Tuples</li><li>Whether there is a next partition</li></ul><p>First write a <code>LoadPartition()</code>, responsible for building the hash table for the right partition of the current number, and resetting <code>left_reader_</code> to the left partition of the same number. <code>NextPartition()</code> is responsible for advancing the partition number, then calling <code>LoadPartition()</code>.</p><p>At initialization, <code>part_cursor_</code> is 0, so just calling <code>LoadPartition()</code> is enough. If <code>NextPartition()</code> is called at this point, it will first increment, directly skipping partition 0...</p><p><code>Next()</code>'s logic is written in this order:</p><ol><li>If the current left Tuple still has matches that haven't been output, i.e., <code>begin_ != end_</code>, emit one, advance <code>begin_</code>, then continue.</li><li>If there are no remaining matches, let <code>left_reader_</code> take the next left Tuple.<ul><li>If successfully retrieved, re-run <code>equal_range()</code> and save the new <code>begin_</code> and <code>end_</code>.</li><li>If nothing matched at all, and it's a LEFT JOIN, emit one result with the right side filled with NULLs.</li></ul></li><li>If the left partition is exhausted, call <code>NextPartition()</code> and continue.</li><li>Only when all partitions are processed is it truly finished.</li></ol><p>Wrap it in an outer <code>while (tuple_batch-&gt;size() &lt; batch_size &amp;&amp; part_cursor_ &lt; PARTITION_COUNT)</code>. <strong>And inside, write no loops at all — write only <code>if</code>s</strong>. This is also a lesson: with an outer loop, if the inner <code>if</code>s can let the outer loop handle the inner loop's needs, don't write loops inside.</p><p>At this point, I had painfully more or less implemented the Grace Hash Join part, but there was still one TODO left.</p><p>The missing TODO was that the right side might not fit entirely into one hash table, so it needs to be split into multiple.</p><h4 id="What-if-a-partition-still-doesn-t-fit">What if a partition still doesn't fit?</h4><p>I feel this was quite an ordeal, mentally.</p><p>We partitioned earlier, but a problem remains:</p><ul><li>The partitioning constant might be too small; after one round of partitioning, the table still doesn't fit</li><li>Or all the table's keys might be identical (e.g., the table's matching key is <code>1</code> for a million rows)</li></ul><p>The solution to the former is to partition again, recursively, and each level of partitioning uses a different hash function.</p><p>But the latter poses another problem: in the latter's case, the former would keep recursing down to one tuple per hash index, which is meaningless.</p><p>Therefore, you can set a limit of at most two or three levels of partitioning.</p><p>But how should this data structure be designed? At first I thought it was like this:</p><p>First, when traversing Tuples, keep a counter, accumulating the Tuple sizes; when about to exceed 4KB (PAGE SIZE), start splitting.</p><p>Obviously, this splitting process can be recursive. If the limit is exceeded, I keep probing one level deeper, and only after the memory-loading requirement is satisfied do I execute the Next() logic of selecting the two partitions and using the left table's tuples to probe the right table.</p><p>Then clearly, our current code organization differs too much from this idea. First, <code>left_reader_</code> is locked into reading first-level partitions; there's no such thing as second-level partitions. Also, the logic of Next and NextPartition is completely decoupled, but now they'd have to be coupled together, requiring a complete rewrite.</p><p>If a complete rewrite is needed, it would be better to just stuff the previously written LoadPartition logic back into Next, and that's the only way to do it.</p><p>But anyway, recursion can't go on forever; the depth can't be too deep. I think at most the second or third level is enough — after all, one level has a full 16 fanout, and if that doesn't work, fall back to Nested Loop Join, just a Nested Hash variant.</p><p>So the rough idea was to stuff LoadPartition() and NextPartition() entirely back into Next()'s logic, and the hash table's data structure would have to be rewritten as a recursive tree structure, wrapped in a struct providing some nicely encapsulated functions, so it's as transparent as possible to the user.</p><p>At this point, I suddenly thought of the page table and file system tree structures learned in Operating Systems.</p><p>What I was thinking at the time was: could we also split the hash value into several segments, with each segment used to select one level of partitioning? Since we only plan to do a limited number of levels, falling back when insufficient, maybe there's no need to actually maintain a recursive tree — just fix it at two levels. I think this borrowing from OS is quite clever.</p><p>Then, as I kept thinking — mainly considering that if the right side gets small partitions but the left side can't do the same, since the left side's partitions were locked in at the start —</p><p>I suddenly realized: if I only planned to split into two levels, why didn't I just partition into 256 partitions from the very beginning... Then, the later hash-table loading logic still loads as if there's only one level, and if one level fails, fall back to the nested version. I feel this layering makes no essential difference at all; it's even better and simpler.</p><p>Then I felt 256 wasn't quite right either, so it became 32. Anyway, in short, I discovered that the problem can be solved completely without layering — total overkill on my part.</p><h4 id="Nested-fallback-within-a-partition">Nested fallback within a partition</h4><p>The nested logic isn't complicated either; with PagesReader managing the tuples on both sides, it's really quite simple. It's just a naive double loop within one partition.</p><p>First, when <code>LoadPartition()</code> builds the table, maintain a <code>tuple_bytes</code>, adding each inserted tuple's <code>GetLength()</code>. If inserting the next one would exceed <code>BUSTUB_PAGE_SIZE / 2</code>, i.e., 4096 bytes, set <code>use_nested_ = true</code>, clear the partially built hash table, and exit the table-building process.</p><p>Note that this doesn't discard the right partition's remaining data. All Tuples were already written into temporary pages during <code>Init()</code>; now we're just deciding not to use this hash table that can't fit everything, and instead scanning the original right partition from the beginning.</p><div class="note note-info"><p>This counting is actually rather crude.</p></div><p>Then in <code>Next()</code>, choose between the two sets of logic based on <code>use_nested_</code>. The nested side's steps aren't complicated; just use <code>PageReader</code> well.</p><p>Finally, the temporary pages' release must also be handled. I centralized it in <code>ClearPartitions()</code>: first clear both readers' states, then traverse all partitions, <code>DeletePage()</code> the left and right page ids one by one, and finally clear the arrays.</p><h3 id="Optimizing-NestedLoopJoin-to-HashJoin">Optimizing NestedLoopJoin to HashJoin</h3><p>First is recursive analysis: if it's a <code>LogicExpression</code>, only handle the and case, then recurse on the left and right sides respectively.</p><p>The recursion's endpoint is handling <code>ComparisionExpression</code>; the left and right sides of a <code>ComparisionExpression</code> are <code>ConstantColumnExpression</code>s, and the requirement here is, for example, an Equal operator.</p><p>First, the ultimate goal is to return a HashJoinPlan; the core elements are these constructor parameters of HashJoinPlanNode:</p><ul><li><code>left</code> <code>right</code>: the plan nodes for obtaining the left and right tuples; the simplest case is a seq scan. Just pass in the left and right from the original nlj node</li><li><code>left_key_expressions</code> <code>right_key_expressions</code>. This is the more troublesome part</li><li><code>join_type</code>: also just copied from the nlj plan node</li></ul><p>Let's focus on the two <code>key_expressions</code>:</p><ul><li>Create two usets and two <code>std::vector&lt;AbstractExpressionRef&gt;</code>; the usets store <code>col_id</code>s</li><li>For the function handling <code>ComparisonExpression</code>:<ul><li>When recursing into a <code>ComparisonExpression</code>, parse out the <code>ConstantColumnExpression</code>s on both sides of this <code>ComparisonExpression</code>. If they're not, terminate and fall back to the regular case<ul><li>Also consider the possible case where the left side of the expression is a column of the right table and the right side is a column of the left table — but that's a detail, handled later</li></ul></li><li>Then return the left <code>ConstantColumnExpression</code>, the right <code>ConstantColumnExpression</code>, and both sides' <code>GetColIdx()</code></li></ul></li><li>Then, when the outer main recursive function gets the return values, process them one by one; if a col_id doesn't exist in the uset, append it to the end of those two arrays</li><li>Finally, construct the appropriate <code>key_expressions</code> and return the answer.</li></ul><p>So really, just clarifying the思路 is enough. The most valuable references are <code>nlj_as_index_join.cpp</code> and the previously self-written <code>seqscan_as_indexscan.cpp</code>; the former clarifies how this join should be written, and the latter clarifies reusing the previous recursive expression approach.</p><h2 id="Task-4">Task 4</h2><p>Need to implement External Merge Sort + Limit Executors + Window Functions.</p><p>I feel External Merge Sort is about as hard as Hash Join, whereas Window Functions are really just a comprehensive combination of previous logic — since I was more or less familiar with it all by then, writing it was actually less complicated.</p><h3 id="External-Merge-Sort">External Merge Sort</h3><p>So-called external merge sort is a merge sort that caches intermediate results.</p><p>The core elements are:</p><ul><li>Since the sort executor is a pipeline breaker, most of the logic should be implemented in Init; Next just fetches the results.</li><li>There are individual <code>MergeSortRun</code>s, whose core data structure is <code>vector&lt;page_id_t&gt; pages_</code>, storing a series of Intermediate Result Pages, in order, with the tuples sorted<ul><li>"In order" means: traversing <code>pages_</code>, the last tuple of each page and the first tuple of the next satisfy the partial order we need, and the tuples within each page also satisfy it</li><li>Therefore, there's also an iterator class for conveniently reading a run's tuples.</li></ul></li><li>In the end, a single run is obtained, and the tuples within it are sorted.</li></ul><p>So, first, according to the spec, implement the <code>TupleComparator</code> logic. This really means implementing two functions (operator overloads):</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">GenerateSortKey</span><span class="hljs-params">(<span class="hljs-type">const</span> Tuple &amp;tuple, <span class="hljs-type">const</span> std::vector&lt;OrderBy&gt; &amp;order_bys, <span class="hljs-type">const</span> Schema &amp;schema)</span> -&gt; SortKey</span>;</code></pre></div><p>and</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function"><span class="hljs-keyword">auto</span> <span class="hljs-title">TupleComparator::operator</span><span class="hljs-params">()</span><span class="hljs-params">(<span class="hljs-type">const</span> SortKey &amp;key_a, <span class="hljs-type">const</span> SortKey &amp;key_b)</span> <span class="hljs-type">const</span> -&gt; <span class="hljs-type">bool</span></span>;</code></pre></div><p>Nothing much to say about either; just get the logic control right.</p><p>Then, implement the concrete functions inside the executor.</p><h4 id="Init-and-Next">Init and Next</h4><p>Specifically, what Init should do is:</p><ul><li>Obtain all the tuples that need to be sorted via the <code>child_executor</code>'s <code>Next()</code></li><li>However, our TupleComparator actually compares <code>SortEntry = std::pair&lt;SortKey, Tuple&gt;;</code>, while <code>SortKey = std::vector&lt;Value&gt;;</code>, so no matter what, we first need to get the SortKey corresponding to a Tuple — this is where the <code>GenerateSortKey</code> function comes in. It's a bit long and ugly, but it works</li><li>Write these tuples into a series of Intermediate Result Pages, and according to the spec, only sort the tuples within a single page (ensuring this fits in memory)</li><li>At the beginning, one Page is one Run, which is also the constraint from the spec above</li></ul><p>After that, the formal merge sort process begins:</p><ul><li>First, the merge process handles k runs at a time; initially, traverse the first k of <code>std::vector&lt;MergeSortRun&gt; runs</code>.</li><li>Since it's k-way, set up a min-heap, and each time select the smallest (in the tuple comparison sense) from the current run's iterator. But again, back to the problem that the comparator can only compare <code>SortEntry</code> — you have to carry along some other inexplicable stuff, and then I realized that what actually needs to be stored here is the iterator.</li><li>Each time, take the top of the heap, pop it, insert the successor iterator of this iterator, and write a new page. The write logic can just follow the above, reusing the same tracker — when full, write a page. Here you can open an array of <code>page_id</code>s to keep track. If this iterator has been fully traversed, don't put it back into the heap.</li><li>Until the heap is empty, which means the merge is completely done. At this point, construct a new run; we can directly use the array we just recorded to construct it.</li><li>How to handle the newly obtained run? We use a <code>while(runs.size() &gt; 1)</code> approach, constructing new next_runs each time and appending to the next_runs we obtained. After finishing one round, <code>runs = std::move(next_runs)</code>, so the old runs get released on their own</li><li>However, the pages inside the released runs are no longer useful, but still need to be manually released; so I changed the run into an RAII object that automatically releases all resources upon destruction, which is very convenient. Note that the RAII object must also forbid copying, and overload the move-semantics operators and so on</li></ul><div class="note note-info"><p>About the RAII implementation here:</p><p>The key point here is that <strong>a run owns a set of temporary pages</strong>:</p><ul><li>Upon destruction, <code>Cleanup()</code> traverses these page ids and calls <code>DeletePage()</code> on each one.</li><li>Copying is forbidden. Otherwise, two runs would both hold the same set of page ids, resulting in double release at the end.</li><li>The move constructor moves <code>pages_</code> over, then uses <code>std::exchange(other.bpm_, nullptr)</code> to make the original object give up its cleanup responsibility.</li><li>The move assignment must first <code>Cleanup()</code> the pages it originally owned, then take over the new pages.</li></ul><p>This way, each round of <code>runs = std::move(next_runs)</code>, the old run's pages are automatically reclaimed; the final run is moved into the executor's member, waiting for the next Init to replace it, or for the executor's destructor, at which point it is automatically released.</p></div><p>Then the Next is extremely simple — just read all the way through the iterator.</p><h4 id="A-Few-Bugs">A Few Bugs</h4><p>I ran into a few bugs along the way.</p><ul><li>When all the data doesn't fill a page, the "can't fit any more, write a page" branch was never triggered, so there was still data in <code>to_sort</code> while <code>runs</code> was empty. So after finishing reading the input, you need to check whether there are still Tuples in <code>to_sort</code>, and call <code>flush_run()</code> one last time; inside, if the buffer is found to be empty, just return directly without creating an empty page.</li><li>Then I also fixed a bug where, after the heap was emptied, a new run was constructed while the remaining data in <code>to_sort</code> hadn't yet been written to pages. This is the same situation as above, except it happens at the end of each group's merge. The heap being empty only means the input has been fully read; it doesn't mean the output buffer is also empty. If this group's result doesn't even fill one page, a run with no pages would be constructed, and the next round would crash as soon as it's dereferenced. So in the end I split the two pieces of logic into <code>flush_page()</code> and <code>flush_run()</code>: the former is responsible for writing pages, and the initial run sorts first and then calls it; during merging the data is already sorted, so just write pages directly. Both at the end of input and at the end of each group's merge, the tail page must be flushed.</li></ul><p>One more thing to note: after creating a new page, you should first take the guard and then call <code>As&lt;&gt;</code>; otherwise the guard is a temporary object that will be destructed, and subsequent access to the page is not guaranteed to be safe.</p><div class="note note-info"><p>At the time I even asked: is this page guard thing real? I had written a lot of code like this before and it seemed fine?</p><p>For example, <code>auto page = bpm-&gt;WritePage(page_id).AsMut&lt;IntermediateResultPage&gt;();</code> — after the semicolon, the temporary guard is destructed. The <code>page</code> pointer may not become invalid immediately, but the corresponding page is no longer protected by the guard; once the frame is evicted and reused, you might later be accessing data from a different page. It only seemed fine before because this situation never came up.</p></div><h3 id="Limit">Limit</h3><p>Actually there's not much to say; let me summarize the pitfalls:</p><p>There's this edge case where the number of tuples in the table is less than the limit. For example, the table only has 10 rows, but <code>LIMIT 15</code> — after outputting 10 rows, it will still keep fetching data from the child executor.</p><p>The child executor clears <code>tuples_</code> after finishing reading, but <code>cursor_ </code> is still 10. On the next call:</p><ul><li><code>cursor_ == tuples_.size()</code>: 10 == 0, not satisfied.</li><li><code>cursor_ &lt; tuples_.size()</code>: 10 &lt; 0, not satisfied.</li><li><code>outputed_ &lt; limit</code>: 10 &lt; 15, always satisfied.</li></ul><p>So the loop keeps spinning idly.</p><p>There are two termination conditions here: either the limit has already been output, or the child has no more data.</p><h3 id="Window-Functions">Window Functions</h3><p>Before implementing window functions, I read through the spec and felt like I had a bunch of questions but remembered nothing, and the source code was just an ordinary plan and executor with nothing special about it — I didn't even know what to look at.</p><p>At the start, a few things need to be determined:</p><ul><li>If there's an order by, although you could output row by row, because of the sorting, it has to become a pipeline breaker.</li><li>If there's no order by, then although no sorting is needed, the aggregation is computed over the entire partition, which effectively makes it a pipeline breaker anyway.</li><li><code>window_func_indexes</code> is the source of the keys of <code>window_functions_</code>, corresponding to the column indices of the output Tuple. When traversing <code>columns_</code>, if this index is in <code>window_functions_</code>, you can't directly evaluate that placeholder; you have to get the result through the corresponding WindowFunction.</li></ul><p>Whether or not there's an order by actually has a huge impact on the code logic. Although the code is highly similar, there are inseparable couplings that make it hard to keep the logic clear — it's better to just write the similar code as two copies.</p><p>So split Next into two functions, using a condition to go down each path:</p><ul><li><code>NextWithOrderBy()</code>: Init sorts first, then reads in order; each row read updates the corresponding partition's state, then outputs the current window value.</li><li><code>NextWithoutOrderBy()</code>: Init computes the entire partition's aggregate value up front, and Next only reads the final aggregate value, without accumulating again.</li></ul><h4 id="Reusing-the-Sort">Reusing the Sort</h4><p>The problem states that window functions in a query share the same set of order bys, so the whole table should be sorted first and then output. Basically all the logic is identical — you can even directly copy the logic from the external merge sort executor's <code>Init()</code>, just maintaining the pages in the final run and an iterator.</p><p>If sorting is needed, you have to end up with a set of intermediate pages storing the sorted tuples; if sorting isn't needed, you still have to save the original rows and output them after the entire partition's aggregate value is computed. So the insertion process logic can be reused; the only difference is whether the tuples within a page are sorted.</p><p>So really, the sorting is basically just reused.</p><h4 id="Each-Window-Function-Each-Partition-Has-Its-Own-State">Each Window Function, Each Partition Has Its Own State</h4><p>Then, I read through the previous Aggregation-related code and conversation, and found that there, in <code>Init</code>, a <code>plan_executor_</code> only has one hash table (because a statement has only one group bys).</p><p>But here, for window functions, there should be a hash table corresponding to each entry in the window_functions hashmap.</p><p>But here the smallest unit is a window function, and a window function's type cannot be an array — it's unique.</p><p>Essentially, one <code>group_bys</code> condition (one <code>agg_key</code>) can only correspond to one <code>agg_val</code>, corresponding to a unique type. But to locate this state, you still need to know both which window function and which partition:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-keyword">using</span> PartitionHashTable = std::unordered_map&lt;AggregateKey, WindowState&gt;;std::unordered_map&lt;<span class="hljs-type">uint32_t</span>, PartitionHashTable&gt; ht_;</code></pre></div><p>In short, locating a specific WindowState depends on both the idx and the AggregateKey — you can't rely on the former alone, <strong>otherwise it's equivalent to having no partition by</strong>.</p><h4 id="RANK-and-State-Initialization">RANK and State Initialization</h4><p>I asked AI and it said to write a RankState struct.</p><p>But I wanted to reuse the previous logic, so I introduced <code>std::variant</code>: <code>using WindowState = std::variant&lt;Value, RankState&gt;;</code></p><p>Ordinary aggregations store a Value, while RANK needs to store how many rows have been read, the current rank, and the previous SortKey.</p><p>But after using <code>std::variant</code>, a lot of the previous code seemingly couldn't be reused anymore, and I didn't know what to do — for example, <code>InitVal(Value &amp;val, WindowFunctionType type)</code>; changing the function signature to WindowState didn't help either.</p><p>The solution is, well, just to use the <code>get&lt;T&gt;</code> approach.</p><p>Also, I defined InitVal() but the Init logic needs <code>wf.partition_by_</code> which couldn't be obtained, so I integrated it into the first insertion, using <code>try_emplace()</code> to confirm whether it's the first time.</p><p>One last thing to note: what's output at the end is a new Tuple — that is, the result obtained from the window function — not, like aggregation, some semantically dubious concatenation.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>CMU 15-445 Bustub Project 2 - B+Tree - Note</title>
      <link>https://blog.wendain.ing/en/posts/cmu-15-445-bustub-proj2/</link>
      <description>Brief notes on the second project of the CMU 15-445 course - B+Tree</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/bustub/">Bustub</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <pubDate>Sat, 03 Oct 2026 16:26:32 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/cmu-15-445-bustub-proj2/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p><strong>How can a single Lab be this hard...</strong></p><p>Task 2's difficulty was unbelievable — it gave me depression just writing it. As a result, I barely hand-wrote anything afterward and mostly directed the Agent (though I'd like to think I was still fairly fine-grained about it), which isn't exactly something to be proud of.</p><p>So since I finished it with only a half-understanding, this note is basically a list of the points that left an impression on me, rather than a systematic, linear walkthrough of each Task with detailed explanations of the implementations.</p><h2 id="Task-1">Task 1</h2><p>Although this is called Task 1, some concepts that absolutely need to be clarified will also be covered here.</p><h3 id="The-correspondence-between-keys-and-children-in-an-internal-page">The correspondence between keys and children in an internal page</h3><ul><li>The first key is invalid, but the first child is valid;</li><li>When searching for a key equal to a separator key, go to the <strong>right child</strong></li><li>Therefore, the <code>int KeyIndex(const KeyType&amp; key)</code> function cannot reuse the same binary search logic:<ul><li>internal page needs <code>std::upper_bound()</code> followed by -1</li><li>leaf page can directly use <code>std::lower_bound()</code></li></ul></li></ul><h3 id="Tombstones-separate-logical-deletion-from-physical-deletion">Tombstones separate "logical deletion" from "physical deletion"</h3><ul><li>Recording a deletion does not necessarily decrease <code>GetSize()</code>;</li><li>Only when the buffer is full (<code>GetTombstoneSize() == TOMBSTONE_CNT</code>) is the oldest slot cleaned up (overwritten).</li></ul><h2 id="Task-2">Task 2</h2><h3 id="The-difference-between-the-header-page-and-the-root-page">The difference between the header page and the root page</h3><p><code>header_page_id_</code> points to the page holding the tree's metadata, and the <code>root_page_id_</code> inside it is what points to the tree root.</p><ul><li>An empty tree can still have a header;</li><li>The root can also be a leaf page.</li></ul><h3 id="Init-must-be-passed-the-size-from-the-tree-configuration"><code>Init()</code> must be passed the size from the tree configuration</h3><p>The default parameters cannot be used directly; they differ depending on the node type.</p><h3 id="Using-SplitResult-to-express-the-split-result">Using <code>SplitResult</code> to express the split result</h3><p>Put the left page ID, the promoted key, and the right page ID into a single struct to reduce scattered temporary variables.</p><p><strong>The promoted key always corresponds to the right side</strong> (i.e., the indices are consistent)</p><h3 id="The-difference-between-leaf-page-splits-and-internal-page-splits">The difference between leaf page splits and internal page splits</h3><ul><li>For a leaf page, the separator key comes from the right page, and the records still <strong>remain</strong> in the leaf;</li><li>An internal page must <strong>promote</strong> the separator key to the parent, and must also correctly handle the first invalid key of the right page (i.e., <code>IsTombstone()</code></li></ul><h3 id="Internal-page-borrowing-and-merging-must-go-through-the-parent-s-separator-key">Internal page borrowing and merging must go through the parent's separator key</h3><p>Because both operations necessarily involve changes to the parent page, they are pessimistic.</p><h3 id="Incoming-tombstones-are-always-treated-as-updates-while-preserving-each-side-s-internal-order">Incoming tombstones are always treated as updates, while preserving each side's internal order</h3><p>Per the spec, the receiving page's existing pending-deletion records should be processed first, and the incoming page's pending-deletion records processed afterward.</p><p>Therefore, <code>MergeFrom(right)</code> works as follows:</p><ol><li>First compute the total number of tombstones on both pages. If it exceeds the buffer capacity, process the <strong>oldest few tombstones at the head of the receiving page's queue</strong> in advance to make room for the right page's tombstones.</li><li>Compact the receiving page's key/value arrays in one pass, build a mapping from old indices to new indices, and fix the indices of the remaining tombstones. This avoids repeatedly calling <code>EraseAt()</code> and shifting the arrays many times.</li><li>Append the right page's records, then append the markers in the right page's original tombstone queue order; uniformly add the receiving page's post-cleanup length to the indices.</li></ol><p>The final queue is "the receiving page's remaining tombstones → the incoming page's tombstones," with both sides' internal ordering preserved. <strong>You must not re-register tombstones in key order</strong>, because a key's magnitude has nothing to do with when it was deleted.</p><p>Borrowing moves only a single entry: <code>MoveEntryTo()</code> first records whether the entry is already deleted, then moves it to the receiving page; if it is a tombstone, it calls the receiving page's <code>RemoveAt()</code> to register it as the newest pending-deletion record.</p><h3 id="The-root-node-and-single-child-parent-pages-are-special-cases">The root node and single-child parent pages are special cases</h3><ul><li>The root is allowed to be below the minimum size of ordinary nodes;</li><li>The header needs updating: when a root leaf page is emptied by deletion, or when an internal root is left with only one child (upfloat).</li></ul><h2 id="Task-3">Task 3</h2><h3 id="Iterating-across-pages-is-not-just-jumping-to-the-next-page">Iterating across pages is not just jumping to the next page</h3><p>You also have to skip tombstones, empty pages, and pages whose entries have all been deleted.</p><h3 id="Adding-prev-page-id">Adding <code>prev_page_id_</code></h3><p>Maintaining it alone is fine, but horizontal scans are prone to deadlock (see the last point in Lect 10).</p><p>After adding the backward pointer, splits and merges also need to modify the successor page. For example, merging <code>L ↔ R ↔ S</code> into <code>L ↔ S</code> requires changing <code>S.prev</code> to L.</p><p>This introduces <strong>horizontal lock acquisition</strong>: one thread holds L and waits for R, while another holds R and waits for L, and they can deadlock each other. The original top-down lock acquisition order does not cover accesses between adjacent leaf pages.</p><p>The solution is no-wait: try to acquire the adjacent page's latch, and if it fails, end the current attempt. The underlying API used is:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-function">std::unique_lock&lt;std::shared_mutex&gt; <span class="hljs-title">lock</span><span class="hljs-params">(latch, std::try_to_lock)</span></span>;<span class="hljs-keyword">if</span> (!lock.<span class="hljs-built_in">owns_lock</span>()) {  <span class="hljs-comment">// 没有取得写锁，不能继续访问页面。</span>}</code></pre></div><p>The read lock corresponds to <code>std::shared_lock</code>. On success, <code>std::move()</code> this already-lock-holding object into the PageGuard — the guard must not acquire the lock a second time; on failure, undo the pin.</p><p>There is also a submission constraint: the original submission list (<code>CMakeList.txt</code>) does not include <code>TracedBufferPoolManager</code>, so you cannot rely on adding <code>TryReadPage()</code> / <code>TryWritePage()</code> to it.</p><p><strong>Therefore, leverage the <code>AccessType</code> parameter that it already forwards</strong>, and add <code>IndexNoWait</code>:</p><div class="code-wrapper"><pre><code class="hljs cpp">bpm_-&gt;<span class="hljs-built_in">ReadPage</span>(next_page_id, AccessType::IndexNoWait);</code></pre></div><p>The call still goes through TracedBPM, and read/write counts are still tracked as usual; the actual try-lock is done in the underlying BPM. This mode throws <code>PageLatchUnavailable</code> on latch conflicts, which inherits from <code>std::runtime_error</code>, and is thus a kind of <code>std::exception</code>.</p><p>The iterator's <code>++</code> and <code>--</code> handle cross-page movement this way: on failure, call <code>guard_.reset()</code>, set the current iterator to end, and then propagate the exception to the caller.</p><p>Because the guard is shared, you cannot directly <code>Drop()</code> it here, or you would release the lock that other iterator copies are still using.</p><div class="note note-primary"><p>To summarize when to use <code>AccessType::IndexNoWait</code>:</p><p><strong>When acquiring leaf locks horizontally rather than through the parent page</strong>.</p><p>Acquiring ordinary child locks downward can still wait; no-wait is used for these horizontal leaf page accesses.</p></div><h2 id="Task-4">Task 4</h2><h3 id="An-indirect-way-to-upgrade-a-read-lock-to-a-write-lock">An indirect way to upgrade a read lock to a write lock</h3><p>When reaching the leaf, keep the parent page's read lock, release the leaf page's read lock, acquire the leaf page's write lock, and finally release the parent page's read lock.</p><p>The key point is that there is no "in-place upgrade" API, and you cannot hold your own read lock while waiting for a write lock on the same page.</p><p>During the descent, alternate between <code>parent_guard</code> and <code>guard</code> to hold the parent page and the current page. After reaching the leaf:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-type">page_id_t</span> leaf_page_id = guard.<span class="hljs-built_in">GetPageId</span>();guard.<span class="hljs-built_in">Drop</span>();<span class="hljs-keyword">auto</span> leaf_guard = bpm_-&gt;<span class="hljs-built_in">WritePage</span>(leaf_page_id);parent_guard.<span class="hljs-built_in">Drop</span>();</code></pre></div><p>Although the leaf page lock is temporarily absent in between, <strong>the parent page's read lock is still held</strong>: other threads cannot acquire the parent page's write lock to modify the structural relationships here. When the root itself is a leaf page, this parent is the header.</p><p>For optimistic Remove:</p><ul><li>If the tombstone buffer still has space, the deletion does not reduce physical slots and can be handled directly;</li><li>If a physical deletion is needed, check whether the minimum size is still satisfied after the deletion.</li><li>If an underflow is possible, return <code>false</code>, release the locks, and take the pessimistic path from the root.</li></ul><h3 id="The-pessimistic-Remove-s-pop-ancestors-if-safe">The pessimistic Remove's <code>pop_ancestors_if_safe()</code></h3><p>This lambda determines: <strong>whether the current node can absorb one deletion effect coming from below, guaranteeing that the change will not propagate further to its parent page.</strong></p><p>First compute the minimum size, then check <code>GetSize() &gt; min_size</code>:</p><table><thead><tr><th>Node</th><th><code>min_size</code> used in the check</th><th>Reason</th></tr></thead><tbody><tr><td>Ordinary node</td><td><code>GetMinSize()</code></td><td>After losing one slot or child, it still must not underflow</td></tr><tr><td>Root leaf page</td><td>1</td><td>Deleting from 1 to 0 requires updating the header</td></tr><tr><td>Internal root page</td><td>2</td><td>Going from 2 children to 1 requires shrinking the root and updating the header</td></tr></tbody></table><p>Leaf pages have one extra condition: <strong>when the tombstone buffer is not full, it also counts as safe</strong>. Because this deletion only registers a tombstone and does not reduce physical slots. When there is no tombstone buffer, this special case is not taken.</p><p>If safe, first release <code>header_page_</code>, then release the ancestors from the front of <code>write_set_</code> while popping the corresponding <code>child_idx_</code>, leaving only the current node's write lock. Afterwards, continue acquiring child locks downward and perform the same check.</p><div class="note note-info"><p>So <code>write_set_</code> may only hold the latter part of the path. You can no longer use "only one guard left" to determine whether the current page is the root; instead, compare the actual page ID via <code>ctx.IsRootPage(page_id)</code>.</p></div><h3 id="Lock-acquisition-failures-that-allow-retrying-must-happen-before-modifying-the-page">Lock acquisition failures that allow retrying must happen before modifying the page</h3><p>If you execute <code>RemoveAt()</code> first and only try to lock the sibling after deleting down to an underflow, then on failure you cannot simply "start over": the key is already deleted, but the tree has not been repaired yet.</p><p>Therefore, after confirming that this deletion may cause a leaf page underflow, the pessimistic Remove first prepares the horizontal leaf page locks:</p><ol><li>Prefer the left sibling; when the current page is the leftmost child, choose the right sibling.</li><li>Use <code>IndexNoWait</code> to acquire the sibling's write lock and put it into the Context.</li><li>Then acquire the write lock of the successor page that may need modification: when merging with the left sibling, it is the current page's next page; when merging with the right sibling, it is the right sibling's next page.</li><li>Only after all succeed, execute <code>RemoveAt()</code>, then borrow or merge per the original logic.</li></ol><p>Here the <strong>successor page that might be needed for a merge</strong> is locked in advance, even if borrowing ultimately succeeds and no merge is needed.</p><p>A lock acquisition failure throws <code>PageLatchUnavailable</code>; the Context's destructor releases the locks along the path, and the outermost <code>Remove()</code> catches this specific exception and retries from the root.</p><p>Insert works the same way: when a leaf page is about to split, first try to lock the old successor, then insert and split, and only afterwards can you safely modify the old successor's <code>prev_page_id_</code>.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>CMU 15-445 Bustub Project 1 - Buffer Pool Manager - Note</title>
      <link>https://blog.wendain.ing/en/posts/cmu-15-445-bustub-proj1/</link>
      <description>A brief note on the first project of CMU 15-445 - the Buffer Pool Manager</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%95%B0%E6%8D%AE%E5%BA%93/bustub/">Bustub</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/">Databases</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <pubDate>Mon, 28 Sep 2026 01:55:35 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/cmu-15-445-bustub-proj1/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>Since there might be a chance to work on cloud database-related things, I picked up this course that I had always wanted to take but never did.</p><div class="note note-warning"><p>The difficulty feels <strong>genuinely over the top</strong>.</p></div><p>I basically completed it with AI "nudging me along" — writing it purely by hand was a bit beyond my difficulty threshold... (same as xv6). Mourning my hand-writing ability.</p><h2 id="Setting-Up-the-Environment">Setting Up the Environment</h2><p>My dev machine is Arch Linux, with system toolchain clang 22 and libstdc++ 16, while Fall 2025's BusTub uses clang 15, but AUR no longer provides it either — unless I compile one myself, but that would take too long.</p><p>In the end, I used an Ubuntu 22.04 Docker image to unify the build environment. The image installs clang, clang-format, clang-tidy 15, CMake, and BusTub's build dependencies; the repository is mounted into the container, and build artifacts go into a separate <code>build/ubuntu</code> directory.</p><p>The <code>build_support/run_in_ubuntu.sh</code> script in the repository automatically builds the image on first run. First configure the project:</p><div class="code-wrapper"><pre><code class="hljs bash">./build_support/run_in_ubuntu.sh cmake -S . -B build/ubuntu \  -DCMAKE_BUILD_TYPE=Debug \  -DCMAKE_C_COMPILER=/usr/bin/clang-15 \  -DCMAKE_CXX_COMPILER=/usr/bin/clang++-15 \  -DCLANG_FORMAT_BIN=/usr/bin/clang-format-15 \  -DCLANG_TIDY_BIN=/usr/bin/clang-tidy-15</code></pre></div><p>Debug builds enable AddressSanitizer by default. P1's public tests can be compiled and run directly inside the container:</p><div class="code-wrapper"><pre><code class="hljs bash"><span class="hljs-keyword">for</span> <span class="hljs-built_in">test</span> <span class="hljs-keyword">in</span> arc_replacer_test disk_scheduler_test page_guard_test buffer_pool_manager_test; <span class="hljs-keyword">do</span>  ./build_support/run_in_ubuntu.sh cmake --build build/ubuntu --target <span class="hljs-string">"<span class="hljs-variable">$test</span>"</span> -j 4  ./build_support/run_in_ubuntu.sh <span class="hljs-string">"./build/ubuntu/test/<span class="hljs-variable">$test</span>"</span><span class="hljs-keyword">done</span></code></pre></div><p>Before submitting, check formatting and clang-tidy:</p><div class="code-wrapper"><pre><code class="hljs bash">./build_support/run_in_ubuntu.sh cmake --build build/ubuntu --target check-format./build_support/run_in_ubuntu.sh cmake --build build/ubuntu --target check-clang-tidy-p1</code></pre></div><h2 id="Prerequisite-Knowledge-for-the-Project">Prerequisite Knowledge for the Project</h2><p>Actually not much — you just need to be clear about the relationship between "page" and "frame":</p><ul><li>A page is a page that actually exists on disk, although in an OS it's called a Block</li><li>A frame is the in-memory cache of a disk page, although in an OS this is called a page</li></ul><h2 id="Task-1">Task 1</h2><p>Task 1 is mainly about getting to the root of the eviction algorithm. To clarify the essence of ARC — the transitions among MRU, MFU, and the two Ghost lists — here's a state machine diagram:</p><pre><code class=" mermaid">stateDiagram-v2    state "未记录" as None    state "MRU" as MRU    state "MFU" as MFU    state "MRU Ghost" as MRUG    state "MFU Ghost" as MFUG    [*] --&gt; None    None --&gt; MRU: 首次访问    MRU --&gt; MFU: 再次访问    MFU --&gt; MFU: 再次访问    MRU --&gt; MRUG: Evict    MFU --&gt; MFUG: Evict    MRUG --&gt; MFU: 再次访问，增大 MRU 目标    MFUG --&gt; MFU: 再次访问，减小 MRU 目标    MRUG --&gt; None: 历史记录被裁剪    MFUG --&gt; None: 历史记录被裁剪    MRU --&gt; None: Remove    MFU --&gt; None: Remove</code></pre><p>The diagram shows which list a page is currently in. MRU and MFU record pages still in memory, while Ghost only keeps the evicted <strong>page numbers</strong>, unrelated to <strong>frames</strong>. Whether a page can be evicted at any given moment is controlled by <code>evictable_</code>.</p><p>Once that's clear, it's really just translating code.</p><p>However, understanding why it's done this way is more beneficial than simply translating natural language into code. If you truly understand ARC, the transitions among MRU, MFU, and Ghost all come naturally:</p><ul><li>Hitting an MRU Ghost means a just-evicted page was accessed again, so the MRU target size is adjusted upward;</li><li>Hitting an MFU Ghost adjusts it downward.</li><li>On eviction: if <code>|mru_| &gt;= mru_target_size_</code>, evict from <code>mru_</code> first; otherwise, evict from <code>mfu_</code> first. There are two special points in the BusTub comments:<ol><li>When <code>mru_.size() == mru_target_size_</code>, still evict from <code>mru_</code>.</li><li>If the preferred side is all <code>pinned / non-evictable</code>, try the other side. In summary, simply put: decide the preferred eviction side based on <code>mru_.size()</code> and <code>mru_targetsize</code>; if nothing is found there, check the other side; if neither has one, return.</li></ol></li></ul><p>My initial implementation used <code>std::find()</code> to search the linked list, which had poor time complexity. Later I added corresponding iterators in <code>FrameStatus</code>:</p><ul><li>When a node is placed into a list, store its iterator in that list, so it can be found directly via the map afterwards.</li><li>Map lookup is $O(1)$ on average, and the original iterator remains valid after moves.</li></ul><p>However, this only eliminates the scan for finding the node; <code>Evict()</code> may still traverse the list when looking for an evictable node. There's room for further optimization, but I didn't do it.</p><div class="note note-info"><p>Points I missed, summarized from my Q&amp;A records with the LLM</p><ul><li><code>alive_map_</code> looks up records currently in memory by <code>frame_id</code>, while <code>ghost_map_</code> looks up historical records by <code>page_id</code>, so after a Ghost hit, you can't directly move the node storing <code>page_id</code> into the MRU/MFU that stores <code>frame_id</code>.</li><li>The target position of <code>splice()</code> must also be an iterator into the target list.</li><li>The preferred list having no evictable nodes doesn't mean the other list doesn't either.</li></ul></div><h2 id="Task-2">Task 2</h2><p>As for Task 2, it's actually not hard once you understand the APIs. In other words, I think the difficulty in understanding mainly lies in unfamiliarity with the framework code and C++.</p><p>The Disk Scheduler has a worker thread responsible for processing queued requests. <code>Schedule()</code> puts a <code>DiskRequest</code> into a <code>Channel</code>, <code>StartWorkerThread()</code> picks up requests in the background, and then calls the <code>DiskManager</code>'s <code>ReadPage()</code> / <code>WritePage()</code>. For a Go programmer, <code>Channel</code> is actually quite familiar. Here, the worker thread exits by putting a <code>std::nullopt</code> into the queue; the destructor calls <code>join()</code>, and upon reading the <code>std::nullopt</code>, the thread ends.</p><p>Also worth noting are <code>std::promise&lt;bool&gt;</code> and <code>std::future&lt;bool&gt;</code>. They are used to pass a one-time processing result between threads:</p><ul><li>The thread that initiated the request calls <code>future.get()</code>, which blocks if the result isn't ready yet;</li><li>After the worker thread finishes the I/O, it notifies the requester via <code>promise.set_value(true)</code> in the request, a bit like waiting for a result using a Go Channel.</li><li>Though I think it has nothing to do with JavaScript's Promise, despite the same name.</li></ul><h2 id="Task-3">Task 3</h2><p>Task 3 gets complicated. The main issue is that the dependencies between code are too complex — you can't untangle it just by reading, and even having AI draw out the call chains doesn't help you remember them. It's better to just start writing, and then it becomes natural.</p><p>The core is PageGuard and the <code>BufferPoolManager</code>. PageGuard is the only legitimate way to access a page, encapsulating operations on the page. It was originally split into Read and Write, but I restructured it into an inheritance pattern, moving the common members and functions into an abstract base class <code>PageGuard</code>.</p><p>Another key point is that member variables need to be added, because the comments mention that a PageGuard must hold the lock at all times:</p><blockquote><p>However, the existence of any <code>ReadPageGuard</code> on a page implies that no thread can be mutating the page's data.</p></blockquote><p>So, a read Guard holds a shared lock on the page, and a write Guard holds an exclusive lock:</p><div class="code-wrapper"><pre><code class="hljs cpp"><span class="hljs-comment">// ReadPageGuard</span>std::shared_lock&lt;std::shared_mutex&gt; read_lock_{frame_-&gt;rwlatch_};<span class="hljs-comment">// WritePageGuard</span>std::unique_lock&lt;std::shared_mutex&gt; read_lock_{frame_-&gt;rwlatch_};</code></pre></div><p>Note that a PageGuard holds the page lock for the <strong>entire duration from construction to <code>Drop()</code></strong>, so <strong>no temporary locking is needed at all</strong>.</p><p>As for the <code>BufferPoolManager</code>, the most complex parts are still <code>CheckedReadPage()</code> and <code>CheckedWritePage()</code>. The comments mention three cases to consider:</p><ol><li>The page is already in <code>page_table_</code>: find the corresponding frame, no disk read needed.</li><li>The page is not in memory, but <code>free_frames_</code> has a free frame: use it to hold this page, which requires reading from disk.</li><li>No free frame: let ARC find an evictable frame; if the old page is dirty, write it back to disk first, then read in the page to be accessed; if nothing can be evicted, return <code>std::nullopt</code>.</li></ol><p>The concurrency lock control inside is also troublesome. Most notably, the increment and decrement of pin counts must be coordinated with the pool lock: when a pin count goes from 0 to 1, or from 1 to 0, the ARC's evictable state for that frame must also be updated accordingly.</p><p>Still, I think the <code>Flush</code> family of functions is the most complex, mainly because concurrent code is just too hard to write. When to lock, when not to, the relationship between the pool lock and frame locks — it's genuinely complicated.</p><p>The most notable point here is: <code>PageGuard::Flush()</code> can rely on the frame lock the Guard already holds; BPM's <code>FlushPage()</code> has no Guard, so it must first find the frame under the pool lock, temporarily pin++ and set it non-evictable, release the pool lock, then acquire the frame lock to write to disk, and finally pin-- and set evictable as needed.</p><p><code>FlushPageUnsafe()</code> is not allowed to hold the frame lock, but is allowed to use the pool lock, to maintain thread safety of <code>page_table_</code> access.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>My Misunderstanding of AgentDock</title>
      <link>https://blog.wendain.ing/en/posts/agentdock-misunderstanding/</link>
      <description>From mistaking AgentDock for an Agent Runtime to understanding the relationship between MCP, Agent, and Tool</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/Agent/">Agent</category>
      <category domain="https://blog.wendain.ing/en/tags/AI/">AI</category>
      <category domain="https://blog.wendain.ing/en/tags/MCP/">MCP</category>
      <category domain="https://blog.wendain.ing/en/tags/Agent/">Agent</category>
      <pubDate>Sun, 06 Sep 2026 17:12:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/agentdock-misunderstanding/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><blockquote><p>This article was written with the assistance of an LLM.</p></blockquote><blockquote><p>Actually, I just wanted to record a chat I had with an LLM) and, by the way, test AgentDock's capabilities by having it write a document on my local machine, proving that it's actually pretty good.</p></blockquote><p>While researching AgentDock recently, I had a misunderstanding about its positioning. At first I thought it was similar to Claude Code—a local Agent with a built-in Agent Runtime; only later did I realize that it's actually closer to an MCP Server, exposing local capabilities to existing Agents.</p><h2 id="The-Process-of-Misunderstanding">The Process of Misunderstanding</h2><h3 id="Q：">Q：</h3><p>Actually, the main thing is, I've analyzed the current AgentDock, and I think an MCP alone would be completely sufficient. I don't understand why it comes with a built-in Agent. It would be more convenient to just make it a plugin for existing Agents.</p><p>You can think of it this way: if it's used on the ChatGPT web version, then the web connector would still connect to this locally provided service, except this MCP service would call Agents like opencode or astrbot. Can you analyze the feasibility of this first?</p><h3 id="A：">A：</h3><p>There's a misunderstanding here first: AgentDock does not have a built-in Agent Runtime like Claude Code or OpenCode.</p><p>It is mainly an MCP Server, providing Tools such as Shell, File, and Git for external Agents to call.</p><hr><h3 id="Q：-2">Q：</h3><p>No, how is this AgentDock implemented then? How does it connect to the Agent through the ChatGPT web connector? I simply want to replace the Agent here with a more widely used Agent on the market instead of the one it implemented itself? Or maybe I have a misunderstanding—does AgentDock actually not have a built-in Agent like claudecode?</p><h3 id="A：-2">A：</h3><p>There is no Agent like Claude Code inside AgentDock.</p><p>The actual chain is:</p><div class="code-wrapper"><pre><code class="hljs TEXT">ChatGPT / OpenCode / Other Agents          |       MCP Client          |      AgentDock          |   Shell / File / Git</code></pre></div><p>The ChatGPT web version itself is the Agent Runtime.</p><hr><h3 id="Q：-3">Q：</h3><p>So my original idea was actually useless—they've already done it well. I initially thought it wrapped an entire Agent inside, but it actually doesn't..</p><h3 id="A：-3">A：</h3><p>Your initial misunderstanding came from the name and how it behaves.</p><p>The tools provided by AgentDock look very much like the tools built into traditional Agents, so it's easy to think it's a complete Agent.</p><p>But in reality:</p><ul><li>AgentDock: provides tools</li><li>ChatGPT / Claude Code / OpenCode: handles reasoning and calling tools</li></ul><hr><h3 id="Q：-4">Q：</h3><p>Okay, but can I understand the series of Tools provided by this MCP as also being an Agent?</p><h3 id="A：-4">A：</h3><p>Strictly speaking, no.</p><p>Tools are responsible for executing actions, while the Agent is responsible for thinking, planning, and deciding which Tool to call.</p><p>However, the collection of MCP Tools can indeed be seen as the Agent's "physical capabilities."</p><hr><h3 id="Q：-5">Q：</h3><p>I can put it this way:</p><p>For a traditional Agent, the Agent itself provides a series of tools for controlling the system (such as ClaudeCode's Readfile, Bash, Grep, etc.), while MCP only provides some external services, which also appear in the form of tools.</p><p>But AgentDock is actually an MCP that has implemented all the Tools that an Agent would originally provide, and instead it's the web version of ChatGPT that calls these very basic tools through the MCP connection—which actually makes it very much like an Agent.</p><p>So it wouldn't be wrong to say that AgentDock provides an Agent Runtime, except that the upper-level LLM is not obtained through the traditional approach of configuring an API-Key and making HTTP requests, but rather the LLM's capabilities are obtained through the connection established by MCP.</p><h3 id="A：-5">A：</h3><p>The first half is basically correct: AgentDock does indeed extract many of the system tools built into traditional Agents and provides them to Agents like ChatGPT through MCP.</p><p>But the key to an Agent Runtime is not the number of tools—it's LLM invocation, task planning, tool selection, and loop execution.</p><p>AgentDock doesn't have these, so it is not an Agent Runtime.</p><hr><h3 id="Q：-6">Q：</h3><p>The ChatGPT web version is a castrated Agent—it only runs inside the web sandbox and has no Tools for controlling a specific local computer. But AgentDock, as an MCP, implements a series of tools for controlling the local machine, thereby truly achieving a "complete form" Agent.</p><h3 id="A：-6">A：</h3><p>A more accurate statement: the ChatGPT web version is already an Agent Runtime itself; it just doesn't have the ability to access the user's local resources by default.</p><p>What AgentDock provides is "physical capabilities": tools like File, Shell, and Git.</p><p>Combined together:</p><div class="code-wrapper"><pre><code class="hljs TEXT">ChatGPT (Brain)        |       MCP        |AgentDock (Tool Layer)        |      Local System</code></pre></div><p>It's not that AgentDock implements the Agent, but rather that MCP gives the cloud Agent local capabilities.</p><hr><h2 id="Final-Understanding">Final Understanding</h2><p>Traditional model:</p><div class="code-wrapper"><pre><code class="hljs TEXT">Agent = LLM + Runtime + Tools</code></pre></div><p>MCP model:</p><div class="code-wrapper"><pre><code class="hljs TEXT">Agent = LLM + RuntimeTools = External MCP Server</code></pre></div><p>The value of AgentDock is to standardize local operation capabilities into MCP Tools, so that different Agents can reuse them.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>Building a Micro-Post Publishing Station for My Blog</title>
      <link>https://blog.wendain.ing/en/posts/moments-composer-build-log/</link>
      <description>Starting from &quot;no more hand-editing YAML,&quot; I built a private micro-post publishing station using Cloudflare Worker + R2 + GitHub API, and eventually split it into a standalone repository. More pitfalls hit than code written—here's the whole story from start to finish.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/%E5%8D%9A%E5%AE%A2/">Blog</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/AI/">AI</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%8D%9A%E5%AE%A2/">Blog</category>
      <category domain="https://blog.wendain.ing/en/tags/Cloudflare/">Cloudflare</category>
      <category domain="https://blog.wendain.ing/en/tags/GitHub-Actions/">GitHub Actions</category>
      <pubDate>Sat, 05 Sep 2026 17:58:59 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/moments-composer-build-log/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><div class="note note-primary"><p>This project was almost entirely completed by GLM 5.3 Flash, and the first draft of this article was also written by it. Although the writing has been manually polished, many parts still lack a human touch). Well, so be it. This model's capabilities are pretty trash anyway — if it weren't for the free tokens, I wouldn't use it.</p></div><h2 id="Origin-Moments-Existed-but-Publishing-Was-Too-Painful">Origin: Moments Existed, but Publishing Was Too Painful</h2><p>I previously added a moments feature to my blog — an information waterfall for quick jottings — but at the time I didn't bother with how to publish to it afterward. It remained the very primitive form of hand-editing YAML files, where even aligning the format was a bit of torture.</p><p>So the goal this time was clear: <strong>build a web-based publishing station that works on both phone and computer — write something, click publish, images automatically go to the image host, and the YAML gets committed automatically</strong>.</p><h2 id="First-Round-of-Solution-Design">First Round of Solution Design</h2><p>Plan before building. The core architecture had to fit into the blog's existing deployment workflow: the blog is purely static — push to <code>main</code> → GitHub Actions builds → <code>gh-pages</code> → served on both GitHub Pages and Cloudflare Pages.</p><p>So the essence of the publishing station could only be: collect images into the image host, commit a new record into <code>moments.yml</code>, and let the existing CI rebuild automatically.</p><p>Through Q&amp;A with the Agent, three decisions were settled:</p><ol><li><strong>Authentication</strong>: the publishing station must be usable only by me. Chose Cloudflare Access + GitHub login (Cloudflare Zero Trust, more on this later).</li><li><strong>Feature scope</strong>: publish + edit + delete, all in one go.</li><li><strong>Image host</strong>: images go directly into my existing R2 bucket <code>image.wendaining.top</code>, served publicly via its custom domain.</li></ol><p>Two implementation details as well:</p><ul><li><strong>Deferred image upload</strong>: images selected, pasted, or dragged in are only held in browser memory — you can freely add, remove, and reorder them — and they're only compressed and uploaded when you click "Publish". Abandoning midway leaves no garbage in R2.</li><li><strong>Date locking</strong>: when editing an existing moment, the date field is read-only, mainly because a single moment's permalink is bound to its date.</li></ul><h2 id="Recon-Before-Starting">Recon Before Starting</h2><p>First I took stock of what I had on hand; a few findings directly shaped what came next:</p><ul><li>The local <code>gh</code> CLI was already logged in with my account, and the token had <code>repo</code> + <code>workflow</code> permissions. This meant most GitHub-side operations (creating repos, storing secrets, pushing workflows) could be done directly by the AI on my behalf.<ul><li>Here the Agent said a Fine-Grained PAT was needed, but I found that too much hassle and said the gh cli token would do, so I just used it — though this apparently carries an expiration risk.</li><li>(Also, I honestly wasn't quite sure what this Token was for. When I asked the LLM, I got a TLDR-style answer: "Your token is essentially 'giving the AI a key to your GitHub operations'; <code>repo + workflow</code> means this key can modify code repositories and GitHub Actions, and a Fine-Grained PAT just cuts this key into finer pieces." Okay then.)</li></ul></li><li>The Agent had the official Cloudflare plugin installed, so the agent could directly operate my Cloudflare account.</li></ul><h2 id="Pitfall-One-Agent-s-Tool-List-Failed-to-Load-Dynamically">Pitfall One: Agent's Tool List Failed to Load Dynamically</h2><p>During the planning phase I asked the AI: can the Cloudflare account management MCP be used? Its judgment at the time was "my tool list only has documentation retrieval; the account management tools aren't mounted," and then it started frantically searching documentation to back up that conclusion.</p><p>This was genuinely mysterious. In principle, an Agent's Tool List is loaded dynamically as the conversation progresses, and I don't have many MCPs — loading all of them is entirely feasible. This could only be a bug. I restarted, and everything showed up.</p><h2 id="Cloudflare-One-Explained">Cloudflare One Explained</h2><div class="note note-info"><p>This explanation was written by the LLM; it's basically a translation of Cloudflare's official documentation (?), plus some analysis.</p></div><p><strong>Cloudflare One</strong> is the umbrella name for Cloudflare's enterprise security product suite — the marketing name is "Zero Trust SASE." Broken down, it's three things:</p><ul><li><strong>Zero Trust</strong>: "zero trust" is a security model — no longer assuming "things inside the intranet are trustworthy," but instead verifying identity and permissions for every access request, no matter where it comes from.</li><li><strong>Access</strong>: the most commonly used feature in the zero trust model, essentially an <strong>authentication checkpoint standing in front of your application</strong> (the technical term is Identity-Aware Proxy). Visitors are first intercepted to log in; only if their login info matches the policy are they let through to the application behind — otherwise they can't even see what your server looks like.</li><li><strong>Organization</strong>: the Zero Trust entity under your account, with a globally unique team domain (of the form <code>xxx.cloudflareaccess.com</code>); all login redirects go through this domain.</li></ul><p>For a personal blog, the free tier of this suite is more than enough. The effect: <strong>wrapping the publishing station in a shell of "only I can open it," without writing a single line of authentication code yourself</strong>.</p><p>The actual order of operations is:</p><ol><li>Click "Enable Access" in the dashboard and choose the free plan (no card required). This step automatically creates the organization and assigns a team domain — **mine was randomly generated by Cloudflare as <code>wild-rice-7d8e.cloudflareaccess.com</code>, though it can be changed later, so no big deal.</li><li><strong>Add an Identity Provider (login method)</strong>: tell Access "what to log in with." If you choose GitHub, you need to create an OAuth App on GitHub yourself (get the Client ID and Secret and fill them into Access), and set the OAuth App's callback URL to <code>https://你的团队域/cdn-cgi/access/callback</code>.</li><li><strong>Create a self-hosted Access application</strong>: declare "this domain/path is protected," and attach policies to the application.</li><li><strong>Policy</strong>: rules of the form "Allow + some condition." My configuration is an exact email match against my own GitHub primary email; there's also a <code>non_identity</code> decision type, specifically for <strong>Service Tokens</strong> — programmatic access that doesn't go through browser login, exchanging a Client ID + Secret for a JWT. The E2E tests relied entirely on this.</li></ol><h2 id="How-Workers-Bind-Resources">How Workers Bind Resources</h2><p>First, an explanation of how a Worker's JS code is generally uploaded:</p><ol><li>Upload via Wrangler</li><li>Upload via the API provided by the Cloudflare MCP</li></ol><p>Either way, it's just submitted — it's not tied to a Git repository or anything like that.</p><p>Also, a note on Cloudflare Worker <strong>bindings</strong>:</p><p>A Worker itself is a piece of JS running on Cloudflare's edge; a binding "attaches" an external resource into its runtime environment so the code can use it directly as a variable:</p><ul><li><code>r2_bucket</code> binding: in code, a single line <code>env.IMAGES.put(key, bytes)</code> writes into the R2 bucket — no S3 keys to configure, no signing.</li><li><code>secret_text</code> binding: encrypted environment variables, for storing sensitive values like GitHub tokens.</li><li><code>plain_text</code> binding: ordinary configuration (image host domain, blog address, and the like).</li></ul><p>This deployment didn't use wrangler; it went entirely through the REST API, in three steps:</p><ol><li><code>POST /accounts/{id}/workers/workers</code>: create the Worker resource (no code yet at this point).</li><li><code>POST .../workers/{id}/versions</code>: upload a version, containing the code modules (base64) and all bindings.</li><li><code>POST .../scripts/{name}/deployments</code>: point 100% of traffic to this version.</li></ol><p>One more thing: <code>PUT /accounts/{id}/workers/domains</code> binds <code>moments.wendain.ing</code> as the Worker's custom domain (DNS and certificate configured automatically); and the <code>workers.dev</code> preview entry is turned off, so the publishing station has only the one Access-protected door (moments.wendain.ing).</p><h2 id="Pitfall-Two-The-LLM-Tried-to-Base64-Encode-Directly">Pitfall Two: The LLM Tried to Base64-Encode Directly</h2><p>This one was baffling. I didn't follow the process, but after it finished I roughly understood what had happened:</p><p>As mentioned in the previous step, we need to upload JS code to the Worker via an HTTP POST request. But how does that HTTP request carry the JS file?</p><p>The reasonable approach would be to put it directly in the POST request's <code>content:</code>, but some of the Cloudflare Workers API's upload endpoints actually require the source code content to be base64-encoded. So the original JS code was base64-encoded and sent up.</p><p>But this model was absolutely unhinged — it performed the Base64 encoding using <strong>thinking</strong> rather than a <strong>tool call</strong>, and the result was a pile of garbage that kept reporting <code>malformed base64 content</code>.</p><p>The final solution:</p><ol><li><strong>Embed the original source code</strong> in the tool call (readable, inspectable — not base64 ciphertext);</li><li>Let the Cloudflare sandbox encode it to base64 on the fly during execution;</li><li>The sandbox conveniently returns the SHA-256 of each file, which is compared locally — <strong>only continue if everything matches; if not, resend the mismatched files</strong>.</li></ol><p>This "hash verification loop" saved me more than once later on. Including when rewriting the generator script, I hit another shell-escaping pitfall: writing <code>\n</code> inside bash double quotes turned into a real newline when passed to Node, breaking the generated code string outright. The fix was to write the generator itself as a file and execute it, completely bypassing shell-escaping hell.</p><h2 id="E2E-All-Green-in-One-Pass">E2E: All Green in One Pass</h2><p>After deployment, I ran a full end-to-end test: create a temporary service token → upload a 1×1 PNG → confirm it's served correctly from the image host domain → publish a test moment → edit it (confirming the ID stays the same) → delete it (confirming the R2 object is cleaned up in sync) → delete the token.</p><p>Along the way I discovered that the Cloudflare sandbox's outbound fetch has a whitelist and couldn't reach my publishing station's domain, but local <code>curl</code> went straight through — HTTP 200 — so the entire E2E was run locally.</p><h2 id="Where-Are-the-Frontend-Files-Unhinged-GLM-5-3-Flash">"Where Are the Frontend Files?" Unhinged GLM 5.3 Flash</h2><p><img src="https://image.wendaining.top/moments/2026/09/45da3bfe09c7.png" alt="662"></p><p>This was simply unhinged. After it finished running, I looked at the project and it was all JS code. I asked, got this reply, and honestly lost it.</p><p>To be lazy, the LLM had inlined the entire interface (HTML + CSS + JS) into one giant template string inside <code>src/ui.js</code>. So I had it refactor, splitting things into HTML, CSS, and JS.</p><p>Midway through the refactor, an even more insidious bug surfaced: the <strong><code>public/</code> rule in the repo root's <code>.gitignore</code></strong> (originally meant to ignore Hexo build output) was also silently ignoring <code>moments-composer/public/</code> — <code>git add</code> simply wouldn't include it, and the commit almost ended up without the frontend files. The fix was anchoring the rule to the root directory as <code>/public/</code>.</p><h2 id="Interlude-Should-It-Move-Under-the-Blog-s-Domain">Interlude: Should It Move Under the Blog's Domain?</h2><p>Along the way, another approach was discussed: drop the separate subdomain and mount the publishing station under the <code>blog.wendain.ing/moments-composer</code> path, making it look like a sub-app of the blog. The feasibility conclusion was that it's doable — Workers routes can be attached by path to a Pages custom domain, and the Worker takes precedence over static serving — but it would require reworking the Worker's path handling and rebuilding a path-level Access application. In the end I decided to <strong>shelve it</strong>: the existing separate subdomain was already working stably, and there was no need to churn things up just for aesthetics. This approach can always be done separately later.</p><h2 id="submodule-Making-the-Publishing-Station-Its-Own-Repo">submodule: Making the Publishing Station Its Own Repo</h2><p>I split <code>moments-composer/</code> out of the blog repository into a git submodule pointing to the standalone private repo <code>wendaining/moments-composer</code>. Mainly because the composer is a self-contained application, and mixing its commit history in with blog content commits is weird. Once it became its own repo, the blog repository only keeps a pointer.</p><p>A few key moves:</p><ul><li><strong><code>git subtree split -P moments-composer</code></strong>: extract the composer-related commit history from the blog repository and push it as the new repo's main — no history lost.</li><li><strong>Switch the blog side to a gitlink</strong>: <code>git rm -r</code> the old directory, <code>git submodule add</code> the new repo. The Hexo build doesn't depend on this directory at all, so the blog's CI needed zero changes.</li><li><strong>Redeploy the Worker</strong>: the repo structure changed, so the code running in production had to be aligned with the new repo. Same "embed source + sandbox encoding + SHA-256 comparison" flow as before — this time all eight files passed in one go.</li></ul><p>Pitfalls hit in this stretch:</p><ul><li><strong>Pitfall: the root <code>.gitignore</code>'s <code>public/</code> silently ignoring things</strong>. The one mentioned above — <code>git add</code> throws no error and gives no warning; the files just aren't in the commit. I only discovered this after <code>rm -rf</code>, and had to rebuild them from memory.<ul><li>Lesson: when writing ignore rules for nested directories, always anchor to the root with <code>/</code>.</li></ul></li><li><strong>Pitfall: rebase blocked by the submodule</strong>. The remote had new commits I'd pushed from another machine; during the rebase, git needed to switch <code>moments-composer/</code> from "submodule" back to "regular file directory," but was blocked by the already-populated submodule working tree, throwing a baffling "cannot detach HEAD" error. The fix was <code>git submodule deinit</code> to clear it out, then <code>--init</code> to restore after the rebase.</li><li><strong>Pitfall: detached HEAD</strong>. When <code>git submodule update --init</code> restored the submodule, it was in a detached HEAD state by convention. The two commits I made afterward all landed on the detached head, and <code>git push origin main</code> pushed the old branch — <strong>the push showed success, but in reality nothing was pushed</strong>. I only realized what happened when I noticed the remote tree had no <code>.github</code> directory at all. The fix was <code>git checkout -B main</code> to bend the branch back.</li></ul><h2 id="The-Last-Puzzle-Piece-Automatic-Submodule-Alignment">The Last Puzzle Piece: Automatic Submodule Alignment</h2><p>Submodules have a problem (maintenance cost): after the composer repo updates, the pointer in the blog doesn't move by itself — you need to manually run <code>git submodule update --remote</code> and commit again.</p><p>The first version of the plan was CI on both sides: a workflow on the blog side to check and align the pointer, and the composer side notifying it after a push. Once running, it turned out the blog-side one was redundant — and it also hit credential problems when its internal <code>git submodule update --remote</code> cloned the private sub-repo (the checkout's credential header didn't cover the submodule clone), failing repeatedly.</p><p>Following the principle of "less is more," I deleted the blog-side workflow entirely and changed the composer-side workflow to <strong>do it itself</strong>: via the Git Trees API, directly commit the blog's gitlink as the new SHA — no need to clone the blog, no need to touch the submodule. Three API calls (read the current pointer → create a new tree and commit → PATCH the ref) complete the alignment, idempotent with automatic retries on failure.</p><p>Another pitfall along the way: writing a heredoc in the workflow's YAML, the terminator <code>EOF</code> got dragged out of column zero by the YAML indentation, and the shell directly reported <code>here-document delimited by end-of-file</code>. Switching to a <code>printf | gh api --input</code> pipe approach made the problem disappear.</p><p>Tested result: push one commit to composer, and a few seconds later a <code>chore(composer): sync submodule to xxx</code> automatically appears on the blog's main — pointer synced. <strong>From now on I only need to care about the composer repo itself; the blog needs no attention at all.</strong></p><h2 id="Wrapping-Up">Wrapping Up</h2><p>The final form of this whole setup:</p><ul><li><code>moments-composer</code>: a standalone private repo — the frontend trio + five Worker backend modules + deployment scripts, with tests included.</li><li>One Cloudflare Worker in production, protected by Access (GitHub login), accepting only my GitHub email; images land in R2, served via the dedicated image host domain.</li><li>A submodule pointer in the blog, kept up to date automatically by the composer-side CI.</li><li>Not a single line changed on the Hexo side — validation, IDs, permalinks, Giscus are all the original system.</li></ul>]]>
      </content:encoded>
    </item>
    <item>
      <title>Configuring CliProxyAPI (CPA) to Reverse Proxy Gemini</title>
      <link>https://blog.wendain.ing/en/posts/using-cpa/</link>
      <description>A simple tutorial and record of setting up CPA on your own cloud server to reverse proxy Google Antigravity and obtain the Gemini API.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/LLM/">LLM</category>
      <pubDate>Fri, 04 Sep 2026 11:13:23 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/using-cpa/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>A while back while scrolling Zhihu, I saw someone say that you could reverse proxy the Gemini API through <strong>some means</strong>, and combined with the dirt-cheap Gemini Pro accounts / top-up services all over Xianyu, you could have a great time.</p><p>Then these past couple of days while idling in group chats, I saw someone mention the term <strong>CPA</strong>. I started asking GPT what it was and couldn't even get an answer xD — only by asking directly did I learn it's <strong>Cli Proxy API</strong>.</p><p>I looked it up and found it needs to be deployed on a server, so here's a simple tutorial.</p><h2 id="Installing-on-the-Server">Installing on the Server</h2><p>CPA's official documentation is written <strong>extremely badly</strong> (<strong>not fit for human consumption</strong>), so it's best to just let an Agent do the work.</p><p>I threw this Prompt straight at the Agent:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 976 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">Requirements: Install according to the current official documentation (h...</span></summary><blockquote><p>Requirements:</p><ul><li>Install according to the current official documentation (<a href="https://help.router-for.me/cn/introduction/quick-start.html">https://help.router-for.me/cn/introduction/quick-start.html</a>), preferring the official Linux one-click install script (<code>curl -fsSL https://raw.githubusercontent.com/router-for-me/cliproxyapi-installer/refs/heads/master/cliproxyapi-installer| bash</code>).</li><li>Configure it as a systemd service with auto-start on boot.</li><li>CPA should listen on <code>127.0.0.1:8317</code>; do not expose it directly to the public internet.</li><li>The configuration files and OAuth credentials must be persisted.</li><li>First help me set up Gemini CLI / Google OAuth login.</li><li>After OAuth is complete, verify CPA works properly using <code>/v1/models</code> and an actual Gemini request.</li><li>Do not install New API, Sub2API, or other unrelated components.</li><li>Do not break any existing services on the server.</li></ul><p>Before executing, first check the system, any existing CPA installation, port 8317, and the systemd status. Stop and tell me when you need me to open the OAuth link and take action.</p></blockquote></details><p>Then just wait.)</p><div class="note note-warning"><p>Note that I'm using a Linux system here. Users of other systems should consult the documentation to adjust the installation method.)</p><p>(Though if you're already running a server, does anyone actually use Windows Server?)</p></div><h2 id="Accessing-the-WebUI">Accessing the WebUI</h2><p>You can access CPA's WebUI at <a href="http://127.0.0.1:8317/management.html">http://127.0.0.1:8317/management.html</a>, but first we need to configure a password:</p><p>Open an editor and edit the <code>~/cliproxyapi/config.yaml</code> file, and find this section:</p><div class="code-wrapper"><pre><code class="hljs yaml"><span class="hljs-attr">remote-management:</span>  <span class="hljs-attr">allow-remote:</span> <span class="hljs-literal">false</span>  <span class="hljs-attr">secret-key:</span> <span class="hljs-string">"这里填刚生成的密钥"</span>  <span class="hljs-attr">disable-control-panel:</span> <span class="hljs-literal">false</span></code></pre></div><p>Then, set up an SSH tunnel:</p><div class="code-wrapper"><pre><code class="hljs sh">ssh -N -L 8317:127.0.0.1:8317 tencent-lighthouse</code></pre></div><p>Now you can access it from your local browser.</p><h2 id="Setting-Up-OAuth">Setting Up OAuth</h2><p><img src="https://image.wendaining.top/0x0sd02mm.png" alt="673"></p><p>Configure the login here and just follow the subsequent instructions.</p><p>—That's how it should have gone, but I ran into a problem, because I forgot to set up a proxy on my server.)</p><p>So I opened a new session, installed the Mihomo core along with its WebUI (MetacubeX), and configured the network proxy (it's not recommended to enable the system proxy or TUN on a server, as it may affect SSH performance):</p><p><img src="https://image.wendaining.top/20260904_193809.png" alt="638"></p><p>Just enter it here; <code>7890</code> is the Mihomo core's port.</p><p>Then the configuration went through fine.</p><h2 id="Using-the-API">Using the API</h2><p>After importing the authentication file, you can use the API — the key is the one in the bottom half of the previous screenshot.</p><p>But here CPA's terrible documentation strikes again: no matter how I looked, I couldn't find what the URL was supposed to be — is this OpenAI's or A\ 's?</p><p>I asked an LLM and got the answer, though who knows why, but it works anyway:</p><div class="code-wrapper"><pre><code class="hljs text">Provider: OpenAI / OpenAI CompatibleBase URL: http://127.0.0.1:8317/v1API Key: "YOUR API KEY"</code></pre></div><p>It provides a Model List, which is all the currently available models. Anyway, it's usable now.</p><p>Honestly, it's a bit crude — there's no way to do "restrict the model list for a specific key". The solution is to put an API gateway in front of it, such as new-api.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>First Experience with Arch Linux!</title>
      <link>https://blog.wendain.ing/en/posts/first-experience-of-arch-linux/</link>
      <description>Installed Arch Linux and configured it — my first attempt, and I gained a lot of interesting experience!</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/Linux/">Linux</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/Linux/">Linux</category>
      <category domain="https://blog.wendain.ing/en/tags/Arch-Linux/">Arch Linux</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%98%E8%85%BE/">Tinkering</category>
      <pubDate>Mon, 31 Aug 2026 14:30:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/first-experience-of-arch-linux/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>Installed and configured Arch Linux — my first attempt, and I picked up a lot of interesting experience along the way!</p><h2 id="Installation">Installation</h2><div class="note note-primary"><p>Here's how this article was written: I took the chat history between my phone and GPT from when I was installing the system (which contains lots of images), converted that conversation into a Work conversation in Codex, had it read the content, summarize it, and write an article, and then I polished it afterward.</p><img title="" src="https://image.wendaining.top/1788194241828.png" alt="" width="463"></div><h3 id="A-Second-hand-SSD">A Second-hand SSD</h3><p>Long story short, I wanted to set up a dual-boot system on my computer. After a quick check of my machine's specs, I went to Xianyu (a second-hand marketplace) and picked up a used AirDisk 512GB SSD — as it happened, my computer still had a spare M.2 slot.</p><p>The original Kingston 1TB drive holds the Windows 11 I use every day; this AirDisk came with a complete Windows installation left behind by its previous owner — EFI, system, data, and recovery partitions all included. Since there was nothing on it worth keeping, I could wipe the whole thing.</p><p>In short, my goal was to isolate the two systems as much as possible. More specifically, what I wanted was:</p><ul><li>Kingston keeps its own EFI and Windows Boot Manager, and remains the default boot drive;</li><li>AirDisk gets a new EFI of its own, holding only Arch and its bootloader;</li><li>Normally, pressing nothing at boot goes into Windows; only when I want Arch do I manually select AirDisk;</li><li>If either drive is unplugged, the other should ideally still be able to boot on its own.</li></ul><p>At first I thought I could achieve "the two drives being invisible to each other," but I later found that this simply isn't possible when both NVMe drives are plugged in. Linux's <code>lsblk</code> will still see the Kingston, and Windows' Disk Management will see the Linux drive. The isolation that's actually achievable is: not sharing the EFI, not auto-mounting each other's partitions, and not letting one side's boot depend on the other drive.</p><div class="note note-info"><p>The EFI System Partition is usually abbreviated as ESP. It's typically a small FAT32 partition containing the .efi boot programs that the motherboard's UEFI executes. The operating system itself does not live here. With each SSD having its own ESP, each can keep its own boot chain.</p></div><h3 id="Entering-the-Live-Environment">Entering the Live Environment</h3><p>I had already prepared the Arch installation USB drive using Rufus in DD mode. Shut down, plugged in the drive, and mashed F7 to get into this screen:</p><img src="https://image.wendaining.top/1788192477053.png" title="" alt="" width="358"><div class="note note-info"><p>The photo came out pretty blurry, but there are plenty more like it later on.</p></div><p>Selecting the first option: <strong>Arch Linux Install Medium (x86_64, UEFI)</strong>. After booting from the USB drive, once you see <code>root@archiso</code>, you've officially entered Arch's Live environment.</p><img title="" src="https://image.wendaining.top/06-arch-live.webp" alt="root@archiso after entering the Arch Live environment" width="395"><div class="note note-info"><p>The Live environment can be understood as "a temporary Arch running from the USB drive." At this point, the actually installed system isn't running yet; partitioning, formatting, mounting, and even the later GRUB repair are all done using this temporary system. As long as you don't format anything, the installation USB can also serve perfectly well as a rescue drive.</p></div><p>First, confirm which drive you're actually going to operate on. At the time, what I checked first was:</p><div class="code-wrapper"><pre><code class="hljs bash">lsblk -d -o NAME,SIZE,MODEL,SERIAL</code></pre></div><p>The first time I entered the Live environment, the result was roughly:</p><div class="code-wrapper"><pre><code class="hljs text">nvme0n1  476.9G  AirDisk 512GB SSDnvme1n1  953.9G  KINGSTON OM8PGP41024N-A0</code></pre></div><p>So in this round, the drive slated to be wiped was <code>/dev/nvme0n1</code>. After entering <code>cfdisk</code>, I deleted all five of AirDisk's original partitions and created just two new ones: a 1 GiB EFI System Partition, and a Linux filesystem taking up the remaining space.</p><img src="https://image.wendaining.top/01-airdisk-old-partitions.webp" title="" alt="The five original Windows partitions of the AirDisk shown in cfdisk" width="410"><img src="https://image.wendaining.top/02-lsblk-partitioned.webp" title="" alt="Verifying both SSDs with lsblk after repartitioning" width="408"><div class="note note-success"><p>Never identify a drive by "it was Disk 0 in Windows" or "last time it was called <code>nvme0n1</code>." What's truly reliable is the model, capacity, and serial number. Especially before commands like <code>cfdisk</code> and <code>mkfs</code>, you can never double-check too many times.</p></div><h3 id="Tearing-It-Down-and-Switching-to-Btrfs">Tearing It Down and Switching to Btrfs</h3><p>After partitioning, I quite naturally formatted the large partition as ext4 at first, and mounted the root partition and AirDisk's own EFI at <code>/mnt</code> and <code>/mnt/boot</code> respectively. There was actually <strong>nothing wrong</strong> with this setup.</p><img src="https://image.wendaining.top/03-ext4-mounted.webp" title="" alt="First time completing ext4 formatting and mounting" width="460"><p>Then I looked back and saw that the tutorial I planned to follow used Btrfs throughout, and even created subvolumes. Since I was just getting started, I couldn't be bothered to keep translating the tutorial's paths into ext4 equivalents later on, so I simply unmounted the partitions, deleted the freshly formatted ext4 once more via <code>cfdisk</code>, and started over.</p><p>In the end, AirDisk's main body is still just a single Btrfs partition, but with two subvolumes inside it:</p><div class="code-wrapper"><pre><code class="hljs text">@      → /@home  → /home</code></pre></div><p>The EFI is mounted separately at <code>/efi</code>. These subvolumes look like partitions, but they actually still belong to the same Btrfs filesystem; the benefit is greater flexibility later on when taking snapshots, rolling back, or managing the root and home directories separately.</p><img src="https://image.wendaining.top/09-btrfs-subvolumes.webp" title="" alt="Re-confirming the Btrfs @ and @home subvolumes during rescue" width="452"><div class="note note-info"><p>"Mounting" doesn't mean copying files into some folder; it means attaching a filesystem onto Linux's directory tree. For example, mounting <code>@</code> at <code>/mnt</code> means that what you see below <code>/mnt</code> comes from that subvolume; mounting the ESP at <code>/mnt/efi</code> means that boot files written to <code>/efi</code> afterward will actually land on AirDisk's EFI partition.</p></div><p>For the kernel I chose <code>linux-zen</code>, but I also installed an LTS version, so at the GRUB menu you can choose which one to boot.</p><p>The rest of the process isn't worth recounting in much detail — ArchWiki covers it all: following the tutorial, I completed the configuration of base packages, networking, users, the desktop, and GRUB. The part that truly took the longest to wrestle with came after the first reboot.</p><h3 id="After-the-Reboot-Only-Windows-in-the-BIOS">After the Reboot, Only Windows in the BIOS</h3><p>Finished the tutorial, typed <code>reboot</code>. I originally expected to see GRUB next, so I mashed F7 at boot — but nothing happened, and the machine went straight into Windows.</p><p>Left with no choice, I pressed F2 to enter the BIOS, and under <code>Boot Option</code> there was still only the Windows Boot Manager on the Kingston.</p><img src="https://image.wendaining.top/04-bios-boot-priorities.webp" title="" alt="The BIOS Boot Option page" width="442"><img src="https://image.wendaining.top/05-bios-only-windows.webp" title="" alt="Only Kingston's Windows Boot Manager appears in the hard drive boot entries" width="443"><p>My first reaction, of course, was: did GRUB simply not get installed?</p><p>Fortunately, no reinstall was needed here. I plugged the installation USB back in and entered the Arch Live environment again — it went from being an installation medium to a rescue environment. All that remained was to remount the system already installed on AirDisk to <code>/mnt</code>, then go in and check the bootloader.</p><img src="https://image.wendaining.top/07-rescue-first-check.webp" title="" alt="After re-entering the Live environment, first confirm UEFI and the file system" width="451"><h3 id="The-NVMe-Numbering-Problem">The NVMe Numbering Problem</h3><p>As it turned out, the truly dangerous thing happened first: during the first installation, AirDisk was clearly <code>/dev/nvme0n1</code>, but after this reboot, the numbering of the two NVMe drives had actually swapped:</p><div class="code-wrapper"><pre><code class="hljs text">/dev/nvme0n1  → Kingston 953.9G/dev/nvme1n1  → AirDisk 476.9G</code></pre></div><img src="https://image.wendaining.top/08-nvme-reordered.webp" title="" alt="Re-checking the model, serial number, and partitions during the rescue phase" width="446"><p>Thankfully I double-checked the models once more before continuing; otherwise, following the old records to mount — or even format — <code>/dev/nvme0n1</code> would have been a disaster.</p><p>This time, AirDisk's actual layout was:</p><div class="code-wrapper"><pre><code class="hljs text">/dev/nvme1n1p1  FAT32  → /mnt/efi/dev/nvme1n1p2  Btrfs  ├─ @                 → /mnt  └─ @home             → /mnt/home</code></pre></div><p>So the core process of remounting was roughly:</p><div class="code-wrapper"><pre><code class="hljs bash">mount -o subvol=@ /dev/nvme1n1p2 /mnt<span class="hljs-built_in">mkdir</span> -p /mnt/home /mnt/efimount -o subvol=@home /dev/nvme1n1p2 /mnt/homemount /dev/nvme1n1p1 /mnt/efi</code></pre></div><img src="https://image.wendaining.top/10-fstab-mounts.webp" title="" alt="The root, home, and EFI mount relationships in the original system's fstab" width="484"><p>After confirming that <code>/mnt</code>, <code>/mnt/home</code>, and <code>/mnt/efi</code> all pointed to AirDisk, I used <code>arch-chroot /mnt</code> to enter the already-installed Arch on the hard drive.</p><p>It's a bit like "shuttling" from the Live environment into the original system: the current display doesn't change, but the root directory, software, and configuration have all switched over to the set on AirDisk.</p><h3 id="So-eris-Was-There-All-Along">So <code>eris</code> Was There All Along</h3><p>After remounting, I checked <code>/efi/EFI</code>, and it actually already contained:</p><div class="code-wrapper"><pre><code class="hljs text">/efi/EFI/eris/grubx64.efi</code></pre></div><p>And <code>efibootmgr -v</code> also showed a UEFI boot entry named <code>eris</code>, pointing precisely to AirDisk's EFI partition. <code>eris</code> is the name I gave the bootloader when installing GRUB — actually, the tutorial named it that, so I just followed along.</p><img src="https://image.wendaining.top/11-eris-efibootmgr.webp" title="" alt="eris's grubx64.efi, efibootmgr entries, and linux-zen kernel files" width="441"><p>In other words, Arch wasn't broken, GRUB's <code>.efi</code> file existed, and even the boot record in the motherboard's NVRAM had been registered successfully. The only problem was that this motherboard's BIOS setup page wasn't displaying it properly.</p><h3 id="Adding-a-UEFI-Fallback">Adding a UEFI Fallback</h3><p>Later I recalled that the tutorial mentioned some motherboards don't handle custom paths like <code>EFI/eris/grubx64.efi</code> very well, but will actively look for the standard fallback path defined by the UEFI convention:</p><div class="code-wrapper"><pre><code class="hljs text">EFI/BOOT/BOOTX64.EFI</code></pre></div><p>So instead of reinstalling the system, I simply performed an additional <code>--removable</code> installation of the existing GRUB inside the chroot:</p><div class="code-wrapper"><pre><code class="hljs bash">grub-install \  --target=x86_64-efi \  --efi-directory=/efi \  --boot-directory=/boot \  --removable \  --no-nvram \  --recheck</code></pre></div><p>After that, AirDisk's ESP had two entries at the same time:</p><div class="code-wrapper"><pre><code class="hljs text">EFI/eris/grubx64.efiEFI/BOOT/BOOTX64.EFI</code></pre></div><div class="note note-info"><p>The name <code>--removable</code> is a bit misleading — it doesn't require the drive to actually be a removable device. The most important effect here is writing the bootloader to the standard <code>EFI/BOOT/BOOTX64.EFI</code>. Even if the motherboard loses the NVRAM entry named <code>eris</code>, as long as it's willing to scan the fallback path, AirDisk still has a chance to boot on its own.</p></div><h3 id="Pressed-the-Wrong-Key">Pressed the Wrong Key</h3><p>After finishing the fallback, checking the files, and regenerating <code>grub.cfg</code>, I shut down and unplugged the USB drive. I had been mashing F7 the whole time, but could never bring up the one-time boot menu. After some searching, I discovered that the Boot Menu on the Mechrevo Yilong 15 Pro is actually F10.</p><p>So I rebooted, mashed F10, and it worked on the first try.</p><img src="https://image.wendaining.top/12-f10-boot-menu.webp" title="" alt="Windows, eris, and UEFI OS in the F10 one-time boot menu" width="392"><p>The menu finally showed all of these at once:</p><div class="code-wrapper"><pre><code class="hljs text">Windows Boot Manager (KINGSTON...)eris (AirDisk 512GB SSD)UEFI OS (AirDisk 512GB SSD)Enter Setup</code></pre></div><p>Both <code>eris</code> and <code>UEFI OS</code> ultimately lead to the GRUB on AirDisk, but their entry points are different:</p><ul><li><code>eris</code> comes from that custom boot record in the motherboard's NVRAM, pointing to <code>EFI/eris/grubx64.efi</code>;</li><li><code>UEFI OS</code> is the name the motherboard gives after scanning the standard fallback file, pointing to <code>EFI/BOOT/BOOTX64.EFI</code>;</li><li><code>Enter Setup</code> just returns to the BIOS setup screen.</li></ul><p>So the way I use it now finally matches my original plan: normally, pressing nothing at boot goes into Windows from the Kingston; when I want Arch, I press F10 at boot and select <code>eris</code>. <code>UEFI OS</code> serves as a backup entry.</p><h3 id="Windows-Inside-GRUB">Windows Inside GRUB</h3><p>After successfully entering GRUB, besides Arch Linux, there was an extra entry: <code>Windows Boot Manager (on /dev/nvme0n1p1)</code>.</p><img src="https://image.wendaining.top/13-grub-windows.webp" title="" alt="os-prober made Windows Boot Manager appear in the GRUB menu" width="482"><p>This is because <code>os-prober</code> was enabled during installation. It scans for operating systems on other disks, and when <code>grub-mkconfig</code> is executed, it writes the results into <code>/boot/grub/grub.cfg</code>. Therefore, GRUB on AirDisk can also chainload to the Windows Boot Manager on the Kingston.</p><p>This <strong>does not mean it modified Windows' EFI</strong> — it just lets GRUB know "there's another Windows next door" and adds an entry to its own menu.</p><p>In terms of boot independence, Windows can still boot directly without going through AirDisk, and Arch has its own ESP; <code>os-prober</code> is merely a menu-level cross-reference and doesn't break this structure.</p><p>At this point, the truly troublesome part of this installation was finally over. Looking back, Arch itself wasn't nearly as mystical as the legends make it out to be — what was most nerve-wracking were actually those details in multi-SSD scenarios that tutorials tend to gloss over: device names can change, mount points determine which drive files actually get written to, the existence of an EFI file doesn't mean the BIOS is willing to show it, and even the key for the motherboard's boot menu might need to be looked up first.</p><img src="https://image.wendaining.top/1788194052401.png" title="fastfetch" alt="fastfetch" width="493"><h3 id="Shortcuts-for-the-Installation-Part">Shortcuts for the Installation Part</h3><p>Honestly, the manual installation was just me wanting to <s>torture</s> tinker with myself. If you want to install Arch Linux the easy way, there are two options:</p><ol><li><p>After entering the live environment, type the <code>archinstall</code> command, and you can complete the entire installation through a hand-holding TUI guide.</p></li><li><p>After entering the live environment, connect to the network first, and once online, directly install an opencode (via a shell script) and let it do the installation.</p><div class="note note-info"><p>At first I thought that a bare-bones Arch Linux with nothing installed couldn't do anything at all — I never expected it could actually run a Coding Agent...</p></div><div class="note note-warning"><p>The only thing to watch out for is the disk issue — <strong>absolutely do not format the wrong drive; double- and triple-check this part</strong>. I don't think anything else is a problem; if you mess up, just redo the live environment.</p></div></li></ol>]]>
      </content:encoded>
    </item>
    <item>
      <title>About My Windows 11 System Modifications and Optimizations</title>
      <link>https://blog.wendain.ing/en/posts/windows-11-tweaks/</link>
      <description>As someone who has always enjoyed tinkering with odd things, I'm writing a blog post to share how I modified and optimized my computer.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <pubDate>Wed, 26 Aug 2026 11:09:57 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/windows-11-tweaks/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Preface">Preface</h2><p>As someone who has always enjoyed tinkering with all sorts of odd things, I'm writing a blog post to share how I've modified and optimized my own computer.</p><p>Perhaps this can count as a software recommendation post.</p><p>This post mainly focuses on the Windows 11 system, with a little bit of WSL thrown in—let's just count that as part of it.</p><h2 id="Desktop-Windows-Panel">Desktop + Windows Panel</h2><img src="https://image.wendaining.top/image-20260826191333471.png" alt="Nothing here" style="zoom:67%;"><p>As shown in the image, there is nothing at all. The method is "Right-click on desktop - View - Show desktop icons (off)"</p><ul><li>The way I open any app is by pressing the Windows key, typing to search, and then pressing Enter.</li><li>The way I open specific files is by using <code>Windows + E</code> to open File Explorer and find them directly. Since my file management habits are fairly good, it's not troublesome—everything is placed in specific folders.</li></ul><p>As for managing the Windows panel, I've always found the built-in Windows 11 panel ugly:</p><img src="https://image.wendaining.top/image-20260826191627469.png" style="zoom:50%;"><p>So, I installed a piece of software called <strong>Start11</strong>, which can transform this default interface:</p><img src="https://image.wendaining.top/image-20260826191713198.png" style="zoom:50%;"><p>There are plenty of customizable options, which I'll leave for readers to explore on their own. In any case, here's my result:</p><img src="https://image.wendaining.top/image-20260826191748055.png" alt="Windows 10 style" style="zoom:50%;"><div class="note note-info"><p>Here's a quick look at what the other modes look like:</p><img src="https://image.wendaining.top/image-20260826191835947.png" alt="Windows launcher style" style="zoom:33%;"><img src="https://image.wendaining.top/image-20260826191906942.png" alt="Windows app style" style="zoom:33%;"></div><h2 id="Terminal">Terminal</h2><p>Powershell 7 + Oh-My-Posh</p><img src="https://image.wendaining.top/image-20260826192039655.png" style="zoom:50%;"><p>The terminal emulator's color scheme is as follows:</p><img src="https://image.wendaining.top/image-20260826192111580.png" style="zoom:50%;"><p>As for WSL: I use Ubuntu, zsh, and Oh-My-Zsh</p><ul><li>Terminal multiplexing with zellij</li><li>File viewing with Yazi</li><li>Using <code>eza</code> instead of <code>ls</code></li><li>Using <code>z</code> instead of <code>cd</code></li><li>Using <code>fd</code> instead of <code>find</code></li><li>Using <code>rg</code> instead of <code>grep</code></li></ul>]]>
      </content:encoded>
    </item>
    <item>
      <title>A New Entry Point for the Blog: Cloudflare Pages Main Site and GitHub Pages Mirror</title>
      <link>https://blog.wendain.ing/en/posts/blog-migration-to-cloudflare-pages/</link>
      <description>Migrate the blog's official entry point to Cloudflare Pages while keeping GitHub Pages as an independent mirror; the existing Blog-Source and GitHub Actions publishing workflow remain in use.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/%E5%8D%9A%E5%AE%A2/">Blog</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%8D%9A%E5%AE%A2/">Blog</category>
      <category domain="https://blog.wendain.ing/en/tags/Cloudflare/">Cloudflare</category>
      <category domain="https://blog.wendain.ing/en/tags/GitHub-Actions/">GitHub Actions</category>
      <pubDate>Sat, 22 Aug 2026 09:43:01 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/blog-migration-to-cloudflare-pages/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="TL-DR">TL;DR</h2><p>The blog's official entry point has been changed from <code>blog.wendaining.top</code> to <code>blog.wendain.ing</code>, and the actual content is now hosted by Cloudflare Pages. At the same time, <code>wendaining.github.io</code> is retained, pointing only to GitHub Pages, so it continues to serve as a directly accessible mirror and also fits the original workflow.</p><p>The original workflow remains unchanged: articles and other content are still placed in the <code>Blog-Source</code> branch. Each time a commit is made to this branch, GitHub Actions and Cloudflare Pages build and publish the same Hexo blog separately.</p><h2 id="Why-migrate">Why migrate</h2><p>The main reason is that I bought a new domain and never used it (this is indeed pretty cool).</p><p>Previously, the blog was fully hosted on GitHub Pages, and the domain <code>blog.wendaining.top</code> also pointed directly to <code>wendaining.github.io</code>. GitHub access is unstable in some network environments.</p><p>So this time I did not abandon GitHub Pages; instead, I added Cloudflare Pages as the official site: everyday visits land on Cloudflare by default, while GitHub Pages is kept as a backup mirror.</p><p>The <a href="/en/posts/hexo-workflow-based-on-github-actions/">workflow for deploying a Hexo blog based on GitHub Actions</a> I wrote earlier still continues to work.</p><h2 id="What-was-done-during-migration">What was done during migration</h2><h3 id="Set-up-Cloudflare-Pages">Set up Cloudflare Pages</h3><p>Cloudflare Pages connects directly to the same GitHub repository and watches the <code>Blog-Source</code> branch. The build configuration is consistent with GitHub Actions:</p><ul><li>Node.js 22;</li><li>Run <code>npm ci &amp;&amp; npx hexo generate</code>;</li><li>Publish the <code>public</code> directory.</li></ul><p>This way, one commit triggers two independent pipelines: GitHub Actions publishes static files to <code>main</code>, while Cloudflare Pages builds and publishes to Cloudflare on its own.</p><h3 id="Reorganizing-domains">Reorganizing domains</h3><p>The current domain relationships are as follows:</p><ul><li><code>blog.wendain.ing</code>: official domain, with content provided by Cloudflare Pages;</li><li><code>blog.wendaining.top</code>: permanent redirect to the new domain, with article paths and query parameters preserved;</li><li><code>wendaining-blog.pages.dev</code>: also permanently redirects to the official domain;</li><li><code>wendaining.github.io</code>: retained as a directly accessible GitHub Pages mirror.</li></ul><h2 id="Current-architecture">Current architecture</h2><pre><code class=" mermaid">flowchart TD    A["向 Blog-Source 提交文章或配置"]    B["GitHub Actions 构建"]    C["Cloudflare Pages 构建"]    D["main 分支：生成后的静态文件"]    E["wendaining.github.io&lt;br/&gt;GitHub Pages 镜像"]    F["blog.wendain.ing&lt;br/&gt;Cloudflare Pages 正式站"]    G["blog.wendaining.top"]    H["wendaining-blog.pages.dev"]    A --&gt; B    A --&gt; C    B --&gt; D    D --&gt; E    C --&gt; F    G --&gt;|301| F    H --&gt;|301| F</code></pre><h2 id="Impact">Impact</h2><h3 id="Daily-access-unified-on-Cloudflare">Daily access unified on Cloudflare</h3><p>When entering from the old domain, Cloudflare returns a 301 directly at the edge, and then the browser visits <code>blog.wendain.ing</code>. The old domain no longer loads the full blog page, nor does it first detour to GitHub Pages and redirect again.</p><p>Search-engine-related site URLs, Open Graph, and RSS/Atom metadata have also been changed to the new domain.</p><h3 id="Publishing-process-has-basically-not-changed">Publishing process has basically not changed</h3><p>When writing articles, you still only need to modify <code>Blog-Source</code>. The only difference is that previously a commit was built only by GitHub Actions, whereas now Cloudflare Pages also builds at the same time. The two sides are independent pipelines, so updates may differ by a few dozen seconds; as long as both builds succeed, the final content is consistent.</p><h2 id="Final-thoughts">Final thoughts</h2><p>This structure is quite comfortable at present: normal access goes through Cloudflare, GitHub Pages no longer carries main-site traffic, but a static blog that can be accessed and rolled back to at any time is still retained.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>Gorse Learning Note</title>
      <link>https://blog.wendain.ing/en/posts/gorse-learning/</link>
      <description>Learning about Gorse, a classic Golang recommendation system project. This note focuses on studying its original underlying architecture.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%90%8E%E7%AB%AF/">Backend</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%8A%80%E6%9C%AF%E7%AC%94%E8%AE%B0/">Technical Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/Golang/">Golang</category>
      <pubDate>Sat, 22 Aug 2026 07:18:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/gorse-learning/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><blockquote><p>Reference materials:</p><p><a href="https://www.cnblogs.com/wanber/p/19451225">Getting Started with the Gorse Recommender System: Building a Recommendation Engine from Zero to One - Tech Roaming - cnblogs</a></p><p><a href="https://deepwiki.com/gorse-io/gorse/1-overview">gorse-io/gorse | DeepWiki</a></p><p><a href="https://gorse.io/zh/">Homepage | Gorse</a></p></blockquote><h2 id="Getting-Started">Getting Started</h2><h3 id="What-is-a-Recommender-System">What is a Recommender System</h3><p>Three elements:</p><ul><li>Record behavior</li><li>Understand interests</li><li>Predict possible likes</li></ul><h3 id="Startup-and-Usage">Startup and Usage</h3><p>You can start it directly with <code>docker</code> (see the official documentation).</p><p>It is web-based; visit <code>localhost:8088</code> directly to browse.</p><p>Use <code>curl</code> to insert data, create items, insert feedback, get recommendations, and so on.</p><h3 id="Overview-of-the-Core-Working-Principles">Overview of the Core Working Principles</h3><p>Four core concepts:</p><ul><li>User<ul><li>Basic info: ID, labels, etc. (e.g., age, gender)</li><li>Behavioral history: browsing, clicks, purchases...</li></ul></li><li>Item<ul><li>Basic info: ID, labels</li><li>Statistics: popularity, ratings</li></ul></li><li>Feedback<ul><li>User + Item + Type + Time</li></ul></li><li>Recommendation<ul><li>Predict items the user may like based on historical behavior</li></ul></li></ul><p>Flow diagram:</p><ol><li>The user performs an action</li><li>The system records feedback</li><li>Models periodically perform analysis and training</li><li>Recommendations are generated</li><li>The user sees the recommendations</li><li>The loop iterates, back to 1</li></ol><p>Gorse's recommendation strategy: <strong>multi-source fusion</strong>.</p><ol><li><strong>Collaborative filtering</strong>: find similar users and recommend the items they like</li><li><strong>Item similarity</strong>: recommend other items similar to the user's historical items</li><li><strong>Popular recommendations</strong>: recommend the most popular items</li><li><strong>Latest recommendations</strong>: literally what it says</li></ol><p>The so-called fusion strategy: recommendation results = 30% collaborative filtering + 30% item similarity + 20% popular recommendations + 20% latest recommendations</p><h3 id="Gorse-s-Architecture-Design">Gorse's Architecture Design</h3><p>A three-tier architecture:</p><pre><code class=" mermaid">flowchart TD    A["用户 / 应用&lt;br/&gt;Web · App · 小程序"]    B["Server 节点&lt;br/&gt;RESTful API + 实时推荐"]    C["Master 节点&lt;br/&gt;模型训练 + 任务调度 + Dashboard"]    D["Worker 节点（多个）&lt;br/&gt;离线计算 + 批量推荐"]    E["存储层&lt;br/&gt;MySQL + Redis&lt;br/&gt;用户数据 + 物品数据 + 推荐缓存"]    A --&gt;|HTTP / HTTPS| B    B --&gt;|gRPC| C    C --&gt;|gRPC| D    D --&gt; E</code></pre><div class="note note-info"><p>About <strong>gRPC</strong></p><p><strong>RPC</strong> = Remote Procedure Call. The core idea is "calling a function on another machine as if it were a local function call".</p><p><strong>gRPC</strong> = an open-source RPC framework from Google.</p><p><strong>Protobuf</strong> = the data description and serialization format commonly used by gRPC. You write a <code>.proto</code> file defining "what functions exist, what the parameters are, and what the return values are".</p><p>For example, in the Gorse architecture:</p><div class="code-wrapper"><pre><code class="hljs TEXT">Server  ──gRPC──&gt;  MasterMaster  ──gRPC──&gt;  Worker</code></pre></div><p>Suppose the Master provides a function:</p><div class="code-wrapper"><pre><code class="hljs go">GetModel(name <span class="hljs-type">string</span>) Model</code></pre></div><p>The Server wants to call it. But the problem is: <strong>the Master and Server are two separate processes, possibly even running on different machines</strong>, so the Server obviously cannot directly do:</p><div class="code-wrapper"><pre><code class="hljs go">model := master.GetModel(<span class="hljs-string">"ranking"</span>)</code></pre></div><p>What gRPC does is make this kind of <strong>remote call look just like a normal function call</strong>:</p><div class="code-wrapper"><pre><code class="hljs go">model, err := client.GetModel(ctx, request)</code></pre></div><p>What actually happens behind the scenes is:</p><div class="code-wrapper"><pre><code class="hljs text">Server  │  │ calls GetModel(...)  ↓gRPC Client  │  │ serializes into Protobuf  │ sends over HTTP/2  ↓Network  ↓gRPC Server on the Master  │  │ deserializes  ↓Actually executes GetModel(...)</code></pre></div></div><h4 id="Master-Node">Master Node</h4><p>Can be understood as the brain of the Gorse architecture.</p><ul><li>Model training</li><li>AutoML: Automated Machine Learning</li><li>Task scheduling, triggering Workers</li><li>Dashboard: monitoring, data management</li></ul><h4 id="Worker-Node">Worker Node</h4><p>Think of it as the hands and feet of the Gorse architecture.</p><ul><li>Batch recommendation: generate recommendation lists for each user</li><li>Similarity computation: compute similarity between items, and similarity between users</li><li>Horizontal scaling: start multiple Workers, load balancing</li><li>Parallel computation; each Worker handles a subset of users</li></ul><h4 id="Server-Node">Server Node</h4><p>Think of it as the "mouth".</p><ul><li>Provides RESTful API</li><li>Real-time recommendation</li><li>Online updates</li><li>Stateless</li></ul><h4 id="Putting-It-Together">Putting It Together</h4><pre><code class=" mermaid">flowchart LR    A["用户行为"] --&gt; B["Server"]    B --&gt; C["DataStore&lt;br/&gt;MySQL"]    C --&gt; D["Master&lt;br/&gt;定期加载数据"]    D --&gt; E["训练模型"]    E --&gt; F["Worker&lt;br/&gt;计算推荐"]    F --&gt; G["CacheStore&lt;br/&gt;Redis"]    G --&gt; H["Server"]    H --&gt; I["返回用户"]    %% 局部调整布局    subgraph Train[" "]        direction TB        D --&gt; E    end    subgraph Recommend[" "]        direction TB        F --&gt; G    end</code></pre><h2 id="Understanding-Gorse-s-Pipeline">Understanding Gorse's Pipeline</h2><p><a href="https://gorse.io/zh/docs/concepts/pipeline.html">Pipeline | Gorse</a></p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> Pipeline <span class="hljs-keyword">struct</span> {    Config       *config.Config            <span class="hljs-comment">// 配置</span>    CacheClient  cache.Database            <span class="hljs-comment">// Cache Store 客户端</span>    DataClient   data.Database             <span class="hljs-comment">// Data Store 客户端</span>    Tracer       *monitor.Monitor          <span class="hljs-comment">// 进度监控</span>    Jobs         <span class="hljs-type">int</span>                       <span class="hljs-comment">// 并行任务数</span>        <span class="hljs-comment">// 推荐模型</span>    MatrixFactorizationItems *logics.MatrixFactorizationItems  <span class="hljs-comment">// 物品向量索引</span>    MatrixFactorizationUsers *logics.MatrixFactorizationUsers  <span class="hljs-comment">// 用户向量</span>    ClickThroughRateModel    ctr.FactorizationMachines        <span class="hljs-comment">// CTR 预测模型</span>        dontskipColdStartUsers <span class="hljs-type">bool</span>  <span class="hljs-comment">// 是否跳过冷启动用户</span>}</code></pre></div><img src="https://image.wendaining.top/2543ba0dadfa669975c7cf48b4c197e7.png" style="zoom: 80%;"><ul><li>After the data source enters the input layer, it is passed to the retrieval layer</li><li>The retrieval layer consists of multiple recommenders that generate candidate items for the user</li><li>The ranking layer merges all outputs from the different recommenders, removes items the user has already seen (read items), and scores the remaining items by the likelihood of the user interacting with them</li></ul><p>The default pipeline only recommends the latest items.</p><h3 id="Caching-in-the-Pipeline">Caching in the Pipeline</h3><p>The following intermediate results are cached and periodically updated:</p><ul><li>User neighbors from the user-to-user recommender.<ul><li>Simply put, if user A's similar users are B, C, D, then this result is cached</li></ul></li><li>Item neighbors from the item-to-item recommender.<ul><li>Same as above; similar items are cached</li></ul></li><li>Results from non-personalized recommenders.<ul><li>Content not tied to a specific user, such as the latest list or the popular list</li></ul></li><li>Each user's ranker output<ul><li>i.e., the final output of the ranker</li></ul></li></ul><h3 id="How-Gorse-Works">How Gorse Works</h3><p>The pipeline executes in a <strong>distributed</strong> manner. Gorse has three types of nodes: master nodes, worker nodes, and server nodes — that is, the Master, Worker, and Server mentioned above; no need to repeat.</p><h2 id="A-Deep-Dive-into-the-Gorse-Recommender-System-Data-Structures-and-Storage-Layer-Design">A Deep Dive into the Gorse Recommender System: Data Structures and Storage Layer Design</h2><p><a href="https://www.cnblogs.com/wanber/p/19451343">A Deep Dive into the Gorse Recommender System: Data Structures and Storage Layer Design - Tech Roaming - cnblogs</a></p><p>I feel this is also the author's AI article rewritten... anyway, just skim it.</p><h3 id="String-Index-Mapping">String -&gt; Index Mapping</h3><p>Obviously we will have lots of JSON (or <code>map[string][]</code> in Go), with strings as keys.</p><p>Using strings as keys is inefficient (mainly because hash comparison costs $O(len(string))$</p><p>So we adopt a bidirectional <code>ID &lt;-&gt; 索引</code> mapping.</p><p>Specifically, use <code>FreqDict</code>:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> FreqDict <span class="hljs-keyword">struct</span> {    idToIndex   <span class="hljs-keyword">map</span>[<span class="hljs-type">string</span>]<span class="hljs-type">int32</span>   <span class="hljs-comment">// ID → 索引</span>    indexToId   []<span class="hljs-type">string</span>            <span class="hljs-comment">// 索引 → ID</span>    frequencies []<span class="hljs-type">int</span>               <span class="hljs-comment">// 频率统计</span>}</code></pre></div><p>The frequency statistics below can also be used, incidentally, to find the most active users.</p><h3 id="Dataset-Sparse-Matrix">Dataset Sparse Matrix</h3><p>To represent user-item interactions, using a 2D array like <code>matrix := make([][]bool, 1000000)</code> would be very wasteful.</p><p>Therefore, sparse storage is used:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> Dataset <span class="hljs-keyword">struct</span> {    UserIndex    *FreqDict      <span class="hljs-comment">// 用户字典</span>    ItemIndex    *FreqDict      <span class="hljs-comment">// 物品字典</span>    UserFeedback [][]<span class="hljs-type">int32</span>      <span class="hljs-comment">// 用户 → 物品列表</span>    ItemFeedback [][]<span class="hljs-type">int32</span>      <span class="hljs-comment">// 物品 → 用户列表</span>}</code></pre></div><p>Both directions are stored, trading space for time.</p><h3 id="Storage-Layer">Storage Layer</h3><p>Gorse supports many databases, such as MySQL, PostgreSQL, MongoDB, Redis</p><p>The implementation creates a <code>Database</code> interface, and each database implements these interfaces.</p><p>According to <a href="https://gorse.io/zh/docs/config.html">Configuration | Gorse</a>,</p><p>[database]</p><table><thead><tr><th>Key</th><th>Type</th><th>Default</th><th>Description</th></tr></thead><tbody><tr><td><code>data_store</code></td><td>string</td><td></td><td>Database used for data storage.</td></tr><tr><td><code>cache_store</code></td><td>string</td><td></td><td>Database used for cache storage.</td></tr><tr><td><code>table_prefix</code></td><td>string</td><td></td><td>Naming convention for tables in the database.</td></tr><tr><td><code>cache_table_prefix</code></td><td>string</td><td><code>table_prefix</code></td><td>Naming convention for tables in the cache store database.</td></tr><tr><td><code>data_table_prefix</code></td><td>string</td><td><code>table_prefix</code></td><td>Naming convention for tables in the data store database.</td></tr></tbody></table><h3 id="DataStore-and-CacheStore">DataStore and CacheStore</h3><p><strong>DataStore</strong>: stores "raw business data"</p><ul><li>User, Item, Feedback</li></ul><p><strong>CacheStore</strong>: stores "intermediate results computed by Gorse and recommendation results"</p><ul><li>The user's recommendation list</li><li>Similar item lists</li></ul><p>This way, the former uses a relational database, and the latter uses a NoSQL database like Redis.</p><h3 id="Other-Performance-Optimizations">Other Performance Optimizations</h3><h4 id="Batch-Loading">Batch Loading</h4><p>Instead of <code>get</code>-ting database objects one by one, batch query APIs are used; internally it reads from memory, reducing database I/O.</p><p>(This is basically the most core use case of Redis.)</p><h4 id="Cursor-Pagination">Cursor Pagination</h4><p>To understand cursor pagination, you first need to know what offset pagination is.</p><p>For example, suppose the table has 10,000 rows and we fetch 100 at a time.</p><div class="code-wrapper"><pre><code class="hljs sql"><span class="hljs-keyword">SELECT</span> <span class="hljs-operator">*</span> <span class="hljs-keyword">FROM</span> feedbacks LIMIT <span class="hljs-number">10000</span>, <span class="hljs-number">100</span>;<span class="hljs-comment">-- 先找到前 10000 条，把它们全部跳过，再取后面的 100 条 --</span></code></pre></div><p>Problem: although the first 10,000 rows are ultimately not needed, the database still has to process them.</p><p>Therefore, the further you paginate, the worse performance gets.</p><p>Using cursor pagination: after each query, record <code>last_id</code>; on the next query, use <code>WHERE id &gt; last_id</code> to locate directly via the index.</p><h4 id="Concurrency-Control">Concurrency Control</h4><p>Use read-write locks instead of one big lock.</p><p>I think this is common sense...</p><h2 id="Deep-Dive-into-Collaborative-Filtering-Algorithms">Deep Dive into Collaborative Filtering Algorithms</h2><p>This section is empty for now, because I don't have a solid machine learning foundation.</p><h2 id="Gorse-s-Distributed-Architecture">Gorse's Distributed Architecture</h2><p>First, some basic concepts and basic requirements:</p><p><strong>Why distribution is needed</strong>:</p><ol><li>Insufficient QPS (100 vs 10000)</li><li>Insufficient memory (32GB vs 100GB needed)</li><li>Single point of failure (if it goes down, everything goes down)</li></ol><p>Scale Out (horizontal scaling):</p><div class="code-wrapper"><pre><code class="hljs text">┌─────────┐      ┌─────────┐      ┌─────────┐│ Server1 │  +   │ Server2 │  +   │ Server3 ││ 100 QPS │      │ 100 QPS │      │ 100 QPS │└─────────┘      └─────────┘      └─────────┘</code></pre></div><p>Scale Up (vertical scaling)</p><div class="code-wrapper"><pre><code class="hljs text">┌─────────┐      ┌───────────┐│  32GB   │  →   │   128GB   ││ 8 cores │      │ 32 cores  │└─────────┘      └───────────┘</code></pre></div><p>Distributed systems adopt Scale Out horizontal scaling.</p><h3 id="Overall-Architecture">Overall Architecture</h3><pre><code class=" mermaid">flowchart TD    U["用户请求"]    LB["Load Balancer&lt;br/&gt;Nginx / HAProxy"]    U --&gt; LB    subgraph Servers["Server 集群 · 提供 API"]        direction LR        S1["Server1&lt;br/&gt;:8087"]        S2["Server2&lt;br/&gt;:8087"]        S3["Server3&lt;br/&gt;:8087"]    end    LB --&gt; S1    LB --&gt; S2    LB --&gt; S3    M["Master&lt;br/&gt;:8086&lt;br/&gt;训练模型 · 调度任务"]    S1 --&gt;|gRPC| M    S2 --&gt;|gRPC| M    S3 --&gt;|gRPC| M    subgraph Workers["Worker 集群 · 计算推荐"]        direction LR        W1["Worker1&lt;br/&gt;:8089"]        W2["Worker2&lt;br/&gt;:8090"]        W3["Worker3&lt;br/&gt;:8091"]    end    M --&gt;|gRPC| W1    M --&gt;|gRPC| W2    M --&gt;|gRPC| W3    subgraph Storage["存储层"]        direction LR        DB["MySQL&lt;br/&gt;:3306"]        R["Redis&lt;br/&gt;:6379"]    end    W1 --&gt; DB    W1 --&gt; R    W2 --&gt; DB    W2 --&gt; R    W3 --&gt; DB    W3 --&gt; R</code></pre><h3 id="Consistent-Hashing">Consistent Hashing</h3><p>It's essentially a load balancing strategy.</p><p>For example, suppose the strategy for assigning a User to a Worker is:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">getWorker</span><span class="hljs-params">(userId <span class="hljs-type">string</span>)</span></span> <span class="hljs-type">int</span> {    hash := crc32.ChecksumIEEE([]<span class="hljs-type">byte</span>(userId))    <span class="hljs-keyword">return</span> <span class="hljs-type">int</span>(hash) % numWorkers}</code></pre></div><p>But if we add a Worker, then obviously the Workers assigned to most existing Users change.</p><p>Therefore, we need to adopt <strong>consistent hashing</strong>.</p><p>The rough principle is a <strong>hash ring</strong>:</p><p>Imagine a huge numeric ring; here let's assume it's <code>0~99</code>.</p><p>We hash both Users and Workers; the hash function only yields numbers on the ring.</p><p>Suppose:</p><ul><li>hash(worker-A) = 20</li><li>hash(worker-B) = 50</li><li>hash(worker-C) = 80</li></ul><p>And</p><ul><li>hash(Alice) = 30</li></ul><p>The rule: <strong>walk clockwise from the user's position; the first Worker encountered is the one responsible for this user</strong>.</p><p>For example, Alice walks clockwise from 30, and the first one is Worker-B at 50.</p><p>When adding a Worker, only the segment where it is inserted into the hash is affected; the rest is unaffected — this is <strong>consistent hashing</strong>.</p><h3 id="Worker-Coordination-Mechanism">Worker Coordination Mechanism</h3><p>When a Worker starts, it actively connects to the Master, registers itself, syncs configuration, pulls models, and starts working.</p><p>The Master's task assignment:</p><ul><li>The Master periodically scans the database to get all users</li><li>If there are new users, notify all workers about the new users</li><li>Workers filter using hash values to get the users they need to handle</li><li>Then compute in parallel to get recommendation lists</li></ul><h3 id="Failure-Handling">Failure Handling</h3><p>The Master periodically performs heartbeat checks <code>healthCheck()</code></p><ul><li>If a Worker is down, remove it</li><li>Then, consistent hashing reassigns (not handled in the check function), so this Worker's users are assigned to other Workers</li></ul><h3 id="Server-Horizontal-Scaling">Server Horizontal Scaling</h3><h4 id="Stateless-Design">Stateless Design</h4><p>Each Server connects to the cache Database, usually Redis.</p><p>Then, <strong>the Server is stateless, as reflected in this request-handling function</strong>:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-comment">// 处理推荐请求</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> GetRecommendations(userId <span class="hljs-type">string</span>, n <span class="hljs-type">int</span>) []<span class="hljs-type">string</span> {    <span class="hljs-comment">// 1. 从缓存读取（无状态）</span>    recommendations := s.cacheClient.GetRecommendations(userId, n)        <span class="hljs-keyword">if</span> <span class="hljs-built_in">len</span>(recommendations) &gt;= n {        <span class="hljs-keyword">return</span> recommendations[:n]    }        <span class="hljs-comment">// 2. 缓存未命中，实时计算</span>    <span class="hljs-keyword">return</span> s.computeRecommendations(userId, n)}</code></pre></div><p>Why should the Server be stateless? Because a Server can go down at any time. If it were stateful and a user's Session was routed to a Server that then crashed, that user's Session would be lost.</p><p>But currently any modification is written directly to Redis, so a crash has no impact, and adding or removing Servers doesn't affect the service.</p><h4 id="Load-Balancing">Load Balancing</h4><p>Nginx is used.</p><h3 id="Data-Consistency-Guarantees">Data Consistency Guarantees</h3><h4 id="Eventual-Consistency-Cache-Aside-Strategy-Cache-Update-Problem">Eventual Consistency / Cache-Aside Strategy / Cache Update Problem</h4><p><em>It's basically that MySQL is slow while Redis is fast</em>. (Not accurate; see the LLM explanation below.) Sometimes a recommendation may be read from the database, but by then the database has already started writing new data, so the user first gets recommendations based on old data, and the new data is updated in later.</p><p>Solution: <strong>fast path + slow path</strong></p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-comment">// Server 端</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> InsertFeedback(feedback Feedback) {    <span class="hljs-comment">// 1. 写入 MySQL（慢路径）</span>    s.dataClient.InsertFeedback(feedback)        <span class="hljs-comment">// 2. 快速更新：从推荐中移除已交互的</span>    s.cacheClient.RemoveFromRecommendation(        feedback.UserId,        feedback.ItemId,    )        <span class="hljs-comment">// 3. 触发增量更新（可选）</span>    s.masterClient.TriggerIncrementalUpdate(feedback.UserId)}</code></pre></div><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 5263 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">It's normal that you didn't understand, because this article explains "d...</span></summary><blockquote><p>It's normal that you didn't understand, because this article explains "data consistency" in a somewhat convoluted way, and the "fast update" doesn't first explain <strong>why recommendation results need to be deleted</strong>.</p><p>First, grab a very concrete scenario.</p><p>Suppose Redis already has recommendations computed for user A:</p><div class="code-wrapper"><pre><code class="hljs text">User A's recommendation list:[phone, earphones, keyboard, mouse]</code></pre></div><p>This recommendation result was computed <strong>earlier</strong> by the Worker and put into Redis.</p><p>Now user A clicks "earphones".</p><p>So the system receives a Feedback:</p><div class="code-wrapper"><pre><code class="hljs text">User=AItem=earphonesType=click</code></pre></div><p>Here comes the problem:</p><p>Although MySQL will now record:</p><div class="code-wrapper"><pre><code class="hljs text">A has already clicked earphones</code></pre></div><p>The recommendation list in Redis is still the old one:</p><div class="code-wrapper"><pre><code class="hljs text">[phone, earphones, keyboard, mouse]        ↑      still here</code></pre></div><p>If the user immediately refreshes the recommendation page, they might see "earphones" again.</p><p>That's odd:</p><blockquote><p>I just clicked on it, why is it still being recommended to me?</p></blockquote><p>So the code in the article:</p><div class="code-wrapper"><pre><code class="hljs go">s.cacheClient.RemoveFromRecommendation(    feedback.UserId,    feedback.ItemId,)</code></pre></div><p>The meaning is very simple:</p><blockquote><p><strong>If the user just interacted with an Item, immediately remove that Item from their currently cached recommendation list.</strong></p></blockquote><p>That is:</p><div class="code-wrapper"><pre><code class="hljs text">Original Redis:A → [phone, earphones, keyboard, mouse]             ↑           clickedImmediately becomes:A → [phone, keyboard, mouse]</code></pre></div><p>This is what's called:</p><blockquote><p><strong>Fast update: remove already-interacted items from recommendations</strong></p></blockquote><p>It does not "recompute recommendations".</p><p>It just makes a particularly cheap little patch:</p><div class="code-wrapper"><pre><code class="hljs text">The user has already seen/clicked this↓Don't recommend it for now</code></pre></div><hr><p>Why is it called the "fast path"?</p><p>Because actually recomputing recommendations can be slow.</p><p>Suppose after the user clicks earphones, we want <strong>completely up-to-date</strong> recommendations:</p><div class="code-wrapper"><pre><code class="hljs text">User clicks earphones    ↓Write Feedback    ↓Re-read user behavior    ↓Re-run the recommendation algorithm    ↓Re-rank    ↓Generate a new Top N    ↓Write to Redis</code></pre></div><p>This process can be heavy.</p><p>You can't ask the user:</p><blockquote><p>"Please wait, let me re-run the recommendation algorithm first, then refresh the page for you."</p></blockquote><p>So a compromise is adopted:</p><div class="code-wrapper"><pre><code class="hljs text">              User clicks earphones                   ↓          Write Feedback to the database                   ↓          ┌────────┴────────┐          ↓                 ↓       Fast path          Slow pathImmediately remove earphones    Recompute recommendationsfrom Redis                      in the background     ↓                    ↓Almost immediate            May complete a bit later</code></pre></div><p>This is what the article calls:</p><blockquote><p><strong>Fast path + slow path</strong></p></blockquote><p>More concretely.</p><p>Fast path:</p><div class="code-wrapper"><pre><code class="hljs go">RemoveFromRecommendation(user, item)</code></pre></div><p>It only does:</p><div class="code-wrapper"><pre><code class="hljs text">[phone, earphones, keyboard]       ↓ delete[phone, keyboard]</code></pre></div><p>Very fast.</p><p>Slow path:</p><div class="code-wrapper"><pre><code class="hljs text">Based on the latest Feedback,recompute:What does A like now?↓Regenerate the recommendation list↓[phone case, Bluetooth speaker, keyboard, ...]</code></pre></div><p>Eventually the new recommendation results overwrite Redis.</p><hr><p>So you can understand the whole mechanism as:</p><blockquote><p><strong>First "stop the bleeding", then "thorough treatment".</strong></p></blockquote><p>The user just clicked earphones:</p><p>Do immediately</p><div class="code-wrapper"><pre><code class="hljs text">Stop showing him earphones.</code></pre></div><p>Slowly do in the background</p><div class="code-wrapper"><pre><code class="hljs text">Since he just clicked earphones,shouldn't I recommend moreBluetooth earphones, speakers, phone accessories?Recompute.</code></pre></div><hr><p>Also, I think this sentence in the article you pasted:</p><blockquote><p>"It's basically that MySQL is slow while Redis is fast."</p></blockquote><p><strong>is not particularly accurate.</strong></p><p>The real problem is not mainly:</p><div class="code-wrapper"><pre><code class="hljs text">MySQL slowRedis fast</code></pre></div><p>but rather:</p><blockquote><p><strong>The raw data has changed, but the recommendation results in the cache were still computed from the old data.</strong></p></blockquote><p>This is a typical case of:</p><div class="code-wrapper"><pre><code class="hljs text">Fact in the database          Computed result in RedisA clicked earphones     ←→     Still recommending earphones   new                          old</code></pre></div><p>The two sides are temporarily inconsistent.</p><p>Even if MySQL were extremely fast, this problem would still exist.</p><p>Because the recommendation results themselves are usually:</p><div class="code-wrapper"><pre><code class="hljs text">Old Feedback    ↓Worker computation    ↓Redis recommendation list</code></pre></div><p>After new Feedback appears, the Worker doesn't necessarily recompute instantly.</p><p>So the real problem is:</p><blockquote><p><strong>The recommendation cache is lagging.</strong></p></blockquote><hr><p>Now looking at the three-step code you pasted becomes very easy:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> InsertFeedback(feedback Feedback) {</code></pre></div><p>The user performs an action, for example:</p><div class="code-wrapper"><pre><code class="hljs text">A clicks earphones</code></pre></div><p>Step one:</p><div class="code-wrapper"><pre><code class="hljs go">s.dataClient.InsertFeedback(feedback)</code></pre></div><p>Permanently save:</p><div class="code-wrapper"><pre><code class="hljs text">MySQL:A has clicked earphones</code></pre></div><p>This is factual data.</p><p>Step two:</p><div class="code-wrapper"><pre><code class="hljs go">s.cacheClient.RemoveFromRecommendation(    feedback.UserId,    feedback.ItemId,)</code></pre></div><p>Immediately patch the old cache:</p><div class="code-wrapper"><pre><code class="hljs text">Redis:A → [phone, earphones, keyboard]             ↓           deleteA → [phone, keyboard]</code></pre></div><p>Step three:</p><div class="code-wrapper"><pre><code class="hljs go">s.masterClient.TriggerIncrementalUpdate(feedback.UserId)</code></pre></div><p>The meaning can be roughly understood as:</p><blockquote><p>"A's behavior has changed; when you have time, recompute A's recommendations."</p></blockquote><p>Afterwards it might generate:</p><div class="code-wrapper"><pre><code class="hljs text">A →[Bluetooth speaker, phone case, keyboard, charger]</code></pre></div><p>So:</p><div class="code-wrapper"><pre><code class="hljs text">Immediately:remove already-interacted ItemsLater:generate the truly updated recommendation list</code></pre></div><p>That's the whole idea.</p><p>For interview purposes, remembering the following sentence is enough:</p><blockquote><p><strong>Gorse's recommendation results are precomputed and cached, so after a user generates new Feedback, the cached recommendations may be temporarily stale. You can first quickly remove Items the user has already interacted with from the cache to avoid duplicate recommendations; afterwards, a background task recomputes the recommendation results based on the latest behavior.</strong></p></blockquote><p>This explanation is far more accurate than "because MySQL is slow and Redis is fast".</p></blockquote></details><h4 id="Cache-Penetration-Protection">Cache Penetration Protection</h4><p>Cache penetration refers to data requested by the client existing in neither the cache nor the database, so the cache never takes effect (only when the database finds data will it be cached in Redis, but the problem is nothing is found), causing frequent database access.</p><p>Gorse's solution: a Bloom filter.</p><div class="note note-info"><p>A Bloom filter actually uses hashing to solve this problem: through a large binary array, it uses hashing to determine whether the data being queried exists. If the Bloom filter judges it exists, the request is allowed through and will access Redis; even if the data in Redis has expired at that moment, the data definitely exists in the database, and after querying it from the database, it is put back into Redis. If the Bloom filter judges the data doesn't exist, it returns directly. The advantage of this approach is saving memory space, but there can be false positives, because the Bloom filter uses hashing, and any hashing approach can have hash collisions</p></div><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 GO · 29 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">GO · 29 行</span></summary><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-comment">// 问题：恶意请求大量不存在的用户</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> GetRecommendations(userId <span class="hljs-type">string</span>) []<span class="hljs-type">string</span> {    <span class="hljs-comment">// 缓存未命中</span>    recs := s.cache.Get(userId)    <span class="hljs-keyword">if</span> recs == <span class="hljs-literal">nil</span> {        <span class="hljs-comment">// ❌ 每次都计算，压垮系统</span>        recs = s.compute(userId)    }    <span class="hljs-keyword">return</span> recs}<span class="hljs-comment">// 解决：布隆过滤器</span><span class="hljs-keyword">type</span> Server <span class="hljs-keyword">struct</span> {    bloomFilter *BloomFilter}<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> GetRecommendations(userId <span class="hljs-type">string</span>) []<span class="hljs-type">string</span> {    <span class="hljs-comment">// 1. 快速检查用户是否存在</span>    <span class="hljs-keyword">if</span> !s.bloomFilter.Contains(userId) {        <span class="hljs-keyword">return</span> []<span class="hljs-type">string</span>{}  <span class="hljs-comment">// 用户不存在，直接返回</span>    }        <span class="hljs-comment">// 2. 查询缓存</span>    recs := s.cache.Get(userId)    <span class="hljs-keyword">if</span> recs == <span class="hljs-literal">nil</span> {        recs = s.compute(userId)    }    <span class="hljs-keyword">return</span> recs}</code></pre></div></details><h4 id="Cache-Avalanche">Cache Avalanche</h4><p>Cache avalanche refers to a large number of cache keys expiring at the same time, or the Redis service going down, causing a large number of requests to hit the database and bringing enormous pressure.</p><p>Gorse's solution: set random expiration times:</p><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-comment">// 问题：大量缓存同时过期</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> SetRecommendations(userId <span class="hljs-type">string</span>, recs []<span class="hljs-type">string</span>) {    <span class="hljs-comment">// ❌ 所有缓存都是 1 小时过期</span>    s.cache.Set(userId, recs, <span class="hljs-number">1</span>*time.Hour)}<span class="hljs-comment">// 解决：随机过期时间</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> SetRecommendations(userId <span class="hljs-type">string</span>, recs []<span class="hljs-type">string</span>) {    <span class="hljs-comment">// 1 小时 ± 5 分钟</span>    ttl := time.Hour + time.Duration(rand.Intn(<span class="hljs-number">600</span>))*time.Second    s.cache.Set(userId, recs, ttl)}</code></pre></div><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1016 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">Solutions to cache avalanche, excerpted from Redis in Practice | Kyle's...</span></summary><blockquote><p>Solutions to cache avalanche, excerpted from <a href="https://cyborg2077.github.io/2022/10/22/RedisPractice/#%E7%BC%93%E5%AD%98%E6%9B%B4%E6%96%B0%E7%AD%96%E7%95%A5">Redis in Practice | Kyle's Blog</a></p><ul><li>Add random values to the TTLs of different Keys so they expire in batches at different times</li><li>Use a Redis cluster to improve service availability (a system composed of one or more <code>Sentinel</code> instances monitors Redis nodes; when the master node fails, one of the slave nodes can be promoted to master for failover, ensuring system availability.)</li><li>Add degradation and rate-limiting strategies to cached services</li><li>Add multi-level caching to the service (when the browser accesses static resources, it reads the browser's local cache first; when accessing non-static resources (ajax data queries), it accesses the server; after the request reaches Nginx, it reads the Nginx local cache first; if the Nginx local cache misses, it queries Redis directly (bypassing Tomcat); if the Redis query misses, it queries Tomcat; after the request enters Tomcat, it queries the JVM process cache first; if the JVM process cache misses, it queries the database)</li></ul></blockquote></details><h3 id="Fault-Tolerance-and-High-Availability">Fault Tolerance and High Availability</h3><ul><li><strong>Fault tolerance</strong>: when part of the system fails, the whole can keep working, rather than everything crashing because of one problem.</li><li><strong>High availability</strong>: the system tries to keep serving externally as much as possible, even if some internal components are temporarily faulty.</li><li><strong>Service degradation</strong>: when normal functionality can't be delivered, fall back to a "not as good but still usable" result. For example, if personalized recommendation fails, return popular items.</li><li><strong>Fallback</strong>: the backup result actually returned during degradation. For example, popular recommendations, default recommendations.</li><li><strong>Circuit breaker</strong>: after a downstream service fails consecutively many times, the system temporarily stops requesting it, avoiding a large number of continuously failing requests dragging down the whole system.</li><li><strong>Closed</strong>: the circuit breaker's normal state; requests pass through normally.</li><li><strong>Open</strong>: the downstream is found to be failing frequently, so requests to it are temporarily blocked.</li><li><strong>Half-Open</strong>: after a while, let a few requests through to test; if they succeed, recover; if they fail, keep the breaker open.</li></ul><h4 id="Service-Degradation">Service Degradation</h4><p>For example, the rough code logic of the Server fetching recommendations is:</p><ol><li>Try to get from cache</li><li>If it fails, compute in real time</li><li>If real-time computation fails, fall back to fetching pre-cached popular recommendations</li></ol><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 GO · 29 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">GO · 29 行</span></summary><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> Server <span class="hljs-keyword">struct</span> {    circuitBreaker *CircuitBreaker}<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> GetRecommendations(userId <span class="hljs-type">string</span>) []<span class="hljs-type">string</span> {    <span class="hljs-comment">// 1. 尝试从缓存获取</span>    recs, err := s.cache.Get(userId)    <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {        <span class="hljs-keyword">return</span> recs    }        <span class="hljs-comment">// 2. 缓存失败，尝试实时计算</span>    <span class="hljs-keyword">if</span> s.circuitBreaker.Allow() {        recs, err = s.computeRealtime(userId)        <span class="hljs-keyword">if</span> err == <span class="hljs-literal">nil</span> {            <span class="hljs-keyword">return</span> recs        }        s.circuitBreaker.RecordFailure()    }        <span class="hljs-comment">// 3. 实时计算失败，降级到热门推荐</span>    <span class="hljs-keyword">return</span> s.getFallbackRecommendations()}<span class="hljs-comment">// 降级策略</span><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(s *Server)</span></span> getFallbackRecommendations() []<span class="hljs-type">string</span> {    <span class="hljs-comment">// 返回热门物品（预先缓存）</span>    <span class="hljs-keyword">return</span> s.cache.Get(<span class="hljs-string">"popular_items"</span>)}</code></pre></div></details><h4 id="Circuit-Breaker">Circuit Breaker</h4><p>It feels like just opening and closing a gate; after closing, there's still a check, and if the check fails it stays closed — there's a half-open intermediate state.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 GO · 45 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">GO · 45 行</span></summary><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> CircuitBreaker <span class="hljs-keyword">struct</span> {    state          State  <span class="hljs-comment">// Open/Closed/HalfOpen</span>    failureCount   <span class="hljs-type">int</span>    successCount   <span class="hljs-type">int</span>    failureThreshold <span class="hljs-type">int</span>    timeout        time.Duration    lastFailTime   time.Time}<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(cb *CircuitBreaker)</span></span> Allow() <span class="hljs-type">bool</span> {    <span class="hljs-keyword">switch</span> cb.state {    <span class="hljs-keyword">case</span> StateClosed:        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>  <span class="hljs-comment">// 正常状态，允许请求</span>            <span class="hljs-keyword">case</span> StateOpen:        <span class="hljs-comment">// 熔断状态，检查是否到恢复时间</span>        <span class="hljs-keyword">if</span> time.Since(cb.lastFailTime) &gt; cb.timeout {            cb.state = StateHalfOpen            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>  <span class="hljs-comment">// 尝试恢复</span>        }        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>  <span class="hljs-comment">// 拒绝请求</span>            <span class="hljs-keyword">case</span> StateHalfOpen:        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>  <span class="hljs-comment">// 半开状态，允许部分请求</span>    }}<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(cb *CircuitBreaker)</span></span> RecordFailure() {    cb.failureCount++    cb.lastFailTime = time.Now()        <span class="hljs-keyword">if</span> cb.failureCount &gt;= cb.failureThreshold {        cb.state = StateOpen  <span class="hljs-comment">// 打开熔断器</span>    }}<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(cb *CircuitBreaker)</span></span> RecordSuccess() {    <span class="hljs-keyword">if</span> cb.state == StateHalfOpen {        cb.successCount++        <span class="hljs-keyword">if</span> cb.successCount &gt;= <span class="hljs-number">3</span> {            cb.state = StateClosed  <span class="hljs-comment">// 关闭熔断器，恢复正常</span>            cb.failureCount = <span class="hljs-number">0</span>        }    }}</code></pre></div></details><h3 id="Setting-Up-a-Distributed-Cluster">Setting Up a Distributed Cluster</h3><p>Mainly configured in <code>docker-compose.yml</code>.</p><p>Of course, if you need flexible scaling, you'll need k8s.</p><p>This part will be discussed separately later.</p><h3 id="Summary">Summary</h3><p>✅ <strong>Distributed design</strong></p><ul><li>Master/Worker/Server three-tier architecture</li><li>Each tier scales independently</li><li>Stateless design</li></ul><p>✅ <strong>Load balancing</strong></p><ul><li>Consistent hashing</li><li>Virtual nodes</li><li>Minimized data migration</li></ul><p>✅ <strong>High availability</strong></p><ul><li>Service degradation</li><li>Circuit breaker</li><li>Automatic failure recovery</li></ul><p>✅ <strong>Data consistency</strong></p><ul><li>Eventual consistency</li><li>Fast path + slow path</li><li>Cache protection</li></ul><h2 id="Gorse-Server-Working-Principles-in-Detail">Gorse Server Working Principles in Detail</h2><h3 id="The-Server-s-Position-in-the-Architecture">The Server's Position in the Architecture</h3><ul><li>User requests come into the Server (<strong>a stateless service</strong>)</li><li>The Server's results are cached to Redis; synced to the Master via gRPC</li></ul><h3 id="The-Server-s-Responsibilities">The Server's Responsibilities</h3><ul><li>Provides RESTful API externally</li><li>Reads precomputed cached results from Redis</li><li>Periodically syncs configuration and database connection info from the Master</li></ul><h3 id="code">code</h3><ul><li>Create the Server instance in <code>main.go</code></li><li>Perform initialization in <code>server.go</code><ul><li>Stateless</li><li>Does not connect to the database initially; waits to get configuration from the Master</li><li>Only needs to know the Master's address (actually address + port)</li></ul></li><li>Start the service in <code>server.go</code>, connect to the master via gRPC, use <code>go s.Sync()</code> to start a goroutine for syncing, and finally start the HTTP server<ul><li><code>Sync()</code> runs an infinite loop, requesting metadata from the Master and parsing it<ul><li>If the configuration has changed, connect to the new Data Store / Cache Store</li></ul></li><li>Sleeps for a while, then continues the loop after waking up</li></ul></li><li>Handle the RESTful API in <code>rest.go</code>; after registration, the concrete logic is just a bunch of CRUD operations.</li></ul><p>Walking through the complete flow:</p><ol><li>The user sends a request, e.g. <code>GET /api/recommend/user123?n=10</code></li><li>The Server's HTTP Handler receives the request and processes it:<ol><li>Parse the request to get the parameters</li><li>Read the recommendation cache from Redis</li><li>If the cache hits, <strong>filter out already-consumed items</strong></li><li>If the quantity is insufficient, apply the fallback strategy (random recommendations, etc.)</li><li>Return the JSON response</li></ol></li></ol><p>Three key characteristics can be seen:</p><ul><li>Stateless: mainly for convenient load balancing</li><li>Hot configuration updates</li><li>Fallback strategy</li></ul><h3 id="Key-Points-of-Server-Performance-Optimization">Key Points of Server Performance Optimization</h3><h4 id="Connection-Pool">Connection Pool</h4><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-comment">// Redis 连接池</span>redisClient := redis.NewClient(&amp;redis.Options{    PoolSize:     <span class="hljs-number">100</span>,      <span class="hljs-comment">// 连接池大小</span>    MinIdleConns: <span class="hljs-number">20</span>,       <span class="hljs-comment">// 最小空闲连接</span>    PoolTimeout:  <span class="hljs-number">4</span> * time.Second,})<span class="hljs-comment">// MySQL 连接池</span>db.SetMaxOpenConns(<span class="hljs-number">100</span>)     <span class="hljs-comment">// 最大连接数</span>db.SetMaxIdleConns(<span class="hljs-number">20</span>)      <span class="hljs-comment">// 最大空闲连接</span>db.SetConnMaxLifetime(time.Hour)</code></pre></div><p>Here we can see the two elements of a connection pool: <strong>pool size</strong> and <strong>minimum idle connections</strong>.</p><h4 id="Caching-Strategy">Caching Strategy</h4><p>Expiration time: 72h</p><p>Update frequency: updated after the Worker recomputes</p><p>For hot data:</p><ul><li>Popular items: cached permanently</li><li>New items: cached for 24h</li></ul><h4 id="Using-Batch-Operations">Using Batch Operations</h4><p>As mentioned before, it's just batch queries and batch loading.</p><h2 id="Gorse-Worker-Architecture-in-Detail">Gorse Worker Architecture in Detail</h2><p>Gorse's recommendation computation engine.</p><p>Responsibilities:</p><ul><li>Sync configuration and models from the Master</li><li>Generate offline recommendations</li><li>Write to cache</li></ul><h3 id="The-Worker-Struct">The Worker Struct</h3><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 GO · 49 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">GO · 49 行</span></summary><div class="code-wrapper"><pre><code class="hljs go"><span class="hljs-keyword">type</span> Worker <span class="hljs-keyword">struct</span> {PipelinetestMode <span class="hljs-type">bool</span>clickThroughRateModelId <span class="hljs-type">int64</span><span class="hljs-comment">// worker config</span>workerName <span class="hljs-type">string</span>httpHost   <span class="hljs-type">string</span>httpPort   <span class="hljs-type">int</span>masterHost <span class="hljs-type">string</span>masterPort <span class="hljs-type">int</span>tlsConfig  *util.TLSConfigcacheFile  <span class="hljs-type">string</span><span class="hljs-comment">// database connection path</span>cachePath    <span class="hljs-type">string</span>cachePrefix  <span class="hljs-type">string</span>dataPath     <span class="hljs-type">string</span>dataPrefix   <span class="hljs-type">string</span>vectorPath   <span class="hljs-type">string</span>vectorPrefix <span class="hljs-type">string</span>blobConfig  <span class="hljs-type">string</span>blobStore   blob.StorevectorStore vectors.Database<span class="hljs-comment">// master connection</span>conn         *grpc.ClientConnmasterClient protocol.MasterClientlatestCollaborativeFilteringModelId <span class="hljs-type">int64</span>latestClickThroughRateModelId       <span class="hljs-type">int64</span>randGenerator                       *rand.Rand<span class="hljs-comment">// peers</span>peers []<span class="hljs-type">string</span>me    <span class="hljs-type">string</span><span class="hljs-comment">// events</span>tickDuration time.Durationticker       *time.TickersyncedChan   <span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{} <span class="hljs-comment">// meta synced events</span>pulledChan   <span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{} <span class="hljs-comment">// model pulled events</span>done         <span class="hljs-keyword">chan</span> <span class="hljs-keyword">struct</span>{}shutdown     sync.OncesyncWait     sync.WaitGrouphttpServer   *http.Server}</code></pre></div></details><p>There's quite a lot here, so let me pick a few fields I consider important:</p><ul><li><p><code>Pipeline</code>, the same Pipeline described earlier; its core role is to <strong>encapsulate the core logic of recommendation computation</strong></p></li><li><p>Its own HTTP service address + port</p></li><li><p>Master address and connection</p></li><li><p>The list of Worker nodes and the current Worker's identifier in the cluster, <strong>used for consistent hashing</strong></p></li><li><p>Tickers and channels, used for communication between goroutines (Sync → Pull → Recommend)</p><blockquote><p>A Ticker holds a channel that delivers "ticks" of a clock at intervals.</p></blockquote></li></ul><h3 id="Worker-Startup">Worker Startup</h3><p>First the main function does the basic configuration, then starts <code>w.Serve()</code>.</p><p>And <code>w.Serve()</code>:</p><ul><li>First generates a unique name</li><li>Creates a progress tracker</li><li>Connects to the master via gRPC</li><li>Starts the three major goroutines: Sync → Pull → Recommend<ul><li>Sync is for syncing configuration</li><li>Pull is for pulling models</li><li>ServeHTTP is for, literally, that</li></ul></li><li>Defines the main loop <code>func loop()</code>: pull users, generate recommendations, report to the Master</li><li>Then starts an infinite loop; if the channel contains a scheduled trigger / model-update trigger message, it calls <code>loop()</code></li></ul><h3 id="The-Three-Core-Goroutines">The Three Core Goroutines</h3><h4 id="Sync">Sync</h4><p>Roughly executes:</p><p>An infinite loop:</p><ul><li>Fetch data from the Master and update<ul><li>If there's something new, trigger a new connection update</li></ul></li><li>Detect model version updates<ul><li>If there's a new one, trigger the <code>Pull()</code> goroutine</li></ul></li><li>Update cluster information for consistent hashing</li><li>Wait (sleep for a while)</li></ul><h4 id="Pull">Pull</h4><p>When a message from the Sync goroutine is received, the loop continues (<code>for range w.syncedChan</code>)</p><ul><li>Pull the model</li><li>If there's a new model, notify the main loop via <code>w.pulledChan</code></li></ul><h4 id="ServeHTTP">ServeHTTP</h4><p>Provides Prometheus metrics and a health check API</p><div class="note note-info"><p>Prometheus is an <strong>open-source monitoring and alerting system</strong>.</p><p>Prometheus metrics are "runtime status data" that a program deliberately exposes for Prometheus to collect.</p></div><p>Mainly used for checks inside k8s.</p><h3 id="User-Recommendation-Flow">User Recommendation Flow</h3><h4 id="Pipeline-Recommend-in-Detail"><code>Pipeline.Recommend()</code> in Detail</h4><pre><code class=" mermaid">flowchart TD    A["开始推荐"] --&gt; B["创建物品缓存"]    B --&gt; C["并行处理每个用户&lt;br/&gt;p.Jobs 个并发"]    C --&gt; D{"是否需要更新推荐？"}    D --&gt;|"不活跃"| SKIP["跳过该用户"]    D --&gt;|"缓存未过期"| SKIP    D --&gt;|"冷启动用户"| SKIP    D --&gt;|"需要更新"| E    E["① 协同过滤推荐&lt;br/&gt;获取用户向量&lt;br/&gt;在物品向量索引中搜索 TopK&lt;br/&gt;写入 CollaborativeFiltering"]    E --&gt; F    subgraph Candidate["② 生成候选集"]        direction LR        F["调用多个 Recommender"]        F --&gt; F1["ItemBased"]        F --&gt; F2["UserBased"]        F --&gt; F3["Latest"]        F --&gt; F4["Popular"]        F --&gt; F5["Custom"]        F1 &amp; F2 &amp; F3 &amp; F4 &amp; F5 --&gt; F6["合并 · 去重"]    end    F6 --&gt; G["③ 过滤候选集&lt;br/&gt;过滤已删除物品&lt;br/&gt;过滤隐藏物品&lt;br/&gt;添加替换候选（用户历史）"]    G --&gt; H    subgraph Ranking["④ Ranking"]        direction LR        H{"排序方式"}        H --&gt; H1["FM 模型&lt;br/&gt;CTR 预测"]        H --&gt; H2["LLM 排序&lt;br/&gt;ChatGPT"]        H --&gt; H3["不排序&lt;br/&gt;使用召回分数"]    end    H1 &amp; H2 &amp; H3 --&gt; I["⑤ 应用替换衰减&lt;br/&gt;降低历史物品分数&lt;br/&gt;重新排序"]    I --&gt; J["⑥ 写入缓存&lt;br/&gt;cache.Recommend&lt;br/&gt;cache.RecommendUpdateTime&lt;br/&gt;cache.RecommendDigest"]    J --&gt; K["汇总所有用户"]    SKIP --&gt; K    K --&gt; L["上报 Metrics"]    L --&gt; M["结束"]</code></pre><div class="note note-info"><p>This is essentially the Pipeline section from earlier, expanded.</p></div><h4 id="Cache-Expiration-Strategy">Cache Expiration Strategy</h4><ol><li>Cache is empty</li><li>Configuration changed (digest mismatch)</li><li>Cache timed out (CacheExpire)</li><li>User has new behavior (activeTime &gt; recommendTime)</li></ol><h3 id="Load-Balancing-2">Load Balancing</h3><p>Consistent hashing for assigning users is implemented in the Worker architecture.</p><p>Specifically, when assigning users, the consistent hashing assignment method described above is used.</p><h3 id="Interactions-Among-the-Three-Architectures">Interactions Among the Three Architectures</h3><pre><code class=" mermaid">flowchart TD    M["Master&lt;br/&gt;训练模型&lt;br/&gt;保存模型到 Blob Store&lt;br/&gt;提供配置、模型版本、Worker 列表&lt;br/&gt;接收 Worker 进度上报"]    W["Worker&lt;br/&gt;同步配置和模型版本&lt;br/&gt;下载模型&lt;br/&gt;生成用户推荐&lt;br/&gt;写入 Cache Store"]    C["Cache Store&lt;br/&gt;cache.Recommend&lt;br/&gt;cache.CollaborativeFiltering&lt;br/&gt;cache.RecommendUpdateTime"]    S["Server&lt;br/&gt;提供推荐 API&lt;br/&gt;读取预计算推荐&lt;br/&gt;应用实时过滤和补充"]    U["Client / User"]    M --&gt;|"gRPC · GetMeta()"| W    W --&gt;|"gRPC · PushProgress()"| M    W --&gt;|"写入推荐结果"| C    C --&gt;|"读取推荐结果"| S    S --&gt;|"HTTP API"| U</code></pre><p>All interactions between the different architectures go through gRPC.</p><p>Workers and Servers <strong>do not communicate directly</strong>; they interact indirectly through the Cache Store.</p><h2 id="Interview-Oriented-Part">Interview-Oriented Part</h2><p>Based on the resume wording provided by the LLM, conduct adversarial deep-dive questioning, aiming to be fully prepared and not get stumped.</p><h3 id="Redis-Cache-Part">Redis / Cache Part</h3><p>Actually, Gorse does not specifically handle the so-called cache breakdown, cache penetration, and cache avalanche problems the way Heima Dianping does.</p><div class="note note-primary"><p>Which means, those cnblogs articles, and the parts of my notes based on them, are all nonsense,,,</p></div><p>But there's no way around it, so I gave the AI this prompt:</p><blockquote><p>However, I still need some Redis highlights, so here's what you should do next:</p><ol><li>Search the internet for relevant excellent blogs / materials that specifically analyze and summarize Gorse's excellent design highlights in Redis / cache handling; if any exist, use them as the highlights written in our blog</li><li>If nothing is found, summarize it yourself based on the source code.</li></ol></blockquote><p>Then with detailed explanation + summarization, this result was obtained:</p><blockquote><p><strong>Cache architecture:</strong> To address the high cost of computing recommendation results and the problem where traditional cache invalidation could transmit rebuild pressure to online requests, recommendation results are precomputed offline by the Worker and written to Redis, with logical invalidation and background refresh driven by user data update time, configuration digest, and cache expiration; combined with RediSearch to support filtering and sorting queries over recommendation results, balancing result freshness, computation cost, and online request latency.</p></blockquote><p>But honestly I didn't quite understand it either, so I had the LLM explain this wording to me in detail.</p><h4 id="First-Understand-the-Difference-Between-Recommendation-Data-and-Ordinary-Business-Data">First, Understand the Difference Between Recommendation Data and Ordinary Business Data</h4><p>For ordinary business data, such as a User ID:</p><ul><li>API query</li><li>If Redis misses, just query the database again</li></ul><p>But recommendation data requires complex ML computation. For this, Gorse's approach is to have a background Worker continuously compute recommendations and store them in Redis, and then the Server reads from Redis to serve user requests.</p><div class="note note-info"><p><strong>What is Cache Aside?</strong></p><p>Cache Aside (bypass cache) is the most common way of using "database + Redis".</p><p>The core logic is simple:</p><div class="code-wrapper"><pre><code class="hljs text">Read request:Client  ↓Check Redis first  ↓Hit → return directlyMiss  ↓Query MySQL  ↓Write the result into Redis  ↓Return</code></pre></div><p>Write requests are usually:</p><div class="code-wrapper"><pre><code class="hljs text">Update MySQL first  ↓Then delete the Redis cache</code></pre></div><p>Why is it called <strong>Aside</strong>? Because the cache is not inside the database, nor is it automatically maintained by the database; instead, <strong>the business code maintains Redis on the side itself</strong>.</p><p>For example, Heima Dianping querying a shop:</p><div class="code-wrapper"><pre><code class="hljs text">GET /shop/123   ↓Redis query shop:123   ↓Not found   ↓MySQL query shop(id=123)   ↓Write into Redis   ↓Return</code></pre></div><p>This is classic Cache Aside.</p><p>Gorse's recommendation cache is quite different from this. Your notes have actually already summarized this difference: an ordinary cache is closer to "a copy of database data", while Gorse's recommendation list is <strong>derived data</strong> obtained after recommendation computation.</p><p>So Gorse cannot simply do:</p><div class="code-wrapper"><pre><code class="hljs text">Redis miss→ SELECT MySQL→ Backfill Redis</code></pre></div><p>It's more like:</p><div class="code-wrapper"><pre><code class="hljs text">DataStore  ↓Recommendation computation  ↓Worker  ↓CacheStore / Redis</code></pre></div><p>This is also why Gorse's design approach to cache breakdown and avalanche differs a lot from typical Cache Aside systems like "Heima Dianping".</p></div><h4 id="The-Cache-Breakdown-Problem">The Cache Breakdown Problem</h4><p>Generally speaking, in projects using Redis like Heima Dianping, the cache breakdown problem is: after a hot key expires, all requests miss Redis and hit the database, causing a breakdown.</p><p>But for Gorse, after recommendation results become invalid, the Worker is not forced to recompute immediately; instead, the Server first returns the Fallback result, and the Worker recomputes in the background.</p><div class="note note-info"><p>Gorse does not use the traditional "mutex lock to prevent breakdown", but rather <strong>offline precomputation + background refresh</strong>, reducing the breakdown problem at the architectural level.</p></div><p>But how does the Worker know whether this cache should be recomputed? It is not triggered after the TTL of some Redis key expires.</p><p>In the Gorse source code, there is a <code>checkRecommendCacheOutOfDate()</code> function, which roughly checks logic like this:</p><ul><li>Whether the recommendation list is empty</li><li>Whether the user's configuration has changed<ul><li>Referring to whether the requested user has recently produced new behavior, e.g. new <code>click / like / favorite</code></li></ul></li><li>Whether the time since the last recommendation computation has exceeded CacheExpire</li><li>Whether the digest of the recommendation configuration has changed<ul><li>The digest can be understood as the result of applying a hash function to the recommendation system's configuration</li><li>The recommendation system's configuration means things like <code>cache_size</code></li></ul></li></ul><h4 id="RediSearch-Related">RediSearch-Related</h4><p>So-called RediSearch: builds indexes over Redis Hash / JSON, supporting conditional filtering, sorting, full-text search, vector similarity, etc.</p><p>Its application in Gorse: a recommendation result is a document-like structure, containing things like:</p><div class="code-wrapper"><pre><code class="hljs text">collectionsubsetidscoreis_hiddencategoriestimestamp</code></pre></div><p>After establishing the User Key -&gt; its K-V structure, a RediSearch index is created.</p><p>This way, when querying, you can filter with conditions like <code>userid=123 &amp;&amp; category = tech</code> + sort by <code>score</code> descending and take the Top 20, which native Redis cannot do.</p><h4 id="Balancing-Result-Freshness-Computation-Cost-and-Online-Request-Latency">Balancing Result Freshness, Computation Cost, and Online Request Latency</h4><ul><li>Requiring results to always be the freshest: enormous computation cost</li><li>Low computation cost: results are not fresh</li><li>Online real-time computation: high request latency</li></ul><h3 id="Vector-Recall">Vector Recall</h3><p>Original resume text:</p><blockquote><p>Vector recall: to address the problem that large-scale items cannot have their relevance computed one by one within online requests, unstructured features such as text are encoded into embeddings, and vector similarity retrieval is used to quickly recall semantically relevant candidate items, which are then passed to the subsequent ranking pipeline to generate the final result, so that vector retrieval is responsible for narrowing the candidate space rather than directly bearing the full recommendation decision.</p></blockquote><p>What an Embedding is, I actually do know: it converts features into a high-dimensional vector.</p><p>So-called "recall": quickly find some similar items from a massive number of items based on Embedding similarity, forming a candidate set; subsequent computation is then performed on the relatively small candidate set.</p><p>The part about quickly finding similar items is done using a <strong>vector database</strong>.</p><p>The plain-language version of that resume part: there are too many items to take them all out and rank them every time; so first convert item content into vectors, use vector similarity to quickly filter out a small batch of possibly relevant content, and then do fine-grained ranking.</p><h2 id="The-Grilling-Part">The Grilling Part</h2><p>I used this prompt:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 12966 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">You are a technical interviewer responsible for backend development inte...</span></summary><blockquote><p>You are a technical interviewer responsible for <strong>backend development internship / campus recruitment interviews</strong>.</p><p>I will give you:</p><ul><li>My resume project descriptions;</li><li>Necessary project background;</li><li>Some project knowledge I may have organized in advance.</li></ul><p>Your task is not to give me questions, but to conduct a <strong>project deep-dive / resume grilling</strong> that is as close as possible to a real backend technical interview.</p><hr><p>I. The Most Important Principle</p><ol><li>You cannot see my code</li></ol><p>You must always assume:</p><p><strong>The interviewer only has my resume, and the information I tell you verbally during the interview.</strong></p><p>Therefore, it is forbidden to ask questions targeting code details just because the background material I gave you contains code.</p><p>Forbidden:</p><ul><li>Asking how a certain function, class, or variable is written;</li><li>Asking why a certain line of code is written that way;</li><li>Asking about the implementation of a certain source file;</li><li>Pretending the interviewer already knows these implementations based on the code content I provided to the AI.</li></ul><p>However, follow-up questions about implementation mechanisms that a candidate should be able to explain in a normal interview are allowed, for example:</p><ul><li>How data flows;</li><li>Why the Redis keys / data structures are designed this way;</li><li>How MQ messages are produced and consumed;</li><li>How idempotency is guaranteed;</li><li>How cache and database stay consistent;</li><li>How concurrency issues are handled;</li><li>Which modules a request passes through;</li><li>Why a certain solution adopted this implementation.</li></ul><p>Judgment criterion:</p><blockquote><p>Would a real interviewer, based only on the resume and the candidate's verbal account, have reason to ask this question?</p></blockquote><p>If not, don't ask it.</p><hr><p>II. Ask Only One Question at a Time</p><p>Strictly simulate a real interview.</p><p>Each round, ask only <strong>one main question</strong>.</p><p>Do not output at once:</p><blockquote><ol><li>Why use Redis?</li><li>How is the TTL set?</li><li>How is consistency guaranteed?</li><li>What if Redis goes down?</li></ol></blockquote><p>The correct way is:</p><blockquote><p>Why did you choose to use Redis here?</p></blockquote><p>Then wait for my answer.</p><p>If I answer:</p><blockquote><p>Because database queries are relatively slow, we cached the recommendation results in Redis.</p></blockquote><p>The next question should prioritize the follow-up:</p><blockquote><p>Then when does this cache expire? How did you think about the TTL?</p></blockquote><p>Then continue following up based on my answers.</p><hr><p>III. Prioritize Follow-ups, Not Switching Topics</p><p>This is the most important rule of the whole interview.</p><p>Every time I answer, you first judge:</p><blockquote><p><strong>Is there anything in this statement worth following up on?</strong></p></blockquote><p>If there is, in principle <strong>prioritize the follow-up</strong>; don't switch topics immediately.</p><p>A single technical point can be followed up <strong>3–5 layers deep, more if necessary</strong>.</p><p>For example:</p><p>Me:</p><blockquote><p>To reduce database pressure, we use Redis to cache recommendation results.</p></blockquote><p>You:</p><blockquote><p>Why is this scenario suitable for caching?</p></blockquote><p>After I answer:</p><blockquote><p>Then how is the cache invalidation strategy designed?</p></blockquote><p>Continue:</p><blockquote><p>When updating recommendation results, how do you handle the database and the cache?</p></blockquote><p>Continue:</p><blockquote><p>What if the database update succeeds but the cache update fails?</p></blockquote><p>Continue:</p><blockquote><p>Then why do you accept eventual consistency in that case, rather than strong consistency?</p></blockquote><p>This is what a normal project deep-dive looks like.</p><hr><p>IV. Sources of Follow-ups</p><p>Prioritize finding points to dig deeper from my previous sentence.</p><p>Focus on:</p><h3 id="Technical-Terms">Technical Terms</h3><p>If I proactively mention:</p><ul><li>Redis</li><li>MySQL</li><li>PostgreSQL</li><li>Kafka / RocketMQ</li><li>gRPC</li><li>RPC</li><li>Distributed locks</li><li>Consistent hashing</li><li>Bloom Filter</li><li>goroutine</li><li>channel</li><li>Elasticsearch</li><li>Docker</li></ul><p>These words can all become entry points for new follow-ups.</p><p>But don't suddenly turn away from the project into a rote-recitation exam.</p><p>For example, if I say:</p><blockquote><p>Use Redis to cache user recommendation results.</p></blockquote><p>You can ask:</p><blockquote><p>Why choose Redis here?</p></blockquote><p>You should not suddenly ask:</p><blockquote><p>What are Redis's five basic data structures?</p></blockquote><p>Unless the question is genuinely relevant to the current discussion.</p><hr><p>My Cause-and-Effect Claims</p><p>If I say:</p><blockquote><p>Because of A, we use B.</p></blockquote><p>Prioritize attacking this causal relationship:</p><ul><li>Why does A lead to B?</li><li>What happens if you don't use B?</li><li>Is B really the most suitable way to solve this problem?</li><li>Are there other solutions?</li><li>Why weren't other solutions chosen?</li></ul><hr><p>My Technical Decisions</p><p>If I say:</p><blockquote><p>We use a message queue for asynchronous updates.</p></blockquote><p>You can continue:</p><blockquote><p>Why is asynchrony needed here?</p></blockquote><p>Then:</p><blockquote><p>If you don't use MQ, what's wrong with direct synchronous calls?</p></blockquote><p>Then:</p><blockquote><p>What if the message is sent successfully but consumption fails?</p></blockquote><p>Then:</p><blockquote><p>Won't retries cause duplicate consumption?</p></blockquote><p>Then:</p><blockquote><p>Then how does your consumer guarantee idempotency?</p></blockquote><hr><p>My Metrics</p><p>If I say:</p><blockquote><p>Performance improved by 50%.</p></blockquote><p>You must consider following up:</p><blockquote><p>How was this 50% measured?</p></blockquote><p>If I say:</p><blockquote><p>It can support high concurrency.</p></blockquote><p>You can follow up:</p><blockquote><p>What is roughly the QPS you actually tested?</p></blockquote><p>If the numbers sound suspicious, keep asking.</p><p>Do not default to accepting the numbers on the resume.</p><hr><p>My Vague Expressions</p><p>For example:</p><blockquote><p>Did some optimizations.</p></blockquote><p>Ask immediately:</p><blockquote><p>What specifically was optimized?</p></blockquote><p>Or:</p><blockquote><p>Improved system stability.</p></blockquote><p>Follow up:</p><blockquote><p>What problems specifically occurred before, and what changed after you finished?</p></blockquote><hr><p>V. Allow Natural Extension from the Project to Rote Fundamentals</p><p>You may test computer science fundamentals, but there must be a natural path:</p><p><strong>Project → Technology → Principle</strong></p><p>For example:</p><p>The project uses Redis</p><p>→ Why use Redis</p><p>→ Why is Redis fast</p><p>→ Memory access / IO multiplexing / data structures</p><p>This is reasonable.</p><p>Not:</p><p>The project uses Redis</p><p>→ What are TCP's four-way handshake waves?</p><p>This kind of jump should not appear.</p><p>Likewise:</p><p>MQ</p><p>→ Duplicate consumption</p><p>→ Idempotency</p><p>→ Database unique index / Redis / state machine</p><p>Reasonable.</p><p>MySQL</p><p>→ Slow queries</p><p>→ Indexes</p><p>→ B+ trees</p><p>Reasonable.</p><hr><p>VI. Answers Must Fit a Real Interview</p><p>My target answer time for each question is:</p><p><strong>30–60 seconds.</strong></p><p>Therefore, when evaluating answers, don't just judge "whether the knowledge is correct"; also judge:</p><ul><li>Whether it can be finished within 30–60 seconds;</li><li>Whether it grabs the key points;</li><li>Whether it answers the question right away;</li><li>Whether it covers too much irrelevant background;</li><li>Whether it piles up technical jargon;</li><li>Whether it sounds like reciting a blog;</li><li>Whether the interviewer can naturally understand it.</li></ul><p>Do not require me to give textbook-style complete answers.</p><p>The fact that a knowledge point could theoretically be explained in five minutes does not mean it should take five minutes in an interview.</p><p>Prioritize training:</p><blockquote><p><strong>Answer the core question in 30–60 seconds first, and leave the remaining details for the interviewer's follow-ups.</strong></p></blockquote><p>If my answer is clearly too long, note it down, but during the real interview do not immediately launch into a long lecture.</p><p>You can briefly remind:</p><blockquote><p>This answer is a bit long; in a real interview I'd suggest compressing it to under a minute.</p></blockquote><p>Then continue the interview.</p><hr><p>VII. Do Not Proactively Complete My Answers</p><p>If my answer has gaps, do not immediately tell me the standard answer.</p><p>For example:</p><p>Me:</p><blockquote><p>MQ can serve to smooth out traffic peaks.</p></blockquote><p>Do not immediately reply:</p><blockquote><p>Right, and besides that there's decoupling, asynchrony...</p></blockquote><p>Instead, keep asking:</p><blockquote><p>Why can it smooth peaks?</p></blockquote><p>Or:</p><blockquote><p>But peak traffic still has to be processed by consumers in the end — what problem does MQ actually solve?</p></blockquote><p>What I want to train is being pressed by an interviewer, not having the AI lecture me.</p><hr><p>VIII. Proactively Look for "Attackable Points"</p><p>Every answer of mine may contain:</p><ul><li>Vague statements;</li><li>Missing data;</li><li>Insufficient causality;</li><li>Unclear technical choices;</li><li>Knowing conclusions but not reasons;</li><li>Things not actually done in the project;</li><li>Only having watched tutorials;</li><li>Over-packaged resume claims.</li></ul><p>Upon discovering these, prioritize continuing to press.</p><p>For example:</p><p>Me:</p><blockquote><p>To ensure high availability, we use Redis.</p></blockquote><p>You can immediately follow up:</p><blockquote><p>What if Redis itself goes down? What does "high availability" specifically mean here?</p></blockquote><hr><p>IX. Scenario-Change Follow-ups</p><p>When a technical point has been fully explained, you may appropriately change constraints and keep pressing.</p><p>Common approaches in real backend interviews include:</p><p>Traffic changes</p><blockquote><p>What if QPS grows 10x?</p></blockquote><p>Component failure</p><blockquote><p>What happens to the system after Redis goes down?</p></blockquote><p>Network anomalies</p><blockquote><p>What if the MQ Broker is briefly unavailable?</p></blockquote><p>Data anomalies</p><blockquote><p>What if messages are duplicated?</p></blockquote><p>Latency anomalies</p><blockquote><p>The API used to take 50ms and suddenly takes 2s — how do you troubleshoot?</p></blockquote><p>Capacity changes</p><blockquote><p>What if the data volume grows 100x?</p></blockquote><p>Counterfactuals</p><blockquote><p>If you were to redesign it, would you still do it this way?</p></blockquote><p>But do not forcibly add ultra-large-scale scenarios unrelated to the project just to create difficulty.</p><hr><p>X. Project Ownership</p><p>The key judgment:</p><blockquote><p><strong>Is this project something I truly understand and actually participated in?</strong></p></blockquote><p>Therefore you should often ask:</p><ul><li>Why was this module designed this way?</li><li>What was the initial symptom of this problem?</li><li>How did you locate it at the time?</li><li>Why was this solution ultimately adopted?</li><li>Did you try other methods along the way?</li><li>What was the biggest problem?</li><li>If you did it again, what would you change?</li></ul><p>For personal projects, do not force questions like:</p><blockquote><p>How did your team divide the work?</p></blockquote><p>Instead ask:</p><blockquote><p>Which part did you focus on modifying or researching in depth?</p></blockquote><hr><p>XI. Do Not Obsess Over "Production Experience"</p><p>If I am an internship / campus recruitment candidate, especially if the project is a personal or open-source project:</p><p>Do not force me to fabricate:</p><ul><li>Millions of QPS;</li><li>Real production incidents;</li><li>Large-scale online users;</li><li>Company-level SLAs.</li></ul><p>If there is no real production data, you can ask:</p><blockquote><p>Have you done load testing?</p></blockquote><blockquote><p>If it hasn't launched, how do you judge that this design can solve the problem?</p></blockquote><blockquote><p>Has the benefit of this optimization been verified through benchmarks or experiments?</p></blockquote><p>Focus on judging engineering thinking, not forcing the candidate to make up data.</p><hr><p>XII. Question Difficulty</p><p>Target position:</p><p><strong>Backend development internship / campus recruitment.</strong></p><p>Questions should be close to a real first / second round.</p><p>Focus:</p><ul><li>Project understanding;</li><li>Backend fundamentals;</li><li>Technical choices;</li><li>Databases;</li><li>Redis;</li><li>MQ;</li><li>Concurrency;</li><li>Networking;</li><li>Distributed fundamentals;</li><li>Performance and reliability;</li><li>Scenario design.</li></ul><p>Do not default to senior backend engineer / architect standards.</p><p>However, if I proactively wrote an advanced concept on my resume, you may press hard on that concept.</p><p>Principle:</p><blockquote><p><strong>The deeper something is written on the resume, the more justified the interviewer is in asking deeply about it.</strong></p></blockquote><hr><p>XIII. Maintain a "Follow-up Tree"</p><p>During the interview, you internally maintain a follow-up tree.</p><p>For example:</p><p>Redis caching recommendation results├─ Why cache├─ Key / Value├─ TTL├─ Update strategy│ ├─ Cache Aside│ ├─ DB update failure│ └─ Cache deletion failure├─ Cache breakdown├─ Redis failure└─ 10x traffic</p><p>As long as the current branch still has obvious value, prioritize continuing along the current branch.</p><p>Only switch when:</p><ol><li>The current knowledge point has been confirmed as mastered;</li><li>I clearly don't know it;</li><li>The follow-ups have already gone deep enough;</li><li>Continuing would clearly exceed internship / campus recruitment requirements;</li><li>The current question has started to drift away from the project.</li></ol><p>Then return to important branches not yet explored.</p><hr><p>XIV. Real Interview Mode</p><p>Under normal circumstances, do not output:</p><ul><li>Standard answers;</li><li>Long commentary;</li><li>Why the next question is asked that way;</li><li>Current scoring;</li><li>The complete follow-up tree;</li><li>Teaching content.</li></ul><p>Your normal output should be very close to a real interviewer:</p><blockquote><p>Why choose a message queue here instead of direct synchronous calls?</p></blockquote><p>Then just wait for my answer.</p><hr><p>XV. Review Mode</p><p>Only when I type:</p><p><strong>Review</strong></p><p>do you pause the interview.</p><p>At that point, output:</p><ol><li>Overall evaluation of this round</li></ol><p>Evaluated against real backend internship / campus recruitment standards.</p><ol start="2"><li>Question-by-question review</li></ol><p>For important questions, give:</p><ul><li>What was good about my answer;</li><li>What was problematic;</li><li>Where the interviewer might attack next.</li></ul><ol start="3"><li>30–60 second reference answers</li></ol><p>For core questions I answered poorly, give:</p><p><strong>A 30–60 second answer suitable for speaking aloud in a real interview.</strong></p><p>Do not write it as a long tutorial.</p><ol start="4"><li>Knowledge status</li></ol><p>Divided into:</p><ul><li>Fairly solid;</li><li>Can answer but easily broken by follow-ups;</li><li>Clearly doesn't know it;</li><li>Needs project facts added.</li></ul><ol start="5"><li>Resume risks</li></ol><p>Point out:</p><ul><li>Which sentence is easy to grill;</li><li>Which sentence is exaggerated;</li><li>Which sentence lacks metrics;</li><li>Which sentence I actually cannot explain clearly.</li></ul><ol start="6"><li>Focus for the next round</li></ol><p>List the 3–5 follow-up chains most worth practicing next round.</p><hr><p>XVI. How to Start</p><p>After receiving my project materials:</p><p>First understand the project, but do not treat all the material I provided to the AI as "information the interviewer already knows".</p><p>A real interviewer initially only knows:</p><p><strong>What is actually written on my resume.</strong></p><p>Other materials are only used for you to judge whether my answers are reasonable and to design subsequent follow-ups.</p><p>Then start directly:</p><blockquote><p>Please briefly introduce this project first, focusing on what problem it solves and what you mainly did.</p></blockquote><p>From then on, enter real interview mode.</p><p>Ask only one question at a time.</p></blockquote></details><h3 id="Some-Interview-Questions">Some Interview Questions</h3><blockquote><p>Understood. Let me rephrase: since the algorithms themselves weren't designed by you, why do you still need to split the whole recommendation service into three types of nodes — Master, Worker, and Server? What engineering problems is this architecture mainly solving?</p></blockquote><p>Splitting it apart solves the problem that recommendation computation and online requests have different latency requirements.</p><ul><li>Recommendation computation is heavy and can be executed offline</li><li>Online APIs require fast responses and as much stability as possible</li></ul><p>Therefore, this way the responsibilities are decoupled, each does its own job, scaling each node is convenient, and it also prevents one service's bottleneck from dragging down another service.</p><blockquote><p>If the same user's recommendation cache has already expired, and many Server requests come in simultaneously within a short time, all of these requests find no usable result in Redis and then all go notify the Master. How do you avoid the same user's recommendation task being scheduled repeatedly and multiple Workers computing it redundantly?</p></blockquote><p>The solution to this is actually quite simple: the architecture is that the Worker periodically generates offline recommendations for all users, and the Server only reads the cache and Fallback results. There is no logic where the Server notifies the Master to schedule a recompute after a cache miss.</p>]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab9 mmap - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab9-mmap/</link>
      <description>The ninth lab of xv6, implementing the mmap mechanism. It is quite comprehensive, combining the page table mechanism with the file system.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Tue, 18 Aug 2026 16:45:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab9-mmap/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><div class="note note-primary"><p>Feels like the hardest lab... at least the one with the largest amount of code.</p></div><p>My implementation:</p><p><a href="https://github.com/wendaining/xv6-lab-2025/tree/mmap">wendaining/xv6-lab-2025 at mmap</a></p><h2 id="Reading">Reading</h2><p>In fact, this is exactly the content covered in the section <a href="https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/lec08-page-faults-frans/8.1-page-fault-basics">8.1 Page Fault Basics | MIT6.S081</a> mentioned in Lab5 COW (a single subsection). So there isn't much to read; it's just a mechanism.</p><p>The core idea of memory mapped files is to load the complete or partial file into memory, so that the file can be manipulated directly using memory <code>load</code> <code>store</code> operations, reducing disk I/O.</p><p>The interfaces to implement (from <code>man 2 mmap</code>):</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span> *<span class="hljs-title function_">mmap</span><span class="hljs-params">(<span class="hljs-type">void</span> *addr, <span class="hljs-type">size_t</span> len, <span class="hljs-type">int</span> prot, <span class="hljs-type">int</span> flags,</span><span class="hljs-params">           <span class="hljs-type">int</span> fd, <span class="hljs-type">off_t</span> offset)</span>;           <span class="hljs-type">int</span> <span class="hljs-title function_">munmap</span><span class="hljs-params">(<span class="hljs-type">void</span> *addr, <span class="hljs-type">size_t</span> len)</span>;</code></pre></div><p>This lab does not require fully implementing the POSIX specification; you can make the following simplifying assumptions:</p><p>For <code>mmap()</code>:</p><ul><li><p><code>addr</code> is always <code>0</code>, meaning the kernel decides which virtual address to map to.</p></li><li><p><code>mmap</code> returns the mapped address on success, and <code>0xffffffffffffffff</code> on failure.</p></li><li><p><code>len</code> is the number of bytes to map; it may differ from the file length.</p></li><li><p><code>prot</code> indicates whether this memory region is readable, writable, and/or executable. In this Lab you only need to handle <code>PROT_READ</code>, <code>PROT_WRITE</code>, or a combination of both.</p></li><li><p><code>flags</code> will only be <code>MAP_SHARED</code> or <code>MAP_PRIVATE</code>.</p></li><li><p><code>MAP_SHARED</code> means modifications to the mapped memory should be written back to the file.</p></li><li><p><code>MAP_PRIVATE</code> means modifications should not be written back to the file.</p></li><li><p><code>fd</code> is an already-opened file descriptor of the file to be mapped.</p></li><li><p><code>offset</code> can be assumed to always be <code>0</code>, i.e., mapping always starts from the beginning of the file.</p></li><li><p>Regarding <strong>lazy allocation</strong>: this lab uses the <strong>lazy allocation mode</strong>. That is, <code>mmap()</code> itself should not allocate physical memory, nor should it read the file. Only when a page fault occurs should the actual allocation and file reading be done in <code>usertrap()</code> or the page fault handling code it calls.</p><div class="note note-info"><p><strong>Recall the cow lab</strong></p></div></li><li><p>If two processes map the same <code>MAP_SHARED</code> file, this Lab allows them to <strong>not share the same physical page</strong>.</p></li></ul><p>About <code>munmap()</code>:</p><ul><li>Remove the mmap mapping within the specified range.</li><li>If the process has already modified this memory, and it corresponds to a <code>MAP_SHARED</code> mapping, then the modifications should be written back to the file before unmapping.</li><li>In principle it might be possible to unmap only part of an entire mmap mapping (punching a hole in the middle) (recall splitting super pages), but in this lab it's either the beginning, the end, or the whole thing — never only the middle.</li></ul><h2 id="Implementation">Implementation</h2><p>Still using the hints as the guide.</p><h3 id="Setting-up-the-system-call">Setting up the system call</h3><p>The same old routine.</p><h3 id="Recording-mmap-regions-per-process">Recording mmap regions per process</h3><p>Create a per-process <code>struct vma</code>, i.e., Virtual Memory Area, which records the virtual address range information created by <code>mmap()</code>.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/proc.h</span><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> {</span>  <span class="hljs-type">int</span> valid;  uint64 addr;  uint64 len;  uint64 offset;  <span class="hljs-type">int</span> prot;  <span class="hljs-type">int</span> flags;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span>;</span>};</code></pre></div><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 908 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">offset and len do not use the same types as in the original signature. T...</span></summary><blockquote><p><code>offset</code> and <code>len</code> do not use the same types as in the original signature.</p><p>The reason is that <code>size_t</code> and <code>off_t</code> belong to the mmap interface types, which are currently defined in <code>defs.h</code>; but many source files include <code>proc.h</code> before <code>defs.h</code>, so when parsing <code>struct vma</code> they are not yet known.</p><p><code>uint64</code> is defined in the more fundamental <code>types.h</code>, and in xv6:</p><ul><li><code>size_t</code> is actually a 64-bit unsigned integer;</li><li>the <code>offset</code> in this lab is fixed at 0, so the signed semantics of <code>off_t</code> are not needed;</li><li>virtual addresses, lengths, and file offsets are themselves well suited to being stored as <code>uint64</code>.</li></ul><p>Therefore, the user interface and <code>sys_mmap()</code> parameters still follow the man page:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">size_t</span> len;<span class="hljs-type">off_t</span> offset;</code></pre></div><p>while the VMA is a kernel-internal data structure, so storing the converted values as <code>uint64</code> is fine. The two layers are not required to use exactly the same type names; the values just need to be represented correctly.</p></blockquote></details><p>Then, since the xv6 kernel has no variable-size kernel allocator, just declare a fixed-size (16) array of VMAs and allocate from it when needed.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/def.h</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> NVMA 16</span></code></pre></div><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/proc.c</span><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> <span class="hljs-title">vma</span>[<span class="hljs-title">NVMA</span>];</span></code></pre></div><h3 id="Implementing-mmap">Implementing <code>mmap()</code></h3><p>First you need to understand which parts of the virtual address space the mmap mapping region actually occupies:</p><p>The address space can be roughly understood as:</p><div class="code-wrapper"><pre><code class="hljs text">Low addresses┌──────────────────────┐│ Program code, data, heap │├──────────────────────┤ ← original p-&gt;sz┤│ Unused address space      │├──────────────────────┤ ← limit / TRAPFRAME│ TRAPFRAME            │├──────────────────────┤│ TRAMPOLINE           │└──────────────────────┘ ← MAXVAHigh addresses</code></pre></div><p>The mmap region must not cover the two special pages at the top.</p><p>At first (and as in the Zhihu article I read, <a href="https://www.zhihu.com/column/c_1633749695578210304">MIT XV6 操作系统 实验全解 - 知乎</a> ), the implementation was like this:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 69 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 69 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_mmap</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">void</span> *addr;  <span class="hljs-type">size_t</span> len;  <span class="hljs-type">int</span> prot, flags, fd;  <span class="hljs-type">off_t</span> offset;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span>;</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">proc</span> *<span class="hljs-title">p</span> =</span> myproc();  argaddr(<span class="hljs-number">0</span>, (uint64 *)&amp;addr);  argaddr(<span class="hljs-number">1</span>, &amp;len);  argint(<span class="hljs-number">2</span>, &amp;prot);  argint(<span class="hljs-number">3</span>, &amp;flags);  argaddr(<span class="hljs-number">5</span>, (uint64 *)&amp;offset);  <span class="hljs-comment">// This lab only supports kernel-selected addresses and mappings that</span>  <span class="hljs-comment">// start at the beginning of a regular file.</span>  <span class="hljs-keyword">if</span>(addr != <span class="hljs-number">0</span> || len == <span class="hljs-number">0</span> || offset != <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>((prot &amp; ~(PROT_READ | PROT_WRITE)) != <span class="hljs-number">0</span> ||     (prot &amp; (PROT_READ | PROT_WRITE)) == <span class="hljs-number">0</span>) {      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(flags != MAP_SHARED &amp;&amp; flags != MAP_PRIVATE) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// 将 fd 对应的文件对应到 struct file *f 上</span>  <span class="hljs-keyword">if</span>(argfd(<span class="hljs-number">4</span>, &amp;fd, &amp;f) &lt; <span class="hljs-number">0</span> || f-&gt;type != FD_INODE || !f-&gt;readable) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(flags == MAP_SHARED &amp;&amp; (prot &amp; PROT_WRITE) &amp;&amp; !f-&gt;writable) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// 为 mmap 选择一段虚拟地址进行映射，</span>  <span class="hljs-comment">// p-&gt;sz 是目前的进程能用到的最高的地址空间，将新映射放在它后面</span>  addr = (<span class="hljs-type">void</span> *)PGROUNDUP(p-&gt;sz);  uint64 limit = MAXVA - <span class="hljs-number">2</span> * PGSIZE;  <span class="hljs-comment">// leave TRAPFRAME/TRAMPOLINE untouched</span>  <span class="hljs-keyword">if</span>((uint64)addr &gt;= limit || len &gt; limit - (uint64)addr) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// 长度 round up 到最近的页面字节数</span>  <span class="hljs-type">size_t</span> maplen = PGROUNDUP(len);  <span class="hljs-type">int</span> idx;  <span class="hljs-keyword">for</span>(idx = <span class="hljs-number">0</span>; idx &lt; NVMA; idx++){    <span class="hljs-keyword">if</span>(!p-&gt;vma[idx].valid) {      <span class="hljs-keyword">break</span>;    }  }  <span class="hljs-keyword">if</span>(idx == NVMA) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">vma</span> =</span> &amp;p-&gt;vma[idx];  vma-&gt;valid = <span class="hljs-number">1</span>;  vma-&gt;addr = (uint64)addr;  vma-&gt;len = len;  vma-&gt;permissions = prot;  vma-&gt;offset = offset;  vma-&gt;prot = prot;  vma-&gt;flags = flags;  vma-&gt;f = filedup(f);  p-&gt;sz = (uint64)addr + maplen;  <span class="hljs-keyword">return</span> (uint64)addr;}</code></pre></div></details><p>If <code>vma</code> is allocated, following the author's implementation, upward from <code>p-&gt;sz</code>, the tests in the 2025 version of the lab (the author was on the Fall 2020 version) will not pass. The rough reasons are:</p><ul><li>Since <code>mmap</code> and <code>munmap</code> are triggered at different times and the current VMA lookup is by index allocation, in fact there is no positive correlation between each <code>vma</code>'s <code>addr</code> and its index, and in practice it is hard to manage <code>p-&gt;sz</code> — it can only grow and cannot shrink.</li><li>Then, suppose we <code>munmap</code> a certain <code>vma</code>; something like internal fragmentation is produced;</li><li>In the test data, if a page fault is triggered again in this already-<code>munmap</code>-ed region, since it satisfies <code>va &lt; p-&gt;sz</code> and is not within the range of any <code>vma</code>, it will be judged as a lazy allocation page produced by <code>sbrk()</code>, and an actual physical page frame will be allocated again;</li><li>But the test data is: after unmapping a page, read it again, expecting an illegal access that kills the process. This clearly fails here.</li></ul><p>So we should actually switch to a different way of allocating <code>vma</code>s. I thought of allocating <strong>in reverse</strong>, starting from <code>MAXVA - 2*PGSIZE</code>, i.e., two pages below the trampoline page.</p><p>Add a <code>uint64 mmap_top;</code> to <code>struct proc</code>, indicating the starting point of the next <code>vma</code> allocation. Since virtual addresses are nearly infinite, this has no impact on the OS.</p><div class="note note-info"><p>But actually I'm not so sure. Because VMAs keep being allocated, <code>p-&gt;mmaptop</code> only grows monotonically.</p><p>In Linux's implementation, the OS looks for free fragments. But implementing that here is indeed a bit troublesome.</p></div><p>So the rough implementation is like this:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 76 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 76 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_mmap</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">void</span> *addr;  <span class="hljs-type">size_t</span> len;  <span class="hljs-type">int</span> prot, flags, fd;  <span class="hljs-type">off_t</span> offset;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span>;</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">proc</span> *<span class="hljs-title">p</span> =</span> myproc();  argaddr(<span class="hljs-number">0</span>, (uint64 *)&amp;addr);  argaddr(<span class="hljs-number">1</span>, &amp;len);  argint(<span class="hljs-number">2</span>, &amp;prot);  argint(<span class="hljs-number">3</span>, &amp;flags);  argaddr(<span class="hljs-number">5</span>, (uint64 *)&amp;offset);  <span class="hljs-comment">// This lab only supports kernel-selected addresses and mappings that</span>  <span class="hljs-comment">// start at the beginning of a regular file.</span>  <span class="hljs-keyword">if</span>(addr != <span class="hljs-number">0</span> || len == <span class="hljs-number">0</span> || offset != <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>((prot &amp; ~(PROT_READ | PROT_WRITE)) != <span class="hljs-number">0</span> ||     (prot &amp; (PROT_READ | PROT_WRITE)) == <span class="hljs-number">0</span>) {      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(flags != MAP_SHARED &amp;&amp; flags != MAP_PRIVATE) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// 将 fd 对应的文件对应到 struct file *f 上</span>  <span class="hljs-keyword">if</span>(argfd(<span class="hljs-number">4</span>, &amp;fd, &amp;f) &lt; <span class="hljs-number">0</span> || f-&gt;type != FD_INODE || !f-&gt;readable) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(flags == MAP_SHARED &amp;&amp; (prot &amp; PROT_WRITE) &amp;&amp; !f-&gt;writable) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// 为了防止从 p-&gt;sz 开始分配，结果因为创建/销毁 vma 的顺序不同，导致 p-&gt;sz 没有可能正确回收的问题</span>  <span class="hljs-comment">// 不使用 p-&gt;sz 开始分配的方法，而是从顶上开始倒着分配</span>  <span class="hljs-comment">// 因为虚拟地址近乎是无穷大的，这样不会对 OS 产生影响</span>  <span class="hljs-comment">// #define MMAPTOP (MAXVA - 2 * PGSIZE)</span>  <span class="hljs-keyword">if</span>(len &gt; MMAPTOP) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-type">size_t</span> maplen = PGROUNDUP(len);  <span class="hljs-keyword">if</span>(maplen &gt; p-&gt;mmap_top) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  uint64 mapaddr = p-&gt;mmap_top - maplen;  <span class="hljs-keyword">if</span>(mapaddr &lt; PGROUNDUP(p-&gt;sz)) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  addr = (<span class="hljs-type">void</span> *)mapaddr;  <span class="hljs-type">int</span> idx;  <span class="hljs-keyword">for</span>(idx = <span class="hljs-number">0</span>; idx &lt; NVMA; idx++){    <span class="hljs-keyword">if</span>(!p-&gt;vma[idx].valid) {      <span class="hljs-keyword">break</span>;    }  }  <span class="hljs-keyword">if</span>(idx == NVMA) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">vma</span> =</span> &amp;p-&gt;vma[idx];  vma-&gt;valid = <span class="hljs-number">1</span>;  vma-&gt;addr = (uint64)addr;  vma-&gt;len = maplen;  vma-&gt;offset = offset;  vma-&gt;prot = prot;  vma-&gt;flags = flags;  vma-&gt;f = filedup(f);  p-&gt;mmap_top = (uint64)addr;  <span class="hljs-keyword">return</span> (uint64)addr;}</code></pre></div></details><p>Be sure to note that <code>mmap()</code> does not actually allocate pages; the actual allocation only happens when a page fault occurs.</p><p>Here it just records that this file (passed in via <code>fd</code>) should be mapped to this particular VMA.</p><h3 id="Handling-mmap-page-faults">Handling mmap page faults</h3><p>Add code so that when a page fault occurs in an mmap region:</p><ol><li>Allocate a physical page;</li><li>Read the relevant <code>PGSIZE</code> from the file into that page;</li><li>Map that page into the user address space.</li></ol><p>Use <code>readi()</code> to read the file.</p><div class="note note-warning"><p><code>readi()</code> works as follows: read a number of bytes starting at a specified offset from the file represented by a given inode, and copy them to a specified memory address.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span> <span class="hljs-title function_">readi</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> inode *ip, <span class="hljs-type">int</span> user_dst, uint64 dst, uint off, uint n)</span>;</code></pre></div><p>Parameter meanings:</p><ul><li><p>ip: the inode of the file to read, e.g., vma-&gt;f-&gt;ip.</p></li><li><p>user_dst: the type of the destination address.</p><ul><li>1: dst is a user virtual address.</li><li>0: dst is a kernel address.</li></ul></li><li><p>dst: where to copy the data.</p></li><li><p>off: which byte of the file to start reading from.</p></li><li><p>n: the maximum number of bytes to read.</p></li><li><p>Return value: the number of bytes actually read; may return -1 on failure.</p></li></ul><p>For example, <code> readi(ip, 0, (uint64)mem, 4096, 4096);</code></p><p>means reading 4096 bytes starting at file offset 4096 and writing them to the kernel address mem.</p></div><p>Based on the experience from the cow lab, the place to modify should be the <code>vmfault()</code> function.</p><p>Code:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 65 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 65 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">vmfault</span><span class="hljs-params">(<span class="hljs-type">pagetable_t</span> pagetable, uint64 va, <span class="hljs-type">int</span> read)</span>{  uint64 mem;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">proc</span> *<span class="hljs-title">p</span> =</span> myproc();  <span class="hljs-keyword">if</span>(va &gt;= MAXVA) {    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  va = PGROUNDDOWN(va);  <span class="hljs-keyword">if</span>(ismapped(pagetable, va)) {    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  <span class="hljs-type">int</span> index = ismmaped(p, va);  <span class="hljs-keyword">if</span>(index != <span class="hljs-number">-1</span>) {    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">vma</span> =</span> &amp;p-&gt;vma[index];    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span> =</span> vma-&gt;f-&gt;ip;    <span class="hljs-comment">// mem 是 kalloc() 返回的内核地址</span>    <span class="hljs-keyword">if</span>((mem = (uint64)kalloc()) == <span class="hljs-number">0</span>) {      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;    }    <span class="hljs-built_in">memset</span>((<span class="hljs-type">void</span> *)mem, <span class="hljs-number">0</span>, PGSIZE);    ilock(ip);    <span class="hljs-comment">// va - vma-&gt;addr = 当前产生 page fault 的页面与 vma 开始地址的距离</span>    <span class="hljs-comment">// 看似没保证页对齐，但是 vma-&gt;offset 永远是 0，而前两者已经页对齐，所以无妨</span>    uint64 fileoff = (va - vma-&gt;addr) + vma-&gt;offset;    <span class="hljs-keyword">if</span>(readi(ip, <span class="hljs-number">0</span>, mem, fileoff, PGSIZE) == <span class="hljs-number">-1</span>) {      iunlock(ip);      kfree((<span class="hljs-type">void</span> *)mem);      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;    }    <span class="hljs-type">int</span> flags = PTE_U;    <span class="hljs-keyword">if</span>(vma-&gt;prot &amp; PROT_READ) {      flags |= PTE_R;    }    <span class="hljs-keyword">if</span>(vma-&gt;prot &amp; PROT_WRITE) {      flags |= PTE_R | PTE_W;    }    <span class="hljs-keyword">if</span>(mappages(pagetable, va, PGSIZE, mem, flags) != <span class="hljs-number">0</span>) {      iunlock(ip);      kfree((<span class="hljs-type">void</span> *)mem);      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;    }    iunlock(ip);    <span class="hljs-keyword">return</span> mem;  }  <span class="hljs-comment">// Only addresses below p-&gt;sz belong to the ordinary lazy-allocation area.</span>  <span class="hljs-comment">// A high address removed by munmap must remain invalid.</span>  <span class="hljs-keyword">if</span>(va &gt;= p-&gt;sz) {    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  mem = (uint64) kalloc();  <span class="hljs-keyword">if</span>(mem == <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  <span class="hljs-built_in">memset</span>((<span class="hljs-type">void</span> *) mem, <span class="hljs-number">0</span>, PGSIZE);  <span class="hljs-keyword">if</span> (mappages(p-&gt;pagetable, va, PGSIZE, mem, PTE_W|PTE_U|PTE_R) != <span class="hljs-number">0</span>) {    kfree((<span class="hljs-type">void</span> *)mem);    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  <span class="hljs-keyword">return</span> mem;}</code></pre></div></details><p>The tricky part here is the <code>fileoff</code>, but it's really just computing an offset.</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1422 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">Assumptions vma-&gt;addr = 0x4000 vma-&gt;offset = 0 fault va = 0x6123 First a...</span></summary><blockquote><p>Assumptions</p><div class="code-wrapper"><pre><code class="hljs text">vma-&gt;addr   = 0x4000vma-&gt;offset = 0fault va    = 0x6123</code></pre></div><p>First align the fault address down to a page boundary:</p><div class="code-wrapper"><pre><code class="hljs text">va = PGROUNDDOWN(0x6123) = 0x6000</code></pre></div><p>Virtual address region:</p><div class="code-wrapper"><pre><code class="hljs text">VMA virtual address space0x4000              0x5000              0x6000              0x7000  │                   │                   │                   │  ▼                   ▼                   ▼                   ▼  ┌───────────────────┬───────────────────┬───────────────────┐  │ VMA page 0        │ VMA page 1        │ VMA page 2        │  └───────────────────┴───────────────────┴───────────────────┘                                            ▲                                            │                                    fault va = 0x6123                                    page = 0x6000</code></pre></div><p>Compute how far it is from the start of the VMA:</p><div class="code-wrapper"><pre><code class="hljs text">va - vma-&gt;addr= 0x6000 - 0x4000= 0x2000</code></pre></div><p>Therefore:</p><div class="code-wrapper"><pre><code class="hljs c">fileoff = (va - vma-&gt;addr) + vma-&gt;offset;</code></pre></div><p>We get:</p><div class="code-wrapper"><pre><code class="hljs text">fileoff = 0x2000 + 0 = 0x2000</code></pre></div><p>File contents:</p><div class="code-wrapper"><pre><code class="hljs text">File byte offsets0x0000              0x1000              0x2000              0x3000  │                   │                   │                   │  ▼                   ▼                   ▼                   ▼  ┌───────────────────┬───────────────────┬───────────────────┐  │ File page 0       │ File page 1       │ File page 2       │  └───────────────────┴───────────────────┴───────────────────┘                                            ▲                                            │                                      fileoff = 0x2000</code></pre></div><p>Final correspondence:</p><div class="code-wrapper"><pre><code class="hljs text">Virtual mmap region                    File0x4000  VMA page 0  ───────────────▶  offset 0x00000x5000  VMA page 1  ───────────────▶  offset 0x10000x6000  VMA page 2  ───────────────▶  offset 0x2000</code></pre></div><p>Therefore the following line:</p><div class="code-wrapper"><pre><code class="hljs c">readi(ip, <span class="hljs-number">0</span>, mem, fileoff, PGSIZE);</code></pre></div><p>means:</p><div class="code-wrapper"><pre><code class="hljs text">File [0x2000, 0x3000)          │          │ readi()          ▼Newly allocated physical page mem          │          │ mappages()          ▼User virtual address [0x6000, 0x7000)</code></pre></div><p>In one sentence: <code>fileoff</code> is used to determine "which page of the file corresponds to the virtual page where the page fault occurred."</p></blockquote></details><p>Also, pay attention to <code>flags</code>.</p><p>Additionally:</p><img src="https://image.wendaining.top/0f174ae0-f325-4fea-aae5-67ce6a1350f1.png" alt="The situation encountered in vm.c requires #include &quot;file.h&quot;" style="zoom:50%;"><h3 id="Implementing-munmap">Implementing <code>munmap()</code></h3><p>The hardest sub-problem.</p><p>The system call's function signature:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span> <span class="hljs-title function_">munmap</span><span class="hljs-params">(<span class="hljs-type">void</span> *addr, <span class="hljs-type">size_t</span> len)</span>;</code></pre></div><p>Both <code>addr</code> and <code>len</code> are virtual addresses (the VMA part of the virtual address space).</p><p>The key point is that there is no need to handle the partial hole-punching case. That is, you only need to consider situations like:</p><img src="https://image.wendaining.top/abd7009c41783e4f13f13a4a26a3e8df.jpg" style="zoom:50%;"><p>The spec is not very detailed, but I think it's fine to handle things across VMAs, and since VMAs are always allocated forward, it's like this:</p><img src="https://image.wendaining.top/3c4029fb0ec63906b2c81abe14dc14cc.jpg" style="zoom:50%;"><div class="note note-info"><p>This diagram is fairly clear: for a <code>vma</code>:</p><ul><li>the leftmost end is <code>vma-&gt;addr</code></li><li>the length of the whole segment is <code>vma-&gt;len</code></li><li>the rest doesn't matter; <code>offset</code> is assumed to be <code>0</code> throughout this problem</li></ul></div><p>Such a situation is only possible.</p><p>So I considered: starting from <code>addr</code>, compute the byte-range window that needs to be freed, then shrink the window while freeing; in each loop iteration, scan all <code>vma</code>s and make the judgment based on where <code>addr</code> falls. (But each round only handles one; once scanned and matched, handle it.)</p><p>After that, through repeated comparisons, determine which case it is (head or tail), and then determine the specific range that needs to be handled.</p><p>Then, within this range, process page by page:</p><ul><li><p>If <code>vma-&gt;flags == MAP_SHARED</code>, then a write-back operation is needed</p><ul><li><p>Compute <code>fileoff</code>, i.e., the offset within the file. Since we are writing back to the file, but the adjustment inside the file is done via the offset in the <code>inode</code> structure, it needs to be specified manually here</p><div class="note note-info"><p>Why can't it be fully handled? Because unmapping can unmap only part of the region.</p></div></li><li><p>Write back to the file; how much to write is also a question. By default, we write one page at a time (since we process page by page). But sometimes the end may have less than a full page, in which case <code>write_len</code> becomes the remaining length at the end.</p><div class="note note-warning"><p>The above part needs to obtain <code>ip-&gt;size</code>; even reading requires taking the inode lock.</p></div></li><li><p>Finally, write back. The spec says to refer to <code>filewrite()</code>, but there's a problem here, because <code>filewrite()</code>'s in-file offset cannot be specified by yourself. See the section below for details; in short, write a <code>filewriteat()</code> helper function that allows specifying the offset.</p></li><li><p>Finally, if exactly an entire <code>vma</code> was freed, then the file's ref count also needs to be decremented (<code>fileclose(f)</code>), and this <code>vma</code> cleared.</p></li></ul></li><li><p>Finally, remember to update the window.</p></li></ul><p>The core logic — since you'll find that the later modification to <code>kexit()</code> needs to do the same thing as <code>munmap()</code> — is extracted into a function taking parameters, placed in <code>vm.c</code>.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/sysfile.c</span>uint64<span class="hljs-title function_">sys_munmap</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  uint64 addr;  <span class="hljs-type">size_t</span> len;  argaddr(<span class="hljs-number">0</span>, &amp;addr);  argaddr(<span class="hljs-number">1</span>, &amp;len);  <span class="hljs-keyword">return</span> vmaunmap(myproc(), addr, len);}</code></pre></div><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 80 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 80 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/vm.c</span><span class="hljs-type">int</span><span class="hljs-title function_">vmaunmap</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> proc *p, uint64 addr, uint64 len)</span>{  addr = PGROUNDDOWN(addr);  len = PGROUNDUP(len);  <span class="hljs-keyword">if</span>(len == <span class="hljs-number">0</span> || addr + len &lt; addr) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">while</span>(len &gt; <span class="hljs-number">0</span>) {    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">vma</span> =</span> <span class="hljs-number">0</span>;    <span class="hljs-comment">// Re-scan because VMA slot order need not match virtual-address order.</span>    <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> idx = <span class="hljs-number">0</span>; idx &lt; NVMA; idx++) {      <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">cand</span> =</span> &amp;p-&gt;vma[idx];      <span class="hljs-keyword">if</span>(cand-&gt;valid &amp;&amp; addr &gt;= cand-&gt;addr &amp;&amp;         addr - cand-&gt;addr &lt; cand-&gt;len) {        vma = cand;        <span class="hljs-keyword">break</span>;      }    }    <span class="hljs-keyword">if</span>(vma == <span class="hljs-number">0</span>) {      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span> =</span> vma-&gt;f;    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span> =</span> f-&gt;ip;    uint64 vma_end = vma-&gt;addr + vma-&gt;len;    uint64 unmap_end = addr + len;    uint64 free_end = unmap_end &lt; vma_end ? unmap_end : vma_end;    uint64 free_len = free_end - addr;    <span class="hljs-keyword">for</span>(uint64 pageva = addr; pageva &lt; free_end; pageva += PGSIZE) {      <span class="hljs-type">pte_t</span> *pte = walk(p-&gt;pagetable, pageva, <span class="hljs-number">0</span>);      <span class="hljs-keyword">if</span>(pte == <span class="hljs-number">0</span> || (*pte &amp; PTE_V) == <span class="hljs-number">0</span>) {        <span class="hljs-keyword">continue</span>;      }      <span class="hljs-keyword">if</span>(vma-&gt;flags == MAP_SHARED &amp;&amp; (vma-&gt;prot &amp; PROT_WRITE)) {        uint64 pa = PTE2PA(*pte);        uint64 fileoff = vma-&gt;offset + (pageva - vma-&gt;addr);        uint write_len = PGSIZE;        ilock(ip);        <span class="hljs-keyword">if</span>(fileoff &gt;= ip-&gt;size) {          write_len = <span class="hljs-number">0</span>;        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(write_len &gt; ip-&gt;size - fileoff) {          write_len = ip-&gt;size - fileoff;        }        iunlock(ip);        <span class="hljs-keyword">if</span>(write_len &gt; <span class="hljs-number">0</span> &amp;&amp;           filewriteat(f, <span class="hljs-number">0</span>, pa, fileoff, write_len) != write_len) {          <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;        }      }      uvmunmap(p-&gt;pagetable, pageva, <span class="hljs-number">1</span>, <span class="hljs-number">1</span>);    }    <span class="hljs-keyword">if</span>(addr == vma-&gt;addr &amp;&amp; free_end == vma_end) {      fileclose(f);      <span class="hljs-built_in">memset</span>(vma, <span class="hljs-number">0</span>, <span class="hljs-keyword">sizeof</span>(*vma));    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(addr == vma-&gt;addr) {      vma-&gt;addr += free_len;      vma-&gt;len -= free_len;      vma-&gt;offset += free_len;    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span>(free_end == vma_end) {      vma-&gt;len -= free_len;    } <span class="hljs-keyword">else</span> {      panic(<span class="hljs-string">"vmaunmap: hole"</span>);    }    addr = free_end;    len -= free_len;  }  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;}</code></pre></div></details><h4 id="Why-filewriteat-is-needed">Why <code>filewriteat()</code> is needed</h4><p>There are two main problems here: the <strong>in-file offset</strong> and the <strong>type of the source address</strong>.</p><p>First look at the most critical part of <code>filewrite()</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">if</span> ((r = writei(f-&gt;ip, <span class="hljs-number">1</span>, addr + i, f-&gt;off, n1)) &gt; <span class="hljs-number">0</span>) {  f-&gt;off += r;}</code></pre></div><p><code>filewrite()</code> does not take a file offset parameter; it uses the <code>f-&gt;off</code> inside <code>struct file</code>. Each time a chunk of data is written, it also automatically advances <code>f-&gt;off</code>. This is correct for ordinary <code>write()</code>, since ordinary file reads and writes inherently need to maintain a current read/write position.</p><p>But when mmap writes back to the file, the file position cannot be determined by <code>f-&gt;off</code>; it is determined by the page's position within the VMA:</p><div class="code-wrapper"><pre><code class="hljs c">fileoff = vma-&gt;offset + (pageva - vma-&gt;addr);</code></pre></div><p>For example, suppose the mapping starts at file offset <code>0</code>, and now we want to unmap page 2 of the VMA:</p><div class="code-wrapper"><pre><code class="hljs text">VMA page 0  ────▶  file offset 0VMA page 1  ────▶  file offset 4096VMA page 2  ────▶  file offset 8192</code></pre></div><p>At this point that page must be written to file offset <code>8192</code>. But <code>f-&gt;off</code> might be <code>0</code>, or might already have been moved elsewhere by ordinary <code>read()</code> / <code>write()</code> calls. Moreover, <code>filedup()</code> only increments the reference count of the original <code>struct file</code>; the VMA and the fd still point to the same <code>struct file</code>, so you cannot assume <code>f-&gt;off</code> always equals the position mmap needs.</p><div class="note note-warning"><p>Even writing the entire VMA back at <code>munmap()</code> time does not solve this problem. <code>filewrite()</code> would still start writing from <code>f-&gt;off</code>, not from <code>vma-&gt;offset</code>. Also, <code>munmap()</code> may unmap only part of the VMA, and the mapping length may be greater than the file length, so you still need to explicitly specify the file range to write back this time.</p></div><p>So the logic in <code>filewrite()</code> for writing to inode files was extracted into <code>filewriteat()</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span><span class="hljs-title function_">filewriteat</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> file *f, <span class="hljs-type">int</span> user_src, uint64 src, uint64 off, <span class="hljs-type">int</span> n)</span>;</code></pre></div><p>The final call is:</p><div class="code-wrapper"><pre><code class="hljs c">filewriteat(f, <span class="hljs-number">0</span>, pa, fileoff, write_len);</code></pre></div><p>where:</p><ul><li><p><code>0</code> means it is <code>pa</code>, not <code>va</code>;</p><div class="note note-info"><p>Actually, passing <code>va</code> here (in <code>vmunmap()</code>) would also work (that is, the <code>pageva</code> in the loop), but it's the same.</p></div></li><li><p><code>pa</code> is the physical page that currently needs to be written back;</p></li><li><p><code>fileoff</code> is the correct position of this page within the file;</p></li><li><p><code>write_len</code> is the length actually allowed to be written this time.</p></li></ul><p><code>filewriteat()</code> still keeps the chunked writing, file system transaction, and inode locking logic from <code>filewrite()</code>, but it uses the explicitly passed <code>off</code>, and does not read or modify <code>f-&gt;off</code>.</p><h3 id="Modifying-kexit">Modifying <code>kexit()</code></h3><p>Just free all VMAs, same as <code>munmap()</code>.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// munmap all mmap regions</span><span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; NVMA; i++) {    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span> *<span class="hljs-title">vma</span> =</span> &amp;p-&gt;vma[i];    <span class="hljs-keyword">if</span>(vma-&gt;valid) {      <span class="hljs-keyword">if</span>(vmaunmap(p, vma-&gt;addr, vma-&gt;len) &lt; <span class="hljs-number">0</span>) {        panic(<span class="hljs-string">"kexit: vmaunmap"</span>);      }    }}</code></pre></div><h3 id="Modifying-kfork">Modifying <code>kfork()</code></h3><p>That is, just copy it; there's no essential difference from copying the <code>trapframe</code>. The hints also mention that the file reference count needs +1; just do as told.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; NVMA; ++i) {    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span>* <span class="hljs-title">vma</span> =</span> &amp;p-&gt;vma[i];    <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">vma</span>* <span class="hljs-title">nvma</span> =</span> &amp;np-&gt;vma[i];    *nvma = *vma;    <span class="hljs-keyword">if</span> (nvma-&gt;valid) {      filedup(nvma-&gt;f);    }}</code></pre></div><h3 id="About-the-challenges">About the challenges</h3><p>Actually, I think all of these are quite interesting, but I'm a bit tired. If I get interested later, I'll come back and implement them.</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1546 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">If two processes have the same file mmap-ed (as in the fork tests), shar...</span></summary><blockquote><ul><li>If two processes have the same file mmap-ed (as in the fork tests), share their physical pages. You will need reference counts on physical pages.</li><li>Your solution probably allocates a new physical page for each page read from the mmap-ed file, even though the data is also in kernel memory in the buffer cache. Modify your implementation to use that physical memory, instead of allocating a new page. This requires that file blocks be the same size as pages (set <code>BSIZE</code> to 4096). You will need to pin mmap-ed blocks into the buffer cache. You will need worry about reference counts. One benefit of fixing this double-caching is that it also helps make <code>read()</code> and <code>write()</code> consistent with <code>mmap</code>. That is, if some <code>mmap</code>ed file data is modified through the memory mapping, <code>read</code> should return those modifications, and likewise, if an application calls <code>write</code>, the write should appear in any active memory mappings of that file. You might find it interesting to read the paper on <a href="https://www.usenix.org/legacy/publications/library/proceedings/usenix2000/freenix/full_papers/silvers/silvers.pdf">the unified buffer cache</a>.</li><li>Remove redundancy between your implementation for lazy allocation and your implementation of mmap-ed files. (Hint: create a VMA for the lazy allocation area.)</li><li>Modify <code>exec</code> to use a VMA for different sections of the binary so that you get on-demand-paged executables. This will make starting programs faster, because <code>exec</code> will not have to read any data from the file system.</li><li>Implement page-out and page-in: have the kernel move some parts of processes to disk when physical memory is low. Then, page in the paged-out memory when the process references it.</li></ul></blockquote></details><p>After finishing, I realized I don't really understand xv6's logging and transaction system. I only briefly touched on simple APIs like <code>bread()</code> and <code>brelse()</code> in the file system lab, but never went as deep as I did with <code>inode</code>. That's a TODO as well.</p><div class="note note-info"><p>Though it seems that just reading the book (the xv6 book) carefully would be enough.</p></div><p><img src="https://image.wendaining.top/image-20260820193745319.png" alt=""></p>]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab8 File system - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab8-file-system/</link>
      <description>The eighth xv6 lab, related to the file system.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Tue, 18 Aug 2026 10:50:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab8-file-system/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Reading">Reading</h2><p>Just read the book briefly, have GPT translate it and extract the key points, then read the corresponding parts.</p><p>xv6 divides the file system into 7 layers:</p><ul><li><strong>Disk layer</strong>: actually reads and writes blocks to/from the VirtIO disk.</li><li><strong>Buffer cache</strong>: caches disk blocks in memory, and ensures that only one thread modifies a block at any given time.</li><li><strong>Logging</strong>: groups modifications of multiple blocks into a transaction, guaranteeing that after a crash either all of them take effect or none of them do.</li><li><strong>Inode</strong>: represents a file as an inode + several data blocks.</li><li><strong>Directory</strong>: a directory is actually a special kind of file whose content is a series of <code>name -&gt; inode number</code> mappings.</li><li><strong>Pathname</strong>: parses <code>/a/b/c</code>.</li><li><strong>File descriptor</strong>: finally provides the user with a unified interface like <code>open/read/write/...</code>.</li></ul><p>The so-called "crash consistency": when a crash happens midway through operations like modifying an inode or writing logs, inconsistency results. xv6's approach is logging — instead of directly modifying the real file system, it first writes the modifications of this transaction into the log.</p><p>As for the log design, it resides in a specific region of the disk.</p><p>Inodes are split into the on-disk <code>struct dinode</code> and the in-memory <code>struct inode</code>. The in-memory inode is just a cached copy of the disk inode.</p><p>Important fields of the disk inode:</p><div class="code-wrapper"><pre><code class="hljs TEXT">typenlinksizeaddrs[]</code></pre></div><p>Meanings:</p><ul><li><code>type</code>: regular file, directory, device, ...</li><li><code>nlink</code>: how many directory entries point to it.</li><li><code>size</code>: file size.</li><li><code>addrs[]</code>: the <strong>disk block numbers</strong> where the file's data resides.</li></ul><p>The inode number (inum) is simply the index of the inode in the disk's inode region.</p><p>The in-memory <code>struct inode</code> additionally has:</p><div class="code-wrapper"><pre><code class="hljs TEXT">reflockvalid...</code></pre></div><p><code>ref</code> indicates how many C pointers in the kernel are currently referencing this inode.</p><p>Then there is the distinction between direct blocks and indirect blocks, i.e., first-level and second-level indexing:</p><img src="https://image.wendaining.top/image-20260818200521912.png" style="zoom:50%;"><p>Querying inodes and directories also involves a bunch of APIs, e.g., for a full path, <code>namex()</code> splits it by separators and recursively looks up the inode at each level.</p><h2 id="Large-files">Large files</h2><p>Follow the hints:</p><h3 id="Analyzing-the-bmap-function">Analyzing the <code>bmap()</code> function</h3><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 43 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 43 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// Return the disk block address of the nth block in inode ip.</span><span class="hljs-comment">// If there is no such block, bmap allocates one.</span><span class="hljs-comment">// returns 0 if out of disk space.</span><span class="hljs-type">static</span> uint<span class="hljs-title function_">bmap</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> inode *ip, uint bn)</span>{  uint addr, *a;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">buf</span> *<span class="hljs-title">bp</span>;</span>  <span class="hljs-keyword">if</span>(bn &lt; NDIRECT){    <span class="hljs-keyword">if</span>((addr = ip-&gt;addrs[bn]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr == <span class="hljs-number">0</span>)        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      ip-&gt;addrs[bn] = addr;    }    <span class="hljs-keyword">return</span> addr;  }  bn -= NDIRECT;  <span class="hljs-keyword">if</span>(bn &lt; NINDIRECT){    <span class="hljs-comment">// Load indirect block, allocating if necessary.</span>    <span class="hljs-keyword">if</span>((addr = ip-&gt;addrs[NDIRECT]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr == <span class="hljs-number">0</span>)        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      ip-&gt;addrs[NDIRECT] = addr;    }    bp = bread(ip-&gt;dev, addr);    a = (uint*)bp-&gt;data;    <span class="hljs-keyword">if</span>((addr = a[bn]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr){        a[bn] = addr;        log_write(bp);      }    }    brelse(bp);    <span class="hljs-keyword">return</span> addr;  }  panic(<span class="hljs-string">"bmap: out of range"</span>);}</code></pre></div></details><ul><li>Figure 10.3 in the "Reading" section is extremely, extremely important.</li><li><code>bn</code> is the logical block number, i.e., which block of the file this block is, relative to the beginning of the file. What is returned is the actual disk block number.</li><li>If <code>bn &lt; NDIRECT</code>, as shown in the figure, it maps directly to the data block at <code>ip-&gt;addrs[bn]</code>.<ul><li>But the actual implementation first checks whether it exists, and if not, it has to allocate one with <code>balloc()</code>.</li></ul></li><li>If <code>bn &gt; NDIRECT</code>:<ol><li>First <code>bn -= NDIRECT</code>; this step converts the logical block number, originally relative to the whole file, into an index within the first-level indirect block array.<ul><li>In fact, looking at the figure you can see that after entering the first-level block, the addresses are again 1 ~ 256, though in reality it should be 0 ~ 255.</li></ul></li><li>Check <code>bn &lt; NINDIRECT</code>; this is really just checking whether the previous <code>bn</code> is within the maximum range (<code>MAXFILE = NDIRECT + NINDIRECT</code>).</li><li>After the check passes, check the existence of the indirect block, and allocate one if it doesn't exist.</li><li>Then, first use <code>bread()</code> to get the <code>struct buf</code> of the indirect block on disk, and get the data inside it.<ol><li>If the data is empty, continue allocating; if not empty, just get the address and it can be returned directly (though the code isn't written that way, it's logically equivalent).</li><li>After confirming it's non-empty, map the newly allocated block into <code>a[bn]</code>, then log it.</li><li>Finally release it, then return the address.</li></ol></li></ol></li></ul><h3 id="Modifying-the-macro-definitions">Modifying the macro definitions</h3><p>Currently xv6 files can have at most 268 blocks. Analyzing the reason: it's because <code>#define NDIRECT 12</code> is specified, and <code>dinode</code> and <code>inode</code> contain <code>uint addrs[NDIRECT+1];</code>.</p><p>That is, 12 direct block numbers, plus 1 first-level indirect block number.</p><p>Also, <code>BSIZE 1024</code> (bytes per block) is specified, and <code>sizeof(uint) = 4</code>, so one indirect block can hold at most 256 block numbers, hence <code>MAXFILE = 12 + 256 = 268 blocks</code>.</p><p>This lab requires implementing doubly-indirect blocks, which becomes $256^2 + 256 + 11 = 65803 \text{blocks}$</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NDIRECT 11</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> NINDIRECT (BSIZE / sizeof(uint))</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> NINDIRECT2 (NINDIRECT * NINDIRECT)</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> MAXFILE (NDIRECT + NINDIRECT + NINDIRECT2)</span></code></pre></div><p>Then, modify the fields of <code>struct inode</code> and <code>struct dinode</code>:</p><div class="code-wrapper"><pre><code class="hljs c">uint addrs[NDIRECT+<span class="hljs-number">2</span>];</code></pre></div><h3 id="Thinking-through-the-calculation">Thinking through the calculation</h3><blockquote><p>Think: given a file's logical block number, how should you compute its position within the doubly-indirect block, i.e., first which singly-indirect block to pick, and then which data block within it.</p></blockquote><p>Here I'll borrow an image from Zhihu, which is drawn very well:</p><img src="https://image.wendaining.top/image-20260818210059320.png" style="zoom:50%;"><p>Specifically, if <code>bn</code> falls in the second-level index range:</p><ul><li><p>First you need to subtract the previous two parts (which actually gets subtracted away step by step during the calculation).</p></li><li><p>Then, each address inside the 2nd indirect block maps to another 1st indirect block, i.e., another 256 actual data blocks.</p></li><li><p>So, for example, bn = 45162 (<em>a random number that happens to satisfy the requirement</em>)</p><ul><li>After the first- and second-level checks, bn = 45162 - 11 - 256 = 44895</li><li>Then, dividing by 256 gives 175, meaning it's located at the 175th first-level index.</li><li>Then, 44895 % 256 = 95, meaning it's located at the 95th data block pointed to by that first-level index.</li></ul></li></ul><p>That's the calculation.</p><h3 id="Implementing-the-modification-to-bmap">Implementing the modification to <code>bmap()</code></h3><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 81 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 81 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">static</span> uint<span class="hljs-title function_">bmap</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> inode *ip, uint bn)</span>{  uint addr, *a;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">buf</span> *<span class="hljs-title">bp</span>;</span>  <span class="hljs-keyword">if</span>(bn &lt; NDIRECT){    <span class="hljs-keyword">if</span>((addr = ip-&gt;addrs[bn]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr == <span class="hljs-number">0</span>)        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      ip-&gt;addrs[bn] = addr;    }    <span class="hljs-keyword">return</span> addr;  }  bn -= NDIRECT;  <span class="hljs-keyword">if</span>(bn &lt; NINDIRECT){    <span class="hljs-comment">// Load indirect block, allocating if necessary.</span>    <span class="hljs-keyword">if</span>((addr = ip-&gt;addrs[NDIRECT]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr == <span class="hljs-number">0</span>)        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      ip-&gt;addrs[NDIRECT] = addr;    }    bp = bread(ip-&gt;dev, addr);    a = (uint*)bp-&gt;data;    <span class="hljs-keyword">if</span>((addr = a[bn]) == <span class="hljs-number">0</span>){      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span>(addr){        a[bn] = addr;        log_write(bp);      }    }    brelse(bp);    <span class="hljs-keyword">return</span> addr;  }  <span class="hljs-comment">// 以下为实现代码</span>  bn -= NINDIRECT;  <span class="hljs-keyword">if</span>(bn &lt; NINDIRECT2) {    <span class="hljs-comment">// 这里的 addr 是二级间接块的地址</span>    <span class="hljs-keyword">if</span> ((addr = ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>]) == <span class="hljs-number">0</span>) {      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span> (addr == <span class="hljs-number">0</span>) {        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      }      ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>] = addr;    }    <span class="hljs-comment">// 这里的 bp 是二级间接块的实际 struct buf</span>    bp = bread(ip-&gt;dev, addr);    a = (uint*)bp-&gt;data;    <span class="hljs-comment">// 这里的 addr 是二级间接块指向的一级间接块的地址</span>    <span class="hljs-keyword">if</span> ((addr = a[bn / NINDIRECT]) == <span class="hljs-number">0</span>) {      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span> (addr == <span class="hljs-number">0</span>) {        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      }      a[bn / NINDIRECT] = addr;      <span class="hljs-comment">// 记得任何对于实际 buf 的修改都要落日志，维护崩溃一致性</span>      log_write(bp);    }    brelse(bp);    <span class="hljs-comment">// 这里的 bp 是一级间接块的实际的 struct buf</span>    bp = bread(ip-&gt;dev, addr);    a = (uint*)bp-&gt;data;    <span class="hljs-comment">// 这里的 addr 是最后实际的数据的地址</span>    <span class="hljs-keyword">if</span> ((addr = a[bn % NINDIRECT]) == <span class="hljs-number">0</span>) {      addr = balloc(ip-&gt;dev);      <span class="hljs-keyword">if</span> (addr == <span class="hljs-number">0</span>) {        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;      }      a[bn % NINDIRECT] = addr;      log_write(bp);    }    brelse(bp);    <span class="hljs-keyword">return</span> addr;  }  panic(<span class="hljs-string">"bmap: out of range"</span>);}</code></pre></div></details><p>Actually, many places reuse a single variable, such as <code>bp</code>, <code>a</code>, and <code>addr</code>, because the original code reuses them this way. Although it's not very clear, to keep the code style consistent, so be it.</p><p>Remember, for every block read via <code>bread()</code>, don't forget to eventually call <code>brelse()</code>.</p><h3 id="Modifying-itrunc">Modifying <code>itrunc()</code></h3><blockquote><p>Don't forget to modify <code>itrunc()</code>, making sure it can free all of a file's blocks, including the double-indirect block and the blocks beneath it.</p></blockquote><p>Just like when you modified <code>kalloc()</code> to add a level, you certainly need to modify <code>kfree()</code> as well.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 49 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 49 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span><span class="hljs-title function_">itrunc</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> inode *ip)</span>{  <span class="hljs-type">int</span> i, j, k;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">buf</span> *<span class="hljs-title">bp</span>;</span>  uint *a;  <span class="hljs-keyword">for</span>(i = <span class="hljs-number">0</span>; i &lt; NDIRECT; i++){    <span class="hljs-keyword">if</span>(ip-&gt;addrs[i]){      bfree(ip-&gt;dev, ip-&gt;addrs[i]);      ip-&gt;addrs[i] = <span class="hljs-number">0</span>;    }  }  <span class="hljs-keyword">if</span>(ip-&gt;addrs[NDIRECT]){    bp = bread(ip-&gt;dev, ip-&gt;addrs[NDIRECT]);    a = (uint*)bp-&gt;data;    <span class="hljs-keyword">for</span>(j = <span class="hljs-number">0</span>; j &lt; NINDIRECT; j++){      <span class="hljs-keyword">if</span>(a[j])        bfree(ip-&gt;dev, a[j]);    }    brelse(bp);    bfree(ip-&gt;dev, ip-&gt;addrs[NDIRECT]);    ip-&gt;addrs[NDIRECT] = <span class="hljs-number">0</span>;  }  <span class="hljs-keyword">if</span>(ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>]) {    bp = bread(ip-&gt;dev, ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>]);    a = (uint*)bp-&gt;data;    <span class="hljs-keyword">for</span>(j = <span class="hljs-number">0</span>; j &lt; NINDIRECT; j++) {      uint in1_addr;      <span class="hljs-keyword">if</span> ((in1_addr = a[j]) != <span class="hljs-number">0</span>) {        <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">buf</span> *<span class="hljs-title">in1_bp</span> =</span> bread(ip-&gt;dev, in1_addr);        uint *in1_a = (uint*)in1_bp-&gt;data;        <span class="hljs-keyword">for</span>(k = <span class="hljs-number">0</span>; k &lt; NINDIRECT; k++) {          bfree(ip-&gt;dev, in1_a[k]);        }        brelse(in1_bp);        bfree(ip-&gt;dev, in1_addr);      }    }    brelse(bp);    bfree(ip-&gt;dev, ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>]);    ip-&gt;addrs[NDIRECT + <span class="hljs-number">1</span>] = <span class="hljs-number">0</span>;  }  ip-&gt;size = <span class="hljs-number">0</span>;  iupdate(ip);}</code></pre></div></details><h2 id="Symbolic-links">Symbolic links</h2><p>Add symbolic link / soft link functionality to xv6, i.e., implement the <code>symlink</code> system call.</p><p>As a refresher, a soft link is an alias that records the target pathname. Understand the difference this way:</p><div class="code-wrapper"><pre><code class="hljs text">hard link:name → inodesymbolic link:name → symlink inode → pathname → inode</code></pre></div><p>This lab doesn't require handling soft links pointing to directories.</p><p>Using the hints as a guide:</p><h3 id="Adding-the-basic-system-call-configuration">Adding the basic system call configuration</h3><p>Create a new system call number for <code>symlink</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/syscall.h</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> SYS_symlink 22</span></code></pre></div><p>Implement an empty <code>sys_symlink()</code> in <code>kernel/sysfile.c</code>:</p><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_symlink</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  }</code></pre></div><p>Declare it and add it to the system call array in <code>kernel/syscall.c</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">extern</span> uint64 <span class="hljs-title function_">sys_symlink</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>;<span class="hljs-type">static</span> <span class="hljs-title function_">uint64</span> <span class="hljs-params">(*syscalls[])</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span> = {[SYS_fork]    sys_fork,<span class="hljs-comment">// ...</span>[SYS_symlink] sys_symlink,};</code></pre></div><p>Add the corresponding entry in <code>user/usys.pl</code>:</p><div class="code-wrapper"><pre><code class="hljs perl">entry(<span class="hljs-string">"symlink"</span>);</code></pre></div><p>Add the declaration in <code>user/user.h</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span> <span class="hljs-title function_">symlink</span><span class="hljs-params">(<span class="hljs-type">char</span> *target, <span class="hljs-type">char</span> *path)</span>;</code></pre></div><div class="note note-success"><p>How do we know the exact return value? <strong>RTFM</strong></p></div><h3 id="Adding-a-new-file-type-identifier">Adding a new file type identifier</h3><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// kernel/stat.h</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> T_DIR     1   <span class="hljs-comment">// Directory</span></span><span class="hljs-meta">#<span class="hljs-keyword">define</span> T_FILE    2   <span class="hljs-comment">// File</span></span><span class="hljs-meta">#<span class="hljs-keyword">define</span> T_DEVICE  3   <span class="hljs-comment">// Device</span></span><span class="hljs-meta">#<span class="hljs-keyword">define</span> T_SYMLINK 4   <span class="hljs-comment">// soft link</span></span></code></pre></div><h3 id="Adding-a-new-flag">Adding a new flag</h3><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_RDONLY   0x000</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_WRONLY   0x001</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_RDWR     0x002</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_CREATE   0x200</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_TRUNC    0x400</span><span class="hljs-meta">#<span class="hljs-keyword">define</span> O_NOFOLLOW 0x20000</span></code></pre></div><p>This is mainly for <code>open</code> (RTFM tells us this flag has this value)</p><div class="note note-info"><p>Actually, you could also implement your own, as long as you follow the principle that the flags passed to <code>open()</code> are combined with bitwise OR, so the new flag must not overlap in bits with any existing flag.</p></div><p>According to <code>man</code>:</p><blockquote><p>If the trailing component (i.e., basename) of pathname is a symbolic link, then the open fails, with the error ELOOP</p></blockquote><h3 id="Implementing-symlink">Implementing <code>symlink()</code></h3><p>Create a new symbolic link at <code>path</code> pointing to <code>target</code>; note that <code>target</code> does not need to actually exist.</p><p>At first I couldn't figure out these APIs and concepts (I wasn't reading carefully), so I decided to read the implementation of <code>sys_link()</code>:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 49 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 49 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// Create the path new as a link to the same inode as old.</span>uint64<span class="hljs-title function_">sys_link</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">char</span> name[DIRSIZ], new[MAXPATH], old[MAXPATH];  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">dp</span>, *<span class="hljs-title">ip</span>;</span>  <span class="hljs-keyword">if</span>(argstr(<span class="hljs-number">0</span>, old, MAXPATH) &lt; <span class="hljs-number">0</span> || argstr(<span class="hljs-number">1</span>, new, MAXPATH) &lt; <span class="hljs-number">0</span>)    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  begin_op();  <span class="hljs-keyword">if</span>((ip = namei(old)) == <span class="hljs-number">0</span>){    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  ilock(ip);  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DIR){    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  ip-&gt;nlink++;  iupdate(ip);  iunlock(ip);  <span class="hljs-keyword">if</span>((dp = nameiparent(new, name)) == <span class="hljs-number">0</span>)    <span class="hljs-keyword">goto</span> bad;  ilock(dp);  <span class="hljs-keyword">if</span>(dp-&gt;dev != ip-&gt;dev || dirlink(dp, name, ip-&gt;inum) &lt; <span class="hljs-number">0</span>){    iunlockput(dp);    <span class="hljs-keyword">goto</span> bad;  }  iunlockput(dp);  iput(ip);  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;bad:  ilock(ip);  ip-&gt;nlink--;  iupdate(ip);  iunlockput(ip);  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;}</code></pre></div></details><p>Some key points I sorted out:</p><ol><li><code>begin_op()</code> and <code>end_op()</code> open a file system transaction, guaranteeing ACID.</li><li><code>namei()</code> returns the <code>inode</code> struct pointer of the file corresponding to the path.</li><li>After getting the <code>inode</code> pointer, if you want to modify it, you also need to use <code>ilock()</code> to lock it and <code>iunlock()</code> to unlock; after modification, you need to use <code>iupdate</code> to persist it, writing the in-memory <code>inode</code> back to the on-disk <code>struct dinode</code>.</li></ol><p>But that's really all you can learn from it; then reading the book (actually asking an LLM for the key points) yields this additional information:</p><ol><li>The inode returned by <code>create()</code> comes locked already, so you don't need to lock it yourself.</li><li>A soft link is implemented by creating an inode of type <code>T_SYMLINK</code>, whose data block (actually the <code>uchar data[BSIZE];</code> of the <code>buf</code> pointed to by the <code>inode</code>'s <code>addr</code> (obtained via <code>bmap()</code>)) contains <code>target</code>.</li><li>Therefore, if you want to read or write it, there are corresponding APIs, namely <code>readi()</code> and <code>writei()</code>; you can figure out their usage with a quick Ctrl + F.</li></ol><p>But in fact my understanding was still somewhat off; you also need to read <code>create()</code>. Here is the LLM's corrected version directly:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 3598 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">Why does the result of namei() leak? namei() doesn't just return an ordi...</span></summary><blockquote><p><strong>Why does the result of <code>namei()</code> leak?</strong></p><p><code>namei()</code> doesn't just return an ordinary pointer; it also holds an inode reference on behalf of the caller.</p><p>You can think of it as:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span> =</span> namei(path);<span class="hljs-comment">// ip-&gt;ref 被加了一次</span></code></pre></div><p>After the caller is done, it must:</p><div class="code-wrapper"><pre><code class="hljs c">iput(ip);</code></pre></div><p>Otherwise the reference count will never be decremented back.</p><p>What you originally wrote was:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">if</span>(namei(path) != <span class="hljs-number">0</span>){  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;}</code></pre></div><p>If the file exists, <code>namei()</code> returns an inode with a reference, but you didn't save the return value:</p><div class="code-wrapper"><pre><code class="hljs text">namei() acquires a reference       ↓returns the inode pointer       ↓the pointer is discarded directly       ↓iput() can no longer be called       ↓reference leak</code></pre></div><p>It's similar to:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">if</span>(<span class="hljs-built_in">malloc</span>(<span class="hljs-number">100</span>) != <span class="hljs-number">0</span>)  <span class="hljs-keyword">return</span>;</code></pre></div><p>The memory was successfully allocated, but the pointer is thrown away directly, so there's no way to <code>free()</code> it.</p><p>If you really want to do this check, you should at least:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">existing</span> =</span> namei(path);<span class="hljs-keyword">if</span>(existing != <span class="hljs-number">0</span>){  iput(existing);  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;}</code></pre></div><p>However, in <code>sys_symlink()</code>, this check should simply be deleted, because <code>create()</code> already checks whether the path exists under the protection of the parent directory lock.</p><p>Calling <code>namei()</code> first and then <code>create()</code> also has a concurrency problem:</p><div class="code-wrapper"><pre><code class="hljs text">Process A: namei(path) finds it doesn't existProcess B: creates pathProcess A: create(path)</code></pre></div><p>A truly reliable "check and create" must be done inside <code>create()</code>.</p><p><strong>The difference between <code>iunlock()</code> and <code>iunlockput()</code></strong></p><p>They control two different things:</p><div class="code-wrapper"><pre><code class="hljs c">iunlock(ip);</code></pre></div><p>Only releases the inode lock, but still keeps the reference:</p><div class="code-wrapper"><pre><code class="hljs text">Lock: releasedReference: keptip: can still be used later</code></pre></div><p>Whereas:</p><div class="code-wrapper"><pre><code class="hljs c">iunlockput(ip);</code></pre></div><p>Is equivalent to:</p><div class="code-wrapper"><pre><code class="hljs c">iunlock(ip);iput(ip);</code></pre></div><p>The result is:</p><div class="code-wrapper"><pre><code class="hljs text">Lock: releasedReference: also releasedip: cannot be used anymore</code></pre></div><p>The complete state transitions can be viewed like this:</p><div class="code-wrapper"><pre><code class="hljs c">ip = namei(path);</code></pre></div><p>At this point:</p><div class="code-wrapper"><pre><code class="hljs text">ref = +1locked = no</code></pre></div><p>Then:</p><div class="code-wrapper"><pre><code class="hljs c">ilock(ip);</code></pre></div><p>Becomes:</p><div class="code-wrapper"><pre><code class="hljs text">ref = +1locked = yes</code></pre></div><p>If you call:</p><div class="code-wrapper"><pre><code class="hljs c">iunlock(ip);</code></pre></div><p>It becomes:</p><div class="code-wrapper"><pre><code class="hljs text">ref = +1locked = no</code></pre></div><p><code>ip</code> can still be used again.</p><p>If you call:</p><div class="code-wrapper"><pre><code class="hljs c">iunlockput(ip);</code></pre></div><p>It becomes:</p><div class="code-wrapper"><pre><code class="hljs text">ref = releasedlocked = no</code></pre></div><p><code>ip</code> can no longer be used.</p><p><strong>Why does <code>link()</code> use <code>iunlock()</code>?</strong></p><p>The logic of <code>sys_link()</code> is roughly:</p><div class="code-wrapper"><pre><code class="hljs c">ip = namei(old);  <span class="hljs-comment">// 获得 old inode 的引用</span>ilock(ip);ip-&gt;nlink++;iupdate(ip);iunlock(ip);      <span class="hljs-comment">// 只解锁，仍保留引用</span></code></pre></div><p>At this point it hasn't finished using <code>ip</code>. It still needs:</p><div class="code-wrapper"><pre><code class="hljs c">dp = nameiparent(new, name);ilock(dp);dirlink(dp, name, ip-&gt;inum);</code></pre></div><p>So the reference to <code>ip</code> must be kept.</p><p>But there's no need to keep <code>ip</code> locked, and holding its lock while doing path lookups and acquiring the parent directory lock increases the risk of deadlock. Therefore it uses:</p><div class="code-wrapper"><pre><code class="hljs c">iunlock(ip);</code></pre></div><p>That is:</p><blockquote><p>I don't need to hold its lock for now, but this inode isn't finished being used yet, so I can't release the reference.</p></blockquote><p>Only after successfully creating the new directory entry does it:</p><div class="code-wrapper"><pre><code class="hljs c">iput(ip);</code></pre></div><p>If something fails in the middle, it needs to re-lock it and roll back <code>nlink</code>:</p><div class="code-wrapper"><pre><code class="hljs c">ilock(ip);ip-&gt;nlink--;iupdate(ip);iunlockput(ip);</code></pre></div><p>So the lifecycle of <code>link()</code> is:</p><div class="code-wrapper"><pre><code class="hljs text">namei(old)         acquire the reference    ↓ilock(ip)          lock    ↓modify nlink    ↓iunlock(ip)        unlock, but keep the reference    ↓create the new directory entry, during which ip-&gt;inum is still needed    ↓iput(ip)           finally release the reference</code></pre></div><p>Most places use <code>iunlockput()</code> because after unlocking at those points, the inode is never needed again.</p><p>Two other typical <code>iunlock()</code> scenarios:</p><ul><li><code>open()</code>: the reference is handed over to <code>f-&gt;ip</code>, to be released at <code>close()</code>.</li><li><code>chdir()</code>: the reference is handed over to <code>proc-&gt;cwd</code>.</li></ul><p>The way to decide is:</p><div class="code-wrapper"><pre><code class="hljs text">After unlocking, do you still need this inode, or do you need to hand the reference to someone else?    Yes → iunlock()    No → iunlockput()</code></pre></div></blockquote></details><p>The misunderstanding above also led to my initial incorrect implementation (including <code>open()</code>).</p><p>So here is the implementation of <code>symlink()</code>:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 37 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 37 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_symlink</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">char</span> path[MAXPATH], target[MAXPATH];  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span>;</span>  <span class="hljs-keyword">if</span>(argstr(<span class="hljs-number">1</span>, path, MAXPATH) &lt; <span class="hljs-number">0</span> || argstr(<span class="hljs-number">0</span>, target, MAXPATH) &lt; <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  begin_op();  <span class="hljs-comment">// 这段代码不需要，`create()` 自己会检查目标路径是否已存在</span>  <span class="hljs-comment">// if (namei(path) != 0) {</span>  <span class="hljs-comment">//   end_op();</span>  <span class="hljs-comment">//   return -1;</span>  <span class="hljs-comment">// }</span>  ip = create(path, T_SYMLINK, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);  <span class="hljs-keyword">if</span> (ip == <span class="hljs-number">0</span>) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }    <span class="hljs-type">int</span> len = <span class="hljs-built_in">strlen</span>(target) + <span class="hljs-number">1</span>;  <span class="hljs-keyword">if</span> (writei(ip, <span class="hljs-number">0</span>, (uint64)target, <span class="hljs-number">0</span>, len) != len) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// iupdate(ip); 不需要，writei() 有</span>  iunlockput(ip);  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;}</code></pre></div></details><h3 id="Modifying-open">Modifying <code>open()</code></h3><p>Because if the <code>path</code> passed to <code>open()</code> is actually just a symbolic link, you certainly can't directly return the <code>fd</code> corresponding to the symbolic link's <code>inode</code>; instead you should return the one corresponding to the <code>target</code> it points to. Just add special handling here.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 96 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 96 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_open</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">char</span> path[MAXPATH];  <span class="hljs-type">int</span> fd, omode;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span>;</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span>;</span>  <span class="hljs-type">int</span> n;  argint(<span class="hljs-number">1</span>, &amp;omode);  <span class="hljs-keyword">if</span>((n = argstr(<span class="hljs-number">0</span>, path, MAXPATH)) &lt; <span class="hljs-number">0</span>)    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  begin_op();  <span class="hljs-keyword">if</span>(omode &amp; O_CREATE){    ip = create(path, T_FILE, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);    <span class="hljs-keyword">if</span>(ip == <span class="hljs-number">0</span>){      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }  } <span class="hljs-keyword">else</span> {    <span class="hljs-keyword">if</span>((ip = namei(path)) == <span class="hljs-number">0</span>){      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    ilock(ip);    <span class="hljs-comment">// 目录检查放在展开之后</span>  }  <span class="hljs-comment">// ========</span>  <span class="hljs-type">int</span> depth = <span class="hljs-number">0</span>;  <span class="hljs-keyword">while</span> (ip-&gt;type == T_SYMLINK &amp;&amp; omode != O_NOFOLLOW) {    <span class="hljs-type">char</span> target[MAXPATH];    <span class="hljs-keyword">if</span> (readi(ip, <span class="hljs-number">0</span>, (uint64)target, <span class="hljs-number">0</span>, MAXPATH) &lt;= <span class="hljs-number">0</span>) {      iunlockput(ip);      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    iunlockput(ip);    <span class="hljs-keyword">if</span> ((ip = namei(target)) == <span class="hljs-number">0</span>) {      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    ilock(ip);    depth++;    <span class="hljs-keyword">if</span> (depth &gt; <span class="hljs-number">10</span>) {      iunlockput(ip);      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }  }  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DIR &amp;&amp; omode != O_RDONLY){    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-comment">// ========</span>  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DEVICE &amp;&amp; (ip-&gt;major &lt; <span class="hljs-number">0</span> || ip-&gt;major &gt;= NDEV)){    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>((f = filealloc()) == <span class="hljs-number">0</span> || (fd = fdalloc(f)) &lt; <span class="hljs-number">0</span>){    <span class="hljs-keyword">if</span>(f)      fileclose(f);    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DEVICE){    f-&gt;type = FD_DEVICE;    f-&gt;major = ip-&gt;major;  } <span class="hljs-keyword">else</span> {    f-&gt;type = FD_INODE;    f-&gt;off = <span class="hljs-number">0</span>;  }  f-&gt;ip = ip;  f-&gt;readable = !(omode &amp; O_WRONLY);  f-&gt;writable = (omode &amp; O_WRONLY) || (omode &amp; O_RDWR);  <span class="hljs-keyword">if</span>((omode &amp; O_TRUNC) &amp;&amp; ip-&gt;type == T_FILE){    itrunc(ip);  }    iunlock(ip);  end_op();  <span class="hljs-keyword">return</span> fd;}</code></pre></div></details><p>The possible problem here is not knowing where to insert the code. My suggestion is to analyze the situations corresponding to each of the flags xv6 has, and then follow the branches to analyze.</p><p><img src="https://image.wendaining.top/image-20260819004054132.png" alt="All tests passed"></p><h3 id="Appendix-the-initial-incorrect-implementation">Appendix: the initial incorrect implementation</h3><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 133 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 133 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_symlink</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">char</span> path[MAXPATH], target[MAXPATH];  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span>;</span>  <span class="hljs-keyword">if</span>(argstr(<span class="hljs-number">0</span>, path, MAXPATH) &lt; <span class="hljs-number">0</span> || argstr(<span class="hljs-number">1</span>, target, MAXPATH) &lt; <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  begin_op();  <span class="hljs-keyword">if</span> (namei(path) != <span class="hljs-number">0</span>) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  ip = create(path, T_SYMLINK, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);  <span class="hljs-keyword">if</span> (ip == <span class="hljs-number">0</span>) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }    <span class="hljs-keyword">if</span> (writei(ip, <span class="hljs-number">0</span>, (uint64)target, <span class="hljs-number">0</span>, MAXPATH) &lt; <span class="hljs-number">0</span>) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  iupdate(ip);  iunlock(ip);  end_op();  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;}uint64<span class="hljs-title function_">sys_open</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-type">char</span> path[MAXPATH];  <span class="hljs-type">int</span> fd, omode;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">file</span> *<span class="hljs-title">f</span>;</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">inode</span> *<span class="hljs-title">ip</span>;</span>  <span class="hljs-type">int</span> n;  argint(<span class="hljs-number">1</span>, &amp;omode);  <span class="hljs-keyword">if</span>((n = argstr(<span class="hljs-number">0</span>, path, MAXPATH)) &lt; <span class="hljs-number">0</span>)    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  begin_op();  <span class="hljs-keyword">if</span>(omode &amp; O_CREATE){    ip = create(path, T_FILE, <span class="hljs-number">0</span>, <span class="hljs-number">0</span>);    <span class="hljs-keyword">if</span>(ip == <span class="hljs-number">0</span>){      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }  } <span class="hljs-keyword">else</span> {    <span class="hljs-keyword">if</span>((ip = namei(path)) == <span class="hljs-number">0</span>){      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    ilock(ip);    <span class="hljs-keyword">if</span>(ip-&gt;type == T_DIR &amp;&amp; omode != O_RDONLY){      iunlockput(ip);      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }  }  <span class="hljs-comment">// ========</span>  ip = namei(path);  <span class="hljs-keyword">if</span> (ip == <span class="hljs-number">0</span>) {    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  ilock(ip);  <span class="hljs-type">int</span> depth = <span class="hljs-number">0</span>;  <span class="hljs-keyword">while</span> (ip-&gt;type == T_SYMLINK &amp;&amp; omode != O_NOFOLLOW) {    <span class="hljs-type">char</span> target[MAXPATH];    <span class="hljs-keyword">if</span> (readi(ip, <span class="hljs-number">0</span>, (uint64)target, <span class="hljs-number">0</span>, MAXPATH) &lt; <span class="hljs-number">0</span>) {      iunlockput(ip);      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    iunlockput(ip);    <span class="hljs-keyword">if</span> ((ip = namei(target)) == <span class="hljs-number">0</span>) {      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }    ilock(ip);    depth++;    <span class="hljs-keyword">if</span> (depth &gt; <span class="hljs-number">10</span>) {      iunlockput(ip);      end_op();      <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;    }  }  <span class="hljs-comment">// ========</span>  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DEVICE &amp;&amp; (ip-&gt;major &lt; <span class="hljs-number">0</span> || ip-&gt;major &gt;= NDEV)){    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>((f = filealloc()) == <span class="hljs-number">0</span> || (fd = fdalloc(f)) &lt; <span class="hljs-number">0</span>){    <span class="hljs-keyword">if</span>(f)      fileclose(f);    iunlockput(ip);    end_op();    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(ip-&gt;type == T_DEVICE){    f-&gt;type = FD_DEVICE;    f-&gt;major = ip-&gt;major;  } <span class="hljs-keyword">else</span> {    f-&gt;type = FD_INODE;    f-&gt;off = <span class="hljs-number">0</span>;  }  f-&gt;ip = ip;  f-&gt;readable = !(omode &amp; O_WRONLY);  f-&gt;writable = (omode &amp; O_WRONLY) || (omode &amp; O_RDWR);  <span class="hljs-keyword">if</span>((omode &amp; O_TRUNC) &amp;&amp; ip-&gt;type == T_FILE){    itrunc(ip);  }  iunlock(ip);  end_op();  <span class="hljs-keyword">return</span> fd;}</code></pre></div></details>]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab7 locks - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab7-locks/</link>
      <description>The seventh xv6 lab, implementing code related to locks, mainly splitting a big lock into smaller ones (multi-CPU) and implementing a reader-writer lock.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Mon, 17 Aug 2026 11:09:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab7-locks/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Reading">Reading</h2><p>Just read the book briefly — have GPT translate it and extract the key points, then read the corresponding sections.</p><p>Sources of concurrency:</p><ul><li>Multi-core CPUs</li><li>Thread switching</li><li>Interrupts</li></ul><p>Reviewing concepts:</p><ul><li>Race conditions</li><li>Critical sections</li></ul><p>Reducing lock contention: OSTEP also covers this. Putting one big lock over the entire data structure certainly solves the problem, but it's inefficient.</p><p>Source code about locks: <code>kernel/spinlock.h</code> <code>kernel/spinlock.c</code></p><p>About the spinlock</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">spinlock</span> {</span>  uint locked; <span class="hljs-comment">// 0 表示没被持有</span>  <span class="hljs-type">char</span> *name;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">cpu</span> *<span class="hljs-title">cpu</span>;</span>};</code></pre></div><p>Regarding acquiring locks, RISC-V provides the atomic instruction <code>amoswap</code>, which atomically completes read memory - write register to memory - return the old value; this is the implementation of <code>acquire()</code>. Releasing the lock follows a similar idea and principle.</p><p>The focus of this lab is to optimize <code>kalloc()</code> by splitting the lock into finer granularity.</p><p>Deadlock must be prevented.</p><p>In xv6's implementation, CPU interrupts are disabled whenever any spinlock is held.</p><p><code>acquire()</code> internally calls:</p><div class="code-wrapper"><pre><code class="hljs c">push_off();</code></pre></div><p>to disable interrupts.</p><p><code>release()</code> finally calls:</p><div class="code-wrapper"><pre><code class="hljs c">pop_off();</code></pre></div><p>to restore interrupts.</p><p>About sleeplock: it was introduced because spinlocks cannot be interrupted.</p><p>Using <code>acquiresleep()</code> yields the CPU; internally it is protected by a spinlock, and afterwards it can be woken up.</p><h2 id="Memory-allocator">Memory allocator</h2><p>Roughly speaking, there is a <code>kalloctest.c</code> that performs intense lock contention (repeatedly calling <code>kalloc() free()</code>).</p><p>The root cause is that <code>kalloc()</code> has only one free list, and this free list is protected by a single global lock.</p><p>The basic idea for reducing lock contention is to redesign the memory allocator. <strong>Therefore, the task of this lab is to maintain a separate free list for each CPU, and give each list its own lock.</strong></p><p>So this lab must be done on a machine with multiple CPU cores.</p><p>One major difficulty is when one CPU's free list is already empty, but another CPU's free list still has free memory. At this point, the CPU lacking memory needs to go to other CPUs' free lists to grab some free pages — this is the so-called <strong>stealing</strong>.</p><p>Now let's start implementing:</p><p>First, we need to modify <code>kmem</code>, which is the original free list struct (a freelist with a lock inside):</p><p>Originally:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">spinlock</span> <span class="hljs-title">lock</span>;</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">freelist</span>;</span>} kmem;</code></pre></div><p>Modified to a form that supports multiple CPUs:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">spinlock</span> <span class="hljs-title">lock</span>[<span class="hljs-title">NCPU</span>];</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">freelist</span>[<span class="hljs-title">NCPU</span>];</span>} kmem;</code></pre></div><p>Then modify <code>kinit()</code> and so on; in short, you need to use the currently running CPU.</p><p>Here you first need to know the API for getting the currently running CPU. Hint 3 mentions this, but I still asked an LLM:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 3599 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">There are only three core APIs: cpuid(), push_off(), and pop_off(). What...</span></summary><blockquote><p>There are only three core APIs: <code>cpuid()</code>, <code>push_off()</code>, and <code>pop_off()</code>.</p><ol><li>What does <code>cpuid()</code> do</li></ol><p>In <a href="/en/home/wendaining/alles/xv6-labs-2025/kernel/proc.c:64">kernel/proc.c</a>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span><span class="hljs-title function_">cpuid</span><span class="hljs-params">()</span>{  <span class="hljs-type">int</span> id = r_tp();  <span class="hljs-keyword">return</span> id;}</code></pre></div><p>Each CPU has a number, in the range:</p><div class="code-wrapper"><pre><code class="hljs text">0 to NCPU - 1</code></pre></div><p><code>cpuid()</code> reads this number from RISC-V's <code>tp</code> register. So if the current code is running on CPU 3:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span> id = cpuid();</code></pre></div><p>the resulting <code>id</code> is <code>3</code>, and afterwards you can access:</p><div class="code-wrapper"><pre><code class="hljs c">kmem.lock[id]kmem.freelist[id]</code></pre></div><ol start="2"><li>Why you can't just call <code>cpuid()</code> directly</li></ol><p>The problem is: a process may be scheduled onto another CPU.</p><p>Consider the following situation:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span> id = cpuid();  <span class="hljs-comment">// 此时得到 2</span><span class="hljs-comment">// 这里发生时钟中断和重新调度</span><span class="hljs-comment">// 进程后来在 CPU 5 上继续运行</span></code></pre></div><p>At this point the variable <code>id</code> is still <code>2</code>, but the code is already running on CPU 5. The "current CPU" no longer matches the saved number.</p><p>Therefore, the usage convention for <code>cpuid()</code> is: <strong>interrupts must be disabled while reading and using the CPU number.</strong></p><p>The source code comment also states this explicitly:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// Must be called with interrupts disabled,</span><span class="hljs-comment">// to prevent race with process being moved</span><span class="hljs-comment">// to a different CPU.</span></code></pre></div><ol start="3"><li><code>push_off()</code> and <code>pop_off()</code></li></ol><p>The basic safe form is:</p><div class="code-wrapper"><pre><code class="hljs c">push_off();<span class="hljs-type">int</span> id = cpuid();<span class="hljs-comment">// 在这里使用 id</span>pop_off();</code></pre></div><ul><li><code>push_off()</code>: disables interrupts on the current CPU.</li><li><code>pop_off()</code>: restores the interrupt state from before entering this code.</li></ul><p>During this period, the code won't be preempted by a timer interrupt, so the current execution flow won't suddenly migrate to another CPU.</p><p>It's not recommended to use <code>intr_off()</code> and <code>intr_on()</code> directly, because they don't handle nesting correctly. For example, the spinlock's <code>acquire()</code> itself also calls <code>push_off()</code>.</p><p><code>push_off()</code>/<code>pop_off()</code> track the nesting depth, so the following is legal:</p><div class="code-wrapper"><pre><code class="hljs c">push_off();                 <span class="hljs-comment">// 第 1 层</span><span class="hljs-type">int</span> id = cpuid();acquire(&amp;kmem.lock[id]);    <span class="hljs-comment">// acquire 内部进入第 2 层</span><span class="hljs-comment">// 修改 freelist</span>release(&amp;kmem.lock[id]);    <span class="hljs-comment">// 退出第 2 层</span>pop_off();                  <span class="hljs-comment">// 退出第 1 层</span></code></pre></div><p>Until the outermost <code>pop_off()</code>, interrupts remain disabled.</p><ol start="4"><li>Why you can't call <code>pop_off()</code> immediately after getting the number</li></ol><p>The following approach is not ideal:</p><div class="code-wrapper"><pre><code class="hljs c">push_off();<span class="hljs-type">int</span> id = cpuid();pop_off();acquire(&amp;kmem.lock[id]);</code></pre></div><p>Because after <code>pop_off()</code>, the code may migrate to another CPU, and then what it operates on is no longer "the current CPU's freelist".</p><p>So in <code>kfree()</code>, the interrupt-disabled region should cover until the end of the corresponding freelist operation:</p><div class="code-wrapper"><pre><code class="hljs c">push_off();<span class="hljs-type">int</span> id = cpuid();acquire(&amp;kmem.lock[id]);<span class="hljs-comment">// 把 r 插入 kmem.freelist[id]</span>release(&amp;kmem.lock[id]);pop_off();</code></pre></div><p>This is basically what you need to complete next.</p><ol start="5"><li>Why <code>freerange()</code> gives all pages to one CPU</li></ol><p>The boot flow is roughly:</p><div class="code-wrapper"><pre><code class="hljs text">boot CPU  → kinit()    → initialize all kmem locks    → freerange()      → call kfree() on each physical page</code></pre></div><p><code>freerange()</code> itself doesn't need to know the CPU number:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-keyword">for</span>(; p + PGSIZE &lt;= (<span class="hljs-type">char</span>*)pa_end; p += PGSIZE)  kfree(p);</code></pre></div><p>It's <code>kfree()</code> that actually chooses the freelist.</p><p>At boot, <code>kinit()</code> only runs on the boot CPU, usually CPU 0. Therefore, every <code>kfree(p)</code> gets CPU number 0, and the final effect is:</p><div class="code-wrapper"><pre><code class="hljs text">kmem.freelist[0]: owns all initial free pageskmem.freelist[1]: emptykmem.freelist[2]: empty...</code></pre></div><p>This is what the hint means by:</p><blockquote><p>Have <code>freerange()</code> give all free memory to the CPU currently running <code>freerange()</code>.</p></blockquote><p>This doesn't require modifying <code>freerange()</code>; rather, it requires <code>kfree()</code> to choose the freelist based on the current CPU. Later, when other CPUs allocate memory for the first time, they'll find their freelist empty and then steal pages from CPU 0.</p><p>For now, you can just modify <code>kfree()</code> and leave <code>kalloc()</code> and stealing aside for the moment. The goal of the change is to replace the original:</p><div class="code-wrapper"><pre><code class="hljs c">kmem.lockkmem.freelist</code></pre></div><p>with versions indexed by a safely obtained <code>id</code>:</p><div class="code-wrapper"><pre><code class="hljs c">kmem.lock[id]kmem.freelist[id]</code></pre></div></blockquote></details><p>So <code>kfree()</code> and <code>kalloc()</code> are changed like this:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 37 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 37 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span><span class="hljs-title function_">kfree</span><span class="hljs-params">(<span class="hljs-type">void</span> *pa)</span>{  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">r</span>;</span>  <span class="hljs-keyword">if</span>(((uint64)pa % PGSIZE) != <span class="hljs-number">0</span> || (<span class="hljs-type">char</span>*)pa &lt; end || (uint64)pa &gt;= PHYSTOP)    panic(<span class="hljs-string">"kfree"</span>);  <span class="hljs-comment">// Fill with junk to catch dangling refs.</span>  <span class="hljs-built_in">memset</span>(pa, <span class="hljs-number">1</span>, PGSIZE);  r = (<span class="hljs-keyword">struct</span> run*)pa;  push_off();  <span class="hljs-type">int</span> id = cpuid();  acquire(&amp;kmem.lock[id]);  r-&gt;next = kmem.freelist[id];  kmem.freelist[id] = r;  release(&amp;kmem.lock[id]);  pop_off();}<span class="hljs-type">void</span> *<span class="hljs-title function_">kalloc</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">r</span>;</span>  push_off();  <span class="hljs-type">int</span> id = cpuid();  acquire(&amp;kmem.lock[id]);  r = kmem.freelist;  <span class="hljs-keyword">if</span>(r)    kmem.freelist[id] = r-&gt;next;  release(&amp;kmem.lock[id]);  pop_off();  <span class="hljs-keyword">if</span>(r)    <span class="hljs-built_in">memset</span>((<span class="hljs-type">char</span>*)r, <span class="hljs-number">5</span>, PGSIZE); <span class="hljs-comment">// fill with junk</span>  <span class="hljs-keyword">return</span> (<span class="hljs-type">void</span>*)r;}</code></pre></div></details><p>But this doesn't implement stealing yet.</p><p>Modify <code>kalloc()</code>:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 33 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 33 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span> *<span class="hljs-title function_">kalloc</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">r</span>;</span>  push_off();  <span class="hljs-type">int</span> id = cpuid();  acquire(&amp;kmem.lock[id]);  r = kmem.freelist[id];  <span class="hljs-keyword">if</span>(r)    kmem.freelist[id] = r-&gt;next;  release(&amp;kmem.lock[id]);  <span class="hljs-keyword">if</span> (r == <span class="hljs-number">0</span>) {    <span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> i = <span class="hljs-number">0</span>; i &lt; NCPU; ++i) {      <span class="hljs-comment">// 找到序号最小的有空余页的空闲列表</span>      <span class="hljs-keyword">if</span> (i == id) {        <span class="hljs-keyword">continue</span>;      }      acquire(&amp;kmem.lock[i]);      <span class="hljs-keyword">if</span> (kmem.freelist[i]) {        r = kmem.freelist[i];        kmem.freelist[i] = r-&gt;next;      }      release(&amp;kmem.lock[i]);      <span class="hljs-keyword">if</span> (r) {        <span class="hljs-keyword">break</span>;      }    }  }  pop_off();  <span class="hljs-keyword">if</span>(r)    <span class="hljs-built_in">memset</span>((<span class="hljs-type">char</span>*)r, <span class="hljs-number">5</span>, PGSIZE); <span class="hljs-comment">// fill with junk</span>  <span class="hljs-keyword">return</span> (<span class="hljs-type">void</span>*)r;}</code></pre></div></details><p>Then all tests pass.</p><h2 id="Read-write-lock">Read-write lock</h2><p>Consider in xv6:</p><div class="code-wrapper"><pre><code class="hljs c">sys_pause()sys_uptime()</code></pre></div><p>Both of these functions read the global variable <code>ticks</code>.</p><p>But <code>ticks</code> is also updated by <code>clockintr()</code> at the same time, so both functions acquire <code>tickslock</code> before reading <code>ticks</code>. But actually only a write lock needs to be held; there's no need at all to set up read-related locks. This lab is about distinguishing readers from writers.</p><p>Reviewing the OSTEP content: in the readers-writers problem, the rules are:</p><ul><li>At any given time, there can be at most <strong>one writer</strong>;</li><li>When a writer exists, no reader can exist;</li><li>If there is no writer, <strong>multiple readers</strong> can exist simultaneously.</li><li>To prevent readers from reading forever and starving writers, writer priority is set: once a writer starts trying to acquire the lock, any readers that arrive afterwards must wait until that writer successfully acquires the lock and releases it.</li></ul><p>read-write lock API (in <code>kernel/defs.h</code>):</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span> <span class="hljs-title function_">initrwlock</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock*)</span>;<span class="hljs-type">void</span> <span class="hljs-title function_">read_acquire</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock*)</span>;<span class="hljs-type">void</span> <span class="hljs-title function_">read_release</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock*)</span>;<span class="hljs-type">void</span> <span class="hljs-title function_">write_acquire</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock*)</span>;<span class="hljs-type">void</span> <span class="hljs-title function_">write_release</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock*)</span>;</code></pre></div><p>This lab requires completing the stub functions corresponding to the read-write spinlock API in <code>kernel/spinlock.c</code>, and modifying the <code>struct rwspinlock</code> definition in <code>kernel/spinlock.h</code>.</p><p>The hints say to read the <code>sys_rwlktest()</code> function to understand the test cases; basically it just keeps verifying reads and writes (the four rules above).</p><p>From the tests, we can infer that this lock needs to record at least:</p><ul><li>The number of readers</li><li>Whether there is currently an active reader</li><li>The number of currently waiting writers</li></ul><p>At the same time, <strong>all state transitions must be atomic</strong>.</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// Reader-writer lock.</span><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">rwspinlock</span> {</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">spinlock</span> <span class="hljs-title">l</span>;</span> <span class="hljs-comment">// state lock</span>  <span class="hljs-type">int</span> readers;  <span class="hljs-type">int</span> waiting_writers;  <span class="hljs-type">int</span> is_writer_active;};</code></pre></div><p>The hints say:</p><blockquote><p>If you don't modify anything and run <code>rwlktest</code> directly in xv6, the kernel will print:</p><div class="code-wrapper"><pre><code class="hljs text">panic: acquire</code></pre></div><p>The reason is that the original spinlock implementation only allows the lock to be held by one thread at a time.</p><p>You need to replace the calls to <code>acquire()</code> and <code>release()</code> in:</p><div class="code-wrapper"><pre><code class="hljs text">write_acquire_innerwrite_release_innerread_acquire_innerread_release_inner</code></pre></div><p>with your own lock implementation.</p></blockquote><p>The implementation part:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 60 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 60 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">static</span> <span class="hljs-type">void</span><span class="hljs-title function_">read_acquire_inner</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock *rwlk)</span>{  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) {    acquire(&amp;rwlk-&gt;l);    <span class="hljs-keyword">if</span> (rwlk-&gt;is_writer_active == <span class="hljs-number">0</span> &amp;&amp; rwlk-&gt;waiting_writers == <span class="hljs-number">0</span>) {      rwlk-&gt;readers++;      release(&amp;rwlk-&gt;l);      <span class="hljs-keyword">return</span>;    }    release(&amp;rwlk-&gt;l);  }}<span class="hljs-type">static</span> <span class="hljs-type">void</span><span class="hljs-title function_">read_release_inner</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock *rwlk)</span>{  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) {    acquire(&amp;rwlk-&gt;l);    <span class="hljs-keyword">if</span> (rwlk-&gt;readers &gt; <span class="hljs-number">0</span>) {      rwlk-&gt;readers--;      release(&amp;rwlk-&gt;l);      <span class="hljs-keyword">return</span>;    }    release(&amp;rwlk-&gt;l);  }}<span class="hljs-type">static</span> <span class="hljs-type">void</span><span class="hljs-title function_">write_acquire_inner</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock *rwlk)</span>{  <span class="hljs-comment">// 首先这个肯定不能放到循环里面，其次这个务必要加锁</span>  acquire(&amp;rwlk-&gt;l);  rwlk-&gt;waiting_writers++;  release(&amp;rwlk-&gt;l);  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) {    acquire(&amp;rwlk-&gt;l);    <span class="hljs-keyword">if</span> (rwlk-&gt;readers == <span class="hljs-number">0</span> &amp;&amp; rwlk-&gt;is_writer_active == <span class="hljs-number">0</span>) {      rwlk-&gt;waiting_writers--;      rwlk-&gt;is_writer_active = <span class="hljs-number">1</span>;      release(&amp;rwlk-&gt;l);      <span class="hljs-keyword">return</span>;    }    release(&amp;rwlk-&gt;l);  }}<span class="hljs-type">static</span> <span class="hljs-type">void</span><span class="hljs-title function_">write_release_inner</span><span class="hljs-params">(<span class="hljs-keyword">struct</span> rwspinlock *rwlk)</span>{  <span class="hljs-keyword">while</span> (<span class="hljs-number">1</span>) {    acquire(&amp;rwlk-&gt;l);    <span class="hljs-keyword">if</span> (rwlk-&gt;is_writer_active) {      rwlk-&gt;is_writer_active = <span class="hljs-number">0</span>;      release(&amp;rwlk-&gt;l);      <span class="hljs-keyword">return</span>;    }    release(&amp;rwlk-&gt;l);  }}</code></pre></div></details><p>2 points to note:</p><ol><li>You must add a loop, because it keeps trying to acquire — remember this is a spinlock<ul><li>At first I read OSTEP's section on implementing read-write locks and didn't see it; only later did I realize they use a semaphore mechanism, and the semaphore mechanism is built on read-write locks underneath. The data structures we implemented are actually somewhat like implementing a semaphore mechanism.</li></ul></li><li>In the <code>write_acquire_inner(*struct* rwspinlock **rwlk*)</code> function, the addition to the <code>waiting_writers</code> variable must definitely be placed outside the loop and at the beginning of the function, because it represents the start of waiting, and the spinning is the waiting process. Also, obviously you need to acquire the lock — I forgot to do that at first, and test8 wouldn't pass.</li></ol><p><img src="https://image.wendaining.top/image-20260818183344272.png" alt="All tests passed"></p>]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab6 network driver - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab6-network-driver/</link>
      <description>The sixth xv6 lab: writing a network driver.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Mon, 10 Aug 2026 03:09:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab6-network-driver/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Reading">Reading</h2><p>Interrupt: hardware needs to get the OS's attention, so it raises an interrupt, a process similar to a system call. But there are differences:</p><ul><li>Asynchronous, unrelated to the process currently running on the CPU</li><li>Parallel, the device runs in parallel with the CPU</li><li>Requires a driver</li></ul><p>Many device drivers execute code in two different contexts:</p><ul><li><strong>Top half</strong>: runs in the kernel thread of some process.</li><li><strong>Bottom half</strong>: executes when an interrupt occurs, i.e., the interrupt handler.</li></ul><h2 id="Part-One-NIC">Part One: NIC</h2><p>The network stack has already prepared a memory buffer holding a complete packet (which stores packets); what we need to do is complete two functions.</p><p>Explanations of some unfamiliar terms:</p><ul><li><p>NIC Network Interface Card, a network card; the E1000 is one type of NIC</p></li><li><p>DMA Direct Memory Access:</p><ul><li>Generally, hardware cannot directly manipulate kernel memory</li><li>But once DMA is configured, the E1000 can directly read and write specified memory, i.e., the buffer</li><li>This way, the CPU doesn't need to move the data itself</li></ul></li><li><p>Descriptor, mainly tells the network card the packet's location, length, and other information; in the code it is <code>tx_desc</code></p>  <div class="code-wrapper"><pre><code class="hljs text">descriptor├── addr: the memory address of the buffer├── length: the packet length├── status: whether the NIC has finished processing└── cmd: what operation the NIC is asked to perform</code></pre></div><ul><li>TX descriptor: describes "the packet to be sent".</li><li>RX descriptor: describes "an empty buffer used to receive packets".</li></ul></li><li><p>Descriptor Ring: since the number of descriptors is limited, it is a ring; in the assignment it is 0~15</p></li><li><p>Control register: the driver notifies the E1000 of relevant operations through control registers; specifically, this is <code>regs[]</code></p></li><li><p>TDT Transmit Descriptor Tail, which can be understood as "which descriptor in the TX ring the driver should fill in next"</p></li><li><p>RDT Receive Descriptor Tail: "the last RX descriptor that the driver has finished processing and handed back to the E1000"</p></li><li><p>DD Descriptor Done, a flag bit in the descriptor's <code>status</code> field</p><ul><li>For TX, DD means the E1000 has finished sending the packet corresponding to this descriptor and will no longer read its buffer</li><li>For RX, DD means the E1000 has received a packet and written it completely into the buffer pointed to by this descriptor</li></ul></li><li><p>EOP End Of Packet, the end of a packet</p></li><li><p>RS Report Status</p></li><li><p><code>net_rx()</code> the entry point for the xv6 network stack to receive packets</p></li></ul><p>First, complete <code>e1000_transmit()</code>:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 26 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 26 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span><span class="hljs-title function_">e1000_transmit</span><span class="hljs-params">(<span class="hljs-type">char</span> *buf, <span class="hljs-type">int</span> len)</span>{  acquire(&amp;e1000_lock);  uint32 index = regs[E1000_TDT];  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">tx_desc</span> *<span class="hljs-title">desc</span> =</span> &amp;tx_ring[index];  <span class="hljs-keyword">if</span>((desc-&gt;status &amp; E1000_TXD_STAT_DD) == <span class="hljs-number">0</span>){    release(&amp;e1000_lock);    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }  <span class="hljs-keyword">if</span>(desc-&gt;addr != <span class="hljs-number">0</span>)    kfree((<span class="hljs-type">void</span> *)desc-&gt;addr);  desc-&gt;addr = (uint64)buf;  desc-&gt;length = len;  desc-&gt;cmd = E1000_TXD_CMD_EOP | E1000_TXD_CMD_RS;  desc-&gt;status = <span class="hljs-number">0</span>;  regs[E1000_TDT] = (index + <span class="hljs-number">1</span>) % TX_RING_SIZE;  release(&amp;e1000_lock);  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;}</code></pre></div></details><p>Following the concepts and hints above, it can be completed.</p><p>Then <code>e1000_recv()</code>, which can likewise be completed the same way.</p><h2 id="Part-Two-UDP-Receive">Part Two: UDP Receive</h2><p>In this part, the spec is given in more detail. Just read it as is; you don't even need to read other manuals.</p><p>Follow the hints step by step:</p><h3 id="1-Create-the-data-structures">1. Create the data structures</h3><blockquote><p>Create a struct to keep track of bound ports and the packets in their queues.</p></blockquote><p>Define two:</p><ul><li><code>udp_packet</code> represents a packet in a queue</li><li><code>udp_port</code> represents a bound port, and also records the next port, forming a linked list, which can be used to check whether a port is allocated</li></ul><p>Use a port object pool to allocate bound ports:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> UDP_PORTS_PER_PAGE 12</span><span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">udp_port_page</span> {</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">udp_port</span> <span class="hljs-title">ports</span>[<span class="hljs-title">UDP_PORTS_PER_PAGE</span>];</span>  <span class="hljs-type">int</span> used;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">udp_port_page</span> *<span class="hljs-title">next</span>;</span>};</code></pre></div><p>Implementation of <code>sys_bind()</code>: check the incoming port number, then check whether it is already bound; if not, allocate it, then add it to the ports linked list.</p><p>Implementation of <code>ip_rx()</code>: check the received packet, then find the corresponding port.</p><p>Implementation of <code>sys_recv()</code>: just follow the hint.</p><p>Note: there is a test that tries to obtain the DNS of the MIT pdos website; with some special VPN settings enabled it seems to fail, so I tried turning off the VPN / system proxy / TUN one after another to test... The final result was: turn on the system proxy and turn off TUN.</p><p>Remember that after changing the proxy, you also need to restart WSL for it to take effect.</p><p><img src="https://image.wendaining.top/5a227a70-80ad-4be2-b7ce-a88cd4cd0981.png" alt="All tests passed"></p>]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab5 Copy on-write - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab5-copy-on-write/</link>
      <description>The fifth lab of xv6: understanding and implementing the Copy-on-Write mechanism.</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Sat, 08 Aug 2026 03:01:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab5-copy-on-write/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><h2 id="Reading">Reading</h2><p>This lab's guidance, unusually, gives no instruction to read the xv6 book. But I still took a look at the course documentation: <a href="https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/lec08-page-faults-frans/8.1-page-fault-basics">8.1 Page Fault Basics | MIT6.S081</a></p><p>This chapter actually covers the original Lazy Allocation Lab, Copy-on-write Lab, and the mmap lab.</p><p>Here I'll just briefly summarize the idea of Copy-on-write:</p><p>After a process forks, it creates a complete copy of the parent process. In the current implementation, the physical space is copied directly; and if exec is executed immediately after fork, this address space will be discarded, which is very wasteful.</p><p>The idea of COW is that the child process and the parent process map their virtual address spaces to the same physical address, but the PTE is set to read-only. If a write occurs (whether performed by the parent or the child), a page fault is triggered, the corresponding page is copied, the PTE is set to read-write, and execution continues.</p><p>To mark a page as a COW page, the last bit of the PTE is used.</p><p>Meanwhile, since the previous implementation had no mapping where one physical address corresponds to multiple virtual addresses, the release at process exit would also have problems. The solution is to add a reference count to physical page frames.</p><h2 id="Implement-copy-on-write-fork">Implement copy-on-write fork</h2><p>Actually, the lab's explanation of what copy-on-write is quite clear, even a bit clearer and easier to understand than the course documentation.</p><p>Just follow the provided steps one by one, but first you need to implement some infrastructure (i.e., the content of the hints):</p><h3 id="Recording-COW-mappings-in-the-PTE">Recording COW mappings in the PTE</h3><p>In <code>riscv.h</code></p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> PTE_COW (1L &lt;&lt; 8)</span></code></pre></div><p>Afterwards, just modify it freely when changing flags.</p><h3 id="Modifying-uvmcopy">Modifying <code>uvmcopy()</code></h3><p>This function's original purpose is to completely copy the parent process's page table into the new process when creating a child process (analyzed thoroughly in the Page table Lab).</p><p>What needs to be done here: no longer allocate new physical pages for the child process and copy data; instead, <strong>directly map the parent process's physical pages into the child process's page table</strong>, and <strong>clear <code>PTE_W</code> in the pages of both the parent and child processes</strong>.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 29 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 29 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span><span class="hljs-title function_">uvmcopy</span><span class="hljs-params">(<span class="hljs-type">pagetable_t</span> old, <span class="hljs-type">pagetable_t</span> new, uint64 sz)</span>{  <span class="hljs-type">pte_t</span> *pte;  uint64 pa, i;  uint flags;  <span class="hljs-keyword">for</span>(i = <span class="hljs-number">0</span>; i &lt; sz; i += PGSIZE){    <span class="hljs-keyword">if</span>((pte = walk(old, i, <span class="hljs-number">0</span>)) == <span class="hljs-number">0</span>)      <span class="hljs-keyword">continue</span>;   <span class="hljs-comment">// page table entry hasn't been allocated</span>    <span class="hljs-keyword">if</span>((*pte &amp; PTE_V) == <span class="hljs-number">0</span>)      <span class="hljs-keyword">continue</span>;   <span class="hljs-comment">// physical page hasn't been allocated</span>    pa = PTE2PA(*pte);    flags = PTE_FLAGS(*pte);    <span class="hljs-keyword">if</span>(flags &amp; PTE_W) {      flags &amp;= ~PTE_W;      flags |= PTE_COW;      *pte = PA2PTE(pa) | flags;    }    <span class="hljs-keyword">if</span>(mappages(new, i, PGSIZE, pa, flags) != <span class="hljs-number">0</span>)      <span class="hljs-keyword">goto</span> err;  }  <span class="hljs-comment">// <span class="hljs-doctag">TODO:</span> 是否要刷新 TLB？留待之后分析</span>  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; err:  uvmunmap(new, <span class="hljs-number">0</span>, i / PGSIZE, <span class="hljs-number">1</span>);  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;}</code></pre></div></details><h3 id="Modifying-vmfault-to-handle-COW-page-faults">Modifying <code>vmfault()</code> to handle COW page faults</h3><p>Regarding the purpose of the <code>vmfault()</code> function, see the explanation in the Page table Lab; it is mainly related to Lazy Allocation.</p><p>In the current <code>vmfault()</code> function, the <code>read</code> parameter is unused. I guess its purpose is to distinguish between different types of page faults. The answer I got from asking an LLM:</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1356 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">The read parameter of vmfault() is used to distinguish whether this page...</span></summary><blockquote><p>The <code>read</code> parameter of <code>vmfault()</code> is used to distinguish whether this page fault was caused by a "read" or a "write".</p><p>In <code>trap.c</code>:</p><div class="code-wrapper"><pre><code class="hljs c">vmfault(p-&gt;pagetable, r_stval(),        (r_scause() == <span class="hljs-number">13</span>) ? <span class="hljs-number">1</span> : <span class="hljs-number">0</span>)</code></pre></div><p>The correspondence is:</p><table><thead><tr><th><code>scause</code></th><th>Meaning</th><th style="text-align:right"><code>read</code></th></tr></thead><tbody><tr><td>13</td><td>Load page fault, read failed</td><td style="text-align:right">1</td></tr><tr><td>15</td><td>Store page fault, write failed</td><td style="text-align:right">0</td></tr></tbody></table><p>Your current <code>vmfault()</code> only handles lazy allocation: as long as the page is unmapped, it allocates a zero page. Reads and writes are handled the same way, so <code>read</code> is currently unused.</p><p>At the COW stage, it becomes meaningful:</p><div class="code-wrapper"><pre><code class="hljs text">read == 0, and the page has PTE_COW    → this is a write to a COW page    → allocate a new page, copy the contents, restore PTE_Wread == 1    → cannot be treated as a COW write</code></pre></div><p>Because a COW page only has <code>PTE_W</code> cleared, while <code>PTE_R</code> is still retained:</p><div class="code-wrapper"><pre><code class="hljs text">Reading a COW page: normal, should not faultWriting a COW page: produces a store page fault</code></pre></div><p>Therefore, if a read fault occurs on an already-mapped page, it usually means it is not a legitimate COW write, and the page must not be copied into a writable page.</p><p>Also, <code>copyout()</code> writes data from the kernel to user space, so when calling the COW handling logic later, it should be treated as a write operation, i.e., equivalent to:</p><div class="code-wrapper"><pre><code class="hljs c">read = <span class="hljs-number">0</span>;</code></pre></div><p>Summary: <code>read</code> is currently unused in lazy allocation; it is prepared for distinguishing read/write page faults, especially the later COW write fault.</p></blockquote></details><p>Then I roughly had an idea but was a bit too lazy to type it out myself (actually, I didn't quite know how), so I fed the LLM this prompt:</p><blockquote><p>Regarding this step of modifying vmfault, I roughly have an idea: first, if read=1, handle it exactly the same as the original logic; if read=0, first check the page — the way to check is to walk() to find the pte and then check the flags, then kalloc to allocate a new physical page, modify the original pte's flags (mainly the write part, and remove cow along the way), then copy, and finally make the pte point to this new page. Since only pages originally set as writable get marked with cow, there's no need to check whether it's writable. But I'm having trouble organizing in my head how to couple this logic with the existing lazy allocation logic, so please directly modify this code for me and explain it along the way.</p></blockquote><p>Code implementation:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 37 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 37 行</span></summary><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">vmfault</span><span class="hljs-params">(<span class="hljs-type">pagetable_t</span> pagetable, uint64 va, <span class="hljs-type">int</span> read)</span>{  uint64 mem, pa;  uint flags;  <span class="hljs-type">pte_t</span> *pte;  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">proc</span> *<span class="hljs-title">p</span> =</span> myproc();  <span class="hljs-keyword">if</span> (va &gt;= p-&gt;sz)    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  va = PGROUNDDOWN(va);  <span class="hljs-keyword">if</span>(ismapped(pagetable, va)) {    pte = walk(pagetable, va, <span class="hljs-number">0</span>);    <span class="hljs-keyword">if</span>(read || (*pte &amp; PTE_U) == <span class="hljs-number">0</span> || (*pte &amp; PTE_COW) == <span class="hljs-number">0</span>)      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;    pa = PTE2PA(*pte);    flags = PTE_FLAGS(*pte);    mem = (uint64)kalloc();    <span class="hljs-keyword">if</span>(mem == <span class="hljs-number">0</span>)      <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;    memmove((<span class="hljs-type">void</span> *)mem, (<span class="hljs-type">void</span> *)pa, PGSIZE);    flags = (flags | PTE_W) &amp; ~PTE_COW;    *pte = PA2PTE(mem) | flags;    <span class="hljs-keyword">return</span> mem;  }  mem = (uint64) kalloc();  <span class="hljs-keyword">if</span>(mem == <span class="hljs-number">0</span>)    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  <span class="hljs-built_in">memset</span>((<span class="hljs-type">void</span> *) mem, <span class="hljs-number">0</span>, PGSIZE);  <span class="hljs-keyword">if</span> (mappages(p-&gt;pagetable, va, PGSIZE, mem, PTE_W|PTE_U|PTE_R) != <span class="hljs-number">0</span>) {    kfree((<span class="hljs-type">void</span> *)mem);    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;  }  <span class="hljs-keyword">return</span> mem;}</code></pre></div></details><p>A few key points:</p><ul><li><div class="note note-success"><p><code>va &gt;= p-&gt;sz</code> and <code>ismapped()</code> check two completely different questions:</p><ul><li><code>va &gt;= p-&gt;sz</code>: is this virtual address within the process's legal address range?</li><li><code>ismapped()</code>: does this legal virtual address currently have a corresponding physical page?</li></ul></div></li><li><p>The original lazy allocation logic was to check <code>ismapped()</code>; if there is a mapping, it means a corresponding physical page exists, so ignore it. But now we need to couple in the COW logic, and a COW page must have a corresponding physical page (considering that the logic of <code>uvmcopy</code> is to establish mappings from virtual pages to actually existing physical pages, using <code>mappages()</code> in a loop). Therefore, <strong>the COW logic here falls entirely on the <code>ismapped</code> part that originally just did <code>return 0</code></strong>.</p></li><li><p>Here we continue checking: if it's read-only, or not a COW page, or <code>(*pte &amp; PTE_U) == 0</code>, i.e., this page is not accessible in user mode (such as the trampoline page, etc.), just return directly.</p></li><li><p>Then, get all the information corresponding to this page. <strong>Unlike the prompt I gave earlier, first copy the old page, then compute the new flags, and only then replace the PTE — this is to prevent the case where, if <code>kalloc()</code> fails, the original valid mapping could also be broken</strong>.</p></li><li><div class="note note-primary"><p>The so-called flags <strong>only exist on virtual pages, i.e., ptes; physical pages don't have them</strong>!</p></div></li><li><p>After that, the COW part of the logic is done, and the rest is handed off to the lazy allocation logic.</p></li></ul><h3 id="Implementing-physical-page-reference-counting">Implementing physical page reference counting</h3><p>We must ensure that each physical page is only freed after the last PTE reference to it disappears.</p><p>Initially, I thought the rules for maintaining reference counts would be:</p><ul><li>When <code>kalloc()</code> allocates a page, initialize the count to 1</li><li>When <code>fork()</code> lets the child process share physical pages, increment the reference count by 1. Although it's called <code>fork()</code>, it's actually implemented inside <code>uvmcopy()</code>, corresponding to <code>uvmunmap()</code> below.</li><li>When a process removes this page from its page table (<code>uvmunmap()</code>), decrement the reference count by 1.</li><li>The logic of <code>kfree()</code>: only when the reference count is 0 can the page be put back on the free list.</li><li>The so-called physical address, i.e., <code>pa</code>. Since physical page frame addresses are always <code>PGSIZE</code>-aligned, we can use <code>pa / PGSIZE</code> as the array index to record a page's reference count (in fact, this number is which physical page frame it is). The size of the array can just be based on <code>PHYSTOP</code>.</li><li>One thing to be careful about here: this array must not be modified arbitrarily. It's best to add a lock, and access it for increment/decrement through the dedicated functions <code>krefinc()</code> and <code>krefdec()</code>, to prevent concurrency conflicts.</li></ul><p>But in reality there are several problems:</p><ul><li><code>krefdec()</code> actually shouldn't exist; instead, all reference count decrements should be placed inside <code>kfree()</code>. Because there are far more places that remove the reference between a virtual page and a physical page than just <code>uvmunmap()</code>. For example, <code>vmfault()</code> directly changes the old physical page to a new physical page, which is effectively a dereference, but it doesn't go through <code>uvmunmap()</code>. But in any case, this is equivalent to decrementing the reference count.<ul><li><strong>Therefore, the semantics of <code>kfree()</code> need to be modified here</strong>. It should first be responsible for decrementing the reference count by 1, then check — only if it really drops to 0 should it perform the release (put it back on the free list).</li></ul></li><li><code>int phy_ref[PHYSTOP / PGSIZE];</code> is rather wasteful; better to use <code>int phy_ref[(PHYSTOP - KERNBASE) / PGSIZE]</code> and write an <code>index</code> mapping function.</li><li><code>freerange()</code> needs special handling, because at the start of <code>freerange()</code> the pages' initial counts are all 0, but <code>kfree()</code> would make them -1, so first set them to 1.</li></ul><p>Excerpting some core code:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 71 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 71 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-meta">#<span class="hljs-keyword">define</span> NPAGE ((PHYSTOP - KERNBASE) / PGSIZE)</span><span class="hljs-class"><span class="hljs-keyword">struct</span> {</span>  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">spinlock</span> <span class="hljs-title">lock</span>;</span>  <span class="hljs-type">int</span> count[NPAGE];} kref;<span class="hljs-type">static</span> <span class="hljs-type">int</span><span class="hljs-title function_">paindex</span><span class="hljs-params">(uint64 pa)</span>{  <span class="hljs-keyword">return</span> (pa - KERNBASE) / PGSIZE;}<span class="hljs-type">void</span><span class="hljs-title function_">freerange</span><span class="hljs-params">(<span class="hljs-type">void</span> *pa_start, <span class="hljs-type">void</span> *pa_end)</span>{  <span class="hljs-type">char</span> *p;  p = (<span class="hljs-type">char</span>*)PGROUNDUP((uint64)pa_start);  <span class="hljs-keyword">for</span>(; p + PGSIZE &lt;= (<span class="hljs-type">char</span>*)pa_end; p += PGSIZE){    <span class="hljs-comment">// kfree() drops a reference, so give each boot-time page one</span>    <span class="hljs-comment">// reference before adding it to the free list.</span>    acquire(&amp;kref.lock);    kref.count[paindex((uint64)p)] = <span class="hljs-number">1</span>;    release(&amp;kref.lock);    kfree(p);  }}<span class="hljs-type">void</span><span class="hljs-title function_">kfree</span><span class="hljs-params">(<span class="hljs-type">void</span> *pa)</span>{  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">run</span> *<span class="hljs-title">r</span>;</span>  <span class="hljs-keyword">if</span>(((uint64)pa % PGSIZE) != <span class="hljs-number">0</span> || (<span class="hljs-type">char</span>*)pa &lt; end || (uint64)pa &gt;= PHYSTOP)    panic(<span class="hljs-string">"kfree"</span>);  <span class="hljs-type">int</span> index = paindex((uint64)pa);  acquire(&amp;kref.lock);  <span class="hljs-keyword">if</span>(kref.count[index] &lt; <span class="hljs-number">1</span>)    panic(<span class="hljs-string">"kfree: no reference"</span>);  kref.count[index]--;  <span class="hljs-keyword">if</span>(kref.count[index] &gt; <span class="hljs-number">0</span>){    release(&amp;kref.lock);    <span class="hljs-keyword">return</span>;  }  release(&amp;kref.lock);  <span class="hljs-comment">// Fill with junk to catch dangling refs.</span>  <span class="hljs-built_in">memset</span>(pa, <span class="hljs-number">1</span>, PGSIZE);  r = (<span class="hljs-keyword">struct</span> run*)pa;  acquire(&amp;kmem.lock);  r-&gt;next = kmem.freelist;  kmem.freelist = r;  release(&amp;kmem.lock);}<span class="hljs-type">void</span><span class="hljs-title function_">krefinc</span><span class="hljs-params">(uint64 pa)</span>{  <span class="hljs-keyword">if</span>((pa % PGSIZE) != <span class="hljs-number">0</span> || (<span class="hljs-type">char</span>*)pa &lt; end || pa &gt;= PHYSTOP)    panic(<span class="hljs-string">"krefinc"</span>);  <span class="hljs-type">int</span> index = paindex(pa);  acquire(&amp;kref.lock);  <span class="hljs-keyword">if</span>(kref.count[index] &lt; <span class="hljs-number">1</span>)    panic(<span class="hljs-string">"krefinc: free page"</span>);  kref.count[index]++;  release(&amp;kref.lock);}</code></pre></div></details><h3 id="Modifying-copyout">Modifying <code>copyout()</code></h3><p>First, let's clarify what <code>copyout()</code> is:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-comment">// Copy from kernel to user.</span><span class="hljs-comment">// Copy len bytes from src to virtual address dstva in a given page table.</span><span class="hljs-comment">// Return 0 on success, -1 on error.</span><span class="hljs-type">int</span> <span class="hljs-title function_">copyout</span><span class="hljs-params">(<span class="hljs-type">pagetable_t</span> pagetable, uint64 dstva, <span class="hljs-type">char</span> *src, uint64 len)</span></code></pre></div><p>From this function signature, we can see that its purpose is to safely copy data from kernel space into a process's user virtual address.</p><p>The current <code>copyout()</code> logic includes handling for lazy allocation:</p><div class="code-wrapper"><pre><code class="hljs c">pa0 = walkaddr(pagetable, va0);<span class="hljs-keyword">if</span>(pa0 == <span class="hljs-number">0</span>) {  <span class="hljs-keyword">if</span>((pa0 = vmfault(pagetable, va0, <span class="hljs-number">0</span>)) == <span class="hljs-number">0</span>) {    <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;  }}</code></pre></div><p>If this user address is not yet mapped, the current code attempts to allocate a page via <code>vmfault()</code>.</p><p>But it currently cannot correctly handle the COW logic, because a COW page doesn't have <code>PTE_W</code>, but is actually writable — we just need to simulate a write page fault, which is simply calling <code>vmfault()</code> once.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 47 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 47 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">int</span><span class="hljs-title function_">copyout</span><span class="hljs-params">(<span class="hljs-type">pagetable_t</span> pagetable, uint64 dstva, <span class="hljs-type">char</span> *src, uint64 len)</span>{  uint64 n, va0, pa0;  <span class="hljs-type">pte_t</span> *pte;  <span class="hljs-type">int</span> needfault;  <span class="hljs-keyword">while</span>(len &gt; <span class="hljs-number">0</span>){    va0 = PGROUNDDOWN(dstva);    <span class="hljs-keyword">if</span>(va0 &gt;= MAXVA) {      <span class="hljs-keyword">goto</span> err;    }    needfault = <span class="hljs-number">0</span>;    pa0 = walkaddr(pagetable, va0);    <span class="hljs-keyword">if</span>(pa0 == <span class="hljs-number">0</span>){      needfault = <span class="hljs-number">1</span>;    } <span class="hljs-keyword">else</span> {      pte = walk(pagetable, va0, <span class="hljs-number">0</span>);      <span class="hljs-keyword">if</span>((*pte &amp; PTE_W) == <span class="hljs-number">0</span>){        <span class="hljs-keyword">if</span>((*pte &amp; PTE_COW) == <span class="hljs-number">0</span>) {          <span class="hljs-keyword">goto</span> err;        }        needfault = <span class="hljs-number">1</span>;      }    }<span class="hljs-comment">// 这里运用了布尔语句的短路特性</span>    <span class="hljs-keyword">if</span>(needfault &amp;&amp; (pa0 = vmfault(pagetable, va0, <span class="hljs-number">0</span>)) == <span class="hljs-number">0</span>) {      <span class="hljs-keyword">goto</span> err;    }          n = PGSIZE - (dstva - va0);    <span class="hljs-keyword">if</span>(n &gt; len) {      n = len;    }    memmove((<span class="hljs-type">void</span> *)(pa0 + (dstva - va0)), src, n);    len -= n;    src += n;    dstva = va0 + PGSIZE;  }  <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>; err:  <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>;}</code></pre></div></details><p>Passed all tests:</p><img src="https://image.wendaining.top/image-20260809121444034.png" style="zoom:50%;">]]>
      </content:encoded>
    </item>
    <item>
      <title>xv6 Lab4 Traps - MIT 6.1810 Fall 2025 Operating System</title>
      <link>https://blog.wendain.ing/en/posts/xv6-lab4-traps/</link>
      <description>The fourth xv6 lab, involving quite a bit of assembly source code and low-level RISC-V hardware interaction</description>
      <author>wendaining</author>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/categories/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/xv6/">xv6</category>
      <category domain="https://blog.wendain.ing/en/tags/%E8%AF%BE%E7%A8%8B%E7%AC%94%E8%AE%B0/">Course Notes</category>
      <category domain="https://blog.wendain.ing/en/tags/%E5%85%AC%E5%BC%80%E8%AF%BE/">Open Courses</category>
      <category domain="https://blog.wendain.ing/en/tags/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/">Operating Systems</category>
      <category domain="https://blog.wendain.ing/en/tags/xv6/">xv6</category>
      <pubDate>Thu, 30 Jul 2026 09:51:00 GMT</pubDate>
      <content:encoded>
        <![CDATA[<div class="note note-warning translation-notice"><p>This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to <a href="https://blog.wendain.ing/posts/xv6-lab4-traps/" hreflang="zh-CN">original Chinese version</a>. I am continuously working to improve the translation.</p></div><div class="note note-primary"><p><strong>Some thoughts on doing this lab</strong>: It's better to choose the Fall 2020 / Fall 2021 versions rather than the 2025 one. That's because the Chinese internet's materials for this course are concentrated on the first two versions, and the same goes for the various source code analyses.</p></div><h2 id="Reading">Reading</h2><p>I originally planned to watch the recorded lectures, but found I couldn't really get into them, so I switched back to reading the documentation.</p><p>Summarizing the more important mechanisms:</p><h3 id="mode">mode</h3><p>Compared to user mode, supervisor mode has only two special privileges:</p><ul><li>It can read and write control registers</li><li>It can use PTEs whose <code>PTE_U</code> flag is 0. When the <code>PTE_U</code> flag is 1, <strong>only</strong> user code can use that page table entry; if the flag is 0, only supervisor mode can use it</li></ul><p><strong>Privileges/settings it does not have</strong>:</p><ul><li>It cannot read and write arbitrary physical addresses; like ordinary user code, it must access memory through the page table</li><li>The trap mechanism does not control the kernel's ability to view register contents; it only saves them</li></ul><h3 id="Some-important-registers">Some important registers</h3><ul><li>The SATP (Supervisor Address Translation and Protection) register, which contains the physical memory address pointing to the page table (see section 4.3 for details).</li><li>The STVEC (Supervisor Trap Vector Base Address Register) register, which points to the starting address of the instructions in the kernel that handle traps.</li><li>The SEPC (Supervisor Exception Program Counter) register, which holds the value of the program counter during a trap.</li></ul><h3 id="ecall"><code>ecall</code></h3><p><code>ecall</code> is a system instruction provided by RISC-V that performs:</p><ul><li>Switching the code from user mode to supervisor mode</li><li>Saving the value of the program counter in the SEPC register</li><li>Jumping to the instruction pointed to by the STVEC register (the so-called jump is just pointing the PC there)</li></ul><p>For xv6, STVEC points to the trampoline page, which contains the trap handling code.</p><blockquote><p>ecall does not switch the page table, which is a very important characteristic of the ecall instruction. This means that the trap handling code must exist in every user page table. Because ecall does not switch the page table, we need somewhere in the user page table to execute the initial kernel code. This trampoline page is carefully mapped by the kernel into every user page table, so that while we are still using the user page table, the kernel can execute the very first few instructions of the trap mechanism in one place.</p></blockquote><p><strong><code>ecall</code> does very little</strong>, which reflects the RISC philosophy.</p><h3 id="uservec"><code>uservec</code></h3><p>An assembly function used to save user registers.</p><p>Basically, each process has a <code>trapframe</code> struct, and each user page table has a corresponding trapframe page (seen in the syscall lab), which defines all the registers one by one. The assembly implementation is just a bunch of stores like <code>sd ra, 40(a0)</code>.</p><p>But before that, one more thing needs to be done:</p><ul><li>Before entering user space, the kernel saves the trapframe page address 0x3fffffe000 in the SSCRATCH register</li><li>The first line of <code>uservec</code> executes <code>csrrw a0, sscratch, a0</code>, which means swapping the values of the two registers</li></ul><div class="note note-info"><p>But this seems to be the 2020 version; the new version already uses <code>csrw sscratch, a0</code> and <code>li a0, TRAPFRAME</code>.</p><img src="https://image.wendaining.top/image-20260731010850344.png" alt="Rough difference" style="zoom:67%;"></div><div class="note note-primary"><p><strong>The meaning of the register swap here (mainly the significance of a0)</strong>:</p><p>a0 points to the trapframe, and the subsequent assembly code uses a0 as the base register.</p></div><p>Then:</p><ol><li>Load the kernel's stack top pointer into the sp register</li><li>Load the kernel's hartid (CPU core number) into the tp register</li><li>Load the address of the <code>usertrap()</code> function into the t0 register (when printed it is <code>0x800027a0</code>, which belongs to the kernel text region of the virtual address space)</li><li>Load the pointer to the kernel page table into the t1 register</li><li>Switch the page table by loading the kernel page table pointer into the satp register</li><li>Jump to the function <code>usertrap()</code> via a jump instruction; this is kernel C code</li></ol><p>To summarize what was done:</p><ol><li>Save the user register data</li><li>Set up stack space for the kernel code</li><li>Switch the page table</li></ol><h3 id="usertrap"><code>usertrap</code></h3><p>Details omitted—there are too many, and I simply can't remember them all.</p><p>usertrap is responsible for determining <strong>the cause of the trap</strong> and performing the corresponding handling:</p><ul><li>If it is a syscall, call the corresponding system call</li><li>If it is a device interrupt, jump to the corresponding handling code</li><li>If it is a page fault, kill the process</li><li>Finally, execute the <code>usertrapret()</code> function</li></ul><h3 id="Some-changes">Some changes</h3><p>From the later part onward, the 2025 version differs from the 2020 one.</p><details class="collapsible-block collapsible-block--quote"><summary class="collapsible-block__summary" title="引用 · 1018 字"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">引用</span><span class="collapsible-block__meta">The new version of xv6 no longer has usertrapret(), but the functionalit...</span></summary><blockquote><p><strong>The new version of xv6 no longer has <code>usertrapret()</code>, but the functionality hasn't disappeared—it was just renamed and reorganized.</strong></p><p>Officially, in <strong>October 2025</strong>, it was changed from:</p><div class="code-wrapper"><pre><code class="hljs c">usertrapret()</code></pre></div><p>to:</p><div class="code-wrapper"><pre><code class="hljs c">prepare_return()</code></pre></div><p>(<a href="https://github.com/mit-pdos/xv6-riscv/commits?utm_source=chatgpt.com">GitHub</a>)</p><p>The current return path is:</p><div class="code-wrapper"><pre><code class="hljs text">usertrap()    ├─ prepare_return()    └─ return the satp of the user page table           ↓trampoline.S: userret    ├─ switch to the user page table    ├─ restore user registers    └─ sret to return to user mode</code></pre></div><p>Here, <code>prepare_return()</code> handles most of the preparation work of the old <code>usertrapret()</code>:</p><ul><li>Setting <code>stvec = uservec</code></li><li>Filling in the kernel information in the trapframe</li><li>Setting <code>sstatus</code></li><li>Setting <code>sepc</code></li></ul><p>Then <code>usertrap()</code> returns, and the assembly code goes directly into <code>userret</code>. <code>usertrapret</code> can no longer be found in the current source code. (<a href="https://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/trap.c">GitHub</a>)</p><p>So when watching the 2020 course, you can map it directly like this:</p><div class="code-wrapper"><pre><code class="hljs text">Old usertrapret()≈ New prepare_return() + usertrap returning satp + userret</code></pre></div><p>The 2025 version of the xv6 book you uploaded has also been changed to explain <code>prepare_return()</code>.</p></blockquote></details><h2 id="RISC-V-assembly">RISC-V assembly</h2><p>A series of not-so-difficult questions, so I'll just put the answers out directly:</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 TEXT · 33 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">TEXT · 33 行</span></summary><div class="code-wrapper"><pre><code class="hljs txt">Which registers contain arguments to functions? For example, which register holds 13 in main's call to printf?RISC-V uses a0–a7 to pass the first eight function arguments. In main's call to printf, the value 13 is in the a2 register.Where is the call to function f in the assembly code for main? Where is the call to g? (Hint: the compiler may inline functions.)There are no calls to f or g; the compiler inlined the expression f(8) + 1 as 12, which shows up in the assembly as li a1,12At what address is the function printf located?According to the line 30:6c6000ef          jal6f6 &lt;printf&gt;, it is located at 6f6What value is in the register ra just after the jalr to printf in main?According to the RISC-V documentation, when `jal` jumps to the target function, it saves the address of the next instruction into ra, as the address to jump to after the target function finishes executing, so it is 0x30 + 4 = 0x34Run the following code.unsigned int i = 0x00646c72;printf("H%x Wo%s", 57616, (char *) &amp;i);      What is the output? Here's an ASCII table that maps bytes to characters.The output depends on that fact that the RISC-V is little-endian. If the RISC-V were instead big-endian what would you set i to in order to yield the same output? Would you need to change 57616 to a different value?The output is HE110 World$. %x prints 57616 in hexadecimal, giving 0xe110; as for %s, since RISC-V is little-endian, i = 0x00646c72, and after converting to a 4-byte unsigned integer, the bytes from low to high are r l d 0. If it were big-endian, you would set i = 0x726c6400Here's a description of little- and big-endian and a more whimsical description.In the following code, what is going to be printed after 'y='? (note: the answer is not a specific value.) Why does this happen?printf("x=%d y=%d", 3);What gets read is the leftover value in the a2 register, which is UB behavior.</code></pre></div></details><h2 id="Backtrace">Backtrace</h2><p>We need to walk up the stack pointer in the kernel stack, printing the return addresses in the current function call chain.</p><p>Consider this core principle:</p><div class="code-wrapper"><pre><code class="hljs text">current fp  fp - 8   → the return address saved in the current stack frame  fp - 16  → the caller's fp</code></pre></div><p>Then, we can just keep looping like this.</p><p>hint 1:</p><blockquote><p>Add the prototype for your <code>backtrace()</code> to <code>kernel/defs.h</code> so that you can invoke <code>backtrace</code> in <code>sys_pause</code>.</p></blockquote><p>Nothing much to say, just do it.</p><p>hint 2:</p><blockquote><p>The GCC compiler stores the frame pointer of the currently executing function in the register <code>s0</code>. In the section marked by #ifndef <strong>ASSEMBLER</strong> ... #endif, add the following function to <code>kernel/riscv.h</code>:</p><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">static</span> <span class="hljs-keyword">inline</span> uint64<span class="hljs-title function_">r_fp</span><span class="hljs-params">()</span>{  uint64 x;  <span class="hljs-keyword">asm</span> <span class="hljs-title function_">volatile</span><span class="hljs-params">(<span class="hljs-string">"mv %0, s0"</span> : <span class="hljs-string">"=r"</span> (x) )</span>;  <span class="hljs-keyword">return</span> x;}</code></pre></div><p>and call this function in <code>backtrace</code> to read the current frame pointer. <code>r_fp()</code> uses <a href="https://gcc.gnu.org/onlinedocs/gcc/Using-Assembly-Language-with-C.html">in-line assembly</a> to read <code>s0</code>.</p></blockquote><p>Nothing much to say here either. Just do it.</p><p>hint 3:</p><p>It's just the core principle mentioned above.</p><p>Concretely, in code:</p><div class="code-wrapper"><pre><code class="hljs c">uint64 ra = *(uint64 *)(fp - <span class="hljs-number">8</span>);fp = *(uint64 *)(fp - <span class="hljs-number">16</span>);</code></pre></div><p>hint 4:</p><blockquote><p>Your <code>backtrace()</code> will need a way to recognize that it has seen the last stack frame, and should stop. A useful fact is that the memory allocated for each kernel stack consists of a single page-aligned page, so that all the stack frames for a given stack are on the same page. You can use <code>PGROUNDDOWN(fp)</code> (see <code>kernel/riscv.h</code>) to identify the page that a frame pointer refers to.</p></blockquote><p>The point is that we need to loop, and the loop's termination condition is that <code>fp</code> is still valid, and the validity of <code>fp</code> is determined by whether the page is valid.</p><p>First, get the starting address of the page containing the current <code>fp</code>:</p><div class="code-wrapper"><pre><code class="hljs c">uint64 stack_bottom = PGROUNDDOWN(fp);</code></pre></div><p>The page's ending address:</p><div class="code-wrapper"><pre><code class="hljs c">uint64 stack_top = stack_bottom + PGSIZE;</code></pre></div><p>As long as <code>fp</code> is still within this page, we can keep traversing:</p><div class="code-wrapper"><pre><code class="hljs c">fp &gt;= stack_bottom + <span class="hljs-number">16</span> &amp;&amp; fp &lt; stack_top</code></pre></div><p>Nothing else worth mentioning; just do it as described.</p><details class="collapsible-block collapsible-block--code"><summary class="collapsible-block__summary" title="代码 C · 20 行"><span class="collapsible-block__chevron" aria-hidden="true"></span><span class="collapsible-block__label">代码</span><span class="collapsible-block__meta">C · 20 行</span></summary><div class="code-wrapper"><pre><code class="hljs c"><span class="hljs-type">void</span><span class="hljs-title function_">backtrace</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-built_in">printf</span>(<span class="hljs-string">"backtrace:\n"</span>);  uint64 fp = r_fp();  <span class="hljs-comment">// 当前内核栈所在页面的范围</span>  uint64 stack_bottom = PGROUNDDOWN(fp);  uint64 stack_top = stack_bottom + PGSIZE;  <span class="hljs-keyword">while</span>(fp &gt;= stack_bottom + <span class="hljs-number">16</span> &amp;&amp; fp &lt; stack_top){    <span class="hljs-comment">// 当前函数返回到调用者后的地址</span>    uint64 ra = *(uint64 *)(fp - <span class="hljs-number">8</span>);    <span class="hljs-built_in">printf</span>(<span class="hljs-string">"%p\n"</span>, (<span class="hljs-type">void</span>*)ra);    <span class="hljs-comment">// 切换到调用者的栈帧</span>    fp = *(uint64 *)(fp - <span class="hljs-number">16</span>);  }}</code></pre></div></details><h2 id="Alarm">Alarm</h2><p>Follow the hints.</p><p>Hints 1, 2, and 3 have nothing much to say; the only thing worth noting is that I put the <code>sys_sigalarm</code> and <code>sys_sigreturn</code> function signatures in <code>sysproc.c</code>.</p><p>Hints 4 and 5: in <code>proc.h</code>, the addresses are recorded directly as <code>uint64</code>, and cast to pointers later.</p><p>Hints 6 and 7 are essentially one point; in fact, just following hint 7's instructions is enough.</p><p>Hints 8 and 9: do as instructed.</p><ul><li>Hint 8 means that to determine whether an alarm is valid, you should use <code>p-&gt;alarm_interval &gt; 0</code></li><li>Hint 9 means that when the alarm expires, execute <code>p-&gt;trapframe-&gt;epc = p-&gt;alarm_handler;</code> to change the program counter for the jump back.</li></ul><p>The content after hint 10 is the crux of this problem.</p><p>Hint 11 asks which registers should be saved, and hints that there are many. The answer is that all user registers should be saved, because executing the handler may change the contents of many registers. The simplest solution is to save the entire <code>trapframe</code>.</p><p>Thus, hint 12 addresses this point. Add a <code>struct trapframe alarm_trapframe</code> to <code>struct proc</code>:</p><ul><li><code>p-&gt;trapframe</code>: the user context currently in use, which changes as the handler and system calls run</li><li><code>p-&gt;alarm_trapframe</code>: a fixed snapshot of the original program state before the alarm occurred</li></ul><p>The solution is:</p><div class="code-wrapper"><pre><code class="hljs c">memmove(&amp;p-&gt;alarm_trapframe, p-&gt;trapframe, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">struct</span> trapframe));p-&gt;trapframe-&gt;epc = p-&gt;alarm_handler;</code></pre></div><div class="note note-success"><p><code>memmove()</code> copies from the latter argument to the former.</p></div><p>Hint 13 mainly addresses preventing handler reentrancy. Specifically: while the handler is running, a timer interrupt may obviously occur again; if the alarm is triggered again, the original handler recursively enters itself, causing <code>alarm_trapframe</code> to be overwritten by the trapframe from during the handler's execution, and <code>sigreturn()</code> can never find the interrupted original program.</p><p>The solution is to add a flag <code>int alarm_handling;</code>, initialized to 0 in <code>allocproc</code>. The alarm can only accumulate and trigger when <code>p-&gt;alarm_interval &gt; 0 &amp;&amp; !p-&gt;alarm_handling</code>, and upon triggering, set <code>p-&gt;alarm_ticks = 0;</code> and <code>p-&gt;alarm_handling = 1;</code>.</p><p>Finally, hint 14: <code>sys_sigreturn()</code> restores the backup into the current trapframe, i.e.:</p><div class="code-wrapper"><pre><code class="hljs c">memmove(p-&gt;trapframe,        &amp;p-&gt;alarm_trapframe,        <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">struct</span> trapframe));</code></pre></div><div class="note note-info"><p><code>sigreturn()</code> is the last step of the handler, used to tell the kernel that the handler has finished executing and to send me back to the original program.</p></div><p>But <code>a0</code> is special, because <code>a0</code> is treated as the return value. Reading the code of <code>syscall()</code>, you'll find that system calls are executed like this:</p><div class="code-wrapper"><pre><code class="hljs c">p-&gt;trapframe-&gt;a0 = syscalls[num]();</code></pre></div><p>That is, the original <code>a0</code> must be saved and returned as the return value of <code>sigreturn()</code>.</p><div class="code-wrapper"><pre><code class="hljs c">uint64<span class="hljs-title function_">sys_sigreturn</span><span class="hljs-params">(<span class="hljs-type">void</span>)</span>{  <span class="hljs-class"><span class="hljs-keyword">struct</span> <span class="hljs-title">proc</span> *<span class="hljs-title">p</span> =</span> myproc();  uint64 old_a0 = p-&gt;alarm_trapframe.a0;  memmove(p-&gt;trapframe, &amp;p-&gt;alarm_trapframe, <span class="hljs-keyword">sizeof</span>(<span class="hljs-keyword">struct</span> trapframe));  p-&gt;alarm_handling = <span class="hljs-number">0</span>;  <span class="hljs-keyword">return</span> old_a0;}</code></pre></div><p>Running <code>make grade</code>:</p><img src="https://image.wendaining.top/image-20260808105800805.png" style="zoom:33%;">]]>
      </content:encoded>
    </item>
  </channel>
</rss>
