Artifactspublic-v0

ply

main
ply4 git calls232 ms46 KiB2 cachedprotocol v2
279 lines23 KiBRaw
1// The pipeline's pure decisions, exercised without a server. Oracles: node zlib / git for codecs, the invariants
2// themselves for the decisions (every branch of decideHead, every rejection of lookupEntry, buildCommitObjects ≡ git).
3import { test } from 'vitest';
4import assert from 'node:assert/strict';
5import zlib from 'node:zlib';
6import { execFileSync } from 'node:child_process';
7import { mkdtempSync, rmSync } from 'node:fs';
8import { tmpdir } from 'node:os';
9import { join } from 'node:path';
10import { Rng } from './fuzz/prng.js';
11import { validateSpec, decideHead, lookupEntry, buildCommitObjects, memFromScan, memAttrs, scanInit, scanStep, MATCH_OFFSETS_KEPT } from '../src/edit.js';
12import { zlibDeflate, spliceDelta } from '../src/pack.js';
13import { inflate } from '../src/inflate.js';
14import { encodeTree, hashObject, parseCommit, TYPE } from '../src/objects.js';
15import { DEFAULT_LIMITS, withLimits } from '../src/limits.js';
16import { plyError as fail, scrubError } from '../src/errors.js';
17import { Tracer, arrayExporter, flattenLine } from '../src/otel.js';
18import { unwrap } from './unwrap.js';
20const A = 'a'.repeat(40), B = 'b'.repeat(40);
22test('decideHead: every branch', () => {
23 assert.deepEqual(decideHead({ hint: null, resolved: A }), { oldCommit: A, hint: null });
24 assert.deepEqual(decideHead({ hint: A, resolved: A }), { oldCommit: A, hint: 'used' });
25 assert.deepEqual(decideHead({ hint: A, resolved: B }), { oldCommit: B, hint: 'stale' }, 'ls-refs wins over the hint');
26});
28test('validateSpec: rejects before any I/O, freezes the plan', () => {
29 const ok = unwrap(validateSpec({ path: 'a/b.txt', find: 'x', replace: 'y', author: { name: 'n', email: 'e@x' }, message: 'm', time: 1 }, DEFAULT_LIMITS, A));
30 assert.ok(Object.isFrozen(ok)); assert.deepEqual(ok.comps, ['a', 'b.txt']); assert.equal(ok.head, A);
31 const base = { path: 'a', find: 'x', replace: 'y', author: { name: 'n', email: 'e@x' }, message: 'm' };
32 for (const [bad, code] of [[{ ...base, find: '' }, 'bad_request'], [{ ...base, time: -1 }, 'bad_request'], [{ ...base, time: 1.5 }, 'bad_request'], [{ ...base, find: 42 }, 'bad_request'], [{ ...base, path: '.git/config' }, 'bad_request'], [{ ...base, ref: 'refs/heads/a..b' }, 'bad_request'], [{ ...base, author: { name: 'n<', email: 'e' } }, 'bad_request']]) {
33 assert.throws(() => unwrap(validateSpec(bad, DEFAULT_LIMITS)), e => e.code === code || e.code === 'bad_request', JSON.stringify(bad));
34 }
35 assert.throws(() => unwrap(validateSpec(base, DEFAULT_LIMITS, 'short')), e => e.code === 'bad_request');
36});
38test('lookupEntry: found/dir/file/mode rules and the entries limit, with attrs on every outcome', () => {
39 const tree = unwrap(encodeTree([{ mode: '40000', name: 'dir', oid: A }, { mode: '100644', name: 'f', oid: B }, { mode: '120000', name: 'link', oid: A }, { mode: '160000', name: 'sub', oid: B }, { mode: '100755', name: 'x', oid: A }]));
40 assert.equal(unwrap(lookupEntry(tree, 'dir', false, DEFAULT_LIMITS)).entry.oid, A);
41 assert.equal(unwrap(lookupEntry(tree, 'f', true, DEFAULT_LIMITS)).entry.oid, B);
42 assert.equal(unwrap(lookupEntry(tree, 'x', true, DEFAULT_LIMITS)).entry.mode, '100755');
43 for (const [name, last, re] of [['nope', true, /not found/], ['f', false, /not a directory/], ['dir', true, /not a regular file/], ['link', true, /not a regular file/], ['sub', true, /not a regular file/], ['sub', false, /not a directory/]]) {
44 assert.throws(() => unwrap(lookupEntry(tree, name, last, DEFAULT_LIMITS)), e => e.code === 'not_found' && re.test(e.message) && typeof e.attrs['git.edit.tree.entries'] === 'number', `${name}/${last}`);
45 }
46 assert.throws(() => unwrap(lookupEntry(tree, 'f', true, withLimits({ maxTreeEntries: 4 }))), e => e.code === 'limit_exceeded');
47});
49test('buildCommitObjects ≡ git: trees and commit hash to what git computes, delta list is thin and minimal', () => {
50 const dir = mkdtempSync(join(tmpdir(), 'gw-pure-'));
51 try {
52 const git = (args, input) => execFileSync('git', ['-C', dir, ...args], { input, encoding: 'utf8', env: { ...process.env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'commit.gpgsign', GIT_CONFIG_VALUE_0: 'false' } }).trim();
53 git(['init', '-q', '--bare']);
54 const oldBlob = git(['hash-object', '-w', '--stdin'], 'hello MARK\n'), newBlob = git(['hash-object', '-w', '--stdin'], 'hello DONE\n');
55 const other = git(['hash-object', '-w', '--stdin'], 'other\n');
56 const leafData = unwrap(encodeTree([{ mode: '100644', name: 'file.txt', oid: oldBlob }, { mode: '100644', name: 'z', oid: other }]));
57 const leafOid = git(['mktree'], `100644 blob ${oldBlob}\tfile.txt\n100644 blob ${other}\tz\n`);
58 assert.equal(hashObject('tree', leafData), leafOid);
59 const rootData = unwrap(encodeTree([{ mode: '40000', name: 'd', oid: leafOid }]));
60 const rootOid = git(['mktree'], `040000 tree ${leafOid}\td\n`);
61 const levels = [{ treeOid: rootOid, data: rootData, entry: unwrap(lookupEntry(rootData, 'd', false, DEFAULT_LIMITS)).entry }, { treeOid: leafOid, data: leafData, entry: unwrap(lookupEntry(leafData, 'file.txt', true, DEFAULT_LIMITS)).entry }];
62 const base = 'hello MARK\n';
63 const { delta } = spliceDelta({ baseLen: base.length, off: 6, oldLen: 4, insert: new TextEncoder().encode('DONE') });
64 const parent = git(['commit-tree', rootOid, '-m', 'p'], undefined);
65 const built = unwrap(buildCommitObjects({ levels, blob: { oldOid: oldBlob, newOid: newBlob, delta, newLen: base.length }, oldCommit: parent, author: { name: 'n', email: 'e@x' }, time: 1700000000, message: 'm' }));
66 // git's answer for the same edit
67 const gitLeaf = git(['mktree'], `100644 blob ${newBlob}\tfile.txt\n100644 blob ${other}\tz\n`), gitRoot = git(['mktree'], `040000 tree ${gitLeaf}\td\n`);
68 assert.deepEqual(built.trees.map(t => t.newOid), [gitRoot, gitLeaf]);
69 const env = { GIT_AUTHOR_NAME: 'n', GIT_AUTHOR_EMAIL: 'e@x', GIT_COMMITTER_NAME: 'n', GIT_COMMITTER_EMAIL: 'e@x', GIT_AUTHOR_DATE: '1700000000 +0000', GIT_COMMITTER_DATE: '1700000000 +0000' };
70 const gitCommit = execFileSync('git', ['-C', dir, 'commit-tree', gitRoot, '-p', parent, '-m', 'm'], { encoding: 'utf8', env: { ...process.env, ...env, GIT_CONFIG_COUNT: '1', GIT_CONFIG_KEY_0: 'commit.gpgsign', GIT_CONFIG_VALUE_0: 'false' } }).trim();
71 assert.equal(built.newCommit, gitCommit);
72 assert.equal(unwrap(parseCommit(built.commitData)).parents[0], parent);
73 // object list: commit (full) + one REF_DELTA per tree + blob REF_DELTA
74 assert.deepEqual(built.objects.map(o => [o.type, o.base?.tag ?? 'none']), [[TYPE.COMMIT, 'none'], [TYPE.TREE, 'ref'], [TYPE.TREE, 'ref'], [TYPE.BLOB, 'ref']]);
75 assert.deepEqual(built.objects.slice(1).map(o => o.base.oid), [rootOid, leafOid, oldBlob]);
76 // a < 4-byte delta becomes a full blob (git's DELTA_SIZE_MIN)
77 const tiny = unwrap(buildCommitObjects({ levels, blob: { oldOid: oldBlob, newOid: newBlob, delta: new Uint8Array(3), newLen: 0 }, oldCommit: parent, author: { name: 'n', email: 'e@x' }, time: 1, message: 'm' }));
78 assert.equal(tiny.objects.at(-1).base, undefined); assert.equal(tiny.objects.at(-1).data.length, 0);
79 } finally { rmSync(dir, { recursive: true, force: true }); }
80});
82test('deflate only: a stored-block zlib stream never beats CompressionStream (the reason buildPack has no stored path)', async () => {
83 // hand-rolled stored zlib, test-side only: 2 header + 5/block + 4 adler
84 const stored = d => { const n = Math.max(1, Math.ceil(d.length / 65535)); const o = new Uint8Array(2 + d.length + 5 * n + 4); o[0] = 0x78; o[1] = 0x01; let p = 2, q = 0; for (let b = 0; b < n; b++) { const len = Math.min(65535, d.length - q); o[p++] = b === n - 1 ? 1 : 0; o[p++] = len & 255; o[p++] = len >> 8; o[p++] = ~len & 255; o[p++] = (~len >> 8) & 255; o.set(d.subarray(q, q + len), p); p += len; q += len; } let a = 1, c = 0; for (const x of d) { a = (a + x) % 65521; c = (c + a) % 65521; } const ad = ((c << 16) | a) >>> 0; o[p++] = ad >>> 24; o[p++] = (ad >>> 16) & 255; o[p++] = (ad >>> 8) & 255; o[p] = ad & 255; return o; };
85 const rng = new Rng(7);
86 for (let i = 0; i < 200; i++) {
87 const n = i < 40 ? i : rng.int(0, 70000);
88 const data = rng.int(0, 1) ? rng.bytes(n) : new Uint8Array(n).fill(0x61);
89 const zs = stored(data), zd = await zlibDeflate(data);
90 assert.deepEqual(new Uint8Array(zlib.inflateSync(zs)), data);
91 assert.deepEqual(unwrap(inflate(zs, 0, { expectedSize: n })).out, data, 'our inflate handles multi-block stored streams');
92 // zlib's own stored blocks are ~16 KiB, ours 64 KiB: deflate can lose by ≤5 bytes per 16 KiB on incompressible input, nothing more
93 assert.ok(zd.length <= zs.length + 5 * Math.ceil(n / 16384), `n=${n}: deflate ${zd.length} vs stored ${zs.length}`);
94 }
95});
97test('scanStep counts every match and keeps the first MATCH_OFFSETS_KEPT offsets; each hit is O(1) (#13)', () => {
98 // CPU time, not wall clock, so load on the box does not count; scaling 16 -> 128 KiB, so a slow machine cancels.
99 // Linear is ~8x (measured 4-7x); the old per-hit offset copy was quadratic (64x and up). A noisy 24-64x is re-measured.
100 const run = n => {
101 const data = new Uint8Array(n).fill(0x61);
102 let st = scanInit({ find: Uint8Array.of(0x61), replace: Uint8Array.of(0x62) });
103 const t0 = process.cpuUsage();
104 for (let o = 0; o < n; o += 16384) st = scanStep(st, data.subarray(o, o + 16384)).state;
105 const d = process.cpuUsage(t0);
106 return { st, ms: (d.user + d.system) / 1000 };
107 };
108 run(16 << 10); // warm-up
109 const small = Math.max(Math.min(run(16 << 10).ms, run(16 << 10).ms, run(16 << 10).ms), 0.05);
110 let big = run(128 << 10);
111 for (let k = 0; k < 2 && big.ms >= 24 * small && big.ms < 64 * small; k++) { const r = run(128 << 10); if (r.ms < big.ms) big = r; }
112 assert.ok(big.ms < 24 * small, `128 KiB of matches cost ${big.ms.toFixed(2)} ms CPU, ${(big.ms / small).toFixed(1)}x 16 KiB (${small.toFixed(2)} ms); linear is ~8x`);
113 const { st } = big;
114 assert.equal(st.count, 128 << 10);
115 assert.equal(st.emitted, 128 << 10);
116 assert.deepEqual(st.matches, Array.from({ length: MATCH_OFFSETS_KEPT }, (_, i) => i));
117 const two = scanStep(scanInit({ find: Uint8Array.of(1), replace: new Uint8Array(0) }), Uint8Array.of(1, 0, 1)).state;
118 assert.equal(two.count, 2);
119 assert.deepEqual(two.matches, [0, 2]);
120});
122test('memFromScan/memAttrs: whole-edit accounting from what was held', () => {
123 let st = scanInit({ find: new Uint8Array([1]), replace: new Uint8Array(0) });
124 for (const n of [10, 4096, 100, 4096]) st = scanStep(st, new Uint8Array(n)).state;
125 assert.deepEqual(memFromScan(st, 8302), { 'mem.alloc.inflate_chunk.bytes': 8302, 'mem.alloc.inflate_chunk.count': 4, 'mem.alloc.inflate_chunk.max_single': 4096 });
126 const m = memAttrs({ objects: [190, 777, 777], scan: st, inflated: 8302 });
127 assert.equal(m['mem.alloc.bytes'], 190 + 777 + 777 + 8302); assert.equal(m['mem.alloc.count'], 3 + 4); assert.equal(m['mem.alloc.max_single'], 4096); assert.equal(m['mem.alloc.object.count'], 3);
128});
130test('otel: links, event cap, isolate counter, flatten round-trip', () => {
131 const ex = arrayExporter(); const t = new Tracer({ exporter: ex, maxEvents: 2 });
132 const a = t.start('a'); a.end();
133 const b = t.start('b'); b.link(a, { 'ply.link': 'retry_of' }); b.event('x'); b.event('y'); b.event('z'); b.end();
134 const [fa, fb] = ex.lines.flatMap(flattenLine);
135 assert.equal(fb.links.length, 1); assert.equal(fb.links[0].spanId, fa.spanId); assert.equal(fb.links[0].attrs['ply.link'], 'retry_of');
136 assert.equal(fb.events.length, 2); assert.equal(fb.droppedEvents, 1);
137 assert.equal(fb.attrs['ply.isolate.invocation'], fa.attrs['ply.isolate.invocation'] + 1); assert.equal(fb.attrs['ply.isolate.cold'], false);
138 const c = t.start('c', { parent: b }); c.end();
139 assert.equal(ex.lines.flatMap(flattenLine)[2].attrs['ply.isolate.invocation'], undefined, 'child spans do not count as invocations');
140});
142test('otel: a follows span is the root of its own trace, linked both ways while the followed span is open; links are capped', () => {
143 const ex = arrayExporter(); const t = new Tracer({ exporter: ex, maxEvents: 2 });
144 const op = t.start('git.op', { scrub: s => s.replaceAll('SECRET', '[redacted]') });
145 const f = t.start('git.op.stream', { follows: op, attrs: { 'git.op.stream.note': 'SECRET' } });
146 assert.notEqual(f.traceId, op.traceId); assert.equal(f.parentSpanId, null);
147 op.end();
148 const late = t.start('git.op.late', { follows: op }); late.end(); // op already exported: no link back
149 t.start('x', { follows: f }); t.start('y', { follows: f }); // f has follows_from + 2 followed_by → the second is dropped
150 f.end();
151 const [fo, fl, ff] = ex.lines.map(l => l.resourceSpans[0].scopeSpans[0].spans[0]);
152 const flat = ex.lines.flatMap(flattenLine);
153 assert.deepEqual(flat[0].links.map(l => [l.spanId, l.attrs['ply.link']]), [[f.spanId, 'followed_by']]);
154 assert.deepEqual(flat[1].links.map(l => [l.traceId, l.spanId, l.attrs['ply.link']]), [[op.traceId, op.spanId, 'follows_from']]);
155 assert.deepEqual(flat[2].links.map(l => l.attrs['ply.link']), ['follows_from', 'followed_by']);
156 assert.deepEqual([fo.droppedLinksCount, fl.droppedLinksCount, ff.droppedLinksCount], [0, 0, 1]);
157 assert.equal(flat[2].attrs['git.op.stream.note'], '[redacted]', 'a follower inherits the scrub of the span it follows');
158 assert.equal(flat[2].attrs['ply.isolate.invocation'], undefined, 'a follower is not an invocation');
159 assert.throws(() => t.start('z', { parent: op, follows: op }), TypeError);
160});
162test('inflate: an incomplete huffman table with a hole is rejected (invalid huffman code), and zlib agrees', () => {
163 // Dynamic block whose lit/len table has a single code (EOB, length 1): the one incomplete literal/length set zlib
164 // accepts (inftrees.c: a single 1-bit code), so the bit that is not that code decodes to nothing. Built bit by bit,
165 // LSB-first as deflate reads it. (This fixture had EOB at length 8, which zlib refuses at the header as `invalid
166 // literal/lengths set`, and so does ply now: asserted below.)
167 const member = eobLen => {
168 const bits = []; const put = (v, n) => { for (let i = 0; i < n; i++) bits.push((v >> i) & 1); };
169 put(1, 1); put(2, 2); // BFINAL=1, BTYPE=dynamic
170 put(0, 5); put(0, 5); put(14, 4); // HLIT=257, HDIST=1, HCLEN=18 → code-length symbols 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1
171 for (const n of [0, 0, 0, 1, eobLen === 8 ? 1 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, eobLen === 1 ? 1 : 0]) put(n, 3); // symbol 0 → `0`, symbol eobLen → `1`
172 for (let i = 0; i < 256; i++) put(0, 1); // literals 0..255: length 0
173 put(1, 1); // symbol 256 (EOB): length eobLen
174 put(0, 1); // the one distance symbol: length 0
175 for (let i = 0; i < 16; i++) put(1, 1); // data: 1111…, which is not the EOB code (0, or 00000000)
176 return Uint8Array.from(Array.from({ length: Math.ceil(bits.length / 8) }, (_, i) => bits.slice(i * 8, i * 8 + 8).reduce((b, v, j) => b | (v << j), 0)));
177 };
178 assert.throws(() => unwrap(inflate(member(1), 0, { raw: true, maxOutput: 1024 })), e => e.code === 'pack_corrupt' && /invalid huffman code/.test(e.message));
179 assert.throws(() => zlib.inflateRawSync(member(1)), /invalid literal\/length code/, 'node zlib rejects the code, not the set');
180 assert.throws(() => zlib.inflateRawSync(member(8)), /invalid literal\/lengths set/, 'node zlib rejects the set');
181 assert.throws(() => unwrap(inflate(member(8), 0, { raw: true, maxOutput: 1024 })), e => e.code === 'pack_corrupt' && e.message === 'inflate: invalid literal/lengths set');
182});
184test('parsePack: reserved object types 0 and 5 are rejected', async () => {
185 const { parsePack } = await import('../src/packresolve.js');
186 const { encodeObjHeader } = await import('../src/pack.js');
187 const { Sha1 } = await import('../src/sha1.js');
188 const { concat } = await import('../src/bytes.js');
189 for (const type of [0, 5]) {
190 const hdr = new Uint8Array(12); hdr.set([0x50, 0x41, 0x43, 0x4b]); new DataView(hdr.buffer).setUint32(4, 2); new DataView(hdr.buffer).setUint32(8, 1);
191 const body = concat([hdr, encodeObjHeader(type, 3), await zlibDeflate(new Uint8Array([1, 2, 3]))]);
192 const pack = concat([body, new Sha1().update(body).digest()]);
193 assert.throws(() => unwrap(parsePack(pack)), e => e.code === 'pack_corrupt' && /bad object type/.test(e.message), `type ${type}`);
194 }
195});
197test('otel: anyValue stringifies objects, fromAny reads bytes', async () => {
198 const { anyValue, fromAny } = await import('../src/otel.js');
199 assert.deepEqual(anyValue({ a: 1 }), { stringValue: '[object Object]' });
200 assert.equal(fromAny({ bytesValue: 'AQID' }), 'AQID');
201 assert.deepEqual(anyValue(new Uint8Array([1, 2, 3])), { bytesValue: btoa('\x01\x02\x03') });
202});
204test('streamingSha1: uses crypto.DigestStream when the platform has one (shimmed here), same digest as pure JS', async () => {
205 const { streamingSha1, Sha1 } = await import('../src/sha1.js');
206 assert.equal(streamingSha1().kind, 'js', 'node has no DigestStream');
207 class FakeDigestStream extends WritableStream {
208 constructor(alg) { let h = new Sha1(); let resolve; const digest = new Promise(r => { resolve = r; }); super({ write(c) { h.update(c); }, close() { resolve(h.digest().buffer); } }); this.digest = digest; assert.equal(alg, 'SHA-1'); }
209 }
210 const orig = globalThis.crypto.DigestStream;
211 Object.defineProperty(globalThis.crypto, 'DigestStream', { value: FakeDigestStream, configurable: true, writable: true });
212 try {
213 const h = streamingSha1(); assert.equal(h.kind, 'digeststream');
214 const parts = [new Uint8Array([1, 2, 3]), new Uint8Array(1000).fill(7), new Uint8Array(0)];
215 for (const p of parts) await h.update(p);
216 const js = new Sha1(); for (const p of parts) js.update(p);
217 assert.equal(await h.hex(), js.hex());
218 } finally { if (orig === undefined) delete globalThis.crypto.DigestStream; else Object.defineProperty(globalThis.crypto, 'DigestStream', { value: orig, configurable: true }); }
219});
221test('span naming convention: every span and attribute key in a trace follows the written rules', async () => {
222 // Rules (README "Telemetry"):
223 // span names: git.<service> <command> for wire round trips (git.upload-pack ls-refs, git.receive-pack, …)
224 // git.<op> operation roots (git.edit, git.merge, git.rebase, git.cherry_pick, git.revert)
225 // git.<op>.<phase> operation children (git.edit.tree, git.edit.blob)
226 // attr keys: dotted lowercase ascii with underscores, under one of: git. http. url. server. mem. error. ply. exception.
227 // outcomes: every root span has <name>.outcome (operation roots, and the spans that follow them: README "Span lifetimes")
228 const { startGitServer, makeBareRepo, tmpRoot, commitFiles, git } = await import('./server.js');
229 const { editFile } = await import('../src/edit.js');
230 const { join } = await import('node:path'); const { mkdirSync } = await import('node:fs');
231 const { root, cleanup } = tmpRoot(); const srv = await startGitServer(root);
232 try {
233 const bare = makeBareRepo(root, 'nm'); const work = join(root, 'w'); mkdirSync(work); git(work, ['init', '-q', '-b', 'main']);
234 commitFiles(work, bare, { 'a/b.txt': 'MARK\n' }, 'seed');
235 const ex = arrayExporter();
236 await editFile(`${srv.url}/nm.git`, { path: 'a/b.txt', find: 'MARK', replace: 'X', author: { name: 'n', email: 'n@x' }, message: 'm' }, { tracer: new Tracer({ exporter: ex }), verify: true });
237 const spans = ex.lines.flatMap(flattenLine);
238 const NAME = /^(git\.(upload-pack|receive-pack)( [a-z-]+)?|git\.[a-z_]+(\.[a-z_]+)?)$/;
239 const KEY = /^(git|http|url|server|mem|error|ply|exception)\.[a-z0-9_.-]+$/;
240 for (const s of spans) {
241 assert.match(s.name, NAME, `span name ${s.name}`);
242 for (const k of Object.keys(s.attrs)) assert.match(k, KEY, `attr ${k} on ${s.name}`);
243 if (!s.parentSpanId) assert.ok(`${s.name}.outcome` in s.attrs, `root ${s.name} has no outcome`);
244 if (/^git\.(upload-pack|receive-pack)/.test(s.name)) for (const k of ['git.transport', 'git.request.bytes', 'git.response.bytes', 'server.address']) assert.ok(k in s.attrs, `${s.name} lacks ${k}`);
245 }
246 } finally { await srv.close(); cleanup(); }
247});
249test('error taxonomy: runtime table and documentation agree; fail refuses unknown codes', async () => {
250 const { RETRY, CODES, plyError: fail, retryPolicy, ambiguousAfterPush } = await import('../src/errors.js');
251 const { CODE_DOCS } = await import('../src/errors-doc.js');
252 assert.deepEqual(Object.keys(CODE_DOCS).sort(), [...CODES].sort(), 'every code documented, nothing documented that does not exist');
253 for (const c of CODES) assert.ok(['yes', 'no', 'fresh', 'read'].includes(RETRY[c]), c);
254 assert.throws(() => fail('not_a_code', 'x'), /unknown error code/);
255 assert.equal(retryPolicy(fail('cas_conflict', 'x')), 'fresh'); assert.equal(retryPolicy(fail('ambiguous', 'x')), 'read'); assert.equal(retryPolicy({ code: 'nope' }), 'no');
256 assert.equal(ambiguousAfterPush(fail('network', 'dropped')).code, 'ambiguous'); assert.equal(ambiguousAfterPush(fail('network', 'dropped')).original, 'network');
257 // a limit hit while reading the report is after the send: the ref may have moved (pre-send refusals never reach it)
258 assert.equal(ambiguousAfterPush(fail('limit_exceeded', 'x')).code, 'ambiguous'); assert.equal(ambiguousAfterPush(fail('limit_exceeded', 'x')).original, 'limit_exceeded');
259 const amb = fail('ambiguous', 'y'); assert.equal(ambiguousAfterPush(amb), amb);
260});
262test('error taxonomy: every error-code literal in src/ is in the table (static)', async () => {
263 const { readdirSync, readFileSync } = await import('node:fs');
264 const { CODES } = await import('../src/errors.js');
265 const used = new Set();
266 for (const f of readdirSync('src')) if (/\.[jt]s$/.test(f)) for (const m of readFileSync(`src/${f}`, 'utf8').matchAll(/\b(?:fail|plyError|thrown)\('([a-z_0-9]+)'/g)) used.add(m[1]);
267 // the three constructors: fail (an Err), plyError (the error value), thrown (the throwing form, until the cut-over)
268 for (const c of used) assert.ok(CODES.includes(c), `code '${c}' constructed in src/ but not in errors.js`);
269 // a floor so a broken regex cannot pass on nothing: 19 literal codes since the SSH transport (the only `fail('auth'` site) left, 2026-10-31
270 assert.ok(used.size >= 19, `only ${used.size} error-code literals found`);
271});
273test('scrubError walks prototype-less maps (#16: merge reasons, report-status options) as it walks plain objects', () => {
274 const options = Object.create(null); options.__proto__ = 'tok SECRET'; options['old-oid'] = 'SECRET';
275 const reasons = Object.create(null); reasons['a.txt'] = 'SECRET';
276 const e = scrubError(fail('push_rejected', 'x', { report: { refs: [{ options }] }, reasons }), s => s.replaceAll('SECRET', '[redacted]'));
277 assert.deepEqual(Object.entries(e.report.refs[0].options), [['__proto__', 'tok [redacted]'], ['old-oid', '[redacted]']]);
278 assert.equal(e.reasons['a.txt'], '[redacted]');
279});
Diagnostics4 git calls · 232 ms
CallStatusSizeTime0232 ms
discover200152 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=152
git.server.agent=gitty/1.0
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch object-format
git.server.fetch=shallow filter sideband-all
git.protocol.version=2
git.pkt.frames=8
git.pkt.data=6
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=152
git.pkt.payload.max=34
ls-refs200145 B · hit3 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=3
git.response.bytes=145
git.response.cache=HIT
git.response.duration_ms=3
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=145
git.pkt.payload.max=76
git.ls_refs.count=2
git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020038 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=226
git.response.bytes=38434
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=blob:none
git.fetch.filter.requested=tree:0
git.fetch.filter.fallback=blob:none
git.fetch.filter.learned=false
git.fetch.wants=19912563f540228593df0c489082e5e2508e21e4
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=6
git.pkt.data=4
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=38434
git.pkt.payload.max=38339
git.sideband.band1.bytes=38338
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=63
git.pack.bytes=38338
git.pack.ofs_delta=0
git.pack.ref_delta=8
git.pack.chain.max=8
git.pack.trailer=0bc36ab7adf82d3109177f11f1ea93f1ce071f77
git.pack.full=55
Open pack map
fetch2008.0 KiB226 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=8155
git.response.cache=MISS
git.response.duration_ms=226
git.fetch.wants=75fbec40550092acac88a9bd42df0a32f50d609e
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=3
git.pkt.data=2
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=8155
git.pkt.payload.max=8134
git.sideband.band1.bytes=8133
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply.git
Ref
refs/heads/main
Commit
19912563f540228593df0c489082e5e2508e21e4
cf-ray
a5e2c08c0e9489da
Request
c2012b92…
Protocol
v2 · sha1
Agent
gitty/1.0
Filter
advertised
Fetch
shallow filter sideband-all
Capabilities
agent ls-refs fetch object-format