commit edff34a513de01eda113390970028d806d2730e0
parent e9be2c3464b4a964aa2b9f586bc4585b90980e29
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 20:47:06 -0500
channels: the priority writer reads and writes under a settings lock; channel-rank places next to a tied anchor
Review of lane/editor-gaps. saveChannelPriorityAction read settings, awaited
the channel list, then wrote the whole channelPriority: a deck save or a
parallel channel-rank in the gap was lost. saveSettings now runs inside
withSettingsLock (withJsonFileLock on settings.json); the priority writer
lists channels first, then reads, compiles and writes inside the lock with
saveSettingsHeld. placeChannelRank inserts into the ranked order and moves the
channels after it only as far as they must, so "after X" lands immediately
after X on a tie and ties below stay tied.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
9 files changed, 223 insertions(+), 128 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -123,7 +123,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| action | what it does | example |
|---|---|---|
| `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` |
-| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (a rank already held, and every rank below it, shift down one) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel). Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
+| `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": <n> (before any channel holding it) or null (unranked), "top": true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked channel; immediately next to it, a tie on its rank included). The channels after it move down only as far as they must. Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` |
| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "<regex with named groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` |
| `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept. An unknown channel is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` |
| `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` |
diff --git a/common/lib/channelPriority.ts b/common/lib/channelPriority.ts
@@ -642,11 +642,11 @@ export function renameChannelInPriority(
// slug) — the same order inside every tier group (`orderWithin`). A placement
// moves one channel and leaves the order of every other exactly as it was:
//
-// rank n the channel takes rank n; when another channel holds n,
-// it and every channel ranked below it shift down one;
+// rank n the channel takes rank n, before any channel holding it;
// top / bottom before every ranked channel / after every ranked channel;
-// before / after immediately before / after another RANKED channel (an
-// unranked one has no place to be next to — refused);
+// before / after immediately before / after another RANKED channel, a tie
+// on its rank included (an unranked one has no place to be
+// next to — refused);
// unrank the rank removed: last in its tier, by slug.
//
// Only the rank moves. Unlike "Add to top" (the deck's promote, which also
@@ -676,40 +676,59 @@ export function placeChannelRank(
const { rank: _dropped, ...rest } = current;
return { ...model, channels: { ...model.channels, [slug]: rest } };
}
- const others = Object.entries(model.channels).filter(
- ([s, e]) => s !== slug && e.rank !== undefined,
- ) as [string, ChannelPriorityEntry & { rank: number }][];
+ // The other ranked channels in the order the lanes take them (rank, then
+ // slug — orderWithin's rule), and where in that list this one goes.
+ const others = rankedOrder(model).filter((r) => r.slug !== slug);
+ let at: number;
let rank: number;
if (place.kind === "rank") {
if (!Number.isInteger(place.rank) || place.rank < 0) {
throw new RankPlacementError(`A rank is a whole number, 0 or more (0 = first); got ${place.rank}.`);
}
+ // Before every channel already holding that rank or a later one.
+ at = others.findIndex((r) => r.rank >= place.rank);
+ if (at < 0) at = others.length;
rank = place.rank;
} else if (place.kind === "top") {
- rank = others.length ? Math.min(...others.map(([, e]) => e.rank)) : 0;
+ at = 0;
+ rank = others[0]?.rank ?? 0;
} else if (place.kind === "bottom") {
- rank = others.length ? Math.max(...others.map(([, e]) => e.rank)) + 1 : 0;
+ at = others.length;
+ rank = others.length ? others[others.length - 1].rank + 1 : 0;
} else {
const anchor = place.slug.trim();
if (anchor === slug) {
throw new RankPlacementError(`"${slug}" cannot be placed ${place.kind} itself.`);
}
- const anchorRank = model.channels[anchor]?.rank;
- if (anchorRank === undefined) {
+ const i = others.findIndex((r) => r.slug === anchor);
+ if (i < 0) {
throw new RankPlacementError(
`"${anchor}" has no rank, so there is no place ${place.kind} it — rank it first ` +
`(top, bottom or a rank), or place "${slug}" by rank.`,
);
}
- rank = place.kind === "before" ? anchorRank : anchorRank + 1;
+ if (place.kind === "before") {
+ at = i;
+ rank = i > 0 ? others[i - 1].rank + 1 : others[i].rank;
+ } else {
+ at = i + 1;
+ rank = others[i].rank + 1;
+ }
}
- const taken = others.some(([, e]) => e.rank === rank);
- const channels: Record<string, ChannelPriorityEntry> = {};
- for (const [s, entry] of Object.entries(model.channels)) {
- channels[s] =
- taken && s !== slug && entry.rank !== undefined && entry.rank >= rank
- ? { ...entry, rank: entry.rank + 1 }
- : entry;
+ // Strictly after the channel before it, so a tie never reorders it by slug.
+ if (at > 0) rank = Math.max(rank, others[at - 1].rank + 1);
+ // Every channel after it moves down only as far as it must to stay after
+ // it and after the one before it, and two that were tied stay tied — so the
+ // order of the rest is kept exactly.
+ const channels: Record<string, ChannelPriorityEntry> = { ...model.channels };
+ let floor = rank;
+ let prevOld: number | null = null;
+ for (const r of others.slice(at)) {
+ // Tied with the one before it (and so after it by slug): tied still.
+ const next: number = prevOld !== null && r.rank === prevOld ? floor : r.rank > floor ? r.rank : floor + 1;
+ if (next !== r.rank) channels[r.slug] = { ...model.channels[r.slug], rank: next };
+ prevOld = r.rank;
+ floor = next;
}
channels[slug] = { ...(current ?? { tier: DEFAULT_CHANNEL_TIER }), rank };
return { ...model, channels };
diff --git a/common/lib/channelRank.test.ts b/common/lib/channelRank.test.ts
@@ -76,3 +76,24 @@ test("rank n: taken pushes it and everything below down one; free takes the gap;
assert.equal(sanitizeChannelPriority(placeChannelRank(ABC, "a", { kind: "unrank" })).channels.a, undefined);
assert.equal(placeChannelRank(ABC, "u", { kind: "unrank" }), ABC, "nothing to remove: the input");
});
+
+test("ties: after X lands immediately after X, before its tie partners, and ties below stay tied", () => {
+ const tied = doc({
+ a: { tier: "normal", rank: 0 },
+ x: { tier: "normal", rank: 0 },
+ y: { tier: "normal", rank: 0 },
+ p: { tier: "normal", rank: 3 },
+ q: { tier: "normal", rank: 3 },
+ });
+ assert.deepEqual(order(tied), ["a", "x", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "a" })), ["a", "z", "x", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "after", slug: "x" })), ["a", "x", "z", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "y" })), ["a", "x", "z", "y", "p", "q"]);
+ assert.deepEqual(order(placeChannelRank(tied, "z", { kind: "before", slug: "a" })), ["z", "a", "x", "y", "p", "q"]);
+ const moved = placeChannelRank(tied, "z", { kind: "after", slug: "a" });
+ assert.equal(moved.channels.x.rank, moved.channels.y.rank, "x and y were tied and stay tied");
+ assert.equal(moved.channels.p.rank, 3, "a channel already far enough down does not move");
+ assert.equal(moved.channels.p.rank, moved.channels.q.rank);
+ // Moving a channel out of a tie.
+ assert.deepEqual(order(placeChannelRank(tied, "a", { kind: "after", slug: "y" })), ["x", "y", "a", "p", "q"]);
+});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,7 +3,7 @@
## [Unreleased]
- **Deleting a channel takes it off every site.** On 9 Nov, deleting `mooler` left it in efapalyzer's `site.json`, and the site had to be fixed by hand. Danger → Delete and `pnpm ops delete-channel` now rewrite every site whose pool (`channels`) or cited scope (`citedChannels`) names the deleted channel, through the one site writer (`writeSite`), as a rename already re-points them. The ops answer names those sites in `sitesUpdated`. A site whose write is refused shows up as a `warnings` line, and the delete still stands. Sites that never named the channel are not written (`common/controller/siteMemberships.ts`).
- **`pnpm ops create-site` is the New site form, without a browser.** On 9 Nov an agent had to call `writeSite` from a tsx script to make `efapalyzer`. `create-site` takes `{"siteId", "siteTitle"}` and any of the form's fields: header title (default the title), description, tagline, wordmark lead, accent, public URL, Pages project, hub URL, audience, listed, publish policy, search, archives, duplicates, transcript downloads, PWA, archive cap, groups, default group, channels, cited channels, social links and related sites. It builds the FormData the form posts and saves it through the form's own action (`saveSiteAction` → `writeSite`), so you get the same validation and the same sentences. A new site is **private and unlisted** unless the body says `"audience": "public"` / `"listed": true`. An existing id is refused (409) unless `"update": true`, which is the site page's Save with only the given keys changed; every other key, and the published page list, is kept. Unknown channels, unknown keys and keys of the wrong type are refused before anything is written. It answers the saved site.
-- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: if the rank is already taken, that channel and every one below it shift down one. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
+- **`pnpm ops channel-rank` places one channel in the order the lanes follow.** Before this, only /channels' "Add to top" moved a channel, and it also sets the tier to normal and turns the download lane on. `channel-rank` moves the rank alone: `{"slug"}` plus exactly one of `"rank": <n>` (or `null` to unrank), `"top": true`, `"bottom": true`, `"before": "<slug>"` or `"after": "<slug>"`. Every other channel keeps its order: channels after it move down only as far as they must, ties stay tied, and `after` lands immediately after its anchor even when the anchor's rank is tied. It goes through the deck's one writer, so the four lane roots are recompiled in the same write. That writer now does its read-modify-write inside a settings lock, which every `saveSettings` takes too, so a concurrent deck save or a parallel `channel-rank` is never written over. Refused before any write: an unknown channel or anchor, an anchor with no rank, a rank that is not a whole number ≥ 0, and a channel paused for every operation (its rank would not be kept). It answers the saved rank and the whole ranked order (`common/lib/channelPriority.ts` `placeChannelRank`).
- **Configure's Caption languages field (`subLangs`) is checked when you save.** Before, any text was saved, and a value yt-dlp's `--sub-langs` cannot use failed every caption download on the channel at the moment it ran. Configure and `pnpm ops channel-config` (`patch.subLangs`) now refuse it, in the field's words, with what you typed kept. Refused: an empty entry (two commas, or one at an end), a space inside an entry, a bare `-`, an entry that is not a regular expression, or a value over 200 characters. Spaces around an entry are dropped (`en.* , es` saves as `en.*,es`). A value saved before this check and submitted unchanged is kept, with a warning in the server log, so Configure is never locked on it. `all` and `-<lang>` exclusions are accepted as before (`common/lib/channelConfig.ts` `subLangsProblem`).
- **Transcribe refuses a video that is live.** On 4 Nov a transcribe-one on a live YouTube video downloaded the stream at 1x and held `platform:youtube` for the stream's whole length. Now the video page's Transcribe and `pnpm ops transcribe-one` refuse a video whose `metadata.info.json` says it is live (`is_live`), scheduled (`is_upcoming`) or still processing its VOD (`post_live`), before anything is queued. The refusal names `pnpm ops record-live` for the stream (not for `post_live`), says to wait for the VOD otherwise, and names `refresh-metadata` to re-read the record once the stream has ended. The job checks again just before its download, in case the record was re-read while it waited. Only the audio download is refused: a video whose audio or container is already on disk still transcribes, and a youtube-handling video with English captions listed still has its captions fetched instead. A finished stream (`was_live`) downloads as before (`common/lib/liveNow.ts`).
- **The X run console: several X channels' posts fetched as one job that stops when the cookies go stale.** On 8 and 9 Nov an agent ran X fetch-posts by hand, one channel after another, watching the cookie jar age and putting off the rest once it went stale. `/review`'s new **X run** section lists the X posts channels in priority order (focus, tier, rank; paused ones unticked), with a tick and up/down buttons for each, and **Start X run** queues ONE `x-run` job on X's queue. The job fetches each channel in turn (new posts only, at most 200 each), waits X's queue gap (`pacing.jobGapSeconds.twitter`) between two channels, and checks the cookie jar again before EACH one. Once the jar is past `social.x.maxCookieAgeMinutes`, or the X alert is up, the run stops and the rest are **deferred until the next refresh**. It never refreshes cookies itself. The console shows each channel's state (queued, running, done with its new posts, deferred, failed), "N done, M deferred until the next refresh", the jar's age counted down to the limit, and the wait before the next channel. **Resume** runs the deferred channels after the operator presses Refresh cookies on /settings. A Retry of the job, and "Re-run stopped jobs", do the same. A restart does not resume a run: an interrupted run ends deferred. `pnpm ops x-run {"channels": [...]}` / `{"resume": "<run id>"}` and `pnpm ops get x-run` do the same from a terminal.
diff --git a/editor/app/api/ops/channel-rank/route.ts b/editor/app/api/ops/channel-rank/route.ts
@@ -22,8 +22,8 @@ export const dynamic = "force-dynamic";
// moved a channel, and it also sets the tier to normal and turns the download
// lane on. This moves the rank alone, through the deck's one writer
// (saveChannelPriorityAction), which recompiles the four lane roots in the
-// same write. Every other channel keeps its order: a rank already held is
-// made room for by shifting it and everything below it down one.
+// same write, under the settings lock. Every other channel keeps its order:
+// the ones after it move down only as far as they must, ties stay tied.
//
// Exactly one placement. `rank: null` removes the rank. Refused before any
// write: an unknown channel or anchor, an anchor with no rank (nothing to be
diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts
@@ -40,7 +40,7 @@ import {
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { X_SEARCH_NOT_ON_A_SITE } from "yt-dlp-transcript-common/lib/site";
import { xSearchFromUrl, xSearchQueryOfUrl } from "yt-dlp-transcript-common/lib/xSearch/config";
-import { saveSettings } from "../settings/saveSettings";
+import { saveSettings, saveSettingsHeld, withSettingsLock } from "../settings/saveSettings";
import {
LANES,
type AutoQueueKind,
@@ -979,108 +979,119 @@ export async function saveChannelPriorityAction(
opts?: { enableLanes?: readonly AutoQueueKind[] },
): Promise<ActionResult> {
const paths = getPaths();
- const settings = getSettings();
- const stored = settings.channelPriority;
+ // The channel population first, OUTSIDE the lock: it is a directory read,
+ // and nothing below writes it.
const configs = await listChannelConfigs(paths);
const slugs = configs.map((c) => c.slug);
- // THE LEGACY SEED, and it is the difference between this feature shipping
- // and this feature destroying the two hand-made 9+9 lane orders on its first
- // click (the S2/S3 review, finding 3, restated with its mechanism in 8).
- //
- // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the
- // moment a document says ANYTHING, the stored trees stop being dispatched
- // from and the compiled ones take over. A first click that set one tier and
- // nothing else would therefore compile a tree in which no channel has a rank
- // — every one of them alphabetical inside `prio-normal` — and the operator's
- // order would be gone with no way back, because the trees it was written in
- // have just been overwritten.
- //
- // So: when the stored document says nothing AND the stored trees are not
- // already compiled, derive the document the migration would have produced
- // and apply the edit on top of THAT. The corpus's existing order survives a
- // first click by an operator who never ran the migration.
- //
- // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not
- // an operator's statement about priority, and neither must silently switch a
- // corpus from its stored trees to compiled ones.
- const base =
- edit.kind !== "recompile" &&
- edit.kind !== "rename" &&
- isDefaultChannelPriority(stored) &&
- !hasCompiledLaneRoots(settings.autoQueue)
- ? channelPriorityFromLegacy(
- // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is
- // deleted and `parseChannelConfig` drops the key, so nothing the
- // editor can read still carries it — turning those 15 channels into
- // `overrides: {sync:"paused"}` is the migration script's half, off
- // the raw config.json. What this seed is for is the ORDER, and the
- // order lives in the stored trees.
- configs.map((c) => ({ slug: c.slug, config: {} })),
- settings.autoQueue,
- )
- : stored;
- let next: ChannelPriority;
- try {
- next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
- } catch (e) {
- // A placement the document cannot carry out (next to an unranked channel,
- // a rank that is not one) is the caller's to fix, said before any write.
- if (e instanceof RankPlacementError) return { error: e.message };
- throw e;
- }
- // A rank the sanitizer drops: a channel paused for every operation is in no
- // group anywhere, so it orders nothing and its rank is not kept. Said, not
- // saved as a silent no-op.
- if (
- edit.kind === "rank" &&
- edit.place.kind !== "unrank" &&
- next.channels[edit.slug.trim()]?.rank === undefined
- ) {
- return {
- error:
- `"${edit.slug.trim()}" is paused for every operation, so it is in no order a rank could place it in — ` +
- `give it a tier first (pnpm ops channel-priority), then rank it.`,
- };
- }
- // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the
- // question are different corpora.
- //
- // The runner's bypass means a default document dispatches from the STORED
- // tree, so what matters here is what that stored tree is:
- //
- // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is
- // the same rule `laneDispatchRoot` applies, and compiling over it would
- // replace an operator's tree with an all-normal one at the moment the last
- // priority was cleared.
- //
- // already compiled -> RECOMPILE, even for a default document. Ending a
- // focus leaves the document saying nothing while every stored root still
- // opens with `prio-focus` — and the runner, back on its bypass, would
- // dispatch from exactly that tree and go on holding the channels the focus
- // was just ended for. There is no hand-made tree left to protect on a
- // corpus whose roots the compiler already wrote.
- const autoQueue = { ...settings.autoQueue };
- if (
- !isDefaultChannelPriority(next) ||
- hasCompiledLaneRoots(settings.autoQueue)
- ) {
- const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs);
- const roots = compileLanes(next, slugs, focusSlugs);
- for (const lane of LANES) {
- autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] };
+ // THE READ-MODIFY-WRITE IS SERIALIZED (review of lane editor-gaps): the
+ // document is read INSIDE the settings lock and written before it is let go,
+ // so a concurrent deck save or a parallel `channel-rank` is never written
+ // over with a copy read before it landed. Every saveSettings takes the same
+ // lock (settings/saveSettings.ts).
+ const saved = await withSettingsLock(async (): Promise<ActionResult | "saved"> => {
+ const settings = getSettings();
+ const stored = settings.channelPriority;
+ // THE LEGACY SEED, and it is the difference between this feature shipping
+ // and this feature destroying the two hand-made 9+9 lane orders on its first
+ // click (the S2/S3 review, finding 3, restated with its mechanism in 8).
+ //
+ // `laneDispatchRoot` is all-or-nothing on `isDefaultChannelPriority`: the
+ // moment a document says ANYTHING, the stored trees stop being dispatched
+ // from and the compiled ones take over. A first click that set one tier and
+ // nothing else would therefore compile a tree in which no channel has a rank
+ // — every one of them alphabetical inside `prio-normal` — and the operator's
+ // order would be gone with no way back, because the trees it was written in
+ // have just been overwritten.
+ //
+ // So: when the stored document says nothing AND the stored trees are not
+ // already compiled, derive the document the migration would have produced
+ // and apply the edit on top of THAT. The corpus's existing order survives a
+ // first click by an operator who never ran the migration.
+ //
+ // NOT ON A `recompile` OR A `rename`: creating or renaming a channel is not
+ // an operator's statement about priority, and neither must silently switch a
+ // corpus from its stored trees to compiled ones.
+ const base =
+ edit.kind !== "recompile" &&
+ edit.kind !== "rename" &&
+ isDefaultChannelPriority(stored) &&
+ !hasCompiledLaneRoots(settings.autoQueue)
+ ? channelPriorityFromLegacy(
+ // THE SEED READS THE LANE ORDERS, NOT THE FLAG. `excludeFromSync` is
+ // deleted and `parseChannelConfig` drops the key, so nothing the
+ // editor can read still carries it — turning those 15 channels into
+ // `overrides: {sync:"paused"}` is the migration script's half, off
+ // the raw config.json. What this seed is for is the ORDER, and the
+ // order lives in the stored trees.
+ configs.map((c) => ({ slug: c.slug, config: {} })),
+ settings.autoQueue,
+ )
+ : stored;
+ let next: ChannelPriority;
+ try {
+ next = sanitizeChannelPriority(applyPriorityEdit(base, edit));
+ } catch (e) {
+ // A placement the document cannot carry out (next to an unranked channel,
+ // a rank that is not one) is the caller's to fix, said before any write.
+ if (e instanceof RankPlacementError) return { error: e.message };
+ throw e;
}
- }
- for (const lane of opts?.enableLanes ?? []) {
- autoQueue[lane] = { ...autoQueue[lane], enabled: true };
- }
- try {
- // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings
- // patch rather than one block. `channelPriority` is a full document (its
- // `channels` map replaces), and `autoQueue` carries all four lanes.
- await saveSettings({ channelPriority: next, autoQueue });
- } catch (e) {
- return { error: (e as Error).message };
- }
+ // A rank the sanitizer drops: a channel paused for every operation is in no
+ // group anywhere, so it orders nothing and its rank is not kept. Said, not
+ // saved as a silent no-op.
+ if (
+ edit.kind === "rank" &&
+ edit.place.kind !== "unrank" &&
+ next.channels[edit.slug.trim()]?.rank === undefined
+ ) {
+ return {
+ error:
+ `"${edit.slug.trim()}" is paused for every operation, so it is in no order a rank could place it in — ` +
+ `give it a tier first (pnpm ops channel-priority), then rank it.`,
+ };
+ }
+ // WHEN A DEFAULT DOCUMENT STILL HAS TO COMPILE, and the two halves of the
+ // question are different corpora.
+ //
+ // The runner's bypass means a default document dispatches from the STORED
+ // tree, so what matters here is what that stored tree is:
+ //
+ // never compiled (hand-made, or the shipped default) -> LEAVE IT. This is
+ // the same rule `laneDispatchRoot` applies, and compiling over it would
+ // replace an operator's tree with an all-normal one at the moment the last
+ // priority was cleared.
+ //
+ // already compiled -> RECOMPILE, even for a default document. Ending a
+ // focus leaves the document saying nothing while every stored root still
+ // opens with `prio-focus` — and the runner, back on its bypass, would
+ // dispatch from exactly that tree and go on holding the channels the focus
+ // was just ended for. There is no hand-made tree left to protect on a
+ // corpus whose roots the compiler already wrote.
+ const autoQueue = { ...settings.autoQueue };
+ if (
+ !isDefaultChannelPriority(next) ||
+ hasCompiledLaneRoots(settings.autoQueue)
+ ) {
+ const focusSlugs = resolveFocusSlugs(next, siteChannelIndex(paths), slugs);
+ const roots = compileLanes(next, slugs, focusSlugs);
+ for (const lane of LANES) {
+ autoQueue[lane] = { ...settings.autoQueue[lane], root: roots[lane] };
+ }
+ }
+ for (const lane of opts?.enableLanes ?? []) {
+ autoQueue[lane] = { ...autoQueue[lane], enabled: true };
+ }
+ try {
+ // BOTH BLOCKS IN ONE WRITE — the reason saveSettings takes a whole-settings
+ // patch rather than one block. `channelPriority` is a full document (its
+ // `channels` map replaces), and `autoQueue` carries all four lanes.
+ await saveSettingsHeld({ channelPriority: next, autoQueue });
+ } catch (e) {
+ return { error: (e as Error).message };
+ }
+ return "saved";
+ });
+ if (saved !== "saved") return saved;
revalidatePath("/channels");
revalidatePath("/operations");
revalidatePath("/operations/[id]", "page");
diff --git a/editor/app/settings/saveSettings.test.ts b/editor/app/settings/saveSettings.test.ts
@@ -18,7 +18,7 @@ const ROOT = mkdtempSync(path.join(os.tmpdir(), "save-settings-"));
process.env.TRANSCRIPTS_DIR = ROOT;
process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
-const { mergeSettingsPatch, saveSettings } = await import("./saveSettings");
+const { mergeSettingsPatch, saveSettings, saveSettingsHeld, withSettingsLock } = await import("./saveSettings");
const { defaultSiteSettings, getSettings } = await import(
"yt-dlp-transcript-common/lib/settings"
);
@@ -134,3 +134,26 @@ test("an icon stored by an older build survives unrelated saves; editing it is c
{ ...stored, svg: `<svg aria-hidden="true" fill="currentColor" viewBox="0 0 8 8"><path d="M0 0"/></svg>` },
]);
});
+
+// THE LOCK (review of lane editor-gaps): a long read-modify-write held under
+// withSettingsLock is not written over by a save that starts while it runs —
+// the save waits, reads what the held writer wrote, and keeps both changes.
+test("a save waits for a held read-modify-write and keeps its change", async () => {
+ writeFileSync(process.env.SETTINGS_FILE!, JSON.stringify(defaultSiteSettings()));
+ let release!: () => void;
+ const gate = new Promise<void>((r) => (release = r));
+ const held = withSettingsLock(async () => {
+ const read = getSettings();
+ await gate; // an await between the read and the write, as the priority writer has
+ // The whole document as read, as a writer of a full block does: a save
+ // that slipped in between would be written over.
+ await saveSettingsHeld({ ...read, syncScheduler: { ...read.syncScheduler, maxConcurrentSyncs: 5 } });
+ });
+ const other = saveSettings({ minFreeDiskGB: 42 });
+ await new Promise((r) => setTimeout(r, 20));
+ release();
+ await Promise.all([held, other]);
+ const after = getSettings();
+ assert.equal(after.syncScheduler.maxConcurrentSyncs, 5);
+ assert.equal(after.minFreeDiskGB, 42, "the later save read the held writer's result");
+});
diff --git a/editor/app/settings/saveSettings.ts b/editor/app/settings/saveSettings.ts
@@ -3,6 +3,8 @@ import {
writeSettings,
type SiteSettings,
} from "yt-dlp-transcript-common/lib/settings";
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { withJsonFileLock } from "yt-dlp-transcript-common/lib/jsonFile-server";
// THE EDITOR'S ONE SETTINGS WRITER (one-core phase 3 slice 4a).
//
@@ -53,6 +55,24 @@ export function mergeSettingsPatch(
return merged as SiteSettings;
}
-export async function saveSettings(patch: Patch): Promise<void> {
+// THE SETTINGS LOCK (review of lane editor-gaps). A save reads the file,
+// merges and writes; two saves that interleave — one reading before the other
+// has written — lose the first one's change. Every save runs inside the lock
+// on settings.json, so the read and the write of one save never straddle
+// another's. A writer whose read-modify-write is longer than one patch (the
+// channel-priority writer reads the document, compiles the lane roots and
+// writes both) takes the lock itself and saves with `saveSettingsHeld`.
+// Per process (withJsonFileLock); NOT re-entrant: never call saveSettings
+// from inside withSettingsLock.
+export function withSettingsLock<T>(fn: () => Promise<T>): Promise<T> {
+ return withJsonFileLock(getPaths().settingsFile, fn);
+}
+
+// A save for a caller already holding the lock.
+export async function saveSettingsHeld(patch: Patch): Promise<void> {
await writeSettings(mergeSettingsPatch(getSettings(), patch));
}
+
+export async function saveSettings(patch: Patch): Promise<void> {
+ await withSettingsLock(() => saveSettingsHeld(patch));
+}
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -1330,9 +1330,10 @@ export function usage() {
'channel-rank places one channel in the order every lane and the sync',
' scheduler follow inside a tier (one rank per channel, 0 first; unranked',
' channels come after every ranked one, by slug): {"slug"} and exactly one',
- ' of "rank": <n> (a rank already held, and every rank below it, shift down',
- ' one) or null (unranked), "top": true, "bottom": true, "before": "<slug>",',
- ' "after": "<slug>" (a ranked channel). Only the rank moves — no tier,',
+ ' of "rank": <n> (before any channel holding it) or null (unranked), "top":',
+ ' true, "bottom": true, "before": "<slug>", "after": "<slug>" (a ranked',
+ ' channel; immediately next to it, a tie on its rank included). The channels',
+ ' after it move down only as far as they must. Only the rank moves — no tier,',
' override or lane changes, unlike /channels\' "Add to top". Refused: an',
' unknown channel, an unranked anchor, a channel paused for every',
' operation. Answers {slug, rank, order: [{slug, rank}, …]}.',