fix(logging): retain safe ZIP and worker failure reasons

This commit is contained in:
Thomas Durieux committed 2026-11-19 15:04:03 +00:00
1 parent 7841201ad1
commit b284bfb4f9
12 files changed
+145 -15

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
// Only fixed codes cross the worker boundary; source text and OS paths never do.
export const ANONYMIZATION_ERRORS = [
"anonymized_output_too_large", "anonymization_memory_budget_exceeded",
"anonymization_queue_full", "anonymization_queue_timeout", "anonymization_cancelled",
"anonymization_worker_exited", "anonymization_deadline_exceeded",
"anonymization_spool_budget_exceeded", "anonymization_worker_failed",
"anonymization_storage_full", "anonymization_io_failed",
] as const;
export function anonymizationErrorCode(error: unknown): string {
const data = (key: string) => {
try { const p = Object.getOwnPropertyDescriptor(error, key); return p && "value" in p ? p.value : undefined; }
catch { return undefined; }
};
const message = data("message"), code = data("code");
if (typeof message === "string" && (ANONYMIZATION_ERRORS as readonly string[]).includes(message)) return message;
if (code === "ERR_SCRIPT_EXECUTION_TIMEOUT" || code === "ERR_WORKER_OUT_OF_MEMORY") {
return code === "ERR_SCRIPT_EXECUTION_TIMEOUT" ? "anonymization_deadline_exceeded" : "anonymization_memory_budget_exceeded";
}
if (code === "ENOSPC") return "anonymization_storage_full";
if (["EIO", "ENOENT", "EACCES", "EMFILE", "ENFILE"].includes(code)) return "anonymization_io_failed";
return "anonymization_worker_failed";
}
+7 -5
View File
@@ -1,3 +1,4 @@
import { anonymizationErrorCode } from "./anonymization-errors";
import { Worker } from "worker_threads";
import { existsSync } from "fs";
import { join } from "path";
@@ -31,18 +32,19 @@ export function anonymizeOnWorker(message: Job["message"], size: number, signal:
// Bind the stage factory to the submitting request, not the preceding job.
const transformDone = AsyncResource.bind(() => startStage("anonymize"));
const job: Job = { message, weight, signal, resolve, reject, waitingDone, transformDone };
job.abort = () => {
const removeWaiting = (code: string) => {
const index = waiting.indexOf(job);
if (index < 0) return;
waiting.splice(index, 1);
clearTimeout(job.timer);
signal.removeEventListener("abort", job.abort!);
waitingDone(true);
reject(new Error("anonymization_cancelled"));
reject(new Error(code));
};
job.abort = () => removeWaiting("anonymization_cancelled");
if (signal.aborted) { waitingDone(true); return reject(new Error("anonymization_cancelled")); }
signal.addEventListener("abort", job.abort, { once: true });
job.timer = setTimeout(job.abort, 30_000);
job.timer = setTimeout(() => removeWaiting("anonymization_queue_timeout"), 30_000);
waiting.push(job);
pump();
});
@@ -81,8 +83,8 @@ function pump() {
} else { idle.push(worker); worker.unref(); release(); }
if (error) job.reject(error); else job.resolve(changed);
};
const message = (result: { error?: string; changed?: boolean }) => finish(result.error ? new Error(result.error) : undefined, result.changed);
const failed = (error: Error) => finish(error);
const message = (result: { error?: string; changed?: boolean }) => finish(result.error ? new Error(anonymizationErrorCode({ message: result.error })) : undefined, result.changed);
const failed = (error: Error) => finish(new Error(anonymizationErrorCode(error)));
const exited = () => finish(new Error("anonymization_worker_exited"));
const cancel = () => finish(new Error("anonymization_cancelled"));
const deadline = setTimeout(() => finish(new Error("anonymization_deadline_exceeded")), 15_000);
+2 -1
View File
@@ -1,3 +1,4 @@
import { anonymizationErrorCode } from "./anonymization-errors";
import config from "../config";
import { parentPort } from "worker_threads";
import { readFileSync, writeFileSync } from "fs";
@@ -21,6 +22,6 @@ parentPort!.on("message", ({ input, output, options, maxOutput, context }) => {
writeFileSync(output, bytes, { flag: "wx" });
parentPort!.postMessage({ changed: anonymizer.wasAnonymized });
} catch (error) {
parentPort!.postMessage({ error: (error as Error).message });
parentPort!.postMessage({ error: anonymizationErrorCode(error) });
}
});
+16 -2
View File
@@ -326,6 +326,16 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"repositoryMembership",
"toJSON"
],
"src/core/anonymization-errors.ts": [
"<anonymous>",
"anonymizationErrorCode",
"data"
],
"build/core/anonymization-errors.js": [
"<anonymous>",
"anonymizationErrorCode",
"data"
],
"src/core/anonymization-pool.ts": [
"<anonymous>",
"anonymizeOnWorker",
@@ -338,6 +348,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"pump",
"release",
"releaseSpool",
"removeWaiting",
"reserveSpool"
],
"build/core/anonymization-pool.js": [
@@ -352,6 +363,7 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
"pump",
"release",
"releaseSpool",
"removeWaiting",
"reserveSpool"
],
"src/core/anonymization.worker.ts": [
@@ -1038,11 +1050,13 @@ export const LOG_SOURCE_FUNCTIONS: Record<string, readonly string[]> = {
],
"src/core/log-memory.ts": [
"<anonymous>",
"logMemory"
"logMemory",
"memoryBreakdown"
],
"build/core/log-memory.js": [
"<anonymous>",
"logMemory"
"logMemory",
"memoryBreakdown"
],
"src/core/log-record.ts": [
"<anonymous>",
+10 -1
View File
@@ -1,4 +1,12 @@
import { readFile } from "fs/promises";
export function memoryBreakdown(used: number, max: number, stat: string) {
const fields = new Map(stat.trim().split("\n").map(line => line.trim().split(/\s+/) as [string, string]));
const file = Number(fields.get("file") ?? fields.get("total_cache"));
const inactive = Number(fields.get("inactive_file") ?? fields.get("total_inactive_file"));
if (!Number.isFinite(file) || !Number.isFinite(inactive) || file < 0 || inactive < 0) return {};
const working = Math.max(0, used - Math.min(used, inactive));
return { memoryFileCacheBytes: file, memoryWorkingSetBytes: working, memoryWorkingSetRatio: working / max };
}
/** Container usage includes sandbox workers and page cache; process RSS does not. */
export async function logMemory() {
const rss = process.memoryUsage().rss;
@@ -8,7 +16,8 @@ export async function logMemory() {
]) {
const [used, max] = await Promise.all([usage, limit].map(path => readFile(path, "utf8").then(Number).catch(() => NaN)));
if (Number.isFinite(used) && max > 0 && max < Number.MAX_SAFE_INTEGER) {
return { rss, memoryLimitBytes: max, memoryRatio: used / max };
const stat = await readFile(usage.replace(/memory\.(current|usage_in_bytes)$/, "memory.stat"), "utf8").catch(() => "");
return { rss, memoryUsedBytes: used, memoryLimitBytes: max, memoryRatio: used / max, ...memoryBreakdown(used, max, stat) };
}
}
return { rss };
+3 -2
View File
@@ -1,3 +1,4 @@
import { ANONYMIZATION_ERRORS } from "./anonymization-errors";
import { requestReproduction, safeReproductionPath } from "./log-reproduction";
import { safeDiagnosticFields, errorDiagnostics } from "./log-diagnostics";
import { LOG_ROUTES } from "./log-diagnostic-schema";
@@ -17,13 +18,13 @@ const events: Record<string, string> = {
"job failed": "job_failed", "job stalled": "job_stalled", "queue heartbeat": "queue_heartbeat",
};
const errorCodes = new Set([
...ERROR_CODES,
...ERROR_CODES, ...ANONYMIZATION_ERRORS, "zip_unsafe_entry_path",
"repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "token_refresh_failed", "quota_exceeded", "quota_repository_limit", "quota_storage_limit", "github_rate_limit_exceeded", "github_app_reconnect_required", "github_token_invalid",
"repository_expired", "repository_not_ready", "repository_not_found", "repository_job_cancelled",
"ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "ENOTFOUND", "EPIPE", "ABORT_ERR",
"upstream_error", "upstream_timeout", "invalid_signature", "webhook_processing_failed",
]);
export const LOG_NUMBERS = ["quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode","droppedLogsInterval","expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
export const LOG_NUMBERS = ["memoryUsedBytes", "memoryFileCacheBytes", "memoryWorkingSetBytes", "memoryWorkingSetRatio", "quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode","droppedLogsInterval","expectedBytes", "measuredMs", "unattributedMs", "overlapMs","status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond",
"attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed",
"oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus"];
export const LOG_STAGES = ["transfer", "database","repository", "credential_resolution", "upstream", "cache_lookup", "cache_fill", "worker_wait", "anonymize", "streamer_headers"];
+1 -1
View File
@@ -212,7 +212,7 @@ export async function streamAnonymizedZip(
if (entry.type === "File") {
try {
const relativePath = entry.path.substring(entry.path.indexOf("/") + 1);
if (!safeRepositoryPath(relativePath)) throw new AnonymousError("invalid_file_path", { httpStatus: 502 });
if (!safeRepositoryPath(relativePath)) throw new AnonymousError("zip_unsafe_entry_path", { httpStatus: 502 });
if (relativePath.split("/").pop() === ".gitmodules") { entry.autodrain(); return; }
if (prefix && ++childEntries > MAX_SUBMODULE_ENTRIES) throw new AnonymousError("file_too_big", { httpStatus: 413 });
const mountedPath = prefix ? `${prefix}/${relativePath}` : relativePath;