// v0 receive-pack: commands + thin pack in, report-status out. Planning the request, reading the response stream, // classifying the report and deciding the outcome are pure; `push` is the one effect. Any failure after the body is on // the wire is 'ambiguous' (the ref may have moved). import { fail, ambiguousAfterPush, remoteText, REMOTE_TEXT_MAX } from './errors.js'; import type { ErrorOf, PlyError } from './errors.js'; import { ok, err, assertNever, flatMapOption, getOrElse, mapOption } from './result.js'; import type { Err, Result } from './result.js'; import { pkt, FLUSH, pktInit, pktStep } from './pktline.js'; import { td, concat, decodeBytes, decodeChunk } from './bytes.js'; import { SIDEBAND_PACK, SIDEBAND_PROGRESS, SIDEBAND_ERROR } from './format.js'; import { ZERO_OID, parseOid } from './oid.js'; import type { Oid } from './oid.js'; import type { Refname } from './refname.js'; import { measurePack, streamPack, streamSource } from './packwrite.js'; import type { MeasuredPack, StreamedPack } from './packwrite.js'; import { frames, coded, clientSpan, spanned, wrapNet, UA } from './transport.js'; import { limitExceeded, parseLimits } from './limits.js'; import type { LimitsInput } from './limits.js'; // oxlint-disable-next-line import/max-dependencies -- the push path: framing, pack writer, transport, limits, validation, the parsed brands, Result import { validatePushRef, validateWire } from './validate.js'; import type { WireField } from './validate.js'; /* oxlint-disable no-magic-numbers -- span tails and the short-oid display width are diagnostics, not wire-format facts */ const SHORT_OID = 8; const BAND_TAIL = 4096; const BAND_ATTR = 1024; const REPORT_KEEP = 64; /* oxlint-enable no-magic-numbers */ const UNPACK = 'unpack '; const OK_REF = 'ok '; const NG_REF = 'ng '; export { ZERO_OID }; // One ref update as a caller writes it. create: oldOid = zeros; delete: newOid = zeros. Plain strings in: planPush parses // every command (parseCommand) before anything is built or sent, and the plan carries only the parsed ones. export type Command = { readonly ref: string; readonly oldOid: string; readonly newOid: string }; export type Commands = readonly [Command, ...Command[]]; // A command parsed once: the ref is one receive-pack takes (validatePushRef), the oids are 40 lowercase hex (parseOid). export type PushCommand = { readonly ref: Refname; readonly oldOid: Oid; readonly newOid: Oid }; // The parsed list: at least one PushCommand, made only by parseCommands / planPush (the brand is a type). declare const PARSED: unique symbol; export type ParsedCommands = readonly [PushCommand, ...PushCommand[]] & { readonly [PARSED]: true }; // The guard is the whole check: every element is already a PushCommand (its type), so what is left is at least one. const isParsed = (cs: readonly PushCommand[]): cs is ParsedCommands => cs.length > 0; // A command from a typed caller, or an untyped one (or the single-ref form, whose fields may be missing). export type RawCommand = { readonly ref: unknown; readonly oldOid: unknown; readonly newOid: unknown }; // @decoder parseCommand prefix=push-command export function parseCommand(c: RawCommand): Result> { const ref = validatePushRef(c.ref, c.newOid === ZERO_OID); if (!ref.ok) return ref; const oldOid = parseOid(c.oldOid); const newOid = parseOid(c.newOid); if (!oldOid.ok || !newOid.ok) return fail('bad_request', 'push: oids must be 40-hex'); return ok({ ref: ref.value, oldOid: oldOid.value, newOid: newOid.value }); } // The list's own check, after every command's: none at all is 'protocol' with nothing sent (push read the first command // for its span; an empty list was the TypeError that read raised, coded 'protocol', before any request or span). const nonEmpty = (cs: readonly PushCommand[]): Result> => (isParsed(cs) ? ok(cs) : fail('protocol', 'push: no commands')); const parseEach = (raw: readonly RawCommand[]): Result> => { const parsed: PushCommand[] = []; for (const c of raw) { const one = parseCommand(c); if (!one.ok) return one; parsed.push(one.value); } return ok(parsed); }; // The public list, parsed once. planPush runs the same two steps with its own checks between them. // @decoder parseCommands prefix=push-command export function parseCommands(raw: readonly RawCommand[]): Result> { const each = parseEach(raw); return each.ok ? nonEmpty(each.value) : each; } // A pkt-line frame as pktStep and the transports' frames() yield it. export type { Frame } from './transport.js'; import type { Frame, RequestBody, Scrub, SpanOpts, Transport } from './transport.js'; import type { PktState } from './pktline.js'; import type { PackInput, BuiltEntry } from './pack.js'; import { WHOLE, inputBase, typeNameOf } from './pack.js'; import { hashObject } from './objects.js'; import type { Span } from './otel.js'; import type { Input } from './absent.js'; import { at, atOr, field, fromNullish, isMissing, mapGet, withDefaults } from './absent.js'; import { lsRefs } from './lsrefs.js'; import type { LsRefsResult } from './lsrefs.js'; // local sideband parser to reduce dependencies const parseSideband = (payload: Uint8Array): { readonly band: number; readonly body: Uint8Array } => ({ band: atOr(payload, 0, 0), body: payload.subarray(1) }); // What send-pack.c send_pack() checks against the advertisement before it sends a byte, as a value: the `atomic` and // `push-options` a push may ask for. receive-pack ignores an `atomic` it did not advertise (the refs land one by one) // and reads unadvertised option lines as the pack, so the request builder takes these only from a CheckedCaps, which // only receivecaps.ts checkPushCaps makes (from the server's advertisement). The brand is a type: nothing at run time. declare const CHECKED: unique symbol; export type CheckedCaps = { readonly atomic: boolean; readonly pushOptions: readonly string[]; readonly [CHECKED]: true }; // Each line as a pkt-line, or the first one pkt() refuses (longer than a pkt-line holds). function pkts(lines: readonly string[]): Result> { const out: Uint8Array[] = []; for (const l of lines) { const p = pkt(l); if (!p.ok) return p; out.push(p.value); } return ok(out); } // commands: [{ ref, oldOid, newOid }] (create: oldOid = zeros; delete: newOid = zeros). A push with only deletes sends no // pack. The wire encoder: `caps` is sent as given (push builds it with requestCaps). A line pkt() refuses is its Err. export const pushBody = ({ commands, caps = ['report-status', `agent=${UA.replace(/ .*/u, '')}`] }: { readonly commands: readonly Command[] } & Input<{ readonly caps: readonly string[] }>, pack: Uint8Array | null = null): Result, ErrorOf<'bad_request'>> => { const lines = commands.map((c, i) => `${c.oldOid} ${c.newOid} ${c.ref}${i === 0 ? `\0${caps.join(' ')}` : ''}\n`); const framed = pkts(lines); return framed.ok ? ok(concat([...framed.value, FLUSH, ...(pack ? [pack] : [])])) : framed; }; // ---- the push outcome (pure): wire → stream shape → report shape → outcome → Result, each a tagged union ---- // Principle (SAFETY.md I36): once the request body may have reached the server, ply says "landed" or "not landed" only on // a report exactly as git's receive-pack writes it (builtin/receive-pack.c report/report_v2, cmd_receive_pack); every // other post-send state is 'ambiguous'. Each step below is an allowlist: what it does not recognize falls to ambiguous. // The space of responses and the expected outcome of each cell: test/space/push-outcome.space.js and SPACE.md. // 1. The stream. A step machine over the outer pkt frames, ending in // { tag: 'report', lines } — the report's pkt payloads, framed as git frames them, nothing before or after — or // { tag: 'broken', why, remote } — anything else (band 3, an unknown band, a missing or extra flush, trailing data); // remote: band 3's message, or null // git's shapes: plain — report pkts, flush (= the report's flush), end; side-band-64k — band 2 (progress, hook stderr) // and empty band-1 keepalives, then the report pkts and their flush inside band 1, band 2 (post-receive), then the // outer flush (cmd_receive_pack: packet_flush(1) when use_sideband), end. export type Broken = { readonly tag: 'broken'; readonly why: string; readonly remote: string | null }; export type Reading = { readonly tag: 'reading'; readonly sideband: boolean; readonly phase: 'report' | 'reported' | 'done'; readonly inner: PktState; readonly lines: Uint8Array[]; readonly band2: string; readonly band2Carry: Uint8Array; readonly band2Frames: number; }; export type StreamReport = { readonly tag: 'report'; readonly lines: readonly Uint8Array[] }; export type StreamState = Reading | Broken | StreamReport; const broken = (why: string, remote: string | null = null): Broken => ({ tag: 'broken', why, remote }); // `lines` grows in place (a report can hold limits.maxReportLines lines): a state is not reused once stepped. export const streamInit = (sideband: boolean): Reading => ({ tag: 'reading', sideband, phase: 'report', inner: pktInit(), lines: [], band2: '', band2Carry: new Uint8Array(0), band2Frames: 0 }); // The band-1 pkt-lines that do not frame (pktStep's protocol error) are the Err: push reads it as a lost response. // @decoder streamStep prefix=stream // oxlint-disable-next-line complexity -- one step machine: each frame kind and band in the order git writes them export function streamStep(st: StreamState, f: Frame): Result> { // Stryker disable next-line ConditionalExpression: push stops stepping at the first non-reading state if (st.tag !== 'reading') return ok(st); if (st.phase === 'done') return ok(broken('data after the final flush')); if (f.kind === 'flush') { if (!st.sideband || (st.phase === 'reported' && st.inner.carry === null)) return ok({ ...st, phase: 'done' }); return ok(broken('flush before the report ended')); } // Stryker disable next-line ConditionalExpression: a delim/end frame has no payload, so read as data it still breaks the stream or the report if (f.kind !== 'data') return ok(broken(`${f.kind} packet`)); if (!st.sideband) { st.lines.push(f.payload); return ok(st); } const { band, body }: { readonly band: number; readonly body: Uint8Array } = parseSideband(f.payload); // decodeChunk: a character cut by a frame boundary is held for the next frame instead of decoding as two U+FFFD (#43) if (band === SIDEBAND_PROGRESS) { const d: { readonly text: string; readonly carry: Uint8Array } = decodeChunk(st.band2Carry, body); return ok({ ...st, band2: (st.band2 + d.text).slice(-BAND_TAIL), band2Carry: d.carry, band2Frames: st.band2Frames + 1 }); } if (band === SIDEBAND_ERROR) return ok(broken('band 3', td.decode(body).trim())); if (band !== SIDEBAND_PACK) return ok(broken(`bad sideband ${band}`)); // an empty band-1 packet is copy_to_sideband's keepalive: sent while hooks run, before the report and after it (post-receive) if (body.length === 0) return ok(st); // Stryker disable next-line ConditionalExpression: without it, band-1 bytes after the report's flush still break it (the loop below, or the carry at the outer flush) if (st.phase !== 'report') return ok(broken('band 1 after the report')); const r = pktStep(st.inner, body); if (!r.ok) return r; let phase: Reading['phase'] = st.phase; for (const g of r.value.frames) { if (phase !== 'report') return ok(broken('band 1 after the report')); switch (g.kind) { case 'flush': phase = 'reported'; continue; case 'data': st.lines.push(g.payload); continue; case 'delim': case 'end': return ok(broken(`${g.kind} packet in the report`)); } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(g); } return ok({ ...st, inner: r.value.state, phase }); } // Stryker disable next-line ConditionalExpression: a broken state has no phase, so it stays broken either way export const streamFinish = (st: StreamState): Broken | StreamReport => { if (st.tag !== 'reading') return st; return st.phase === 'done' ? { tag: 'report', lines: st.lines } : broken('no final flush'); }; // 2. The report. git's grammar, exactly: "unpack ok" or "unpack ", then for each // commanded ref exactly one "ok " or "ng " (reason: printable ASCII), every line ending in LF, and // nothing else (report_v2's option lines come only from a proc-receive hook, which redirects the update: not modelled). // A step machine over the report's lines, one parser (send-pack.c receive_unpack_status, then receive_status): // { tag: 'unpack' } — before the first line: it must be git's unpack line // { tag: 'refs', unpack, want, seen } — after it: one well-formed status per commanded ref, each at most once // { tag: 'malformed', why } — anything else (absorbing) // and reportFinish's shapes: // { tag: 'statuses', refs } — unpack ok, one status per commanded ref // { tag: 'unpackFailed', status, refs } — unpack failed and every ref is "ng unpacker error" (git), or every // ref is "ng ", the unpack status echoed (a host: echoedFailure) // { tag: 'malformed', why } // execute_commands: an unpack failure marks every command "unpacker error", and nothing else does. export type RefStatus = { readonly ref: string; readonly ok: true; readonly reason: '' } | { readonly ref: string; readonly ok: false; readonly reason: string }; export type Malformed = { readonly tag: 'malformed'; readonly why: string }; export type ReportState = | { readonly tag: 'unpack'; readonly want: ReadonlySet } | { readonly tag: 'refs'; readonly unpack: string; readonly want: ReadonlySet; readonly seen: Map } | Malformed; export type ReportShape = | { readonly tag: 'statuses'; readonly refs: readonly RefStatus[] } | { readonly tag: 'unpackFailed'; readonly status: string; readonly refs: readonly RefStatus[] } | Malformed; const GIT_UNPACK_ERROR_LIST = [ 'eof before pack header was fully read', 'protocol error (pack signature mismatch detected)', 'protocol error (pack version unsupported)', 'unknown error in parse_pack_header', 'unable to create temporary object directory', 'unpack-objects abnormal exit', 'index-pack fork failed', 'index-pack abnormal exit', ] as const; export type GitUnpackError = typeof GIT_UNPACK_ERROR_LIST[number]; export const GIT_UNPACK_ERRORS: readonly GitUnpackError[] = Object.freeze(GIT_UNPACK_ERROR_LIST); const seenUnpack = (status: GitUnpackError): true => { switch (status) { case 'eof before pack header was fully read': case 'protocol error (pack signature mismatch detected)': case 'protocol error (pack version unsupported)': case 'unknown error in parse_pack_header': case 'unable to create temporary object directory': case 'unpack-objects abnormal exit': case 'index-pack fork failed': case 'index-pack abnormal exit': return true; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(status); }; const isGitUnpackError = (status: string): boolean => { for (const item of GIT_UNPACK_ERRORS) if (item === status) return seenUnpack(item); return false; }; const UNPACKER_ERROR = 'unpacker error'; const PRINTABLE = /^[ -~]+$/u; // A host's unpack failure (not git's grammar): every commanded ref is refused with the unpack status itself as its // reason, or with a documented alias of that status. Cloudflare Artifacts writes the exact echo ("unpack invalid pack // entry type 0", then "ng invalid pack entry type 0" for each ref; observed 2026-11-10, #246) and one alias // ("unpack reachable object is missing", then "ng missing object"; observed 2026-11-10, #266, ray // a589199bca2624ad-IAD). Positive evidence, not a guess: a landed or refused report is never one byte from an exact // echo, and the alias is a closed table (SPACE.md, judgment 3). Any other unmatched ng reason stays malformed. const HOST_UNPACK_ALIASES: ReadonlyArray = Object.freeze([ ['reachable object is missing', 'missing object'], ]); const unpackReasonMatches = (status: string, reason: string): boolean => { if (reason === status) return true; for (const [s, r] of HOST_UNPACK_ALIASES) if (status === s && reason === r) return true; return false; }; const echoedFailure = (status: string, refs: readonly RefStatus[]): boolean => status !== 'ok' && refs.every(r => !r.ok && unpackReasonMatches(status, r.reason)); // Artifacts' body cap, echoed on unpack and ng (observed 2026-11-10, #266, ray a58a707c0a76c98d-IAD): // artifacts_git_receive_pack_request_too_large: push is 286.3 MiB, limit is 64.0 MiB // A reason is host-written, up to a pkt-line long, so it is parsed by hand in time linear in its length: the literal // parts are compared in place, one indexOf finds the middle, and each figure is matched against MIB_FIGURE: two // anchored alternatives, every quantifier bounded, the two digit runs separated by a required '.', so a digit run // matches one way only and a long one is refused within 10 characters. (The pattern this replaces, // `[0-9]+[.]?[0-9]*` twice, split a digit run every possible way: 12.9 s for a 2,492-byte reason.) No length cap: // the grammar itself admits at most 105 characters, so a cap could not change a result. const TOO_LARGE_HEAD = 'artifacts_git_receive_pack_request_too_large: push is '; const TOO_LARGE_MID = ' MiB, limit is '; const TOO_LARGE_TAIL = ' MiB'; // At most 9 integer digits and 6 decimals: under 10^9 MiB, about 2^50 bytes, so the byte count is always a safe // integer (999999999.999999 MiB = 1,048,575,999,999,999 bytes, under 2^53) and needs no check of its own. const MIB_FIGURE = /^[0-9]{1,9}$|^[0-9]{1,9}[.][0-9]{1,6}$/u; // oxlint-disable-next-line no-magic-numbers -- 2^10; MIB is 2^20, converting Artifacts' MiB figures to bytes const KIB = 1024; const MIB = KIB * KIB; // One figure in bytes, or null: not a decimal figure, or not a positive exact byte count. const mibBytes = (figure: string): number | null => { if (!MIB_FIGURE.test(figure)) return null; const bytes = Math.round(Number(figure) * MIB); return bytes > 0 ? bytes : null; }; // With no middle, indexOf is -1 and the first slice stops one short of the end: it is empty or ends in the tail's // 'i', never a figure, so that case needs no branch. The head holds no ' MiB', so the search starts at 0. export const parseReceivePackTooLarge = (reason: string): { readonly got: number; readonly max: number } | null => { if (!reason.startsWith(TOO_LARGE_HEAD) || !reason.endsWith(TOO_LARGE_TAIL)) return null; const mid = reason.indexOf(TOO_LARGE_MID); const got = mibBytes(reason.slice(TOO_LARGE_HEAD.length, mid)); const max = mibBytes(reason.slice(mid + TOO_LARGE_MID.length, reason.length - TOO_LARGE_TAIL.length)); return got === null || max === null ? null : { got, max }; }; const malformed = (why: string): Malformed => ({ tag: 'malformed', why }); // Stryker disable next-line ConditionalExpression,EqualityOperator,ArrayDeclaration: reportStep calls it on "ng " only; with no space or a leading one, every split names no commanded ref const splitOnce = (s: string, sep: string): readonly [string, string] => { const i = s.indexOf(sep); return i < 0 ? [s, ''] : [s.slice(0, i), s.slice(i + sep.length)]; }; export const reportInit = (commands: ReadonlyArray<{ readonly ref: string }>): ReportState => ({ tag: 'unpack', want: new Set(commands.map(c => c.ref)) }); // `seen` grows in place, as the stream's `lines` do: a state is not reused once stepped. // @decoder reportStep prefix=report export function reportStep(st: ReportState, payload: Uint8Array): ReportState { if (st.tag === 'malformed') return st; // A ref name is bytes (check_refname_format refuses only control bytes, space, ~ ^ : ? * [ and backslash, `..`, `@{` and the // dot/slash/.lock rules; any byte >= 0x80 is legal), and receive-pack echoes it as it got it. decodeBytes maps it to // the string the command was built from (encodeBytes is its inverse), so `ok ` matches its command (#43). const l: string = decodeBytes(payload); const line = l.slice(0, l.length - 1); if (!l.endsWith('\n') || line.includes('\n')) return malformed('a line is not one LF-terminated line'); switch (st.tag) { case 'unpack': { // '' (no unpack line) is neither "ok" nor a failure. A printable status that is neither "ok" nor one of git's // failures may still be a host's echoed failure (reportFinish decides, from the ref lines). const unpack = line.startsWith(UNPACK) ? line.slice(UNPACK.length) : ''; return unpack === 'ok' || isGitUnpackError(unpack) || PRINTABLE.test(unpack) ? { tag: 'refs', unpack, want: st.want, seen: new Map() } : malformed('no git unpack line first'); } case 'refs': { const isOk = line.startsWith(OK_REF); if (!isOk && !line.startsWith(NG_REF)) return malformed('a line is not a ref status'); // validateRef forbids spaces in a ref, so the first space after "ng " ends the ref name const rest = line.slice(OK_REF.length); const [ref, reason] = isOk ? [rest, ''] : splitOnce(rest, ' '); if (!st.want.has(ref)) return malformed('status for a ref not commanded'); if (st.seen.has(ref)) return malformed(`two statuses for ${ref}`); if (isOk) st.seen.set(ref, { ref, ok: true, reason: '' }); else if (PRINTABLE.test(reason)) st.seen.set(ref, { ref, ok: false, reason }); else return malformed(`no readable reason for ${ref}`); return st; } } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(st); } export function reportFinish(st: ReportState): ReportShape { switch (st.tag) { case 'malformed': return st; case 'unpack': return malformed('no git unpack line first'); case 'refs': { const complete = [...st.want].every(ref => st.seen.has(ref)); const refs = [...st.seen.values()]; // neither "ok" nor git's: definite only as a host's echoed failure over every commanded ref if (st.unpack !== 'ok' && !isGitUnpackError(st.unpack)) return complete && echoedFailure(st.unpack, refs) ? { tag: 'unpackFailed', status: st.unpack, refs } : malformed('no git unpack line first'); for (const ref of st.want) if (!st.seen.has(ref)) return malformed(`no status for ${ref}`); if (st.unpack !== 'ok') return refs.every(r => !r.ok && r.reason === UNPACKER_ERROR) || echoedFailure(st.unpack, refs) ? { tag: 'unpackFailed', status: st.unpack, refs } : malformed('unpack failed, a ref is not "unpacker error"'); if (refs.some(r => !r.ok && r.reason === UNPACKER_ERROR)) return malformed('"unpacker error" beside "unpack ok"'); return { tag: 'statuses', refs }; } } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(st); } // The driver: the report's pkt payloads (StreamReport.lines) against the commands sent. // @decoder classifyReport prefix=report export function classifyReport(payloads: readonly Uint8Array[], commands: ReadonlyArray<{ readonly ref: string }>): ReportShape { let st = reportInit(commands); for (const p of payloads) st = reportStep(st, p); return reportFinish(st); } // The class of one ng reason. git v2.50.0 receive-pack's own reasons are a table, each justified by what a caller can // safely do next and judged by real git: test/space/push-ng.space.js (every reason × command × atomic × refs; SPACE.md). // cas the ref is not where the command said (stale old oid, create over an existing ref, a held lock): fresh retry // nff receive.denyNonFastForwards, and the new commit does not descend from the command's own old oid // ambiguous a proc-receive hook was handed the command and did not answer for it: it may have acted // innocent 'atomic push failure', an atomic push's other members: the culprit's class decides // rejected a refusal: resending the same request is refused again // git >= 2.51 reports a non-atomic ref's failed update by cause (refs.c ref_transaction_error_msg): a stale old oid, a // create over an existing ref and a ref deleted since the read are cas; 'refname conflict' (D/F) and the rest refuse. // Every other git reason is a refusal (push_rejected). A reason git does not write is another host's: 'stale ref' is // Cloudflare Artifacts' only ref-update rejection (stale old oid, create over an existing ref, stale delete, and the // innocent members of a multi-ref push, which it always treats as atomic; observed 2026-10-23, SAFETY.md I31). export type NgClass = 'cas' | 'nff' | 'innocent' | 'ambiguous' | 'rejected'; const KNOWN_NG = [ 'failed to update ref', 'atomic transaction failed', 'bad ref', 'incorrect old value provided', 'reference already exists', 'reference does not exist', 'non-fast-forward', 'atomic push failure', 'proc-receive failed to report status', 'fail to run proc-receive hook', ] as const; type KnownNgReason = typeof KNOWN_NG[number]; const knownNgClass = (reason: KnownNgReason): NgClass => { switch (reason) { case 'failed to update ref': case 'atomic transaction failed': case 'bad ref': case 'incorrect old value provided': case 'reference already exists': case 'reference does not exist': return 'cas'; case 'non-fast-forward': return 'nff'; case 'atomic push failure': return 'innocent'; case 'proc-receive failed to report status': case 'fail to run proc-receive hook': return 'ambiguous'; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(reason); }; const HOST_CAS = /^(failed to lock|stale ref)$|fetch first|non-fast-forward|already exists/u; export const ngClass = (reason: string): NgClass => { for (const known of KNOWN_NG) if (known === reason) return knownNgClass(known); return HOST_CAS.test(reason) ? 'cas' : 'rejected'; }; // 3. The outcome. An exhaustive match on the report shape; 'ambiguous' is the only fallthrough. A refused ref carries // its reason and the reason's class. Every ref refused is a rejection whose code is the classes' verdict: a refusal // anywhere wins (push_rejected), then a non-fast-forward, then a lost compare-and-swap; 'innocent' members alone refuse. // { tag: 'landed' } | { tag: 'rejected', code, refs } | { tag: 'partial', landed, rejected } | { tag: 'ambiguous', why } export type Refused = { readonly ref: string; readonly reason: string; readonly cls: NgClass }; export type RejectionCode = 'push_rejected' | 'not_fast_forward' | 'cas_conflict' | 'limit_exceeded'; export type Outcome = | { readonly tag: 'landed' } | { readonly tag: 'rejected'; readonly code: RejectionCode; readonly refs: readonly Refused[] } | { readonly tag: 'partial'; readonly landed: readonly string[]; readonly rejected: readonly Refused[] } | { readonly tag: 'ambiguous'; readonly why: string }; const refused = (refs: readonly RefStatus[]): Refused[] => refs.flatMap(r => (r.ok ? [] : [{ ref: r.ref, reason: r.reason, cls: ngClass(r.reason) }])); // every ref refused, none ambiguous: which rejection export const rejectionCode = (ng: readonly Refused[]): RejectionCode => { if (ng.length > 0) { let tooLarge = true; for (const r of ng) if (parseReceivePackTooLarge(r.reason) === null) { tooLarge = false; break; } if (tooLarge) return 'limit_exceeded'; } const cls = new Set(ng.map(r => r.cls)); if (cls.has('rejected')) return 'push_rejected'; if (cls.has('nff')) return 'not_fast_forward'; return cls.has('cas') ? 'cas_conflict' : 'push_rejected'; }; // atomic: the push asked for all-or-nothing (default no); pack: a pack was sent (default yes) export type DecideOptions = Input<{ readonly atomic: boolean; readonly pack: boolean }>; export function decideOutcome(shape: ReportShape | Broken, { atomic = false, pack = true }: DecideOptions = {}): Outcome { switch (shape.tag) { // receive-pack writes an unpack failure only after reading a pack (delete_only() skips unpack) case 'unpackFailed': { if (!pack) return { tag: 'ambiguous', why: 'unpack failed but no pack was sent' }; const refs = refused(shape.refs); // a host body-cap unpack is limit_exceeded; every other unpack failure stays push_rejected (the refs may // carry an unrelated reason in a test shape; the unpack itself is the refusal) let tooLarge = refs.length > 0; for (const r of refs) if (parseReceivePackTooLarge(r.reason) === null) { tooLarge = false; break; } return { tag: 'rejected', code: tooLarge ? 'limit_exceeded' : 'push_rejected', refs }; } case 'statuses': { const ng = refused(shape.refs); if (ng.length === 0) return { tag: 'landed' }; // a proc-receive hook took the command and did not answer for it: it may have acted (test/space/push-ng.space.js) const amb = fromNullish(ng.find(r => r.cls === 'ambiguous')); if (amb.tag === 'some') return { tag: 'ambiguous', why: `proc-receive: ${amb.value.reason}` }; if (ng.length === shape.refs.length) return { tag: 'rejected', code: rejectionCode(ng), refs: ng }; // atomic: all or none. A split is git-shaped only for refs refused before the transaction (hidden refs, observed); // ply does not claim a partial outcome for a push the caller made atomic (SPACE.md). if (atomic) return { tag: 'ambiguous', why: 'atomic push split: some refs ok, some ng' }; return { tag: 'partial', landed: shape.refs.filter(r => r.ok).map(r => r.ref), rejected: ng }; } case 'malformed': case 'broken': return { tag: 'ambiguous', why: shape.why }; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(shape); } // The report as classified (one parser: classifyReport), for the caller and the span: null when it was not git's. export type PushReport = Exclude; // 4. The Result. 'landed' is Ok; every other outcome is the PlyError a caller matches on, carrying the report and // band 2. A rejection's message names the first refused ref's reason (git's report order; an unpack failure's refs // are all "unpacker error", and there is at least one command). export type PushError = ErrorOf; // remote: band 3's message when the stream broke on one, else null (a JS caller's missing value reads as null). export type OutcomeContext = { readonly report: PushReport | null; readonly hookOutput: string; readonly remote: string | null; readonly commands: readonly Command[] }; // scrub: the transport's credential scrubber (or null), applied to band 3's text before it is cut (errors.ts remoteText). export function outcomeResult(o: Outcome, { report, hookOutput, remote, commands }: OutcomeContext, scrub: Scrub | null = null): Result { const extra = { report, hookOutput }; switch (o.tag) { case 'landed': return ok(report); case 'rejected': { const reason = getOrElse(mapOption(at(o.refs, 0), r => r.reason), ''); if (o.code === 'limit_exceeded') { const sizes = parseReceivePackTooLarge(reason); // rejectionCode only returns limit_exceeded when every ng reason parsed const got = sizes === null ? 0 : sizes.got; const max = sizes === null ? 0 : sizes.max; return fail('limit_exceeded', `push is too large: ${remoteText(reason)}`, { ...extra, what: 'receive-pack request', got, max }); } const message = `push rejected: ${reason}`; if (o.code !== 'cas_conflict') return fail(o.code, message, extra); // what the culprit's command said the ref was (null: absent); receive-pack does not say where it is (actual: null) const culprit = fromNullish(o.refs.find(r => r.cls === 'cas')); const old = flatMapOption(culprit, x => mapOption(fromNullish(commands.find(c => c.ref === x.ref)), c => c.oldOid)); return fail('cas_conflict', message, { ...extra, expected: old.tag === 'none' || old.value === ZERO_OID ? null : old.value, actual: null }); } case 'partial': return fail('push_partial', `push partially applied: ${o.landed.join(', ')} updated; ${o.rejected.map(r => `${r.ref} (${r.reason})`).join(', ')} refused`, { ...extra, landed: o.landed, rejected: o.rejected }); case 'ambiguous': { const said = fromNullish(remote); return fail('ambiguous', `push outcome unknown: ${said.tag === 'none' ? '' : `remote: ${remoteText(said.value, REMOTE_TEXT_MAX, scrub)}: `}${o.why}`, said.tag === 'none' ? extra : { ...extra, original: 'remote_error' }); } } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(o); } const bandLines = (text: string): string[] => text.split(/\r?\n|\r/u).map(l => l.trim()).filter(Boolean).slice(-REPORT_KEEP); // The transport surface push reads (http.ts and test doubles provide more). export type PushSpan = { set(attrs: Readonly>): unknown; event(name: string, attrs: Readonly>): unknown; }; export type PushTransport = Transport; // One object for buildPack: { type, data, base } (pack.ts PackInput; a left-out base is none). export type PackObject = PackInput; export type PackEntry = BuiltEntry; // Single-ref form { ref, oldOid, newOid, objects } or multi-ref { commands: [...], objects }. Options: // sideband (default on): side-band-64k — the server's human-readable explanation of a rejection (hook stderr, GitHub's // GH006 text) arrives on band 2 and is recorded as git.push.remote.messages. Every receive-pack since 1.7 has it. // reportV2: report-status-v2 (per-ref option lines). // checked: atomic (all-or-nothing) and push options, as checked against the server's advertisement (receivecaps.ts // checkPushCaps; pushWithOptions and GitHttp.push do it). // commands null: the single-ref form, ref/oldOid/newOid (each refused by planPush when left out). export type PushConfig = { readonly ref: string | null; readonly oldOid: string; readonly newOid: string; readonly objects: readonly PackObject[]; readonly commands: Commands | null; readonly sideband: boolean; readonly reportV2: boolean; readonly checked: CheckedCaps | null; }; export type PushOptions = Input; const pushDefaults = (): { -readonly [K in keyof PushConfig]: PushConfig[K] } => ({ ref: null, oldOid: '', newOid: '', objects: [], commands: null, sideband: true, reportV2: false, checked: null }); export type PushResult = { readonly report: PushReport | null; readonly packBytes: number; readonly entries: readonly PackEntry[]; readonly hookOutput: string }; // The request, planned before anything is built or sent (pure): every refusal here happens with nothing on the wire. export type PushPlan = { readonly commands: ParsedCommands; readonly caps: readonly string[]; readonly checked: CheckedCaps | null; readonly pushOptions: readonly WireField[]; readonly needPack: boolean; readonly maxReportLines: number; readonly maxReportReason: number; readonly maxReportProgress: number; readonly maxPack: number; readonly objects: readonly PackObject[]; readonly sideband: boolean }; // The capabilities a push asks for; atomic and push-options only from a CheckedCaps. export type PushRequestCap = 'report-status' | 'report-status-v2' | 'side-band-64k' | 'atomic' | 'delete-refs' | 'push-options'; const requestCap = (cap: PushRequestCap): PushRequestCap => { switch (cap) { case 'report-status': case 'report-status-v2': case 'side-band-64k': case 'atomic': case 'delete-refs': case 'push-options': return cap; } // Stryker disable next-line ConditionalExpression: unreachable, the compiler's exhaustiveness check return assertNever(cap); }; export const requestCaps = (commands: readonly Command[], { sideband = true, reportV2 = false }: Input<{ readonly sideband: boolean; readonly reportV2: boolean }>, checked: CheckedCaps | null = null): string[] => [reportV2 ? requestCap('report-status-v2') : requestCap('report-status'), ...(sideband ? [requestCap('side-band-64k')] : []), ...(checked !== null && checked.atomic ? [requestCap('atomic')] : []), ...(commands.some(c => c.newOid === ZERO_OID) ? [requestCap('delete-refs')] : []), ...(checked !== null && checked.pushOptions.length > 0 ? [requestCap('push-options')] : []), `agent=${UA.replace(/ .*/u, '')}`]; // An untyped (JS) caller's atomic / pushOptions, which the type no longer has: refused rather than silently dropped. const unchecked = (o: unknown): boolean => { const atomic = field(o, 'atomic'); const options = flatMapOption(field(o, 'pushOptions'), p => field(p, 'length')); return (atomic.tag === 'some' && atomic.value === true) || (options.tag === 'some' && Number(options.value) > 0); }; // Each object's base, checked before anything is built (pack.ts buildPack checks none): an OFS_DELTA's is an earlier // object of the same pack, a REF_DELTA's an object id. A JavaScript caller's base outside the three tags, or the flag // fields the tagged base replaced (baseIndex, baseOid), is refused rather than ignored: a delta sent as a whole object // would be a corrupt pack. function checkBases(objects: readonly PackObject[]): Result> { for (const [i, obj] of objects.entries()) { const base = getOrElse(field(obj, 'base'), WHOLE); const tag = getOrElse(field(base, 'tag'), null); const flags = field(obj, 'baseIndex').tag === 'some' || field(obj, 'baseOid').tag === 'some'; if (flags || (tag !== 'none' && tag !== 'ofs' && tag !== 'ref')) return fail('bad_request', "push: an object's base is { tag: 'none' }, { tag: 'ofs', index } or { tag: 'ref', oid }", { what: 'base', got: flags ? 'baseIndex/baseOid' : tag }); const index = getOrElse(field(base, 'index'), null); if (tag === 'ofs' && !(typeof index === 'number' && Number.isInteger(index) && index >= 0 && index < i)) return fail('bad_request', 'push: an ofs base must name an earlier object', { what: 'base', got: index }); if (tag === 'ref' && !parseOid(getOrElse(field(base, 'oid'), null)).ok) return fail('bad_request', 'push: a ref base must be an object id', { what: 'base', got: getOrElse(field(base, 'oid'), null) }); } return ok(null); } // Each object once: the one place every producer's list passes (commitChanges, pushTree, merge, rebase, editFile, a // caller's own). A pack that holds one object twice is refused by a strict receiver: git index-pack --strict says // "The same object appears twice in the pack", unpack-objects --strict "tried to add buffer twice!", and // receive-pack reports either as "unpacker error" (git 2.50). Two whole objects are one object when type and bytes // are equal, so only objects that share a type, a length and a fingerprint (below) with another are hashed, each at // most once, and two are one object when their ids are equal; a list with no such pair costs a fingerprint (at most // 256 bytes read) and a map insert per object and no SHA-1. The first of a pair is kept, in its place, and an // ofs base index is renumbered to the kept list (a base that was a repeat becomes the kept copy, which is earlier). // A delta entry is kept as given: its object id is not known without applying it. Runs in send, on a list planPush // passed (checkBases), before the pack is measured. // FNV-1a (32 bits) over at most FINGERPRINT_RUNS runs of FINGERPRINT_RUN bytes, evenly spaced from the first run to // the last: every byte of an object no longer than that. Runs, not single bytes at a stride: data with a period (a // record layout, a generator's low byte) is the same at every stride and differs inside a run. Equal bytes give equal // fingerprints; it decides only which objects are hashed, never which are equal. const FINGERPRINT_RUNS = 32; const FINGERPRINT_RUN = 8; const FNV_OFFSET = 0x81_1c_9d_c5; const FNV_PRIME = 0x01_00_01_93; const fingerprint = (data: Uint8Array): number => { const whole = data.length <= FINGERPRINT_RUNS * FINGERPRINT_RUN; const runs = whole ? 1 : FINGERPRINT_RUNS; const run = whole ? data.length : FINGERPRINT_RUN; // the last run ends at the object's end const spread = (data.length - run) / Math.max(1, runs - 1); let h = FNV_OFFSET; for (let r = 0; r < runs; r++) { const start = Math.floor(r * spread); // oxlint-disable-next-line typescript/no-unsafe-type-assertion, typescript/non-nullable-type-assertion-style -- start + run <= data.length: the read is in range (`as`, not the `!` src/ forbids) for (let i = start; i < start + run; i++) h = Math.imul(h ^ (data[i] as number), FNV_PRIME); } return h >>> 0; }; function oncePerObject(objects: readonly PackObject[]): readonly PackObject[] { const buckets = new Map | null }>(); const out: PackObject[] = []; const keptAt: number[] = []; for (const [i, obj] of objects.entries()) { const base = inputBase(obj); const name = typeNameOf(obj.type); if (base.tag !== 'none' || name === null || !(obj.data instanceof Uint8Array)) { keptAt.push(out.length); out.push(base.tag === 'ofs' && out.length !== i ? { ...obj, base: { tag: 'ofs', index: atOr(keptAt, base.index, base.index) } } : obj); continue; } const key = `${obj.type}:${obj.data.length}:${fingerprint(obj.data)}`; const bucket = mapGet(buckets, key); if (bucket.tag === 'none') { buckets.set(key, { first: out.length, byOid: null }); keptAt.push(out.length); out.push(obj); continue; } const held = bucket.value; const firstObj = at(out, held.first); const byOid = held.byOid === null ? new Map(firstObj.tag === 'some' ? [[hashObject(name, firstObj.value.data), held.first]] : []) : held.byOid; held.byOid = byOid; const oid = hashObject(name, obj.data); const seen = mapGet(byOid, oid); if (seen.tag === 'some') { keptAt.push(seen.value); continue; } byOid.set(oid, out.length); keptAt.push(out.length); out.push(obj); } return out.length === objects.length ? objects : out; } // limits: the transport's (checked), or a caller's record (any subset, a key left out is the default; null is the defaults). export function planPush(o: PushOptions, limits: LimitsInput | null): Result { const checkedLimits = parseLimits(limits); if (!checkedLimits.ok) return checkedLimits; const { maxRefs, maxReportLines, maxReportReasonBytes, maxReportProgressBytes, maxPackBytes } = checkedLimits.value; const cfg = withDefaults(o, pushDefaults()); if (cfg.checked === null && unchecked(o)) return fail('bad_request', 'push: unchecked atomic or push options'); // the single-ref form's fields may be missing (null ref, '' oids): parseCommand refuses them as it refuses any other const raw: readonly RawCommand[] = cfg.commands === null ? [{ ref: cfg.ref, oldOid: cfg.oldOid, newOid: cfg.newOid }] : cfg.commands; if (raw.length > maxRefs) return err(limitExceeded('push commands', raw.length, maxRefs)); const parsed = parseEach(raw); if (!parsed.ok) return parsed; const bases = checkBases(cfg.objects); if (!bases.ok) return bases; // each option parsed once into the plan; the request body writes the parsed ones const pushOptions: WireField[] = []; for (const p of cfg.checked === null ? [] : cfg.checked.pushOptions) { const option = validateWire(p, 'push option'); if (!option.ok) return option; pushOptions.push(option.value); } // last, as before: every other refusal comes first for an empty list const listed = nonEmpty(parsed.value); if (!listed.ok) return listed; const commands = listed.value; return ok({ commands, caps: requestCaps(commands, cfg, cfg.checked), checked: cfg.checked, pushOptions, needPack: commands.some(c => c.newOid !== ZERO_OID), maxReportLines, maxReportReason: maxReportReasonBytes, maxReportProgress: maxReportProgressBytes, maxPack: maxPackBytes, objects: cfg.objects, sideband: cfg.sideband }); } // The request body: commands, flush, then (push-options) the options and another flush, then the pack. const requestBody = (plan: PushPlan, pack: Uint8Array | null): Result, ErrorOf<'bad_request'>> => { const options = plan.pushOptions; if (options.length === 0) return pushBody(plan, pack); const head = pushBody(plan); if (!head.ok) return head; const framed = pkts(options.map(p => `${p}\n`)); return framed.ok ? ok(concat([head.value, ...framed.value, FLUSH, ...(pack ? [pack] : [])])) : framed; }; // The report's line cap: limits.maxReportLines, but never fewer lines than git sends for the commands pushed (one unpack // line, then one status per command; report-status-v2 adds up to four option lines a ref: refname, old-oid, new-oid, // forced-update), so a push maxRefs allows is never cut off by its own honest report (#144: maxRefs commands read // maxRefs + 1 lines). A larger cap is for a proc-receive hook that reports one command as several refs. export const REPORT_V2_OPTION_LINES = 4; const honestReportLines = (plan: Pick): number => 1 + plan.commands.length * (plan.caps.includes('report-status-v2') ? 1 + REPORT_V2_OPTION_LINES : 1); export const reportLineCap = (plan: Pick): number => Math.max(plan.maxReportLines, honestReportLines(plan)); // The bytes kept of one reason: limits.maxReportReasonBytes, but never fewer than git's own longest status or reason, so // a reason git writes is never cut and its class (ngClass, isGitUnpackError) is read from the whole of it. const GIT_REASON_BYTES = Math.max(...[...GIT_UNPACK_ERROR_LIST, ...KNOWN_NG, UNPACKER_ERROR].map(s => s.length)); export const reportReasonCap = (plan: Pick): number => Math.max(plan.maxReportReason, GIT_REASON_BYTES); // One report line with its reason ("ng ") or status ("unpack ") cut to its first `max` bytes. A cap // bounds what is kept, never the outcome: the line is cut only when it is one reportStep reads whole (it ends in LF and // the reason is printable ASCII to its end, so a character is a byte), and any other line is returned as it came, for // reportStep to refuse as it always did. The copy drops the frame the line arrived in. export const cutReportLine = (line: Uint8Array, max: number): Uint8Array => { if (line.length - NG_REF.length - 1 <= max) return line; const text = decodeBytes(line); let start = 0; if (text.startsWith(UNPACK)) start = UNPACK.length; else if (text.startsWith(NG_REF)) start = text.indexOf(' ', NG_REF.length) + 1; const reason = text.slice(start, text.length - 1); if (start === 0 || reason.length <= max || !text.endsWith('\n') || !PRINTABLE.test(reason)) return line; return concat([line.subarray(0, line.length - 1 - reason.length + max), line.subarray(line.length - 1)]); }; // The reason of an "ng " line as it came, before any cut (reportStep's split: a ref holds no space). const wholeReason = (line: Uint8Array): string => { const text = decodeBytes(line); return text.slice(text.indexOf(' ', NG_REF.length) + 1, text.length - 1); }; // The report as the read classifies it: reportStep's state, the unpack status whole (at most one pkt-line, held for this // read only), whether it was cut, and whether a line beside a cut is not that status repeated. type Classifying = { report: ReportState; status: string; statusCut: boolean; cutNoEcho: boolean }; // Classifies lines[from..] once, where they lie: only a line over the cap is replaced, by its cut copy. The echo // (echoedFailure) is read from the whole lines, before the cut: where the unpack status or a ref's reason is cut, // anything but the status repeated whole is no unpack failure, however the kept parts compare. function classifyNew(c: Classifying, lines: Uint8Array[], from: number, max: number): void { let { report } = c; for (let i = from; i < lines.length; i += 1) { const whole = lines[i]; // Stryker disable next-line ConditionalExpression: unreachable, i < lines.length if (isMissing(whole)) break; const line = cutReportLine(whole, max); if (i === 0) { const text = decodeBytes(whole); c.status = text.slice(UNPACK.length, text.length - 1); c.statusCut = line !== whole; } else if ((c.statusCut || line !== whole) && wholeReason(whole) !== c.status) c.cutNoEcho = true; if (line !== whole) lines[i] = line; report = reportStep(report, line); } c.report = report; } // An unpack failure read only because a cut made two different lines agree is none: whole, that report is not git's. const classified = (c: Classifying): ReportShape => { const shape = reportFinish(c.report); return c.cutNoEcho && shape.tag === 'unpackFailed' ? malformed('no git unpack line first') : shape; }; // A band-2 frame past limits.maxReportProgressBytes, as the stream reads it: its place in the answer, none of its text. const PROGRESS_DROPPED: Frame = { kind: 'data', payload: Uint8Array.of(SIDEBAND_PROGRESS) }; // The read, the platform edge: whatever the transport throws (network, HTTP status, framing) and our own limits on the // response end the read as `lost`; the stream otherwise ends as a report or broken. `reading` is the last reading state. // `answered`: a frame of receive-pack's answer was read before the failure (false: the exchange failed at its status line). // `shape`: the report as the read classified it, line by line (decide() does not classify it again). type Read = { readonly done: Broken | StreamReport; readonly shape: ReportShape | Broken; readonly reading: Reading } | { readonly cause: unknown; readonly answered: boolean }; // An HTTP refusal of the receive-pack request itself (401/403: receive-pack disabled or not for this credential; 404: no // such repository), seen before any frame of its answer. git's http-backend decides that at the status line, before it // runs receive-pack (http.receivepack false is a 403), but the request body was sent, and a middlebox that forwarded // it and rewrote the status would look the same. So the refusal stands only when the service refuses its advertisement // (GET info/refs?service=git-receive-pack) with the same code: then receive-pack is not there for this caller and the // ref did not move, and the push is that error, not 'ambiguous' (#144). Anything else stays 'ambiguous'. const NOT_RUN: ReadonlySet = new Set(['auth', 'not_found']); const codeOf = (e: unknown): unknown => getOrElse(field(e, 'code'), null); export const refusedBeforeReceivePack = (r: { readonly cause: unknown; readonly answered: boolean }): boolean => !r.answered && NOT_RUN.has(codeOf(r.cause)); async function serviceRefused(t: PushTransport, span: Span, cause: unknown): Promise { try { const ad = await t.advertise('git-receive-pack', span); return !ad.ok && ad.error.code === codeOf(cause); } catch { return false; } // a transport that cannot advertise confirms nothing } async function readResponse(t: PushTransport, plan: PushPlan, body: RequestBody, span: Span, sideband: boolean): Promise { let reportBytes = 0; let reading = streamInit(sideband); let st: StreamState = reading; let lost: { readonly cause: unknown } | null = null; let answered = false; const maxLines = reportLineCap(plan); // The answer is classified as its lines arrive: the read ends, and leaving the loop cancels the response body, the // moment the report cannot be git's (its first line is not an unpack line, a status for a ref not commanded or // already answered). So what is kept is at most one line a command, its reason cut at reportReasonCap, and band 2's // tail; what is read is held to maxPackBytes (keepalives and band 2 with it) and the transport's timers. A limit here // ends the read only when the report itself cannot be read inside it (report bytes, report lines). const reasonCap = reportReasonCap(plan); let progressBytes = 0; const report: Classifying = { report: reportInit(plan.commands), status: '', statusCut: false, cutNoEcho: false }; let unreadable = false; let fed = 0; try { for await (const f of frames(t, 'git-receive-pack', body, span)) { answered = true; const size = f.kind === 'data' ? f.payload.length : 0; reportBytes += size; if (reportBytes > plan.maxPack) { lost = { cause: limitExceeded('report bytes', reportBytes, plan.maxPack) }; break; } let kept = f; if (sideband && f.kind === 'data' && f.payload[0] === SIDEBAND_PROGRESS) { progressBytes += size; if (progressBytes > plan.maxReportProgress) kept = PROGRESS_DROPPED; } const stepped = streamStep(st, kept); if (!stepped.ok) { lost = { cause: stepped.error }; break; } st = stepped.value; // Stryker disable next-line ConditionalExpression: a broken state has no lines, so reading on fails the read: ambiguous either way if (st.tag !== 'reading') break; reading = st; const { lines } = st; if (lines.length > maxLines) { lost = { cause: limitExceeded('report lines', lines.length, maxLines) }; break; } classifyNew(report, lines, fed, reasonCap); fed = lines.length; unreadable = report.report.tag === 'malformed'; if (unreadable) break; } } catch (e) { lost = { cause: e }; } if (lost !== null) return { ...lost, answered }; // a report that cannot be git's is that report, as far as it was read const done: Broken | StreamReport = unreadable ? { tag: 'report', lines: reading.lines } : streamFinish(st); return { done, shape: done.tag === 'report' ? classified(report) : done, reading }; } // The span's view of the outcome, from the classified report (no second parser). const unpackOf = (report: PushReport | null): string => { if (report === null) return ''; return report.tag === 'statuses' ? 'ok' : report.status; }; const outcomeAttrs = (done: Broken | StreamReport, report: PushReport | null, outcome: Outcome, band2Frames: number, band2: string): Record => { const refs = report === null ? [] : report.refs; return { 'git.push.report.lines': done.tag === 'report' ? done.lines.slice(0, REPORT_KEEP).map(p => decodeBytes(p).replace(/\n$/u, '')) : [], 'git.push.unpack': unpackOf(report), 'git.push.ok': outcome.tag === 'landed', 'git.push.outcome': outcome.tag, 'git.push.ng.reason': getOrElse(mapOption(fromNullish(refs.find(x => !x.ok)), x => x.reason), ''), 'git.push.band2.frames': band2Frames, 'git.push.band2.tail': remoteText(band2.slice(-BAND_ATTR), BAND_ATTR), 'git.push.remote.messages': bandLines(band2), 'git.push.refs.ok': refs.filter(x => x.ok).length, 'git.push.refs.ng': refs.filter(x => !x.ok).length, }; }; // git.object.type for a built entry: its name, or the type id in decimal for an id a caller passed that names no type // (pack.ts typeNameOf), so the attribute is never otel.ts's null-as-empty-string. const objectTypeAttr = (e: PackEntry): string => getOrElse(fromNullish(e.typeName), String(e.type)); // The request body: the bytes (no pack, or a pack pass 1 kept), or the commands then pass 2 of the pack as a stream. type Body = { readonly body: RequestBody; readonly streamed: StreamedPack | null }; const bodyOf = (plan: PushPlan, packed: MeasuredPack | null): Result> => { const bytes = requestBody(plan, packed === null ? null : packed.held); if (!bytes.ok || packed === null || packed.held !== null) return bytes.ok ? ok({ body: bytes.value, streamed: null }) : bytes; const streamed = streamPack(packed, bytes.value); return ok({ body: streamed, streamed }); }; // After a sideband band-3 report (often empty under Artifacts), a single-ref update can still be named: read the tip. // At our newOid → the push landed (report lost). Anywhere else → cas_conflict (lost the CAS / refused). // Multi-ref and deletes stay ambiguous: the tip alone does not name which command acted. Observed 2026-11-08 on // Cloudflare Artifacts under a same-ref race (phase6 F34): band 3 + empty report → was HTTP 502 `ambiguous`. // finishPush gates on isEmptyBand3Ambiguous so non-empty band 3 / cut / drop / verify stay ambiguous. async function resolveAmbiguousByTip(t: PushTransport, span: Span, plan: PushPlan, ambiguous: PlyError): Promise | null> { if (plan.commands.length !== 1) return null; const [cmd] = plan.commands; if (cmd.newOid === ZERO_OID) return null; const read: Result = await lsRefs(t, [String(cmd.ref)]).then(r => r, (e: unknown) => err(e)); if (!read.ok) { span.set({ 'git.push.ambiguous.resolved': 'unread' }); return null; } const tip = mapGet(read.value.refs, String(cmd.ref)); const seen = tip.tag === 'some' ? tip.value.oid : null; const landed = seen === cmd.newOid; span.set({ 'git.push.verify.ref': seen === null ? '' : seen, 'git.push.ambiguous.resolved': landed ? 'landed' : 'cas_conflict' }); if (landed) { span.set({ 'git.push.ok': true, 'git.push.outcome': 'landed', 'git.push.ng.reason': '' }); return ok({ tag: 'statuses', refs: [{ ref: String(cmd.ref), ok: true as const, reason: '' as const }] }); } span.set({ 'git.push.ok': false, 'git.push.outcome': 'rejected', 'git.push.ng.reason': 'stale ref' }); return fail('cas_conflict', 'push rejected: stale ref', { expected: cmd.oldOid === ZERO_OID ? null : cmd.oldOid, actual: seen, cause: ambiguous, original: 'ambiguous' }); } type FinishPush = { readonly t: PushTransport; readonly span: Span; readonly plan: PushPlan; readonly packBytes: number; readonly entries: readonly PackEntry[]; readonly hookOutput: string; }; // Tip read-back is only for empty sideband band 3 (Artifacts race: no report-status lines). // Band 3 with a remote message (credential echo, fatal text), cuts, drops, and forged-ok verify // stay ambiguous: cas_conflict would trigger edit's one retry and mis-name those outcomes. function isEmptyBand3Ambiguous(e: PlyError): boolean { // outcomeResult embeds why as: `push outcome unknown: remote: ${remote}: band 3` // empty remote (Artifacts) → trailing `remote: : band 3`. return e.code === 'ambiguous' && e.message.endsWith('remote: : band 3'); } async function finishPush(ctx: FinishPush, res: Result): Promise> { const { t, span, plan, packBytes, entries, hookOutput } = ctx; if (res.ok) return ok({ report: res.value, packBytes, entries, hookOutput }); if (!isEmptyBand3Ambiguous(res.error)) return res; const resolved = await resolveAmbiguousByTip(t, span, plan, res.error); if (resolved === null) return res; if (resolved.ok) return ok({ report: resolved.value, packBytes, entries, hookOutput }); return resolved; } // The answer to a request whose body went out: `cut` is the body's own failure, whatever the server said. async function decide(base: FinishPush, r: Read, cut: PlyError | null): Promise> { const { t, span, plan } = base; // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ambiguousAfterPush of a PlyError is a PlyError if (cut !== null) return finishPush(base, err(ambiguousAfterPush(cut) as PlyError)); if ('cause' in r) { const notRun = refusedBeforeReceivePack(r) && await serviceRefused(t, span, r.cause); // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- refused: the cause carries one of ply's codes (a PlyError); else ambiguousAfterPush returns one (the cause itself when it already is an 'ambiguous' one) if (notRun) return err(r.cause as PlyError); // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- ambiguousAfterPush returns a PlyError return finishPush(base, err(ambiguousAfterPush(r.cause) as PlyError)); } const { done, shape, reading } = r; const band2 = reading.band2Carry.length > 0 ? (reading.band2 + td.decode(reading.band2Carry)).slice(-BAND_TAIL) : reading.band2; const outcome = decideOutcome(shape, { atomic: plan.checked !== null && plan.checked.atomic, pack: plan.needPack }); const report = shape.tag === 'malformed' || shape.tag === 'broken' ? null : shape; span.set(outcomeAttrs(done, report, outcome, reading.band2Frames, band2)); if (outcome.tag === 'ambiguous') span.set({ 'git.push.ambiguous': outcome.why }); const res = outcomeResult(outcome, { report, hookOutput: band2, remote: shape.tag === 'broken' ? shape.remote : null, commands: plan.commands }, t.scrub); return finishPush({ ...base, hookOutput: band2 }, res); } // The send, inside the span: measure the pack, refuse an oversized one before the first byte, send, read, decide. async function send(t: PushTransport, plan: PushPlan, span: Span): Promise> { // each object once (oncePerObject), here and not in planPush: under the span, where an entry that cannot be read is // the push's 'protocol' error as it is when the pack writer reads it const packed = plan.needPack ? await measurePack(oncePerObject(plan.objects)) : null; const entries: readonly PackEntry[] = packed === null ? [] : packed.entries; const packBytes = packed === null ? 0 : packed.bytes; span.set({ 'git.push.pack.bytes': packBytes, 'git.push.pack.objects': entries.length, 'git.push.pack.thin': entries.some(e => Boolean(e.baseOid)), 'git.push.pack.compressed.bytes': entries.reduce((a, e) => a + e.compressed, 0), 'git.push.pack.raw.bytes': entries.reduce((a, e) => a + e.size, 0) }); for (const [i, e] of entries.entries()) span.event('git.push.object', { 'git.object.index': i, 'git.object.type': objectTypeAttr(e), 'git.object.size': e.size, 'git.object.compressed': e.compressed, 'git.object.base.oid': getOrElse(fromNullish(e.baseOid), ''), 'git.object.bytes': e.bytes }); // Refuse before the first byte is sent: a host with a push cap (Artifacts: 64 MiB of request body) would otherwise take the whole // upload and answer 4xx. The measured size is the pack as pass 1 wrote it, so `got` is what the server would have // received; pass 2 never sends more (packwrite.ts). if (packBytes > plan.maxPack) return err(limitExceeded('push pack bytes', packBytes, plan.maxPack)); // The request body (commands + pack) is on the wire from here. Every failure — transport, HTTP status, framing, // band 3, a limit — and every report that is not exactly git's is 'ambiguous': the ref may have moved. The one // exception is the server refusing the service itself (refusedBeforeReceivePack, confirmed by its advertisement). const body = bodyOf(plan, packed); if (!body.ok) return body; // The caller's signal had fired before the request: none is made, so this is the definite 'aborted' (or 'timeout', // by the signal's reason), not 'ambiguous'. const signal = getOrElse(field(t, 'signal'), null); if (signal instanceof AbortSignal && signal.aborted) return err(wrapNet(signal.reason, signal)); const r = await readResponse(t, plan, body.value.body, span, plan.sideband); // The exchange failed with no answer and the transport never pulled the streamed body: the command list did not // leave this process, so no ref can have moved, and the failure is its own cause, not 'ambiguous'. A body handed // over as bytes cannot be seen leaving or not, so it stays under the rule above. const { streamed } = body.value; if ('cause' in r && !r.answered && streamed !== null && !streamed.pulled()) return err(wrapNet(r.cause, signal instanceof AbortSignal ? signal : null)); // pass 2 refused to finish the pack: whatever the server answered (workerd ends an errored body as if it were whole), // it was not sent the pack that was measured const cut = streamed === null ? null : streamed.failure(); return decide({ t, span, plan, packBytes, entries, hookOutput: '' }, r, cut); } // The request under its span (push and pushPackChecked, below, are the entries). const receiveSpan = (t: PushTransport, { commands, caps }: PushPlan): SpanOpts => { const [first] = commands; return clientSpan(t, { 'git.command': 'receive-pack', 'git.protocol.version': 0, 'git.push.commands': commands.map(c => `${c.oldOid.slice(0, SHORT_OID)} ${c.newOid.slice(0, SHORT_OID)} ${c.ref}`), 'git.push.caps': caps, 'git.push.ref': first.ref, 'git.push.old': first.oldOid, 'git.push.new': first.newOid }); }; // oxlint-disable-next-line eslint/require-await -- async, as push was async function receivePack(t: PushTransport, plan: PushPlan, run: (span: Span) => Promise>): Promise> { // oxlint-disable-next-line typescript/promise-function-async -- the exchange's promise, passed through (an async wrapper adds bytes, not behaviour) return coded('protocol', () => spanned(t, 'git.receive-pack', receiveSpan(t, plan), run)); } // The effect. A refusal before the request (planPush) is an Err with no span; everything after is under the span, whose // error is the PlyError the Result carries. // oxlint-disable-next-line typescript/promise-function-async -- receivePack's promise, returned as is export function push(t: PushTransport, opts: PushOptions): Promise> { const plan = planPush(opts, t.limits); if (!plan.ok) return Promise.resolve(plan); // oxlint-disable-next-line typescript/promise-function-async -- send's promise, returned as is return receivePack(t, plan.value, span => send(t, plan.value, span)); } // ---- a pack the caller already has (#234) ---- // `pack` is a complete pack: header, entries, trailer. It is read once and never retried. A refusal here leaves it // unread and unlocked, and so does a request that failed before the transport pulled the body's first chunk (a signal // already fired, a connect or DNS failure): that is the failure itself, definite. From the first pull the pack is // spent, and every failure is 'ambiguous'. // `length` is the pack's own length, without the commands, when the caller knows it (default null). It is checked against // maxPackBytes before anything is sent and against the bytes as they go. The request is chunked either way. export type PackPushOptions = Input & { readonly length: number | null }> & { readonly pack: ReadableStream }; export type PackPushPlan = { readonly plan: PushPlan; readonly pack: ReadableStream; readonly length: number | null }; const isPackLength = (n: unknown): n is number | null => n === null || (typeof n === 'number' && Number.isSafeInteger(n) && n >= 0); // Pure: every refusal happens with nothing read and nothing on the wire. export function planPackPush(o: PackPushOptions, limits: LimitsInput | null): Result { if (field(o, 'objects').tag === 'some') return fail('bad_request', 'pushPack: takes a pack, not objects', { what: 'objects' }); const pack = getOrElse(field(o, 'pack'), null); if (!(pack instanceof ReadableStream) || pack.locked) return fail('bad_request', 'pushPack: pack must be an unlocked ReadableStream', { what: 'pack' }); const planned = planPush(o, limits); if (!planned.ok) return planned; if (!planned.value.needPack) return fail('bad_request', 'pushPack: a push of only deletes sends no pack', { what: 'pack' }); const length = getOrElse(field(o, 'length'), null); if (!isPackLength(length)) return fail('bad_request', 'pushPack: length must be a non-negative integer', { what: 'length', got: length }); if (length !== null && length > planned.value.maxPack) return err(limitExceeded('push pack bytes', length, planned.value.maxPack)); // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the guard above checked the stream; its chunks are checked as they are read (packwrite.ts streamSource) return ok({ plan: planned.value, pack: pack as ReadableStream, length }); } // Whether the push request left this process, beside what it came to (#272): the one fact a PushResult cannot carry. // `sent: 'no'` is a refusal before the request, or a request that failed before the transport pulled the body's first // chunk (a signal already fired, a connect or DNS failure, an HTTP answer with the body unpulled): receive-pack never // got the command list, so no ref can have moved. `sent: 'yes'` is the request and whatever it came to, 'ambiguous' // from the first pull. transfer.ts reads this, never the error's code. export type PackPushOutcome = | { readonly sent: 'no'; readonly result: Err } | { readonly sent: 'yes'; readonly result: Result }; const unsent = (result: Err): PackPushOutcome => ({ sent: 'no', result }); async function sendSource(t: PushTransport, p: PackPushPlan, span: Span): Promise { const { plan } = p; const prefix = requestBody(plan, null); if (!prefix.ok) return unsent(prefix); // The caller's signal had fired before the send: no request is made and the pack is not locked, read or cancelled, // so this is the definite 'aborted' (or 'timeout', by the signal's reason), not 'ambiguous'. const signal = getOrElse(field(t, 'signal'), null); if (signal instanceof AbortSignal && signal.aborted) return unsent(err(wrapNet(signal.reason, signal))); const body = streamSource(p.pack, prefix.value, p.length, plan.maxPack); const r = await readResponse(t, plan, body, span, plan.sideband); // The exchange failed with no answer and the transport never pulled the body: the command list did not leave this // process, so no ref can have moved. The failure is its own cause (network, aborted, timeout, or the code of an HTTP // answer that came with the body still unpulled: auth, not_found, rate_limited, upstream_5xx, http, not_git), not 'ambiguous', and // the pack goes back to the caller unread, unlocked and uncancelled. 'ambiguous' starts at the first pull. if ('cause' in r && !r.answered && !body.pulled()) { body.giveBack(); return unsent(err(wrapNet(r.cause, signal instanceof AbortSignal ? signal : null))); } // read before release: abandoning the rest of a pack the server already answered is not a failure of the pack const cut = body.failure(); await body.release(); const packBytes = body.sent(); const requestBytes = prefix.value.length + packBytes; span.set({ 'git.push.pack.bytes': packBytes, 'git.request.bytes': requestBytes, 'http.request.body.size': requestBytes }); return { sent: 'yes', result: await decide({ t, span, plan, packBytes, entries: [], hookOutput: '' }, r, cut) }; } // The effect, for `checked` caps (pushPack in receivecaps.ts reads them from the advertisement), with whether the // request was sent. The span is push's: its error is the Err the outcome carries; a raise (a transport the caller handed // in) is 'protocol' and counts as sent, since nothing says the body was not pulled. export async function pushPackChecked(t: PushTransport, opts: PackPushOptions): Promise { const p = planPackPush(opts, t.limits); if (!p.ok) return unsent(p); // the outcome's Err is the span's error; receivePack's Err (a raise) is recorded by the tracer const r = await receivePack(t, p.value.plan, async (span: Span): Promise> => { const o = await sendSource(t, p.value, span); if (!o.result.ok) span.error(o.result.error); return ok(o); }); return r.ok ? r.value : { sent: 'yes', result: r }; }