Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,11 @@ by the code under test, so a trusted pull request must not read the volume that
Renovate writes. Cluster admission reserves main's formatter volume for main, so
an owner pull request mounts neither and runs Prettier in full. Source objects
are different: only the extension's pinned checkout image writes them, so owner
pull requests share main's source cache.
pull requests share main's source cache. Sharing the claim also shares its
quota. Every snapshot is a full object store, so a burst of owner pull requests
once filled the claim between two collections and failed main's checkouts. A
miss now publishes only below a ceiling of the claim's capacity, and a
proposal's ceiling sits below main's, so main always keeps room to publish.

[`cacheTrustDomain`](https://github.com/shepherdjerred/monorepo/blob/main/packages/woodpecker-config-extension/src/pipeline/cache-trust-domain.ts)
decides from forge identity alone. It reads the author and sender logins and
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { afterEach, expect, test } from "vitest";
import { mkdir, mkdtemp, rm, symlink, utimes } from "node:fs/promises";
import { mkdir, mkdtemp, readdir, rm, symlink, utimes } from "node:fs/promises";
import { tmpdir } from "node:os";
import nodePath from "node:path";
import { collectSourceCache } from "./source-cache-gc.ts";
Expand All @@ -20,13 +20,15 @@ async function entry(root: string, sha: string, touched: number) {
const path = join(root, "v1", "a".repeat(64), sha.repeat(40));
await mkdir(path, { recursive: true });
await Bun.write(join(path, "objects"), "1234567890");
await Bun.write(join(path, "manifest.json"), "");
await utimes(path, touched / 1000, touched / 1000);
return path;
}
test("fresh volumes need no cleanup; retention and capacity evict oldest entries", async () => {
const root = await fixture();
expect(await collectSourceCache(root)).toEqual({
removed: 0,
abandoned: 0,
retainedBytes: 0,
});
const now = Date.now();
Expand All @@ -35,6 +37,7 @@ test("fresh volumes need no cleanup; retention and capacity evict oldest entries
const newest = await entry(root, "3", now);
expect(await collectSourceCache(root, now, 10)).toEqual({
removed: 2,
abandoned: 0,
retainedBytes: 10,
});
expect(await Bun.file(join(newest, "objects")).text()).toBe("1234567890");
Expand All @@ -48,3 +51,34 @@ test("unexpected names and symlinks fail before deleting a target", async () =>
);
expect(await Bun.file(join(path, "objects")).text()).toBe("1234567890");
});

test("abandoned copies and manifest-less snapshots go whatever their age or the target", async () => {
const root = await fixture();
const now = Date.now();
const kept = await entry(root, "1", now);
// A writer killed mid-copy leaves its reservation behind, which the
// checkout's admission survey counts at the snapshot's full size.
const killed = join(
root,
"v1",
"a".repeat(64),
`${"2".repeat(40)}.tmp-${crypto.randomUUID()}`,
);
await mkdir(killed, { recursive: true });
await Bun.write(
join(killed, "reservation.json"),
JSON.stringify({ bytes: 1_247_308_780 }),
);
// A collection interrupted mid-delete can leave a snapshot without its manifest.
const interrupted = await entry(root, "3", now);
await rm(join(interrupted, "manifest.json"));
expect(await collectSourceCache(root, now, 1024 ** 3)).toEqual({
removed: 0,
abandoned: 2,
retainedBytes: 10,
});
expect(await readdir(join(root, "v1", "a".repeat(64)))).toEqual([
"1".repeat(40),
]);
expect(await Bun.file(join(kept, "objects")).text()).toBe("1234567890");
});
Original file line number Diff line number Diff line change
Expand Up @@ -31,33 +31,62 @@ async function versionExists(version: string): Promise<boolean> {
}
}

type Candidate = { path: string; touched: number; bytes: number };

/**
* List one repository's snapshots for collection, removing abandoned ones.
*
* Every checkout holds the GC lock shared for its whole run, and the caller
* holds it exclusively, so nothing is being written now. An in-progress copy
* belongs to a killed writer and a published snapshot without a manifest to an
* interrupted collection. Neither can be read, and a dead copy's reservation
* counts against the checkout's publication ceiling until removed, so both go
* whatever their age.
*/
async function scanRepository(directory: string) {
const candidates: Candidate[] = [];
let abandoned = 0;
for (const entry of await readdir(directory, { withFileTypes: true })) {
if (
!entry.isDirectory() ||
!/^[a-f\d]{40}(?:\.tmp-[a-f\d-]{36})?$/u.test(entry.name)
)
throw new Error("Unexpected source cache snapshot directory");
const path = join(directory, entry.name);
if (
entry.name.includes(".tmp-") ||
!(await Bun.file(join(path, "manifest.json")).exists())
) {
await rm(path, { recursive: true });
abandoned++;
} else {
const info = await lstat(path);
candidates.push({
path,
touched: info.mtimeMs,
bytes: await directoryBytes(path),
});
}
}
return { candidates, abandoned };
}

export async function collectSourceCache(
root: string,
now = Date.now(),
targetBytes = TARGET_BYTES,
) {
const version = join(root, "v1");
if (!(await versionExists(version))) return { removed: 0, retainedBytes: 0 };
const candidates: { path: string; touched: number; bytes: number }[] = [];
if (!(await versionExists(version)))
return { removed: 0, abandoned: 0, retainedBytes: 0 };
const candidates: Candidate[] = [];
let abandoned = 0;
for (const repo of await readdir(version, { withFileTypes: true })) {
if (!repo.isDirectory() || !/^[a-f\d]{64}$/u.test(repo.name))
throw new Error("Unexpected source cache repository directory");
for (const entry of await readdir(join(version, repo.name), {
withFileTypes: true,
})) {
if (
!entry.isDirectory() ||
!/^[a-f\d]{40}(?:\.tmp-[a-f\d-]{36})?$/u.test(entry.name)
)
throw new Error("Unexpected source cache snapshot directory");
const path = join(version, repo.name, entry.name);
const info = await lstat(path);
candidates.push({
path,
touched: info.mtimeMs,
bytes: await directoryBytes(path),
});
}
const scanned = await scanRepository(join(version, repo.name));
candidates.push(...scanned.candidates);
abandoned += scanned.abandoned;
}
let retainedBytes = candidates.reduce(
(total, entry) => total + entry.bytes,
Expand All @@ -71,7 +100,7 @@ export async function collectSourceCache(
retainedBytes -= entry.bytes;
removed++;
}
return { removed, retainedBytes };
return { removed, abandoned, retainedBytes };
}

// The Temporal activity invokes this under the same exclusive GC lock that
Expand Down
31 changes: 26 additions & 5 deletions packages/woodpecker-config-extension/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,32 @@ its original mode and symlinks. Origin and later history fetches remain usable.

Clones hold a shared GC lock and an exclusive per-commit lock. This collapses
simultaneous misses and prevents collection during reads. The existing Temporal
cache maintenance activity evicts entries unused for seven days and then the
oldest entries above 8 GiB in each 10 GiB data claim. Disabling the flag rolls
back checkout behavior without deleting claims. `CI_CHECKOUT_DIAGNOSTIC` logs
cache outcome, source SHA, object bytes downloaded, fetch/materialization time,
and total helper time; object bytes exclude network protocol overhead.
cache maintenance activity runs every five minutes, evicting entries unused for
seven days and then the oldest entries above 8 GiB in each 20 GiB data claim.
Disabling the flag rolls back checkout behavior without deleting claims.
`CI_CHECKOUT_DIAGNOSTIC` logs cache outcome, whether a miss published its
snapshot, source SHA, object bytes downloaded, fetch/materialization time, and
total helper time; object bytes exclude network protocol overhead.

Every snapshot is a complete depth-one object store (about 1.16 GiB), and ZFS
charges each block clone to the claim's quota in full, so collection alone
cannot bound a claim: a burst of distinct commits between two runs fills it,
after which even the preparation container's `chown` fails with EDQUOT. A miss
therefore reserves its snapshot's size in the claim before fetching
(`src/checkout/admission.ts`) and publishes only while every published and
in-flight snapshot stays under a ceiling of the claim's `statfs` capacity:
70% for proposals and 85% for main pushes and manual runs, so owner pull
requests sharing `woodpecker-source-main` cannot take main's last headroom. A
refused miss still checks out from its own fetch and unlocks the per-commit
lock descriptor that `checkout.sh` hands it, so the commit's other workflows
fetch alongside it instead of queueing. `statfs` reports the claim's ZFS
`quota` (the OpenEBS volume's `quotaType`), 20 GiB for both source claims. A
writer killed mid-copy leaves its reservation behind, still counted; the
collector, which holds the GC lock exclusively and so never meets a live
writer, removes every in-progress copy and any snapshot missing its manifest
on each run. A pipeline emitted before the tier existed carries no
`CI_SOURCE_CACHE_TIER`; for rollout compatibility its misses publish under the
proposal ceiling.

Registry access uses explicit per-lane grants. Image and toolchain publishers
and Scout tag publication receive the scoped Docker Hub publisher identity.
Expand Down
1 change: 1 addition & 0 deletions packages/woodpecker-config-extension/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ async function pipelineEmitter(
enabled,
credentialless,
trustDomain,
main,
image: options.trustedGateImage,
}),
performance,
Expand Down
145 changes: 145 additions & 0 deletions packages/woodpecker-config-extension/src/checkout/admission.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { mkdir, readdir, rename, rm, statfs } from "node:fs/promises";
import nodePath from "node:path";
import { z } from "zod";
import { SnapshotSchema } from "./git.ts";
const { join } = nodePath;

/**
* Whose checkout publishes a snapshot. Default-branch work may fill more of a
* claim than a proposal, so a burst of pull requests never takes the headroom
* main's own checkouts publish into.
*/
export const SourceCacheTierSchema = z.enum(["main", "proposal"]);
export type SourceCacheTier = z.infer<typeof SourceCacheTierSchema>;

/**
* Share of a claim's capacity that declared snapshot bytes may reach.
*
* Every snapshot is a complete object store, about 1.16 GiB for the monorepo,
* and ZFS charges each block clone to the claim's quota in full. Collection
* runs every five minutes and keeps 8 GiB, so without a ceiling a burst of
* distinct commits between two runs fills the claim, and from then on every
* checkout on it fails with EDQUOT, hits included. The quota above the main
* ceiling stays free for metadata, ownership setup and snapshot times.
*/
export const SOURCE_CACHE_CEILING: Readonly<Record<SourceCacheTier, number>> = {
main: 0.85,
proposal: 0.7,
};

const RESERVATION = "reservation.json";
const ReservationSchema = z.object({
bytes: z.number().int().nonnegative(),
});
const ENTRY = /^[a-f\d]{40}(?:\.tmp-[a-f\d-]{36})?$/u;

/** The bytes the cache root's claim can hold. */
export async function claimCapacity(root: string): Promise<number> {
const space = await statfs(root);
return space.blocks * space.bsize;
}

export function ceilingBytes(tier: SourceCacheTier, capacity: number): number {
return Math.floor(SOURCE_CACHE_CEILING[tier] * capacity);
}

/** Published by rename, so a concurrent survey never reads a partial file. */
async function writeReservation(temporary: string, bytes: number) {
const partial = join(temporary, `${RESERVATION}.${crypto.randomUUID()}`);
await Bun.write(partial, JSON.stringify({ bytes }));
await rename(partial, join(temporary, RESERVATION));
}

async function declared(path: string, temporary: boolean) {
try {
const json: unknown = await Bun.file(
join(path, temporary ? RESERVATION : "manifest.json"),
).json();
return temporary
? ReservationSchema.parse(json).bytes
: SnapshotSchema.parse(json).objectBytes;
} catch (error) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT"))
throw error;
// A copy that has not declared yet or was withdrawn since the listing.
// Published snapshots gain their manifest before the rename, so one
// without it was cut short by an interrupted collection; the next
// collection removes it, and a hit on it still fails its manifest read.
if (!temporary)
console.warn(`Source cache snapshot without a manifest: ${path}`);
// Either way the caller counts it at full size, which can only refuse more.
return;
}
}

/**
* Sum every snapshot's declared object bytes: published manifests and the
* reservations of copies in flight. A copy that has not declared yet (a
* writer between `mkdir` and its reservation) or a snapshot that lost its
* manifest counts as `undeclared`. A killed writer's reservation stays
* counted until the next collection removes its directory.
*/
export async function surveySnapshots(parent: string, undeclared: number) {
let total = 0;
let largest = 0;
for (const entry of await readdir(parent, { withFileTypes: true })) {
if (!entry.isDirectory() || !ENTRY.test(entry.name))
throw new Error("Unexpected source cache snapshot entry");
const bytes =
(await declared(
join(parent, entry.name),
entry.name.includes(".tmp-"),
)) ?? undeclared;
total += bytes;
largest = Math.max(largest, bytes);
}
return { total, largest };
}

/**
* Reserve room for a snapshot before writing it. The reservation is visible
* to every other writer before this one counts, so of two concurrent writers
* at least one sees the other: both may be refused, never both admitted past
* the ceiling. Returns the temporary directory to publish from, or undefined
* when the snapshot would cross the ceiling.
*/
export async function reserveSnapshot(input: {
readonly parent: string;
readonly commit: string;
readonly bytes: number;
readonly ceiling: number;
}): Promise<string | undefined> {
await mkdir(input.parent, { recursive: true });
const temporary = join(
input.parent,
`${input.commit}.tmp-${crypto.randomUUID()}`,
);
await mkdir(temporary);
return (await resizeReservation({ ...input, temporary }))
? temporary
: undefined;
Comment thread
shepherdjerred marked this conversation as resolved.
Resolved
}

/** Restate a reservation's size; on refusal its directory is removed. */
export async function resizeReservation(input: {
readonly parent: string;
readonly temporary: string;
readonly bytes: number;
readonly ceiling: number;
}): Promise<boolean> {
try {
await writeReservation(input.temporary, input.bytes);
const { total } = await surveySnapshots(input.parent, input.bytes);
if (total <= input.ceiling) return true;
} catch (error) {
await rm(input.temporary, { recursive: true, force: true });
throw error;
}
await rm(input.temporary, { recursive: true, force: true });
return false;
}

/** A published snapshot carries its manifest, not its reservation. */
export async function releaseReservation(temporary: string) {
await rm(join(temporary, RESERVATION));
}
4 changes: 4 additions & 0 deletions packages/woodpecker-config-extension/src/checkout/checkout.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,9 @@ flock --exclusive 9
# before reading it; retain the shared GC lock inherited from our parent.
if [[ -d "$snapshot" ]]; then
flock --unlock 9
exec bun "$helper" "$cache" "$commit"
fi
# The claim's ceiling may refuse this miss's snapshot. The helper then unlocks
# descriptor 9, so the commit's other workflows fetch instead of queueing.
export CI_SOURCE_COMMIT_LOCK_FD=9
exec bun "$helper" "$cache" "$commit"
Loading