Skip to content

1 - OS Lab: Linux System V IPC

Learning Linux process communication while doing an OS lab: when to use message queues, shared memory, and semaphores, and how to write rock-paper-scissors with them.

On November 15 I was working through an OS lab. The assignment asks for rock-paper-scissors over Linux IPC, a producer-consumer program with semaphores, and a networked version. While doing the lab, I also wanted to understand Linux process communication: what the three System V mechanisms are for, how to create and use them, and how rock-paper-scissors can be written with them.

Processes created with fork() each have their own address space. A variable in one process is invisible to the other. To exchange data, they need a kernel channel. System V IPC is the set of interfaces that comes up first in this lab.

Linux System V IPC: message queues, shared memory, semaphores, rock-paper-scissors, and producer-consumer
Message queues, shared memory, and semaphores, with rock-paper-scissors and producer-consumer

Why IPC Is Needed

Separate address spaces protect processes, and they also break casual sharing. A parent cannot tell a child “scissors this round” through an ordinary global variable; each side only sees its own copy.

IPC leaves a place in the kernel that both sides can touch: a queue of messages, one physical memory region, or a semaphore that only counts and blocks. Rock-paper-scissors in this lab is exactly that problem: take turns, then read the other player’s move.

Three System V Mechanisms

Classic System V IPC has three main tools: message queues, semaphore sets, and shared memory segments. None is simply “better.” They trade convenience against speed.

Message Queues

A message queue moves bounded blocks of data. A process packs a typed message and leaves it with the kernel; the receiver can pull messages by type.

The gain is decoupling and order. The sender does not wait for the receiver to be ready; messages line up in the kernel. The receiver can pick only the types it cares about. The cost is a copy into the kernel and another copy out, so this path is usually the slowest of the three.

For a little discrete control traffic, such as exchanging one move per round, a message queue is often enough: a few lines of code, and the kernel handles queuing, blocking, and type filters.

Semaphores

A semaphore itself carries no business data. It keeps an integer that means “how many resources are free” or “whether the gate is open.” Processes change that value with semop; if there is nothing left, the kernel puts the caller to sleep.

Its core is a counter plus a wait queue, used to order access to a shared resource. If the goal is only “at most two processes may write the log,” a semaphore is enough. There is no need to reserve a large memory region for that.

Shared Memory

Shared memory is a physical region the kernel carves out. Processes map it into their own address spaces with shmat. One process writes, the other sees it at once, with no kernel copy of the payload, so this path is usually the fastest.

Speed comes with no built-in sync. If two processes write the same location at once, the data breaks. Shared memory needs a semaphore, or some other lock you provide.

When throughput is high and latency matters, the copy cost of a message queue becomes hard to accept. Then shared memory pulls the speed up, and semaphores keep the read and write order under control.

Using Message Queues

Think of the kernel side as a list of typed messages. Processes append nodes or remove a node of a chosen type.

FunctionRole
msggetCreate a queue, or get the id of an existing one
msgsndAppend one message
msgrcvRemove one message

The important field is mtype. msgrcv can ask for one type only. For example, mtype=1 can mean player A’s move and mtype=2 player B’s, so neither side reads the message it just sent.

If the wanted type is missing and IPC_NOWAIT is not set, the caller sleeps until a matching message appears, a signal arrives, or the queue is deleted.

Creating a Queue and Choosing a Key

int msqid = msgget(key, msgflg);

key tells the OS which IPC object you mean. Related processes often write:

int msqid = msgget(IPC_PRIVATE, IPC_CREAT | 0600);

IPC_PRIVATE always creates a new object instead of looking up an existing one. IPC_CREAT is the create flag, and 0600 is the permission.

The flow is: the parent creates the queue, keeps msqid, then calls fork(). The child inherits that id, and both sides use the same queue. The child does not create another queue and does not look one up by key.

Unrelated programs do not inherit msqid. They can agree on an ordinary key, or build one with ftok() from a path and a project id. ftok() is not guaranteed unique, so collisions still matter in practice.

Message Layout and Send / Receive

System V requires the first field of the message struct to be a long message type, and the value must be positive when sending. The kernel does not know your other members; it only reads that leading long by convention:

struct Message {
    long mtype;
    int round;
    int move;
};

On send, msgsz is the body length and does not include mtype:

msgsnd(msqid, msg, sizeof(struct Message) - sizeof(long), 0);

msgflg of 0 means the default: the sender may block if the queue is full.

Receive adds msgtyp, which chooses the type:

msgtypMeaning
0First message in the queue, any type
> 0First message whose type equals that value
< 0Among messages whose type is at most the absolute value, the one with the smallest type

Negative msgtyp exists so a receiver can take higher-priority types first, instead of always following send order. Urgent, normal, and low-priority work can use different mtype values.

What Happens When a Signal Interrupts

While blocked in msgsnd or msgrcv, the process is not spinning. The kernel parks it on a wait queue and runs other ready work. A matching message means the original wait condition is met. A signal means a new event needs a response now.

A signal handler is still code of that same process. If the process is blocked, the kernel must wake it first so it can run the handler. After the handler returns, the original call often comes back as -1 with errno set to EINTR, meaning the call was interrupted before it finished.

The usual pattern is to retry on EINTR and fail on other errors:

while (msgsnd(...) == -1) {
    if (errno == EINTR)
        continue;
    perror("msgsnd");
    return -1;
}

Delete the Queue When Done

msgctl(msqid, IPC_RMID, NULL);

Message queues live in the kernel. They do not vanish when the parent exits. Leaving them behind leaks IPC resources.

Using Shared Memory

shmget creates or looks up a shared segment. It returns an id shmid, not a usable pointer yet:

int shmid = shmget(IPC_PRIVATE,
                   sizeof(struct SharedData),
                   IPC_CREAT | 0600);

Every process has its own virtual address space. After the kernel owns the segment, shmat maps it into the current process so you get a pointer:

struct SharedData *shared = shmat(shmid, NULL, 0);

Mapping failure returns (void *)-1. If the parent maps before fork(), the child inherits that mapping. The calls can also happen after fork(), with each side attaching the same shmid.

Detach with shmdt, then remove the segment with shmctl(..., IPC_RMID, ...).

Using Semaphores

Create and Initialize

int semid = semget(IPC_PRIVATE, 2, IPC_CREAT | 0600);

The 2 means the set holds two semaphores. After the parent creates it, the child inherits semid through fork().

Initial values come from semctl. SETVAL sets one semaphore by index; the argument is often passed through union semun:

union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
};

union semun arg;
arg.val = 0;
semctl(semid, 0, SETVAL, arg);
semctl(semid, 1, SETVAL, arg);

P and V

The real work is semop. One operation is described by struct sembuf: which semaphore, how much to add or subtract, and which flags.

I wrap the common add and subtract as sem_change, then as P and V:

int sem_change(int semid, unsigned short num, short op)
{
    struct sembuf sb = {num, op, 0};

    while (semop(semid, &sb, 1) == -1) {
        if (errno == EINTR)
            continue;
        perror("semop");
        return -1;
    }
    return 0;
}

int P(int semid, unsigned short num)
{
    return sem_change(semid, num, -1);
}

int V(int semid, unsigned short num)
{
    return sem_change(semid, num, 1);
}

The kernel value must not go negative under a P. When there is no resource left, the process waits instead of driving semval below zero.

Textbook Negatives and Linux Wait Queues

Textbooks often record waiting processes as a negative semaphore value. Linux System V does not need that: the kernel keeps its own wait queue. So 0 is legal, and negatives are not. Both descriptions talk about the same sync idea; they bookkeep differently.

Two Designs for Rock-Paper-Scissors

From an engineering angle, a message queue is the clearer fit: send a move, receive the other move, then score. Shared memory plus semaphores exercises both the shared table and the traffic light. I planned both.

Message Queue

The parent creates the queue, then fork(). The parent is player A: each round it draws a move and sends it. The child is player B: after reading A’s move, it draws its own and sends it back. The parent scores the round. After several rounds it prints the totals and deletes the queue.

No extra semaphore is required here. Blocking in msgsnd and msgrcv already means “read after the other side has written.” Different mtype values keep each side from reading its own message.

Shared Memory Plus Semaphores

The shared segment holds both moves and the round number. Two semaphores guard the two directions:

  • After A writes, wake B to read
  • After B writes, wake A to read

Without those semaphores, shared memory is only bare storage both sides can touch, and the timing of reads and writes can still collide.

Review

This pass folds System V IPC into three lines:

  1. Message queues fit small bounded control messages, and the type field can filter them.
  2. Shared memory is fastest, but you must handle sync yourself.
  3. Semaphores do not carry payload; they only count and wait. On Linux the waiters live in a kernel wait queue, not in a negative counter.

Rock-paper-scissors can sync with a message queue alone, or with shared memory plus two direction semaphores.

2 - An Attempt at a Vibe Knowledge Video

An attempt to make a vibe-style video of Quoit Design, and what Grok bot, Opus, and a more specific script each changed.

After finishing Quoit Design on October 30, I wanted to turn it into a vibe-style explainer video. Videos of that kind have been everywhere lately. I already had a Cursor Premium subscription. The idea came from hearing that Grok bot in it can call Opus 5.5, and that Opus 5.5 looks better than the others for video built from generated code. I had also heard that one video costs about 5 to 6 yuan. I wanted to see two things with this problem: how far the result has got, and whether it gets any traffic once it is posted.

I have not subscribed to Claude. From what I had learned, its bans and limits on users in China are strict, and I did not want the account banned. So I did not open that subscription. I started with the Grok bot I was already using.

The video is not finished. Only stage 1 and stage 2 are done, 1 minute 12 seconds in total. This note only records the models, the cost, and the picture changes as of November 1.

Filming a Quoit Design vibe video in front of a neon voxel stall
The script, the ten seconds, and the stack of coins stayed separate parts of this trial

The Standing Brief

For this kind of video I start by giving the model the same four instructions.

  1. Set the format. Make it in Remotion, 1920×1080, 30 frames per second, 16:9 landscape. No voiceover. Chinese subtitles carry the points. The music is We Never, a track that has been everywhere lately.
  2. Hit the beats. Analyze the music first, measure the beats per minute, and list the time of every downbeat. Every picture change lands on a downbeat.
  3. Add sound effects. Every key action gets a sound, synthesized in code. The timbre is an instrument that fits whatever the picture is emphasizing.
  4. Show a test cut. Make the first 10 seconds for me to look at. After I confirm it, continue one segment at a time, and redo only the segment that is not good enough.

What the Grok Bot Video Was Like

The clip I made for a classmate at the start was a project introduction, not this algorithm explainer, and it looked all right. When I later made the algorithm explainer, the quality came out very poor, and I still don’t know why. That result was certainly not from Opus 5.5. It was worse than what I got on my own computer with Cursor’s auto mode.

Opus Had Spent Ten Yuan Before Ten Seconds Were Done

I changed route: through a relay, I called Opus 5.5 inside Claude Code. The four instructions above are the standing brief. The version I gave Opus was written shot by shot, and that original text is not in my notes, so I am not reconstructing it here.

On one 10-second segment, Opus 5.5 had already cost 10 yuan before the segment was finished. Finishing the whole video at that price would be well above the 5 to 6 yuan I had heard, so I did not keep the whole video on Opus 5.5.

A Vague Note Does Not Change the Shot

I then stayed in Claude Code and continued with the auto mode of the API provided by Cursor. The first cut went through about four or five revisions. A change usually landed closer to what I wanted only after the picture was described specifically.

The opening felt empty and plain. Sending that impression back did not fix it. After I gave Gemini 4 Argon the same description together with the frame, it returned a list of concrete changes. Generating from that list made the opening much clearer. The Chinese prompt I actually used is below.

将当前扁平的 3D 场景升级为具有真实物理光影和景深质感的 3D 体素微缩景观(Lego Brick / MagicaVoxel 渲染风格),具体修改要求如下:

- PBR 物理材质替换:移除纯色无光材质(BasicMaterial)。地面改为带微弱镜面反射的深色粗糙石板(Roughness 0.4, Metalness 0.2),以反射上方霓虹灯光;套圈摊顶棚采用有布料纹理的红白条纹材质;玩偶与橘色 Claude 机器人采用光滑的亚克力/塑料玩具材质(Clearcoat 效果)。

- 全局光照与自发光(Bloom):添加 Three.js EffectComposer 的 UnrealBloomPass 辉光后处理。让“CYBER QUOIT·赛博套圈”灯牌、摩天轮彩灯、串灯和烟花具有真实的霓虹灯管发光(Emissive)与光晕扩散效果。

- 立体光影与体积感:在摊位内部上方增加一排暖黄色点光源(PointLight)照亮货架玩偶并投射真实阴影(castShadow = true);场景底部加入深紫色的指数雾效(FogExp2),拉开前景摊位与后方摩天轮、旋转木马及城市剪影的空间纵深感。

- 镜头与景深(DoF):使用透视相机(FOV 35-45),添加轻微的移轴景深效果(BokehPass),让前景的套圈网格区域和摊位保持绝对清晰,背景的摩天轮、旋转木马和远景大楼产生自然的光学虚化。

- 地面套圈区强化:将摊位前方的矩形地毯改为带有发光网格刻度线的 3D 赛博电子地垫,为后续“地面生成玩具点集”的算法动画留出高亮视觉中心。

Ten Seconds Took Half an Hour or More

A clear script did not make the wait short. About 10 seconds of demo, from reading the request through writing the code to rendering the video, took at least 30 to 40 minutes, sometimes longer. The version that came out of that wait looked all right to me.

Those two stages already add up to 1 minute 12 seconds. The script is planned as 14 stages, and these two alone used more than 40% of a week’s Cursor allowance. Making the video does spend a lot of tokens.

Auto mode does not label which model ran. This is a fairly complex job, so it would generally call the strongest in-house model, Grok 4.7 high.

This Cut on Bilibili

Added on November 3: this cut is on Bilibili. The player stays on this page. The link under it opens Bilibili. It is not on Douyin yet, and the view counts are not written down here.

Open on Bilibili

3 - Divide and Conquer: Quoit Design and the Closest Pair

The largest quoit radius is half the closest-pair distance. This note follows why divide and conquer does not have to check every pair.

On October 30 I worked through Quoit Design from this contest. The public statement is HDU 1007. Every toy is a point, and the ring should be as large as possible without encircling two toys at once. I did not start by picking an algorithm. I asked what actually limits the radius.

A toy is encircled when its distance to the center is strictly less than the radius. If two points are less than 2r2r apart, some circle of radius rr contains both of them strictly: put the center at the midpoint. The radius can therefore be at most half the distance of the closest pair. If two toys coincide, the radius is 0. The output keeps two decimal places.

For Pi=(xi,yi)P_i=(x_i,y_i) and Pj=(xj,yj)P_j=(x_j,y_j), the Euclidean distance is

dij=(xi−xj)2+(yi−yj)2. d_{ij}=\sqrt{(x_i-x_j)^2+(y_i-y_j)^2}.

Let dmin⁡d_{\min} be the minimum over all pairs. The answer is r=dmin⁡/2r=d_{\min}/2.

While comparing pairs, I can compare squared distances, (xi−xj)2+(yi−yj)2(x_i-x_j)^2+(y_i-y_j)^2. The square root is increasing on nonnegative numbers, so the pair with the smallest square is the closest pair. The square root and the division by 2 wait until the radius is printed.

Quoit Design: the largest radius is half the closest distance, and the merge checks the strip
The closest pair sets the radius. Across the cut, only a few points in the strip are compared

Turn the Radius into the Closest Pair

After that reduction, the problem is the closest pair of points in the plane. NN can be 100000100000, and the value to find is dmin⁡d_{\min}.

A half with fewer than two points has no pair, so it does not enter the minimum. If a duplicate pair has already made the distance 0, the strip does not need to be searched.

Why Checking Every Pair Is Not Enough

My first idea was to measure every pair, each pair once:

for (int i = 0; i < N; i++) {
    for (int j = i + 1; j < N; j++) {
        // update the minimum with the squared distance
    }
}

The time is O(N2)O(N^2). At N=100000N=100000, the number of pairs is

N(N−1)2=4999950000. \frac{N(N-1)}{2}=4999950000.

That is nearly five billion comparisons. The distance formula is not the expensive part. The number of pairs is.

Sorting and Pruning Do Not Change the Worst Case

I then sorted the points by xx. Let dd be the best distance so far. Once a later point PjP_j satisfies xj−xi≥dx_j-x_i\ge d, its Euclidean distance from PiP_i is at least that large. Later points are even farther in xx, so the inner loop can stop.

This skips some comparisons. It does nothing when every point has the same xx and the points differ only in yy: the xx gap stays 0, and the worst case is still O(N2)O(N^2).

Doing fewer comparisons inside a loop is not the same as improving the worst-case bound.

The Halves Are Easy, and the Merge Cost Is the Hard Part

Pruning did not change the worst case. At N=100000N=100000 I needed a way to reduce the number of pairs in the whole problem.

The points are already sorted by xx, so a cut down the middle leaves about half the points on each side. Each half asks the same question: how close is the closest pair inside this half? The question is unchanged and the size is smaller, so the same procedure can run recursively. The closest distance on the left and the closest distance on the right both come straight out of that recursion. Each half’s dmin⁡d_{\min} is the easy part.

What is still open is the cost of putting the two halves together. Take the smaller of the two results:

d=min⁡(dL,dR). d=\min(d_L,d_R).

That only constrains pairs inside one half: points on the left are at least dd apart, and so are points on the right. One point on the left and one point on the right can still be closer, so the answer cannot stop at this dd. The merge still has to handle pairs that cross the cut.

That merge cost is the hard part. If every left point is compared with every right point, one level is O(N2)O(N^2), and splitting the set has not removed any work. The rest of the argument is about how many crossing pairs still have to be checked once dd is known, and whether that level can be brought down to O(N)O(N).

Only the Strip Near the Cut Matters

Let the cut be x=xmx=x_m. If a pair is closer than dd, its xx gap is also less than dd, because ∣xi−xj∣≤dij|x_i-x_j|\le d_{ij}. A crossing pair that might update the answer has to lie in the vertical strip

∣x−xm∣<d. |x-x_m|<d.

The strip has width 2d2d.

The strip can still hold many points. Scan them by increasing yy. For a fixed point PP, a later point QQ with yQ−yP≥dy_Q-y_P\ge d cannot be closer than dd, and neither can any point after it. A candidate QQ must satisfy both

{∣xQ−xm∣<d,0≤yQ−yP<d. \begin{cases} |x_Q-x_m|<d,\\ 0\le y_Q-y_P<d. \end{cases}

A candidate might be closer than dd. It is not already known to be closer.

Why Each Point Has Only a Constant Number of Candidates

This was the part that took the longest. The known fact is that pairs inside one half are at least dd apart. Pairs across the cut are not known to be that far. If they were, the merge would be unnecessary. I cannot claim that every pair in the whole strip is at least dd.

For a fixed PP, take the rectangle from xm−dx_m-d to xm+dx_m+d and from yPy_P to yP+dy_P+d. It is 2d2d wide and dd tall. Split it into 4 columns and 2 rows, eight squares of side d/2d/2. A cell’s edge may lie on the cut, but its interior does not contain both halves: a point exactly on the cut was assigned to one half when the set was split.

Eight cells above P, with Q1 through Q7 in the other cells
P takes one cell, so at most seven candidates follow it. Two points in one cell would be less than d apart

Two points in the same cell are at most a diagonal apart:

(d2)2+(d2)2=d2<d. \sqrt{\left(\frac{d}{2}\right)^2+\left(\frac{d}{2}\right)^2}=\frac{d}{\sqrt{2}}<d.

The chain is:

  1. Two points in one cell are less than dd apart.
  2. That cell belongs entirely to one half.
  3. Two points in the same half cannot be less than dd apart.
  4. Therefore one cell cannot contain two points.

Eight cells and one point per cell give at most eight points in the rectangle. One of them is PP, so at most seven candidates follow it. Each point is compared with a constant number of successors, not with every point in the strip.

The cells do not directly limit distances across the cut. They prove that the number of candidates has a fixed upper bound.

The Rectangle Is Rebuilt for the Current Point

I also asked whether PP could only slide along the bottom edge of one fixed rectangle.

The strip is fixed by the cut and the current dd. The local rectangle is drawn separately for each current point. Scanning by increasing yy, a fixed PP only needs later points, so the bottom edge is y=yPy=y_P and the top edge is y=yP+dy=y_P+d. The next point gets a new bottom edge. PP is not moving along one shared edge.

Scanning downward uses a rectangle that extends the other way. The direction is not the point. The sort is what lets points whose yy gap is already at least dd be skipped.

How the Time Bound Becomes N log N

The whole procedure sorts by xx, splits into halves, finds dLd_L and dRd_R, checks crossing pairs through the strip and the yy order, and keeps the smaller distance. The radius is half of that distance.

Sorting again at every recursive level can cost O(Nlog⁡N)O(N\log N) per level and O(Nlog⁡2N)O(N\log^2 N) overall. For O(Nlog⁡N)O(N\log N), I can prepare an xx-ordered sequence and a yy-ordered sequence at the start. Each call splits the yy-ordered sequence into the two halves, then merges those ordered sequences on the way back. The strip scan and the at most seven comparisons then run linearly in that order.

The merge at one level is O(N)O(N), so

T(N)=2T(N2)+O(N), T(N)=2T\left(\frac{N}{2}\right)+O(N),

and T(N)=O(Nlog⁡N)T(N)=O(N\log N). The initial xx sort is the same order of growth and does not raise the bound.

Review

I did not start from divide and conquer. Checking every pair is correct, and there are too many pairs. Stopping the inner loop after an xx sort removes some work without changing the worst case. What divide and conquer adds is the distance dd already found in the two halves: points far from the cut can be ignored, points whose yy gap is at least dd can be ignored, and each point has only a constant number of candidates left.

The sentence I want to keep is this: split the problem, then use the subproblem results to prove which pairs need not be checked. That is what makes the merge affordable.

Note

Added on November 1: I later tried to turn this problem into a vibe-style explainer video. The models and the cost are in An Attempt at a Vibe Knowledge Video.

4 - A Close Reading of NavGPT-3

A reading of NavGPT-3 through the Planner, Harness, VLA, and Runtime, and what its tools, visual budget, and motion authority each solve.

On October 25 I read NavGPT-3 by following its architecture. In the previous post I had already placed it among hybrid systems: a language model understands and checks, while a trained policy moves more frequently. This post does not explain R2R-CE again. I wanted to see what each of the four parts does, and how one part can tell whether it should continue after another part stops.

The project page is NavGPT-3. The numbers below come from this preprint. The full splits and the 100-episode subset should not be read as the same evaluation.

NavGPT-3: Planner, Harness, VLA, and Runtime form one route
The wrong branch is marked with a cross, and the route continues to the doorway

Four Responsibilities

I started from what each layer takes in and gives back, rather than from the module names.

The Planner is the decision layer. It sees the current context and the available tools, and it outputs one tool call: look around, move locally, hand part of the instruction to the VLA, or end the task.

The Harness is the information and tool layer. It turns images, the instruction, and history into a context the Planner can read, exposes spatial tools, and records visited places and the result of the latest execution.

The VLA is the motion-prediction layer. NavGPT VLA predicts the next short trajectory from the navigation instruction and visual observations. It does not declare that the whole instruction is finished.

The Runtime is the coordination layer. The Planner, the VLA, and safety monitoring can proceed at the same time, but the Runtime decides who may move the robot at each moment. The environment is what actually executes motion and returns sensor results.

My shorthand is: the Planner decides what to do, the VLA turns an instruction into the next waypoints, the Harness makes the rollout inspectable afterward, and the Runtime decides who holds motion authority now.

What each of the four layers is responsible for
Deciding, keeping evidence, moving a short distance, and holding motion authority are four different jobs

The paper figures below come from this preprint. The red notes and arrows are what I marked while reading.

One call from the instruction and context to environment execution
Context goes to the Planner first. Execution then falls to the VLA or the spatial tools

Two Ways the Harness Can Move

Calling the Planner on every perception and motion update is impractical. The Harness therefore gives it two ways to move: call spatial tools itself, or delegate continuous navigation to the VLA. Delegation is optional. The Planner can finish the decisions with the existing tools, or hand over the instruction when it judges that appropriate.

These interfaces were not fixed first and explained later. The paper uses recursive self-improvement (RSI) to try tool definitions and visual prompts, then ablates the interfaces that remain. I come back to that search later. Here I first want to see what the Planner can actually call.

Eight Tools in Four Groups

Four basic tools are always available:

ToolRole
observe_forward()Look at the forward image for finer semantic checks
observe_panorama()Look forward, right, back, and left, with bearings, clearance, pose displacement, and node information
navigate_relative()Make one local move with a given turn and distance
terminate_episode()End the whole task explicitly

Three further groups can be added. navigate_by_instruction() gives the full or remaining instruction to the VLA, which continues until it signals a stop or reaches the step limit of one delegation. What comes back is at most eight keyframes, the endpoint observation, and the execution status. observe_map() returns a top-down view of the area observed so far, with visited places numbered in order. navigate_to_node() returns to a visited place, and annotate_node() attaches a semantic label to it.

A node number only says where the robot has been. The Planner can label it with something that matters to the instruction, such as “beside the table.” History is then not only a list of coordinates. It can also remember what that place meant.

I separate the spatial information from observe_panorama() by where it comes from. Bearings come from the camera orientation relative to the robot, clearance from geometric information maintained by the environment, pose displacement from translation and rotation relative to the previous pose, and node information from the history kept by the Harness.

A VLA Stop Is Not Task Completion

This was easy for me to collapse into one event. A VLA stop may only mean that it considers the current stretch of navigation finished. It does not mean that the user’s whole instruction is done.

The paper makes completion an explicit operation. A VLA stop ends only that delegation. The episode ends when the Planner calls terminate_episode(). Ending may first return to a selected node, and that call cannot be undone.

Repair also comes in two forms. Returning to a visited place uses navigate_to_node(). Turning by an angle and moving a short distance uses navigate_relative(). Annotation keeps the meaning of a place, and termination makes “finished” explicit.

The Runtime Manages Concurrency and Motion Authority

If the robot waits for the Planner to finish thinking before every move, it stands still. The NavGPT-3 runtime separates reasoning, execution, and monitoring into threads, each with its own context, tools, and permissions.

I follow the paper’s division of labor. The main task thread makes navigation decisions and can switch between the language model and the VLA. Another thread lets the VLA keep executing, so the robot does not have to wait while the Planner inspects the route. The monitor thread handles danger and anomalies, and it must be able to stop motion that should not continue.

Synchronous waiting beside three overlapping threads
The upper path waits for the whole VLA rollout. Below, execution, reasoning, and monitoring overlap

At each event, motion authority has two possibilities: it is given to one authorized thread, or it is given to no one. A thread may move the robot only if both conditions hold. It is the thread that currently holds motion authority, and the action belongs to the operations it is allowed to perform. Even if the monitor proposes “return to a node,” that navigation tool is outside its permissions.

Concurrency creates a direct problem. An event can be valid when it is produced and stale by the time the runtime handles it. Each event carries its operation, permission version, timestamp, and sequence number. Outdated review or completion events are discarded, so an operation that has already been interrupted does not continue.

Revoking permission is not enough by itself. A command filter is still needed, because VLA prediction and physical execution are asynchronous. The VLA may already have produced a forward waypoint, the monitor may then revoke motion authority because of an obstacle, and the old command may arrive at the robot later. The permission version changes when authority is revoked or replaced, and a waypoint issued under the old version cannot move the robot.

Clearing a safety alert does not resume motion. The protective stop has to be cleared, fresh observations and state have to be available, and the runtime has to grant motion authority again.

Timeline of route repair and a safety interrupt
Route repair pauses the main execution. A safety interrupt revokes motion authority while reasoning continues

Episode limits take priority over ordinary review. Once the environment-step limit, the delegation-step limit, the Planner-call limit, or the timeout is reached, the robot does not keep moving just to inspect the route. The appendix settings are at most 500 environment steps for the episode, 200 steps for one VLA delegation, 200 Planner calls, and a timeout of 2,400 seconds.

How the VLA Looks within a Visual Budget

NavGPT VLA starts from Qwen3-VL-Instruct and adds an MLP action head. The head outputs eight waypoints. Each waypoint is a forward position, a lateral position, and a relative heading in the current robot frame. The robot executes only the first waypoint, observes again, and predicts the next trajectory. The 4B and 8B models share this output.

The visual context is bounded. The policy keeps at most 16 past observations, and each observation can contain front, right, back, and left views, so at most 64 images. With a fixed token budget, not every image can be kept at the highest resolution.

Position-only allocation weights an image by how recent it is and which view it comes from. More recent observations receive higher weight, and in the reported setup the forward view is usually preferred to the back view. This rule knows when and from which direction an image was taken. It does not know whether the image shows anything new.

Codec allocation multiplies that position weight by a change score. Within one view, the first image is an I-frame and receives a change score of 1. Each later P-frame is reduced to a 64 by 64 thumbnail, compared with the previous thumbnail by mean absolute pixel difference, and clipped into a range. Images that change more receive a higher score. Optical flow and change masks only show frame-to-frame differences to a reader. The allocation itself uses the thumbnail score.

Allocation happens before an image enters the visual encoder. The image is resized to the token count it received, rather than encoded first and then trimmed arbitrarily.

How four-view history receives resolution from scene change
With a fixed budget, views that change more receive higher resolution. The flow field only shows the difference
The change score comes from a thumbnail difference times a position weight
An I-frame gets a full score. Later frames use the pixel difference of a 64 by 64 thumbnail

The change score does not always matter. If the ratio of budget to capacity is already at least 1, every image can reach its allocation cap and the two rules agree. Only when the budget cannot give every image that cap do tokens move from low-change images toward high-change images. Training samples the visual budget from 1,024 to 4,096 so that histories which actually require this trade-off appear.

The training data is also not a separate policy for every task. The full mixture has about 19.28 million effective records per epoch, drawn from several tasks, platforms, and camera setups, with one action-output format. Evaluation still uses each benchmark’s own test tasks and metrics. Rewritten training data does not stand in for the test set.

The Interface Was Searched For

RSI is set up here as a constrained tree search. Each round has four steps: propose a change from the current framework and the record of failures, check whether the change respects the interface and repeats a known failure, run it in the task environment and measure the result, then record what worked, why something failed, and which hypothesis is still untested. When progress stalls, the search reflects.

What changes is the Harness: the system prompt, the available tools, the persistent spatial state, and the way observations and execution results are shown to the Planner. This stage does not retrain the VLA.

Candidates are compared on a fixed 100-episode sample from the R2R-CE training split. Those scenes are disjoint from Val-Unseen, and the selection signal is success rate. On this development curve, front-view observation with primitive steps scores 66%. Delegating to the VLA reaches 72% with the 4B policy and 76% with the 8B policy. Adding spatial tools reaches a development best of 81%. An early place-graph interface falls to 54%, and the later consolidated interface scores 77%. One review found that the prompt described local movement while no such tool existed. A later revision added the tool and replaced the stitched panorama with four separate 512-pixel views.

The automatic Harness search and its development curve
The search changes tools, prompts, and execution feedback. The 81% comes from the 100-episode development subset
Note

The 66% and 81% here come from the 100-episode training subset used to search for a Harness. They are not the same evaluation as the full Val-Unseen results below.

What Tools and Visual Layout Each Change

The tool ablation also uses 100 R2R-CE episodes. The two Planners are GPT-6 Astra and Claude Opus 5, and the VLA is the 8B model. Only the tools exposed to the Planner change.

Tool ablation and what each of the eight tools returns
On the same hundred episodes, tools change success. With the VLA, reaction time is about 0.78 seconds

With only the basic tools, every environment action waits for a Planner decision. Astra reaches 72% success at about 325.0k tokens per episode. Opus reaches 66% at about 721.0k tokens. Adding the map and backtracking raises the two results to 83% and 73%, while cutting tokens by about 41% and 33%. The map lets the Planner assemble spatial context beyond the current view, and backtracking lets it return to a recorded place instead of searching with repeated observations and short moves.

The VLA always shortens the reasoning loop, but it does not always raise success. Opus moves from about 73% to 76%–81%, and the cost per episode falls from about $0.99 to $0.35–$0.40. Astra’s turn count drops sharply, but success falls to about 75%, because tokens saved on navigation are spent supervising and correcting the VLA. Once the VLA also receives mapping and backtracking, token use reaches the low point in this table for both models: 155.0k for Astra and 185.6k for Opus, with success close to each model’s best row.

My reading is: what the VLA adds to success depends on whether the Planner can already understand the environment. When the language model is strong enough, the ceiling on success comes more from its own navigation ability than from a missing interface. The clearer effect of the interface is then to reduce cost.

Reaction time is a separate question. Without the VLA, the system can act only as often as the language model decides, about once every 3 to 19 seconds. With the VLA, the 8B model predicts a step in about 0.78 seconds on average.

Check frequency reverses the bargain. Without periodic checks, the Planner usually waits until the VLA stops or hits the delegation limit, after a median of about 51 steps. Checking every 32 steps moves success only from 77% to 78%. Checking every 16 steps reaches 83% success, raises SPL from 67.51% to 77.36%, and lowers navigation error from 3.82 m to 2.01 m, while tokens rise from 179.2k to 2,319.5k per episode. More frequent checks can improve the route, and the cost grows faster than the accuracy.

The visual-prompt study keeps the tools and environment information fixed and changes only how they are shown to the Planner. The paper compares five presentations, including moving labels into text beside the image, using smaller digits, rotating the map with the robot, and replacing relative turn cues with absolute bearings. Astra’s success stays around 76%–78%, and Opus stays around 73%–77%. Absolute bearings, which are harder for a person to read, use the fewest tokens for both models. Success is not very sensitive to visual layout, token cost is, and the layout that is easiest for a person is not necessarily the one a language model uses most cheaply.

Success and on-image marks for five visual prompts
Success stays close across the five layouts. Token use does not fall in the order a person would find easiest to read

Results on the Full Splits

Table 6 is the full Val-Unseen evaluation on R2R-CE and RxR-CE. The 8B NavGPT VLA alone reaches 76.94% SR and 70.61% SPL on R2R-CE, and 82.39% SR on RxR-CE. For comparison, Qwen-RobotNav 8B reaches 72.1% and 76.5% SR on these two sets.

With the Harness, the GPT-6 Astra configuration raises R2R-CE SR to 81.51%, with 70.42% SPL. Claude Opus 5 reaches 79.01% SR and 70.16% SPL. On RxR-CE, Astra reaches 90.43% SR and 78.47 nDTW. The paper places this next to English human followers at 90.4% SR and 77.7 nDTW. The human demonstrations follow a discrete navigation graph, while the system uses continuous control. The paper states that difference itself.

On R2R-CE, success rises without a similarly clear gain in SPL. RxR instructions are longer and specify more of what must be passed along the way, so returned route evidence, visited nodes, and local repairs have more to act on. Success and path fidelity rise together there. A higher completion rate does not by itself mean a shorter path.

Object-goal navigation gives the robot an object to find and reach. The paper evaluates 500-episode subsets of MP3D and HM3D v2, and success also requires stopping within the distance threshold while facing the target. Passing near the object is not enough. The comparable range differs too: earlier methods often use HM3D v1, while this evaluation uses v2. Embodied question answering requires moving, observing, and then answering a question about the environment. For these two tasks I first keep the task definition and the stop condition, and I do not compare their scores directly with full-split VLN success.

The effect of codec allocation also depends on the model and the data. In the training ranges compared by the paper, the 8B model gains success from change-aware allocation throughout. On R2R-CE, the 4B model shows that gain after cross-embodiment data is added. With cross-embodiment data, both 4B and 8B improve SR and SPL on both test sets. A larger model is usually better, but data coverage can outweigh parameter count: the 4B model trained with cross-embodiment data can surpass the 8B model trained only on VLN data. Growing the mixture from about 11.57 million to 19.28 million records still has not flattened the curve.

For the real-robot section I only keep the division of responsibility. Onboard inference places the 4B VLA on the robot’s Jetson Thor, with FP8 quantization and TensorRT, and removes the network round trip for VLA prediction. The Planner stays remote. Overlapped execution mainly improves the efficiency of route repair. Priority monitoring mainly improves how quickly a safety stop and a permission change take effect.

What Makes a Wrong Route Repairable

I do not read Figure 10 as evidence that the VLA stops at the correct endpoint by itself. What I want to remember is that the VLA can overshoot, and the Planner can still recover the error from evidence kept by the Harness.

The instruction requires the robot to pass a table and remain in the corridor. One VLA delegation runs for 67 steps and enters the bedroom. The Planner compares the instruction with the returned keyframes, decides that the endpoint should still be in the corridor, and returns to node 1 beside the table. Being beside the table does not yet satisfy “just past the table,” so it adjusts its heading, moves forward about 1.2 meters, confirms from the back view that the table is behind it, and only then calls termination.

The figure uses three numbering schemes. Sampled visual keyframes, historical nodes stored by the Harness, and the order of the Planner’s tool calls are not one sequence. The paper also does not say whether the VLA stopped in the bedroom because it knew the bedroom was off the route. What is definite is that task completion is not inferred from that stop.

The blocked aisle and the missed turn use the same method. After the VLA stops, the Planner checks which clause is still unfinished. When another local move fails, it uses navigate_to_node() to return to an earlier place and navigate_relative() to take another aisle. In the stair episode, the Planner first tries to climb with local motion, does not succeed, hands the full instruction back to the VLA near the stove, and checks the bed, door, and toilet only after the robot is upstairs.

Together these episodes do not say that the VLA is correct. They say that an error has to remain as a route, nodes, and status that can be inspected, or the Planner has nothing to repair.

The appendix leaves one question that I am not turning into a conclusion. After two consecutive blocked steps, the system records a review request, but the Planner is not woken immediately. It waits for the next periodic check. If that check would have happened anyway, does the earlier request change what the Planner sees, or does it only mark that a blockage occurred? The interaction-frequency experiment does not separate this. I am leaving the question here.

Review

This time I keep the four layers first, and then three boundaries that are easy to mix together.

A VLA stop and task completion are not the same event. Visual tokens are first allocated by time and view. Scene change changes who receives more tokens only when the budget is not large enough for every image. Motion authority, the permission version, and the command filter have to be read together. Otherwise an old waypoint can still move the robot while threads run concurrently.

Tools mainly change whether the Planner can understand and repair a route efficiently. Visual layout mainly changes token cost. The VLA mainly changes how soon the robot can act. Success, path efficiency, and reaction time are therefore not one number. When I return to a table, I also write down first whether it is the 100-episode development subset or the full Val-Unseen split.

5 - Operating System Fundamentals Review (2)

A review of scheduling levels, evaluation metrics, and the rules and trade-offs of FCFS, SJF, HRRN, round robin, and multilevel feedback queues.

My October 20 notes focus on CPU scheduling. The previous post distinguished programs, jobs, and processes, along with concepts such as concurrency and synchronous calls. This post continues with a related question: when several tasks need to run, how does the system decide who gets the CPU first, for how long, and when to switch?

I start by separating the levels of scheduling, then look at the metrics used to evaluate it, and finally compare the algorithms. Seen this way, the algorithms do more than carry different names. They address different priorities: finishing tasks sooner, responding to users sooner, or meeting deadlines.

Concept illustration of tasks waiting in ready queues and taking turns on the CPU through time slices
Scheduling rules determine which task runs first and how long it uses the shared CPU

Three Levels of Scheduling

When I first learned these levels, I focused on the decision each one makes.

High-level scheduling, or job scheduling, decides which jobs to admit. In the traditional batch-processing model, the system selects suitable jobs from a backing-store queue, loads them into memory, and creates processes so they can participate in execution. This controls the number and mix of jobs competing for resources.

Medium-level scheduling, or memory scheduling, decides which processes to suspend temporarily and which to bring back into memory. When memory is tight, the system can swap out processes that are not currently running and bring them back later. This concerns the residency and suspension of admitted processes, rather than choosing the next process to use the CPU.

Low-level scheduling, also called process scheduling or short-term scheduling, selects the next process to run from the ready processes. This is the level at which I mainly consider FCFS, round robin, and the other rules below.

My shorthand is: first decide who can enter, then who stays in memory for now, and finally who runs right now. This is a textbook model; an actual system does not have to implement three independent schedulers.

Why Multiprogrammed Batch Systems Need Scheduling

Batch processing means that users submit jobs for the system to organize and execute, usually without continuous interaction during execution.

Multiprogramming means that processes belonging to several jobs can reside in memory at once. When one process waits for I/O, the CPU can run another ready process, reducing idle time.

A multiprogrammed batch system therefore does not mean that several jobs execute on one CPU simultaneously. It lets several jobs participate in resource use and switches between them when appropriate. The goal is better resource utilization, not simply maintaining a queue.

Preemptive versus Non-Preemptive Scheduling

To me, the essential difference is this: while a process could still continue running, can the system take the CPU away and give it to another process?

With non-preemptive scheduling, once a process obtains the CPU, the system normally waits until it finishes or voluntarily gives up the CPU, such as by waiting for I/O or another event, before choosing another process.

Preemptive scheduling allows the system to switch away from a process that could still run, for example when its time slice expires or a higher-priority process becomes ready.

I also need to distinguish rescheduling from preemption. If the current process has already finished and the system selects the next one, that is rescheduling, but it has not displaced a process that was still running. This distinction also matters when considering shortest-remaining-time scheduling.

Evaluating Scheduling

Before comparing algorithms, I separate the metrics. A short turnaround time, a busy CPU, and a large number of completed tasks are not the same thing.

Turnaround Time and Average Turnaround Time

Turnaround time = completion time - submission or arrival time.

It measures the elapsed time from submitting a job to its eventual completion. This may include waiting for the CPU, executing, waiting for I/O, and other delays.

Average turnaround time = sum of all job turnaround times / number of jobs.

This describes how long jobs in a batch take to finish on average. CPU utilization instead measures the proportion of an observation interval during which the CPU is busy. Throughput measures the number of tasks completed per unit time. These three metrics need to be considered separately.

Normalized Turnaround Time

Turnaround time alone makes it difficult to compare jobs of different lengths. I use normalized turnaround time, also called weighted turnaround time, to see how much the total elapsed time has grown relative to the job’s own service requirement:

Normalized turnaround time = turnaround time / service time

In a simple model that ignores I/O and switching overhead, with just one CPU burst per task, service time is the required CPU time. The expression can then be expanded:

Turnaround time = waiting time + service time
Normalized turnaround time = (waiting time + service time) / service time
                           = 1 + waiting time / service time

The parentheses matter. Writing “waiting time + service time / service time” produces a different expression. If the actual execution includes I/O or other delays, ready-queue waiting time and CPU execution time alone do not explain the entire turnaround time.

For example, suppose two jobs each finish after 10 time units. A job requiring only 2 units of execution has a normalized turnaround time of 5; one requiring 10 units has a value of 1. The former experienced more extra delay relative to its own execution requirement.

For a positive service time, this ratio is normally at least 1. In the simple model where the CPU starts idle, the first job runs immediately upon arrival, and there is no I/O or other extra delay, that job’s ratio is 1. Non-preemptive scheduling alone does not guarantee all these conditions.

Different Systems Have Different Priorities

Batch systems mainly focus on average turnaround time, throughput, and CPU utilization. Jobs should finish sooner, the system should complete more tasks per unit time, and resources should not remain idle for long periods.

Time-sharing systems care more about interactive response. Users should receive responses reasonably quickly and consistently. A quick response does not mean that the entire task finishes immediately: a task can receive an opportunity to run and then continue its work later.

Real-time systems focus on timing constraints. The issue is not merely a good average speed, but whether important tasks finish before their deadlines and whether this behavior is predictable.

Before judging an algorithm, I therefore need to know the system’s priorities. A policy with a shorter average turnaround time does not necessarily provide the best interactive response.

Common Scheduling Algorithms

For now, I use a simplified textbook model with a single processor. Execution time represents the service requirement of a job or its current CPU burst. Actual systems generally need to estimate these times rather than know in advance how long a process will run.

First-Come, First-Served: FCFS

FCFS means First-Come, First-Served. Its central rule is arrival order. A newly ready process joins the tail of the ready queue, and the scheduler selects from the head.

It is normally non-preemptive and can also be used for job scheduling. It is simple to implement, and tasks already waiting are not repeatedly overtaken by newer arrivals.

But fairness in queue order does not imply a short wait. If a very long task starts first, much shorter tasks behind it still have to wait. In the usual model where preceding tasks eventually release the CPU, continued new arrivals do not indefinitely postpone a task already in the queue.

Shortest Job or Process First: SJF / SPF

SJF stands for Shortest Job First, while SPF commonly means Shortest Process First. These policies favor tasks with shorter service requirements. For process scheduling, this usually concerns the estimated length of the next CPU burst, not the process’s entire lifetime.

The non-preemptive version selects the shortest eligible task that has already arrived whenever the CPU becomes available for reassignment.

The preemptive version is usually called Shortest Remaining Time First, or SRTF. It compares remaining execution times. When a new process enters the ready queue, it may preempt the running process if its required time is shorter than the running process’s remaining time. Completion of the running process also requires a new selection, but that is not preemption.

These algorithms favor short tasks but may starve long ones. If shorter tasks keep arriving, a long task may keep being pushed back.

Highest Response Ratio Next: HRRN

HRRN stands for Highest Response Ratio Next. It considers both how short a task is and how long it has already waited:

Response ratio R = (time already waiting W + estimated service time S) / S
                 = 1 + W / S

Whenever a task must be selected, the scheduler chooses the candidate with the highest response ratio. The policy is normally non-preemptive.

Unlike shortest-job-first alone, it also considers waiting time. With equal service times, the task that has waited longer has priority. With equal waiting times, the shorter task has the higher response ratio.

For example, suppose task A has waited 6 units and is expected to need 3 units of service. Its response ratio is 3. Task B has waited 2 units and needs 1 unit of service, so its ratio is also 3. A tie is resolved according to the rule specified in the exercise.

This response ratio is a selection criterion calculated from the current waiting time and estimated service time before a task finishes. It is not the actual turnaround time measured after completion. Increasing priority as waiting time grows helps address the prolonged waits that long tasks can experience under SJF.

Round Robin: RR

RR stands for Round Robin. The system divides CPU time into slices and lets processes in the ready queue take turns.

When a process uses its entire time slice without finishing or blocking, it returns to the tail of the queue. If it finishes early or blocks, such as for I/O, it gives up the CPU sooner. A blocked process belongs in the appropriate waiting queue rather than continuing to rotate through the ready queue.

This is preemptive scheduling. As long as queued tasks take turns with finite time slices and new arrivals join the tail according to the rules, tasks do not starve through repeated overtaking.

If the time slice is too large, many tasks finish within one turn and RR approaches FCFS. A smaller slice offers more frequent opportunities to run but also causes more frequent scheduling and context switches. The overhead mainly includes saving and restoring execution state and possible cache effects; it is not simply switching a PCB or JCB.

Multilevel Queue Scheduling

Multilevel queue scheduling divides ready processes into separate queues. Each queue can have its own priority and algorithm. For example, foreground interactive tasks might use round robin while background batch tasks use FCFS.

I need to examine two sets of rules: how tasks are selected within a queue, and how CPU time is divided between queues.

Queues can use strict priorities or receive specified shares of CPU time. Whether a higher-priority queue may preempt a lower-priority queue must also be specified.

Traditional multilevel queues usually assign processes to fixed groups by category rather than freely moving them in response to runtime behavior. Giving system processes priority over user processes, or foreground tasks priority over background tasks, is one possible policy, not a universal ordering every system must follow.

Multilevel Feedback Queues: MLFQ

The key difference between multilevel feedback queues and multilevel queues is that processes can change queues and priorities according to their observed behavior.

I first understand it through a common textbook model:

  1. There are several ready queues with different priorities. New processes start in a high-priority queue.
  2. Higher-priority queues run first, with round robin among processes at the same level. A common design gives longer time slices to lower-priority queues.
  3. If a process exhausts its allocation at a level without finishing, it moves to the tail of the next lower queue. At the lowest level, it continues rotating within that queue.
  4. A newly ready process in a higher-priority queue may preempt a process running in a lower-priority queue. How the preempted process is requeued and how its remaining allocation is counted depend on the specific rules.

Selecting processes in queue order does not mean that the queue uses non-preemptive FCFS. If expiration of a time slice passes execution to the next process, scheduling within that level is round robin.

The “feedback” is the system observing CPU use and adjusting subsequent scheduling. Exhausting an allocation without finishing is one reason to change priority. Implementations may also account for early blocking, cumulative CPU use, and priority boosts.

Observe behavior -> adjust priority -> schedule again -> observe again

The scheduler does not need to know each task’s exact execution time in advance. New tasks can receive service quickly, short tasks may finish at a high priority, and long tasks gradually move to queues better suited to sustained execution.

However, a continuous stream of higher-priority tasks can still starve lower-priority tasks. Aging or periodic priority boosts can help, so whether starvation occurs also depends on the protective rules.

Comparing Three Policies with the Same Tasks

To bring the trade-offs together, I use a simplified hypothetical example. A and B both arrive at time 0, with A ahead of B in the queue. A requires 8 time units and B requires 2. I ignore I/O and context-switch overhead.

FCFS runs A to completion before B:

0        8    10
|   A    | B  |

A’s turnaround time is 8 and B’s is 10, giving an average of 9. B first receives the CPU at time 8.

Non-preemptive SJF runs the shorter task B first, followed by A. B finishes at time 2 and A at time 10, giving an average turnaround time of 6. It finishes the shorter task quickly, but this assumes that the service requirements are known or can be estimated.

RR, with a time slice of 2, runs A for two units and then B. B finishes at time 4. Only A remains, so it continues running until time 10. The average turnaround time is 7, and B first receives the CPU at time 2.

Under all three policies, the CPU works continuously from time 0 to time 10. Its utilization is 100% in this example without overhead, but the average turnaround times are 9, 6, and 7.

This makes the distinction clearer to me: whether the CPU is busy, when tasks finish, and how soon tasks first receive service are three different questions.

Review

This time, I start with the scheduling levels and then remember what each algorithm looks at: FCFS considers arrival order, SJF service time, SRTF remaining time, HRRN also considers time already spent waiting, RR lets processes take turns using time slices, and MLFQ adjusts priorities according to runtime behavior.

An algorithm appearing later in the list is not automatically better. Batch, interactive, and real-time tasks have different goals. Fairness, completion speed, response, and switching overhead can pull in different directions.

When working through an exercise, I will first write down the arrival times, service requirements, time slices, and queue rules, then draw the execution sequence and calculate the metrics. Looking at how the rules change waiting and execution makes it easier to connect the concepts than memorizing advantages and disadvantages in isolation.

Which Algorithms Are Only for Process Scheduling

Some scheduling algorithms can be used only for process scheduling, not for job scheduling. A time slice is the amount of CPU time the operating system allocates to a process. Job scheduling does not allocate the CPU. It only decides which jobs to admit, load into memory, and turn into processes.

The object of job scheduling is the job. A process is created only after the job has been loaded into memory. At the job-scheduling stage, a job may not yet have a process, and therefore may not yet have a ready process.

Round robin (RR) gives each ready process a time slice. Applied to job scheduling, its object would still be jobs, and those jobs often have no ready process yet. RR requires a ready process as its scheduling object, so that object is not available at this stage. RR applies to process scheduling, not to job scheduling.

Multilevel queue scheduling allocates the CPU among different types of ready processes. Its object is also the ready process, for the same reason as RR.

Multilevel feedback queue scheduling also rotates ready processes by time slice and uses that behavior to adjust priority. It likewise depends on time slices and ready processes, so it too applies only to process scheduling.

Among the algorithms in this post, only the first three below are limited to process scheduling. The other three can be used for both job scheduling and process scheduling:

AlgorithmWhere it applies
Round robin (RR)Process scheduling only
Multilevel queue schedulingProcess scheduling only
Multilevel feedback queue schedulingProcess scheduling only
First-come, first-served (FCFS)Both job and process scheduling
Shortest job / process first (SJF / SPF)Both job and process scheduling
Highest response ratio next (HRRN)Both job and process scheduling

FCFS can select by the arrival order of jobs or processes, SJF / SPF can select the one with the shorter estimated service time, and HRRN can select by response ratio. None of these three comparisons requires dividing the CPU into time slices and assigning them to processes that are already ready.

SRTF, mentioned earlier as the preemptive form of SJF, compares the remaining execution time of ready processes, so it is still only for process scheduling. In the table, SJF / SPF can be used at both levels when the choice is the shorter job or the shorter process by estimated service time, without relying on a time slice.

6 - Operating System Fundamentals: A Review (1)

Using image resizing to understand programs, jobs, processes, and threads, then distinguish concurrency, parallelism, and synchronous and asynchronous calls.

Today I went back over programs, jobs, processes, concurrency, parallelism, and synchronous and asynchronous calls. I could remember roughly what each term meant, but when I put them together, I still wasn’t clear on what each one actually described.

On my second pass, I found it easier to start with one question: What is this concept meant to explain? I’ll use that question to work through their differences.

Illustration comparing programs, jobs, and processes, with examples of concurrency, parallelism, and asynchronous execution
First distinguish the work, the method, and its execution; then look at how multiple tasks make progress

Programs, jobs, and processes

What I most wanted to separate was the method described by a program, the work requested from the system, and the execution of that work. Which concept describes each of these?

A program describes a method

More precisely, a program consists of instructions and related data organized to perform certain tasks. It records a method and tells the computer what to do.

For example, some image-resizing code might specify how to read an image, calculate its new dimensions, and output the result. That program exists even before it runs.

So when I think about a program, I focus first on the method it describes. Whether it is stored on disk or loaded into memory is a separate question.

A job describes the complete work request

A job was the concept I initially found hardest to understand. A concrete example helped make it clearer.

Suppose I want to resize two images. Having the resizing program is only part of the request: I also need to specify which images to process, the scaling ratio, and where to save the results. If there are several processing steps, their requirements and order matter too.

In the batch-processing context of operating system textbooks, a job can be understood as a complete unit of work submitted to the system. It includes the necessary programs, data, and control information.

In other words, a program describes how to do something; a job describes the work I want the system to carry out.

One thing to keep in mind is that “task” has a broad everyday meaning. It doesn’t always correspond to an operating system job. I use “the complete work request” as a starting point, then check the specific textbook context.

A process is an execution instance

A process is an instance of a program in execution, together with its execution environment. To manage that execution, the system needs to track its progress, resources, and current state.

Returning to the image-resizing example:

  • The resizing code and related data describe the program.
  • The input images, scaling ratio, output location, and processing requirements make up the submitted job.
  • The running instance created to carry out the work is a process.

These concepts do not have a strict one-to-one relationship. The same program can run multiple times as different processes. A job can also contain several steps carried out by multiple processes.

An important point here is that a process can exist without executing on the CPU at that moment. Its current state matters too.

In the three-state model, a process can be ready, running, or blocked. Ready means it has what it needs to run and is waiting for CPU time. Running means it is executing. Blocked means it is waiting for an event, such as I/O completion. The five-state model adds new and terminated states.

Seen this way, the “dynamic” nature of a process refers to an execution that moves through different states.

Threads and execution scheduling

A process can contain one or more threads. In a common modern operating system model, a process is generally the basic unit of resource allocation and protection, while a thread is the basic unit of CPU scheduling. Microsoft’s documentation on processes and threads likewise describes a thread as the basic unit to which the operating system allocates processor time.

The way I understand it is this: a process organizes resources, while its threads carry the execution flows. Threads in the same process usually share resources such as the address space, but each can have its own execution progress.

Review:

  1. A program describes a method, a job describes the complete submitted work, and a process is an execution instance.
  2. A program and a process are different things. A process does not have to occupy the CPU continuously.
  3. When distinguishing processes from threads, separate resource allocation from execution scheduling.

Concurrency and parallelism

Once I have a clearer picture of how a program runs, the next question is: how do several tasks make progress together?

Concurrency and parallelism are more general concepts. I can use processes and threads to understand them in an operating system, but their use is not limited to that setting.

Concurrency concerns making progress together

Concurrency means multiple tasks make progress over the same period of time. They do not have to execute at the same instant.

First consider the simplified case of a single logical processor. Tasks A and B can take turns:

Time moves to the right
Execution order: A -> B -> A -> B -> A -> B

Only one task executes at any instant. But over the whole interval, both tasks make progress. That is concurrency.

Taking turns is therefore one way to implement concurrency. When multiple execution resources are available, tasks may also execute simultaneously.

Parallelism concerns simultaneous execution

Parallelism means multiple tasks execute at the same time.

For example, two logical processors can each execute a task:

Over the same time interval
Logical processor 1: A A A A
Logical processor 2: B B B B

Here, A and B both make progress over the same interval and actually execute simultaneously. This example exhibits both concurrency and parallelism.

The Go project’s explanation of concurrency and parallelism distinguishes their concerns: concurrency is about organizing independently progressing activities, while parallelism is about whether computations execute simultaneously. I find it helpful to identify those two questions before judging a particular example.

For ordinary software threads, multiple threads must take turns when there is only one logical processor; with multiple logical processors, multiple threads can execute simultaneously. As a starting point, I think of a logical processor as a processing unit on which the operating system can independently schedule a thread. It does not necessarily correspond one-to-one with a physical core. This section is about software-thread execution.

Review:

  1. Concurrency asks whether tasks make progress over the same interval; parallelism asks whether they execute simultaneously.
  2. Concurrency can be implemented by taking turns or by using multiple execution resources.
  3. First establish whether the discussion is about tasks, threads, or hardware. A blanket statement that “a CPU can only do one thing at a time” is too broad.

Synchronous and asynchronous calls

Concurrency and parallelism describe how multiple tasks make progress. Synchronous and asynchronous calls address a different question here: after starting an operation, does the caller have to wait for it to finish before continuing?

I start with these two descriptions:

  • A synchronous call: the current calling flow continues after the operation finishes and the call returns.
  • An asynchronous call: the caller can continue after starting the operation and obtain the result later through an agreed mechanism.

For an operation that takes some time, I picture a synchronous call like this:

I start operation A -> Wait for A to finish and return -> Continue

An asynchronous call looks like this:

I start operation A -> Continue with other work
When A finishes     -> Handle its result through a callback, event, or similar mechanism

“Not waiting for the result” does not mean the result is unimportant, or that I will never need to wait for it. Later work that depends on the result still needs coordination. MDN’s introduction to asynchronous programming follows the same idea: start a potentially lengthy operation, continue responding to other events, and receive the result when it is ready.

Execution order in a synchronous call

The Chinese word used for “synchronous” can easily make me think of things happening simultaneously. For a synchronous call, though, the useful question is whether the caller can continue executing.

Take image resizing again. If I call a synchronous resizing function, the current flow cannot execute its next step until that call finishes and returns. Even if the next step is unrelated to the resized image, it still has to wait for the call to return.

With an asynchronous resizing interface, the current flow can first do work that does not depend on the result. When resizing finishes, a callback, event, or another agreed mechanism can deliver the result so it can be saved.

For now, I understand it this way: a synchronous call lets the current flow continue after the call finishes; an asynchronous call lets it continue first and handle the result later. Either way, actually using the resized image requires the result to be ready.

Asynchronous execution and parallelism

Asynchronous execution does not guarantee that two tasks execute on the CPU simultaneously. For example, a single-threaded event loop can process other events after a request is sent and handle its callback when the result arrives. Those callbacks can still execute sequentially on the same thread.

Conversely, an operation may use multiple threads to perform calculations in parallel while its caller waits for the result. So “asynchronous” does not automatically mean “start another thread.” Whether execution can be interrupted is not the criterion for distinguishing synchronous from asynchronous calls either.

Review:

  1. Synchronous and asynchronous calls concern the relationship between the calling flow and operation completion. Concurrency and parallelism concern how multiple tasks make progress.
  2. An asynchronous result is generally handled later. It still needs handling, and asynchronous execution does not guarantee parallelism.
  3. An asynchronous call allows other work that does not depend on the result to proceed first. Actually using the result still requires it to be ready.

Today’s review

After going through these concepts again, what I most want to remember is that similar-sounding definitions can be answering different questions.

For programs, jobs, and processes, I ask what method is described, what work is requested, and how the system organizes its execution. For concurrency and parallelism, I distinguish making progress together from executing simultaneously. For synchronous and asynchronous calls, I look at the relationship between the calling flow and the result after an operation starts.

Separating those questions first makes the definitions easier to understand than memorizing words such as “static,” “dynamic,” “alternating,” and “waiting” on their own.

7 - VLN Foundations and a Survey of Navigation Methods

Notes on scenes, tasks, simulators, evaluation metrics, and success rates for my zero-shot R2R-CE navigation project using qwen3-vl-plus.

Recently, I have been working on a VLN project that uses the relatively affordable qwen3-vl-plus API for zero-shot navigation on R2R-CE. While going through the related material, I have mainly been trying to understand a few things: what each dataset provides, what kind of environment the robot moves through, and how to read the success rates reported by different methods.

This post covers the foundations I organized on October 15, followed by a survey of methods updated through October 17. I first separate scenes, tasks, and simulation platforms, then work through navigation approaches, evaluation metrics, and paper results.

Concept illustration of a wheeled robot observing an indoor environment and choosing its next action from a language instruction
Language instructions, current observations, and actions form a navigation loop that keeps updating

Zero-Shot Navigation and Affordable APIs

VLN stands for Vision-and-Language Navigation. A simple way to understand it is this: a robot receives a natural-language instruction, uses what it can see to decide where to go next, and stops at an appropriate location.

For example, “leave the bedroom, walk through the hallway, and stop beside the table” contains more than a destination. The robot also needs to recognize the bedroom, hallway, and table, understand how they relate to one another, and work out how much of the instruction it has completed.

I am taking a zero-shot approach: rather than training or fine-tuning a navigation policy on R2R-CE demonstrations, I use an existing vision-language model to make decisions. Here, “zero-shot” refers to the navigation task; the foundation model itself has already been pretrained.

I think of “affordable API” as a budget constraint for the project. Alongside success rate, I need to consider how many calls, images, and tokens a complete route requires, as well as how long it takes. A cheap individual call does not necessarily make the whole route cheap.

Scenes, Navigation Tasks, and Simulators

When I first encountered these names, the most useful distinction was between three layers.

Scene data provides the environment. Matterport3D, or MP3D, includes images, 3D reconstructions, and other data obtained by scanning real buildings. It first answers the question, “What does the building look like?”

Navigation task data specifies what to do. R2R and RxR provide starting locations, language instructions, reference routes or goals, and evaluation splits. They answer, “What route should the agent follow in this building?”

A simulator makes the interaction run. Matterport3D Simulator and Habitat execute actions and return observations according to their environment representations, allowing navigation algorithms to interact with the environment.

Having a 3D scene therefore does not mean having a complete VLN task. Even a basic experiment needs to connect the environment, task definition, and execution platform.

MP3D and HM3D

MP3D contains 90 building-scale scenes, with RGB-D images, camera poses, 3D reconstructions, and other data. Classic navigation tasks such as R2R and RxR are built on these scenes. For my current project, its immediate value is that I can reuse established task annotations and evaluation settings.

HM3D provides 1,000 building-scale 3D scenes, offering more environments for embodied navigation. But it is not, by itself, a complete VLN dataset with human-written route instructions. Using these environments for language-guided navigation also requires routes, instructions, and corresponding task definitions.

Both can be used with Habitat, but replacing MP3D with HM3D does not mean I am still running the original R2R-CE evaluation. Having more scenes and having the same task are two different things.

Common VLN Datasets

The differences between these names mainly come down to task design. Some share the same buildings but ask the robot to do different things.

R2R: Following a Route Instruction

R2R stands for Room-to-Room, a classic indoor VLN dataset. It uses MP3D scenes and pairs routes with human-written English instructions that guide an agent from a starting point to a goal.

The R2R dataset in the original paper contains 7,189 routes and 21,567 instructions, with three independent English descriptions for each route. These are three ways of describing the same route, not three subtasks to execute in sequence.

The original R2R task is built around viewpoints on a navigation graph. Understanding this representation helps explain how it differs from R2R-CE.

RxR: Richer Routes and Language-Visual Alignment

RxR stands for Room-Across-Room. It also uses MP3D environments, but expands the instruction languages to English, Hindi, and Telugu, with longer and more varied routes.

One feature I find worth remembering is dense spatiotemporal grounding. I first understand this as fine-grained alignment between language, observations, and movement.

During data collection, a guide moves along a route and describes the surroundings. The system records timestamped views and poses, which are then aligned with words in the instruction. Researchers can therefore study not just the final route, but also “what the person saw and where they were facing when they said this sentence.” These are observations recorded during collection, not human pose trajectories automatically available to a model at test time. The official RxR explanation gives a more visual introduction.

Official RxR animation aligning words in a navigation instruction with observations and movement along the route
An example of language, observation, and movement alignment in RxR

Image source: example animation in the official RxR repository.

R4R: Separating Arrival from Route Following

R4R stands for Room-for-Room. It creates longer navigation tasks by joining compatible routes from R2R and concatenating their instructions. The “4” in the name does not mean a fixed route through four rooms.

It drew my attention to a distinction: reaching the destination and faithfully following the instruction are two abilities that need separate evaluation.

Suppose an instruction asks the robot to leave the hall, enter the study, go through a corridor, and then enter the bedroom. But there happens to be a door connecting the hall directly to the bedroom. Taking that shortcut might reach the goal without following the full instruction.

Checking the final location is therefore not enough; the actual route matters too. This is why the R4R paper emphasizes instruction fidelity.

REVERIE: Identifying an Object as Well as Navigating

REVERIE defines a different task. It uses high-level language descriptions to guide an agent near a target object and requires the agent to identify that object correctly.

For example, “go to the bedroom and find the lamp on the bedside table” is not just about completing a route. Once in the bedroom, the agent still needs to identify the particular object.

My shorthand for these differences is: R2R focuses on route instructions; RxR adds multilingual instructions and fine-grained alignment; R4R emphasizes instruction fidelity over longer routes; and REVERIE combines navigation with object identification. Similar names alone are not a reason to compare their success rates directly.

R2R versus R2R-CE

For my current project, the most directly relevant distinction is between R2R and R2R-CE.

In the original R2R, the agent moves between predefined panoramic observation locations. Navigation graph edges already indicate which locations are mutually reachable, so the algorithm mainly chooses the next adjacent viewpoint.

R2R-CE transfers these language navigation tasks into continuous 3D environments, usually running in Habitat. The agent must actually move and turn, changing its position incrementally within navigable space while encountering obstacles and collisions.

Original VLN-CE task setup showing 3D simulation, first-person observations, and low-level movement actions
Continuous environments and low-level movement actions in VLN-CE

Image source: official VLN-CE project page.

Continuous Environments Do Not Require Continuous Actions

One point to keep clear is that a continuous environment does not require continuously valued actions.

The base VLN-CE task configuration can use fixed-distance forward steps and fixed-angle turns, such as moving forward 0.25 meters or turning 15 degrees. The action choices are finite, but movement is no longer restricted to the observation nodes of the original navigation graph.

Another approach is for a higher-level component to propose a local waypoint and let a lower-level component move toward it. However, proposing a point does not guarantee that the robot can reach it. Checking reachability, avoiding obstacles, and reporting failures are still part of the system.

This makes the connection between language understanding, visual judgment, and physical movement clearer to me. Switching to a stronger API does not automatically replace all the control and traversability decisions.

Measuring Navigation Results

I divide evaluation into three questions: did it arrive, did it move efficiently, and did it follow the specified route?

NE, SR, and OSR: Reaching the Goal

NE, or Navigation Error, usually measures the shortest navigable distance from the final position to the goal, in meters. Lower is better. This distance follows traversable paths through the environment; a short straight-line distance through a wall does not necessarily mean the robot is close to the goal.

SR means Success Rate. Each episode is judged against the task’s success rules, and the overall proportion is reported. In common R2R-CE settings, the agent must stop within the goal’s success distance, usually three meters. The exact implementation, including how STOP is counted, depends on the evaluation code for the version being used.

OSR, or Oracle Success Rate, asks whether the trajectory ever entered the goal’s success region. Even if the agent later moves away, the trajectory may still count as an oracle success. The VLN-CE metric implementation is useful for checking the calculation.

A high OSR but low SR therefore means that some trajectories passed near the goal without successfully finishing. Stopping decisions, task progress, and subsequent movement are worth examining, but the gap between the two numbers alone does not identify the cause of failure.

SPL and Path Length: Moving Efficiently

SPL, or Success weighted by Path Length, combines success with path efficiency. An unsuccessful episode scores zero. A successful episode is discounted according to the ratio between the shortest path length and the actual path length.

For example, if the shortest navigable path from the start to the goal is 10 meters and the agent succeeds after traveling 20 meters, the episode’s SPL score is 0.5. The scores are then averaged across episodes. The SPL evaluation paper gives the formal definition.

TL / PL usually refers to the actual trajectory or path length, also in meters. It needs to be read alongside success rate: a short path might mean efficient navigation, or it might mean the agent stopped incorrectly very early.

SPL uses the shortest path between the start and goal as its reference. That is not always the full route requested by the instruction, so SPL alone cannot tell us whether the agent faithfully followed the entire instruction.

nDTW: Following the Reference Route

To check how closely the actual route matches the reference route, I can also look at nDTW. It uses dynamic time warping to align trajectories and measures their similarity, rather than just comparing their endpoints. The nDTW paper discusses this type of evaluation for instruction-guided navigation.

In the earlier R4R example, taking a shortcut from the hall to the bedroom could reach the destination while following the reference route less faithfully. This makes the distinction between “reaching the goal” and “following the route” feel much more concrete to me.

A Survey of Success Rates across Approaches

When reading an experimental results table, I first check the kind of approach and then the tasks it was evaluated on. I keep a few comparison conditions in mind:

  • Is the task the original R2R or R2R-CE in continuous environments?
  • Is the split val_seen, val_unseen, or the test set? Does the evaluation use the full split or a subset?
  • Does the model receive RGB, depth, or pose information? Can it access panoramic observations?
  • Does the system include a trained navigation policy, waypoint predictor, or other modules? Is prior exploration allowed?
  • Which model version is used? How many calls, how much time, and how much money does each episode require?

Whether a model is trained, how the foundation model is deployed, and which additional modules are used are different dimensions. For example, a method can leave the main model unchanged while using both an API and pretrained perception modules. I organized the following representative results around these distinctions to get a sense of what different approaches currently achieve.

Representative Results as of October 17

1. Small zero-shot models: around 30%.

LightZeroNav, using Qwen3-VL-8B, reports 30.0% +/- 2.0% SR on a 100-episode R2R-CE subset; its 4B version reports 27.0% +/- 3.0%. Rather than fine-tuning on navigation tasks, it organizes execution through task decomposition, observation filtering, and progress assessment. This is the concrete reference behind “small models at around 30%” in my notes.

2. Zero-shot open-weight large models or affordable APIs: representative results around 40%-50%.

SpaceVLN evaluates 1,839 episodes from R2R-CE val_unseen. Its Qwen3-VL-Plus + Qwen3-VL-Flash configuration achieves 40.3% SR, while its locally deployed Qwen3.5 configuration achieves 48.9%. Plus handles planning and Flash handles execution, with RGB-D, pose information, and spatial memory also used in the system. These results are directly relevant to my project using an affordable API.

3. Trained navigation models: representative full-split results around 70%-80%.

Qwen-RobotNav-8B reports 72.1% SR on R2R-CE val_unseen; Robostral Navigate reports 76.6%. The latter is an 8B model trained for navigation using monocular RGB input. This approach encodes more navigation ability into model parameters, unlike zero-shot navigation through direct calls to a general-purpose model.

4. Zero-shot navigation with flagship APIs: some 100-episode subset results approach 80%.

The zero-shot navigation evaluation of GPT-6-Astra uses monocular RGB and primitive actions on a 100-episode R2R-CE subset. It achieves 76.0% SR with medium reasoning and 79.0% with ultra reasoning. The reasoning budget matters alongside the model itself: changing the reasoning configuration changes the result even with the same model.

5. Hybrid systems combining flagship models and trained modules: full-split results around 80%.

Table 6 of the NavGPT-3 preprint provides a representative example. On the full R2R-CE val_unseen split, GPT-6 Astra combined with the 8B NavGPT VLA achieves 81.51% SR and 70.42% SPL; the Claude Opus 5 configuration achieves 79.01% SR. For comparison, the standalone 8B NavGPT VLA achieves 74.51% SR.

I classify this as a hybrid system because it combines the reasoning ability of a flagship language model with a trained navigation policy. The higher-level model interprets instructions, plans, and reviews execution, while NavGPT VLA executes actions at a higher frequency. The system also provides mapping and backtracking tools. The comparison is not just about model size, but also how these abilities work together.

I am interested in these results not just to find the highest success rate, but to understand the roles of model capability, observations, and navigation modules. For a “zero-shot + affordable API” approach, the cost of completing an episode is another unavoidable part of the comparison.

8 - How Hugo and Oink Integrate Giscus Comments

A complete walkthrough from Hugo parameters and Oink templates to the Giscus iframe and GitHub Discussions, including shared comments across languages and deployments.

Hugo produces static HTML. It does not provide a server that accepts comments, a database, or a user system. Adding comments to a Hugo site with Oink therefore means delegating the comment interface to Giscus and storing the data in GitHub Discussions.

When I added comments to the site, I wanted one conversation for everyone—whether they opened the Chinese or English page, on Vercel or GitHub Pages. Here’s how the pieces work together to bring a comment onto a static blog page.

Chinese illustration showing a static blog receiving comments through Giscus
A static blog joins the conversation through Giscus and GitHub Discussions

What the four components do

ComponentResponsibility
HugoReads Markdown and configuration and generates blog pages
OinkProvides page templates and decides when and where to output a comment container
GiscusDisplays the comment interface and communicates with GitHub
GitHub DiscussionsStores discussions, replies, identities, and reactions

The relationship is:

Markdown + hugo.yml
        │
        ▼
Hugo renders HTML with Oink templates
        │
        ▼
The page loads a Giscus iframe
        │
        ▼
Giscus finds or creates a GitHub Discussion

Comment data always remains in GitHub Discussions. The blog embeds an entry point for viewing and posting Discussion content. The official Giscus documentation explains that Giscus uses the GitHub Discussions search API to find the discussion mapped to a page and creates one when a visitor first comments or reacts if none exists.

Why a static site needs an external comment backend

A conventional comment system needs at least this flow:

A visitor submits a comment
    ↓
A server authenticates the visitor and receives the request
    ↓
A database stores the comment
    ↓
Another visitor opens the page
    ↓
The server reads previous comments
    ↓
The page displays them

That normally means maintaining an application server, database, login system, permissions, and spam controls. Hugo only builds static files; it does not continuously run an application that handles those requests.

Giscus reuses GitHub’s existing services:

  • GitHub accounts provide identity.
  • GitHub Discussions store the main post, replies, and reactions.
  • Giscus maps the current page to one Discussion and provides the embedded interface.
  • Repository maintainers moderate, reply, pin, lock, or remove content in Discussions.

The site therefore needs neither a comment database nor a GitHub token in hugo.yml.

Why a Hugo parameter can control comments

Hugo lets a site define parameters in configuration or page front matter. For example:

comments: true

To Hugo, this is simply a value. Oink’s templates give it meaning by reading site-level and page-level comment parameters and deciding whether to output the comment container and load Giscus.

Hugo’s front matter documentation explains that metadata at the top of a page can describe content and influence template selection and publication structure. This site keeps the full Giscus configuration in hugo.yml and uses section cascades to control where it appears:

  • Blog articles inherit the global comment setting.
  • The blog index explicitly sets comments: false.
  • The home, learning, and experience sections do not display comments.
  • Chinese and English versions of a blog post use the same discussion identifier.

This avoids repeating the entire Giscus configuration in every article.

What the Giscus configuration contains

The central configuration for this site is:

params:
  comments:
    enable: true
    type: giscus
    giscus:
      repo: RyanYhy/my-project-docs-vercel
      repoId: R_kgDOUXvkaw
      category: Announcements
      categoryId: DIC_kwDOUXvka84DGph2
      mapping: specific
      strict: 0
      reactionsEnabled: 1
      emitMetadata: 0
      inputPosition: bottom
      theme: auto
      loading: lazy

The four essential identifiers are:

SettingPurpose
repoSelects the public repository containing Discussions
repoIdGitHub’s public unique identifier for that repository
categorySelects the category for new discussions
categoryIdGitHub’s public unique identifier for that category

These are routing identifiers, not secrets or access tokens. The target repository must also be public, have Discussions enabled, and have the Giscus App installed. The official configurator recommends an Announcements-type category so only maintainers and Giscus can create new Discussions there.

The remaining settings control behavior:

  • reactionsEnabled: 1 displays reactions on the main discussion post.
  • emitMetadata: 0 disables periodic Discussion metadata messages to the parent page.
  • inputPosition: bottom puts the input box below existing comments.
  • loading: lazy delays loading until the iframe is near the viewport.
  • theme: auto follows the site’s light or dark mode.
  • Chinese pages use zh-CN, while English pages use en. This changes the Giscus interface, not the language of user comments.

How the page loads comments

The process has a build phase and a browser phase.

Build phase

When Hugo builds a blog page, Oink checks the comment switch and required configuration. If the conditions pass, the template outputs a parameterized container similar to:

<section
  data-td-giscus
  data-repo="RyanYhy/my-project-docs-vercel"
  data-category="Announcements"
  data-mapping="specific"
  data-term="/blog/hugo-oink-giscus-comments/">
  <div data-td-giscus-container></div>
</section>

No comment data exists in the generated HTML. It only reserves a container and tells the browser which repository, category, and discussion identifier to use later.

Browser phase

After a visitor opens the page, Oink’s JavaScript dynamically loads:

https://giscus.app/client.js

Giscus then creates an iframe. It appears at the bottom of the blog, but technically comes from an independent page served by giscus.app:

Blog page
├── Article
├── Images and code
└── iframe
    └── Giscus comment interface
        └── GitHub Discussions API

The iframe isolates the comment application from the blog page. Oink also watches the site’s color mode and uses browser postMessage events to send theme changes to the Giscus iframe.

If the script or iframe fails to load, Oink exits the loading state and displays a localized error message instead of leaving the page waiting indefinitely.

How one article maps to one Discussion

Giscus needs to know which Discussion belongs to the current page. Available mappings include the full URL, pathname, the page title, and a specific string.

A single-language site on one domain can often use:

mapping: pathname

Different paths then normally create different discussions. This site, however, has Chinese and English content on two deployments:

/blog/example/
/en/blog/example/
/YHY-Website/blog/example/
/YHY-Website/en/blog/example/

Using the browser pathname directly would split one article across several Discussions. The site therefore uses:

mapping: specific

A Hugo template derives a common data-term from .Page.Path:

/blog/example/

Hugo’s Page.Path documentation states that the logical path excludes file extensions and language identifiers. Removing deployment domains and the GitHub Pages base path gives all four entry points the same identifier:

Chinese on Vercel ─┐
English on Vercel ─┼─→ /blog/example/ ─→ one Discussion
Chinese on Pages  ─┤
English on Pages  ─┘

The title may be translated and the domain may change while the comment thread remains stable. Changing the article slug changes this identifier, so a slug change should preserve the old term or include a deliberate Discussion migration plan.

How comments are created and moderated

After loading, Giscus searches the configured repository and category with the mapping term:

  1. If a match exists, it fetches and displays the existing comments.
  2. If no match exists, it initially displays an empty comment section.
  3. The first comment or reaction causes Giscus Bot to create the Discussion.
  4. A visitor authorizes Giscus through GitHub OAuth to post on their behalf.
  5. The site owner moderates content in GitHub Discussions.

Visitors may also participate directly in the GitHub Discussion. Both interfaces operate on the same data.

Summary

Giscus does not copy comments into Hugo. It embeds a GitHub Discussion in the blog: Hugo generates the page, Oink decides whether to load comments and passes the configuration, Giscus provides the interface and communication layer, and GitHub Discussions persists identities and data.

For a simple site, pathname may be enough. For a bilingual site with two deployments, the important design choice is a stable identifier independent of language and domain. This site uses specific + /blog/<slug>/ so every version of the same article shares one comment thread.

9 - Installing a Custom Linux Kernel in a Virtual Machine

Stabilize VMware Ubuntu’s NAT network, compile and install a custom kernel, then load a hello module—a complete operating-systems lab workflow.

This article has one goal: compile and install a custom kernel in Ubuntu running inside VMware, then load a .ko module I wrote myself.

Compilation and kernel replacement both happen in that virtual machine. They consume CPU, memory, and disk space and involve GRUB. Unstable networking can interrupt long builds or SSH sessions; without booting the new kernel, the module will not match the running version. The order is therefore static IP first, custom kernel second, and module last.

From a virtual machine to a custom kernel
Host → Ubuntu virtual machine → custom vmlinuz → hello.ko
Illustrative placeholders

ip1 is the host’s address on VMnet8, ip2 is the NAT gateway, and ip3 is the virtual machine’s static address. These and username are placeholders. Use the actual subnet shown in your Virtual Network Editor.

Why compile the kernel in a virtual machine?

The kernel is the innermost operating-system layer, managing CPU, memory, disks, network adapters, and process scheduling. Terminals, browsers, and apt run in user space. They cannot directly access hardware and instead ask the kernel through system calls such as read, write, and mmap.

LayerExamplesAccess
User spacebash, browsers, PythonNo direct hardware access
Kernelvmlinuz, scheduler, driversThe layer that directly operates hardware
HardwareCPU, memory, network adapters, disks—

uname -r prints the currently running kernel version. A later .ko build must use headers and an ABI matching that kernel, so booting the custom kernel first is not optional in this experiment.

My host runs Windows. Although I have also installed Ubuntu in a dual-boot setup, replacing its kernel could affect existing software dependencies. I therefore created a separate VMware machine for this experiment. Builds still consume disk space and time, but snapshots provide a way back without experimenting on my everyday environment. First, give this machine a static IP so DHCP address changes do not interrupt SSH during a long build.

Configuring a static IP for the virtual machine

VMware’s VMnet8 uses NAT by default: the virtual machine accesses the network through the host. A network adapter can communicate directly only with devices on its own subnet; traffic outside it goes through the default gateway. The path is:

Ubuntu → Gateway (usually .2 on the subnet) → VMware NAT → Windows physical adapter → Internet

Record the VMnet8 subnet and gateway

Open Virtual Network Editor and select VMnet8:

FieldMeaningPlaceholder here
Subnet IPNAT subnet, such as x.x.x.0The subnet itself
Gateway IPVirtual network gateway, usually .2ip2

Then check Windows: Control Panel → Network and Sharing Center → Change adapter settings → VMware Network Adapter VMnet8. The host’s address on this network is usually .1, called ip1 here.

AdapterPurpose
VMnet0Bridged networking into the physical LAN; usually no subnet is assigned in the editor
VMnet1Host-only; DHCP is available by default, without Internet access
VMnet8NAT; virtual machines access external networks through the host
Warning

If you use ip1, the host, as the gateway instead of ip2, the NAT gateway, a common symptom is being able to ping Windows but not reach the Internet.

Configure static IPv4 in Ubuntu

Settings → Network → IPv4 → Manual:

  1. Address: ip3, on the same subnet; avoid .0, ip1, ip2, and the DHCP pool.
  2. Netmask: 255.255.255.0, a 24-bit prefix.
  3. Gateway: ip2.
  4. DNS: use a public resolver such as 8.8.8.8 or 223.5.5.5. This specifies the domain-name resolver, not your machine’s IP.

Open a new terminal and check:

hostname -I

The output should include ip3. The lab machine now has a fixed address for the hours-long kernel build.

Compiling and installing a custom kernel

A kernel does not have to be one giant binary. Features can be built in, [*]; built as modules, [M], producing .ko files loaded when needed; or omitted, [ ]. Use lsmod to view loaded modules.

Prepare the source and .config

Check the current kernel and select a nearby version from kernel.org. The example uses 5.15.221: if uname -r shows 5.15.0-139-generic, choosing 5.15.x is simpler than jumping across major versions.

uname -r
tar -Jxvf linux-5.15.221.tar.xz
cd linux-5.15.221
cp /boot/config-$(uname -r) .config
make olddefconfig
tar optionMeaning
-Jxz compression
-xExtract
-vList filenames
-fThe archive filename follows

make olddefconfig supplies defaults for new options in an existing .config without an interactive questionnaire. It only updates the configuration; it does not compile the kernel.

The upstream kernel.org source does not include Ubuntu’s two certificate files. Clear their paths so the configuration does not point to nonexistent files:

./scripts/config --file .config --set-str SYSTEM_TRUSTED_KEYS ''
./scripts/config --file .config --set-str SYSTEM_REVOCATION_KEYS ''
OptionOriginal purpose
CONFIG_SYSTEM_TRUSTED_KEYSBuild trusted CA certificates into the kernel for module-signature verification and related uses
CONFIG_SYSTEM_REVOCATION_KEYSBuild revoked certificates into the kernel

To confirm that you booted your own build, add this line near the start of start_kernel() in init/main.c. Line numbers vary by version.

printk(KERN_ALERT "Hello, World! This is a custom kernel!\n");

Compilation and disk space

The first build takes a long time. Ensure the virtual machine has enough CPU cores, memory, and free disk space. Check space first:

df -h /

My observations:

ConfigurationDisk space
Keep default debug informationA 40G virtual disk was insufficient
Disable debug information before rebuildingAbout 30G was enough to finish

If space is insufficient, disable debug information and run make olddefconfig again:

./scripts/config --disable DEBUG_INFO_BTF_MODULES
./scripts/config --disable DEBUG_INFO_BTF
./scripts/config --disable DEBUG_INFO_DWARF4
./scripts/config --disable DEBUG_INFO_DWARF_TOOLCHAIN_DEFAULT
./scripts/config --disable DEBUG_INFO_REDUCED
./scripts/config --disable DEBUG_INFO_COMPRESSED
./scripts/config --disable DEBUG_INFO_SPLIT
./scripts/config --disable DEBUG_INFO
./scripts/config --disable NFSD
make olddefconfig

Then build, keeping -j at or below the virtual machine’s CPU-core count:

sudo make -j8

The source root should contain modules.order after the modules finish building. GCC’s role here is straightforward: compile .c source into machine code for the kernel and its modules.

Expanding a disk after it fills up

If compilation fills the root partition, do not immediately shut down to expand the virtual disk. Shutting down with no free system space may leave Ubuntu unable to reach the desktop, with a black screen.

While you can still access the system, free some space first, for example by removing temporary files or incomplete build artifacts. Then shut down and enlarge the disk in VMware settings. Expanding the disk only increases the .vmdk; the guest sees the extra capacity as unallocated space. A partitioning tool must add it to the filesystem.

  1. If Ubuntu still boots, install and open GParted and extend the root partition into the unallocated space.
  2. If the screen is already black and the system will not boot, start from an Ubuntu installation image, choose Try Ubuntu, and use GParted in the live environment to extend the root partition into the new unallocated space.
Warning

Free space first, shut down second, and expand the virtual disk third. Expanding only after shutting down a full system commonly leaves it unbootable, requiring Try Ubuntu from a live USB or image.

Install, update GRUB, and verify

sudo make INSTALL_MOD_STRIP=1 modules_install
sudo make install
ls /lib/modules/5.15.221
sudo update-grub

After rebooting, the new kernel should be available. Following make install, GRUB’s first entry is usually the newly compiled version.

Additional option, not used in this experiment

To enter BIOS and change boot settings, power off the virtual machine and append bios.forceSetupOnce = "TRUE" to its .vmx. This is a one-time setting reset to FALSE after boot. If Windows hides extensions, use File Explorer → View → Show → File name extensions.

The custom printk message should appear in the kernel log. Check:

uname -r
sudo dmesg | grep -i hello

This stage is complete only when uname -r shows 5.15.221, or your chosen version, and dmesg contains the Hello message. The module below uses uname -r to locate /lib/modules/…/build, so reach this point before proceeding.

Writing and loading a kernel module

A module runs inside the kernel without requiring a rebuild of the entire kernel. insmod loads it into the currently running kernel, so use the kernel’s Kbuild system rather than gcc hello.c -o hello. The build tree is /lib/modules/$(uname -r)/build.

Source and Makefile

Create hello_module.c in a clean directory:

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>

static int __init hello_init(void)
{
	printk(KERN_INFO "Hello, Kernel!\n");
	return 0;
}

static void __exit hello_exit(void)
{
	printk(KERN_INFO "Goodbye, Kernel!\n");
}

module_init(hello_init);
module_exit(hello_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("username");
MODULE_DESCRIPTION("A simple hello world Linux kernel module");
MODULE_VERSION("1.0");
Invisible spaces

Copying from a web page can introduce non-breaking spaces, NBSP. gcc may treat a trailing NBSP on an #include line as an extra token or report a leading NBSP as stray '\302'. Use ordinary spaces.

Create a Makefile in the same directory. Recipe lines must start with a Tab, not spaces.

obj-m += hello_module.o

all:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
FragmentMeaning
obj-mBuild a .ko module: m means module, while obj-y builds into vmlinuz
-C .../buildEnter Kbuild for the currently running kernel
M=$(PWD)Module source is in the current directory, outside the kernel tree
$(shell uname -r)Automatically match the version installed in the previous section

Load and unload

make
sudo insmod hello_module.ko
sudo dmesg | tail
sudo rmmod hello_module
sudo dmesg | tail
make clean

A successful load produces Hello, Kernel! in the log, and unloading produces Goodbye, Kernel!. The Entering directory line in the build log should point to the kernel source/build installed above, not another build tree supplied by the distribution.

Summary

StepResultWhy the next step needs it
VMnet8 static IPFixed ip3 with working NAT Internet accessThe address stays stable during long builds and SSH sessions
Successful custom-kernel installationuname -r shows your own buildModules must match the running kernel’s ABI
hello_module.ko and insmodHello appears in dmesgConfirms that the complete kernel-and-module experiment works

If insmod fails next time, first check uname -r and ls /lib/modules/$(uname -r)/build. Confirm that you are not still running the distribution kernel and that the Makefile points to the correct build tree.

10 - DNS Notes: Domain Lookups, Resource Records, and HTTPS Certificates

How domain names become IP addresses, what A/CNAME/NS records do, and where CNAME values and TLS certificates fit into the process.

When connecting a personal site to a custom domain, the console presents CNAME, A, and sometimes TXT records. These notes follow the process from the browser finding an IP address, through the purpose of each record type, to the point where HTTPS certificates enter the chain.

DNS translates a name before reaching a locked server
Name → DNS records → machine; TLS proves that the name belongs to the server
About the examples

0412.online and ryan.0412.online are this site’s public domains. The CNAME target, verification string, and mail hostname are illustrative.

What DNS does

DNS translates domain names: people remember ryan.0412.online, while machines connect to an IP address.

When a browser opens a URL, roughly:

  1. It checks the local cache and uses a cached answer if available.
  2. Otherwise, it asks the DNS server configured locally, a recursive resolver.
  3. That server queries the global hierarchy until an authoritative server supplies the record.
The browser does not query the root itself

The configured DNS service performs the recursive lookup. It may be your ISP, 1.1.1.1, your router, or a service run locally by proxy software. Answers are cached for a period specified by the TTL, so changing a record does not update the entire world immediately.

Where local DNS settings come from:

  • Automatic: DHCP supplies them when you connect to Wi-Fi or Ethernet, often pointing to your ISP or router.
  • Manual: a resolver address is entered in the network adapter’s IPv4 settings.
  • Proxy / VPN: some software points system DNS at loopback and performs lookups locally. Like Git using a local proxy port, the request first goes through another program.

Resource records: an entry in the ledger

A Resource Record (RR) is a rule in authoritative DNS: a name, a type, a value, and a cache lifetime.

FieldMeaningExample
Hostname / NameWhich name the rule applies to@ for the apex, www, ryan
TypeKind of recordA, CNAME, NS, etc.
TTLHow long others may cache it600 = 10 minutes
ValueWhat it points toAn IP address or another hostname

The value’s meaning depends on the type. A / AAAA / CNAME are most relevant to opening websites. NS / SOA / MX / TXT govern zone ownership, mail, and verification; browsers usually do not read the latter types when requesting a page.

A / AAAA / CNAME

A: name → IPv4

An A record identifies the IPv4 address for a name. When connecting the apex domain, 0412.online, to Vercel, the console often asks for an A record because many DNS panels do not permit CNAME at the apex.

The limitation is that an IP change requires a record update. Subdomains more commonly use CNAME, leaving the cloud provider to update the target’s IP.

AAAA: name → IPv6

The same idea as A, but for IPv6. Dual-stack sites often have both A and AAAA records.

CNAME: name → another name

CNAME means Canonical Name, or an alias. It does not supply an IP; it tells the resolver to look up another name instead.

ryan.0412.online.    CNAME    xxxxxxxxxxxxxxxx.vercel-dns-017.com.

Resolution proceeds as follows:

  1. Query ryan.0412.online → receive a CNAME → the DNS target hostname assigned by Vercel.
  2. Query that hostname → receive A/AAAA records → obtain an IP.
  3. The browser connects to that IP while still using your domain in TLS/HTTP.

Remember: Name is your label; Value is the hostname assigned by the other provider for DNS to locate the machine. It is usually not xxx.vercel.app, which people open in a browser, but the hashed ….vercel-dns-017.com. target shown in the console.

Key points:

  • Value must be a hostname, not an IP. Use A for an IPv4 address.
  • The trailing . marks a fully qualified name so that your suffix is not appended again.
  • A name with a CNAME generally cannot also have A, MX, or TXT records.
  • The hash prefix is a project-specific identifier. It belongs to your Vercel project: do not copy the public cname.vercel-dns.com from a tutorial or another project’s hash.

NS / SOA / MX / TXT

These four do not supply the website’s destination address. Web access uses A/CNAME.

NS: who answers for this zone?

Name Server records point not to the website but to the provider authorized to answer questions for the zone: where the ledger is kept.

After buying 0412.online, you may see:

0412.online.    NS    f1g1ns1.dnspod.net.
0412.online.    NS    f1g1ns2.dnspod.net.

This means DNSPod / Tencent Cloud DNS supplies the authoritative A and CNAME records. Changing DNS providers means changing NS, not changing each A record. If NS points elsewhere, editing CNAME in the old panel has no effect.

SOA: the ledger’s cover page

Start of Authority. Each zone has one, containing its primary DNS server, administrator email, serial number, and refresh interval. The panel generates it automatically; adding a website does not require editing it manually.

MX: where mail goes

Mail Exchanger. It is queried when mail is sent to an address such as xxx@0412.online; opening a website does not use MX.

0412.online.    MX    10  mx1.example.com.

The number is the priority: lower values are preferred. A/CNAME for a website and MX for mail can coexist, subject to the CNAME restriction. A domain without hosted email can have no MX and still serve a website.

That restriction is another reason to avoid CNAME at the apex: the same name cannot also hold MX records. Using CNAME for the ryan.0412.online subdomain avoids this issue.

TXT: a note for machines

A TXT value is plain text, ignored by the browser when fetching a page. It can let another company confirm that you control the domain.

For example, a platform may ask you to add:

0412.online.    TXT    "vercel-verification=abcd1234"

The platform checks the string in authoritative DNS and allows the domain to be attached to your project only if it matches. Otherwise, anyone could type someone else’s domain into their console.

Email anti-spoofing mechanisms such as SPF also use TXT and likewise do not supply a website’s address.

How TLS certificates fit in

DNS answers “which machine?” TLS certificates help establish “does this machine really represent this name?” and TLS protects the connection against eavesdropping.

1. DNS: ryan.0412.online → IP (NS locates the zone, then A/CNAME supplies the address)
2. TCP: connect to port 443 on that IP
3. TLS: request the certificate, verify the name, and encrypt
4. HTTP: request the web page

The certificates discussed here are issued for domain names, not an IP. The browser checks the name in the address bar. Many Vercel sites share an IP, and the hostname in the handshake, SNI, selects the appropriate certificate.

Certificate issuance often involves DNS. Two common validation methods are:

MethodWhat the CA doesRecords involved
HTTP-01Visits http://你的域名/.well-known/acme-challenge/..., substituting your domainA/CNAME must already point to a machine that can answer
DNS-01Queries a TXT record at _acme-challenge.…TXT

After connecting the domain to Vercel, the platform usually manages certificate requests. You rarely add _acme-challenge yourself. The verification TXT commonly shown in the console lets Vercel verify domain ownership; it is not the same record as a CA challenge.

Summary

RoleMechanism
Find the authoritative ledgerNS
Locate the websiteA / AAAA / CNAME
CNAME ValueProvider-assigned DNS target hostname, possibly including a project hash
MailMX
Prove domain ownershipTXT
Padlock / HTTPSTLS certificate, after DNS has found the IP

When filling in a CNAME: put your host label, such as ryan, in Name; copy the complete Value from Vercel’s domain page. Do not invent it or enter an IP.

11 - SSH Login and Security Hardening on Linux Servers

Practical CentOS/Ubuntu VPS notes, from connection failures and private-key permission errors to port changes, UFW rules, and key-based authentication.

My recent SSH experiments on a VPS involved public-network timeouts, private-key permission errors, and port changes that systemd did not pick up. This article combines several Obsidian notes in the order of getting connected, hardening access, and coordinating firewall rules.

SSH login and security hardening diagram
From client to server: allowing traffic through the cloud security group, UFW, and sshd
Illustrative placeholders

IPs are represented by ip1, ip2, and similar placeholders, for example ip1 for the server and ip2 for an allowed source. The domain xxx.xxx.com, ports such as 22222, and username are also example placeholders, not a real environment. Replace them with your own values.

The four elements of SSH login

Think of remote login in terms of four values:

ElementMeaningCommon default
IP / hostnameA publicly reachable addressScanners probe address ranges at random; it cannot truly be hidden
PortTCP port22
UsernameLogin accountOften root
CredentialsPassword or keyThere is no default password; keys require a local private key and a server-side public key

Hardening can change the port, username, and authentication method. A common combination is keys instead of passwords, no root login, and a non-22 port.

Connection failures: timeouts and troubleshooting

A typical error:

ssh username@xxx.xxx.com
ssh: connect to host xxx.xxx.com port 22: Connection timed out

Possible causes:

  1. SSH is not on port 22 — Specify -p <PORT>.
  2. The cloud security group does not allow the connection — Allow your IP or source range in the provider’s console.
  3. A VPN or jump host is required first — Internal servers often cannot be reached directly over SSH from a dormitory or home connection. Connect to the VPN or jump host first, then ssh to the target.

Confirm both the port and the username.

The public-network path is roughly cloud security group → local firewall (UFW) → sshd. A block at any layer can produce a timeout or rejection.

A pitfall: overly permissive private keys

OpenSSH can refuse to load a private key before login even begins:

@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@         WARNING: UNPROTECTED PRIVATE KEY FILE!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0664 for '/home/username/.ssh/id_ed25519' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.
Load key "/home/username/.ssh/id_ed25519": bad permissions

Cause: permissions 0664 allow the group and other users to read the private key. OpenSSH treats that as a potential exposure and refuses to use the key rather than risk it. This login therefore has no usable private key.

Fix: restrict access to the owner, tightening the directory permissions if needed:

chmod 700 ~/.ssh
chmod 600 ~/.ssh/id_ed25519
PathSuggested permissions
~/.ssh/700
Private key600
Public key *.pub644 is usually acceptable
Server-side ~/.ssh/authorized_keys600
Public-key filenames

Public keys uploaded to the VPS should not have an extra suffix such as .txt; rename them if necessary. The notes also recommend chmod 600 for the server-side public-key file.

Changing the SSH port with systemd and UFW

A cautious order: add the new port first, verify it, and only then remove the old one.

  1. Append a new Port in sshd_config, keeping the old port temporarily.
  2. Run daemon-reload and restart ssh.socket / ssh.service.
  3. Check the new listening port with sshd -T and ss.
  4. Allow the new port in UFW and the cloud security group.
  5. Open a new terminal and try connecting through the new port.
  6. After confirming access, remove the old rules and close port 22.

Editing the sshd configuration

sudo nano /etc/ssh/sshd_config

Add a line, for example adding 9753 alongside the existing 22222:

Port 9753

sshd_config configures the sshd server: listening ports, root login, password authentication, and more. In nano, use Ctrl+O to save and Ctrl+X to exit.

Why Ubuntu also needs ssh.socket updated

Ubuntu often uses systemd socket activation for SSH: ssh.socket listens first, then hands the socket to sshd in ssh.service. Editing sshd_config alone is not enough; the generator must update the socket configuration with the new ports:

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket ssh.service
ActionConfiguration on diskUnit in memoryKernel LISTEN socket
Only change Port 9753NewOldOld
daemon-reloadNewNew; generator updatedMay still be old
restart ssh.socketNewNewNew; bind recreated

Check which ports the configuration says should listen:

sudo sshd -T | grep -i '^port '
# 例:port 22222 \n port 9753

Check which ports the system actually listens on:

sudo ss -tlnp | grep ssh

ss -tlnp selects TCP, listening sockets, numeric ports, and process information. Remember: listening locally does not mean reachable publicly. UFW and the security group also matter.

Allowing the new port in UFW

UFW is Ubuntu’s firewall frontend. Traffic passes through:

Cloud security group → UFW (on the server) → sshd

Check the status:

sudo ufw status verbose
  • inactive: UFW is disabled; only the security group and sshd apply.
  • active: incoming traffic is filtered according to the rules.

Interpreting the output:

ColumnMeaning
ToPort exposed on this server
ActionALLOW permits traffic; DENY / REJECT blocks it
FromAnywhere means any IP; rules can instead allow only your home IP

Allow the new port:

sudo ufw allow 9753/tcp
sudo ufw status verbose

9753/tcp ALLOW IN means the rule is present. Common maintenance commands:

sudo ufw status numbered
sudo ufw delete 3
sudo ufw allow from <ip2> to any port 22222 proto tcp   # 仅允许 ip2 连入(替换为你的来源 IP)
sudo ufw limit 22222/tcp    # 对同一 IP 短时多次连接节流,减轻扫端口

Users, root restrictions, and key-based login

  1. Create a non-root user — Use sudo adduser username. On Debian/Ubuntu, install sudo with apt install sudo if needed and configure sudo-group access using visudo. Follow least privilege rather than assigning NOPASSWD everywhere.
  2. Disable root SSH login — Set PermitRootLogin no in sshd_config.
  3. Use keys and disable passwords — Generate a key pair locally, preferably Ed25519, avoiding DSA; see the next section for ECDSA/Ed25519 notes. Put the public key in the server’s ~/.ssh/authorized_keys, and set:
    • PubkeyAuthentication yes
    • PasswordAuthentication no

Reload or restart after configuration changes, and keep an already authenticated session open so that you do not lock yourself out.

A brief guide to key algorithms

TypeNotes
RSACommon, with longer keys; usable but not the only choice
DSANo longer secure; do not use it
ECDSAShort and fast; the algorithm has attracted more debate
Ed25519One modern default recommendation, with public documentation and good performance

systemd and SSH: two units

systemd is the init and service manager, PID 1, on most modern distributions. For SSH:

  • ssh.service runs the /usr/sbin/sshd process.
  • ssh.socket lets systemd listen first and activate the service, known as socket activation.

A simplified relationship:

systemd (pid 1)
  ├── ssh.socket   → listens on 0.0.0.0:22222 / 9753 …
  ├── ssh.service  → sshd takes over the existing fd
  └── generator    → reads sshd_config and generates the socket's port list

Unit files live under /usr/lib/systemd/system/ for package definitions and /etc/systemd/system/ for local overrides. systemctl cat ssh.service shows the combined definition. For port changes, remember that Ubuntu needs a reload and a socket restart, not just systemctl restart ssh.

Summary

StageKey points
Cannot connectCheck the port, security group, and VPN/jump host; all three layers must allow traffic
Private-key errorsUse chmod 600 for the private key and 700 for .ssh; OpenSSH rejects overly open keys
Port changesAdd before removing; verify with sshd -T and ss; update UFW and the security group together
HardeningNon-root users, disabled root login, key authentication, and a non-default port

These are learning notes, not a production checklist. Practice on a test machine first, and always retain a login path that will not leave you locked out.

12 - Building a Personal Site with Oink, from Setup to Publication

Notes on building a documentation site with Hugo and Oink as a frontend beginner, covering content structure, blog posts, hugo.yml, and local preview commands.

The official Oink tutorial is comprehensive, but connecting the folders, configuration, and commands can still be confusing the first time, especially without much frontend experience. These notes from building YHY Study Website follow one path: understand Oink, learn how content/ is organized, and then write and publish a blog post.

Oink site setup diagram
Markdown → Hugo → the Oink theme → a deployable static site

What Hugo and Oink each do

Hugo is a static site generator: it reads Markdown and configuration and produces HTML. Oink is a Hugo theme: it controls the appearance of sidebars, cards, callouts, code blocks, and other components.

Content and appearance are maintained separately:

  • Site repository (my-project-docs): Markdown articles and hugo.yml configuration
  • Theme repository, github.com/pgsty/oink: templates and styles

The site declares the Oink theme in hugo.yml, and go.mod pins its version, currently v0.6.0. When you run hugo server, Hugo:

  1. Reads articles and configuration from the site repository.
  2. Reads templates and styles from the theme module downloaded according to go.mod.
  3. Renders the content with the theme to generate web pages.
One command for everyday use

When writing documentation rather than changing the theme, hugo server is enough to remember. You do not need to start with make dev.

Local preview: get the site running first

Enter the project directory and start the server:

cd D:\MyData\yhy\6data\repository\my-project-docs
hugo server

Open http://localhost:1313/ in a browser. Saving a changed .md file under content/ automatically refreshes the page.

For a more complete rerender after each change, useful when investigating styling problems:

hugo server -DFE --disableFastRender
  • -DFE: includes draft and future-dated pages for writing.
  • --disableFastRender: disables fast rendering to avoid discrepancies caused by incremental updates.

Organizing content/

Oink does not maintain a separate navigation database: the folder structure on disk determines both the sidebar structure and URL paths.

Three common concepts:

ConceptMeaning
SectionA folder with _index.md; this level also has its own entry page
PageA .md file in a folder, or index.md in a subfolder
SiblingPages in the same directory, ordered with weight: 10/20/30…

The root content structure of this site:

content/
├── _index.md           → Home page
├── search.md           → Search page (special; usually left unchanged)
├── links.md            → Friends and links
├── experience/         → Experience (documentation-style, type: docs)
├── learn/              → Learning
└── blog/               → Blog (ordered by date)

Two ways to store an article:

FormatExample pathSuitable for
Single filecontent/blog/my-post.mdText posts with images stored in static/
Page bundlecontent/blog/my-post/index.md plus images in the same directoryPosts with multiple images kept beside the text

The first hugo.yml keys to learn

You do not need to read the whole configuration at once. Start with these fields:

KeyPurpose
titleSite name shown in browser tabs, the navbar, and elsewhere
params.productionURL + baseURLFull production address; affects sitemaps, RSS, and absolute links
params.github_repoContent repository used by buttons such as “Edit this page”
params.copyrightFooter copyright information
languages.zh.menus.mainNavbar menus: Experience, Learning, Blog, and Links

baseURL is often tied to productionURL with a YAML anchor:

productionURL: &productionURL https://ryanyhy.github.io/YHY-Website/
baseURL: *productionURL

&productionURL defines the name; *productionURL references it. Changing one value updates the whole site.

Writing a blog post in five steps

  1. Choose a filename — Create a .md file under content/blog/. Its filename becomes part of the URL, so use an English slug, such as oink-site-setup-notes.md → /blog/oink-site-setup-notes/.
  2. Add front matter — Metadata at the top should include at least title, date, and description. linkTitle is the shorter title displayed in lists and cards.
  3. Write the body — Adjust syntax copied from Obsidian, as explained below. Add callouts, step lists, heading anchors, and images as needed.
  4. Preview locally — Run hugo server and open /blog/ to check the card and article page.
  5. Publish — git add → git commit → git push; GitHub Actions builds and updates GitHub Pages.

A front matter template:

---
title: Full article title
linkTitle: Short list title
description: A one-sentence summary used by search and cards.
date: 2026-08-29
tags: [Oink, Hugo]
---

Moving from Obsidian to Oink: syntax comparison

ObsidianOink / MarkdownWhat to do
==highlight==**bold**Replace throughout
[[wikilink]][text](/path/) or an external linkUse an actual link
Image ![[x.png]]![description](path)See below

Common Oink components are described in the component documentation:

Callouts

> [!NOTE] Reading note
> Write the body here.

Step lists — Start each item with 1. and add {.steps} at the end, as in the five steps above.

Heading anchors — Use ## Section {#id}. The {#id} is not displayed and supports in-page links such as [text](#id).

Images and captions — Put {caption="..."} on the next line after the image, not on the same line as ![...](...):

![Diagram](/images/blog/example.png)
{caption="The caption appears directly below the image"}
  • Global images go in static/images/... and are referenced as /images/....
  • Page-bundle images sit beside index.md and use relative paths.

Four make commands for theme development

The four commands in Makefile are aliases. Windows often has no make, and make dev / make check require the theme source at ../oink.

CommandTheme sourceSuitable for
make devLocal ../oinkQuick previews while changing the theme
make checkLocal ../oinkRunning npm test after theme changes
make buildVersion pinned in go.modProduction builds matching the deployed site
make serveVersion pinned in go.modLocal previews with production configuration

When only editing content, use the PowerShell equivalents:

GoalPowerShell
Everyday previewhugo server
Production buildhugo --cleanDestinationDir --minify
Preview close to productionhugo server --environment production --minify
How dev and check differ

dev prioritizes fast visual feedback; check takes longer and runs automated tests. When changing the theme, first get the result right with dev, then pass check.

Publishing: three Git steps

After confirming the local preview:

git add content/blog/oink-site-setup-notes.md
git commit -m "blog: add Oink site setup notes"
git push origin main
  • git add: selects files for this commit. Specify the exact path when committing only the blog post; use git add -A to stage everything.
  • git commit: creates a local snapshot.
  • git push: sends it to GitHub and triggers Actions deployment.

The order is add → commit → push.

Summary

The main idea is: Hugo generates pages, Oink controls their appearance, and the content/ folders form the navigation tree. Writing a blog post means adding front matter and Markdown, previewing with hugo server, and pushing. Put {caption=...} on its own line, and convert Obsidian’s == and [[links]] to standard Markdown before publishing.

For a more systematic introduction, read chapters 1–3 of the Oink tutorial book. This site’s RAICOM documentation is a writing example in Chinese.

13 - Migrating and Consolidating ROS Workspaces

Practical notes on consolidating ROS robots and catkin workspaces into one clean source chain, including duplicate packages, build-time snapshots, and udev rules.

When moving a ROS robot to a new computer or disk, or sharing one codebase across several robots, the easiest trap is not copying the files: it is leaving the old workspace source chain in the shell. When several catkin workspaces overlap on the same machine, especially with identically named packages, you may not discover which copy is actually running until something fails.

These are my notes from consolidating and migrating workspaces: understand how catkin finds packages, simplify the source chain in order, and finally restore hardware bindings such as udev rules.

ROS workspace migration diagram
Consolidating several tangled source chains into one clean main workspace

Why consolidate the workspaces?

Typical situations include:

  • One robot overlays a main workspace, cartographer_ws, cv_bridge_ws, and other workspaces.
  • Different directories contain packages with the same name, such as several copies of mw_multi.
  • .bashrc, startup scripts, and even a one-off export ROS_PACKAGE_PATH=... each define their own environment.

Without a deliberate cleanup, the code may compile and the launch file may start while an old package path is still used. My goal is simple: keep one main source chain, extend it with auxiliary workspaces only when needed, and verify the effective package with one command.

How catkin searches for packages

For ROS Melodic and catkin, the overlay rule is:

A workspace sourced later has higher priority.

From lower to higher priority:

/opt/ros/melodic  →  先 source 的 ws  →  后 source 的 ws

Before migrating, you do not need to memorize every path. Answer two questions:

  1. Which packages does the current task depend on?
  2. Which workspace do those packages actually come from?

Check the copy currently in effect:

rospack find mw_multi

Replace mw_multi with the package you want to check. The output is the path ROS will currently use.

A useful habit

Run rospack find both before and after changing .bashrc or a script, and check whether the path switches to the new workspace.

Migration steps

This is the order I followed. The first few steps address explicit sourcing; step 4 checks the implicit underlay that catkin writes into its setup files at build time.

  1. Keep one main source chain and retain auxiliary workspaces separately — Put the robot code in the main workspace, such as the consolidated 1raicom_ws. If cartographer_ws or cv_bridge_ws is still needed, use it as an auxiliary workspace in the extend chain rather than repeatedly sourcing it alongside the main workspace. Create or select the main workspace and collect the required packages there. Comment out old workspace source lines in .bashrc, keeping only the new main workspace and necessary extensions. Then use rospack find to verify important package paths.
  2. Remove manual prepends to ROS_PACKAGE_PATH — Commenting out source lines is often insufficient. A shell or script may contain:
    export ROS_PACKAGE_PATH=/home/username/old_ws/src:$ROS_PACKAGE_PATH
    This puts old_ws/src first, ahead of the catkin overlay. It affects the session that executed the export and processes launched from that session. Comment out or remove these lines too. The username in the path is a placeholder; substitute your own home directory.
  3. Check sourcing in startup scripts — Editing .bashrc is not enough. Competition scripts, wrappers around launch commands, and setup_env.sh may still source the old workspace, so nodes launched through them retain the old chain. Review every entry-point script and make them consistently use the new workspace.
  4. Check whether other workspaces retain the old underlay — When only some workspaces are migrated, remember that devel/setup.sh is a build-time snapshot. catkin records the underlay present in the shell where catkin_make runs. Later, source .../devel/setup.bash --extend can bring the old chain back. Options include writing a setup_env.sh with an explicit source order, or rebuilding auxiliary workspaces such as cv_bridge_ws with the correct underlay.
  5. Migrate udev serial-port rules — Changing robots or USB ports can change device nodes for the chassis, IMU, and lidar. Copy config/udev/ to the new machine, adjust the rules to the actual ports on the new robot, and reload them.
A trap I encountered

After changing only .bashrc, rospack find returned the right path, but rosrun from an old script still reported a missing package. The script sourced the old workspace again. Check entry-point scripts and interactive shells together.

How to verify the migration

CheckHowExpected result
Package pathrospack find <包名>A path inside the new workspace
Environmentecho $ROS_PACKAGE_PATHNo manually prepended old workspace; empty or otherwise as expected
Startup entry pointsSearch .bashrc and .sh files for sourceOnly the new workspace and necessary extensions
Node startuproslaunch or preparation on the robotNo package not found errors or wrong package versions
Hardwarels -l /dev/carserial, etc.Correct udev bindings

Only after every check passes should you consider archiving or removing the old workspace directories to prevent accidentally sourcing them later.

Summary

Workspace migration is not primarily about copying files. It is about having one runtime overlay chain you can explain: a clear main workspace, auxiliary workspaces extended as needed, and no stale ROS_PACKAGE_PATH entries or old underlays in build-time snapshots. rospack find is a cheap regression check; udev is the hardware step not to forget when switching robots.

If you are consolidating ROS environments across multiple robots, work through the checklist above one item at a time.