Merge pull request #976 from tdurieux/fix/zip-worker-diagnostics

fix(logging): explain ZIP and worker failures and memory pressure
This commit is contained in:
Thomas Durieux authored and GitHub committed 2026-11-20 17:53:09 -08:00
commit d34df81c8c
12 files changed
+145 -15

No files matched your search

+3 -3
View File
@@ -40,7 +40,7 @@ if service == "mongodb" {
if includes(["quota_denied", "deployment", "account_removed", "application_log", "billing_maintenance_failed", "billing_reconciliation_deferred", "billing_requires_attention", "billing_worker_failed", "blob_api_failed_falling_back_to_raw_url", "branch_not_found", "cache_removal_failed", "cache_removed", "checking_repository_status_and_unused_repositories", "cleared_lock_for_active_job", "conference_expire_failed", "content_expiration_failed", "daily_stats_snapshot_failed", "daily_stats_snapshot_stored", "download_completed", "download_start", "downloaded", "downloadfile_failed", "downloading_file", "downloading_gist", "downloading_pull_request", "downloading_via_raw_url_lfs", "duplicate_stripe_customer_requires_review", "ensuretodaysnapshot_failed", "error_log_redis_connect_failed", "expired_repository_cleanup_failed", "failed_removal_recovery_failed", "failed_to_persist_error_status", "failed_to_record_repository_removal_error", "gettoken", "github_primary_rate_limit_hit", "github_secondary_rate_limit_hit", "grant_revocation_failed", "initial_repository_status_check_failed", "job_completed", "job_failed", "job_stalled", "job_started", "lastusedat_update_failed", "login_token_failed", "login_token_req_login_failed", "logout_after_account_removal_failed", "logout_failed", "lookup_failed", "markerrorifinflight_failed", "markerrorifremoving_failed", "metadata_cleanup_complete", "metadata_cleanup_deferred", "owner_access_alert_reset_unavailable", "owner_access_email_accepted", "owner_access_email_audit_unavailable", "owner_access_email_claim_cleanup_unavailable", "owner_access_email_deferred_recovery_unavailable", "owner_access_email_delivery_failed", "owner_access_email_preparation_cleanup_unavailable", "owner_access_email_recovery_recorded", "owner_access_email_recovery_unavailable", "owner_access_email_result_reconciliation_required", "owner_access_email_unavailable", "pr_comments_404_continuing_without_them", "process_fatal_error", "process_heartbeat", "process_started", "progress", "queue_heartbeat", "queued_for_download", "rate_limit_gate_active_delaying_job_before_work", "rate_limit_gate_set", "rate_limited_delaying_job", "recover_failed", "recovered_expired_repository_cleanup", "recovered_file_from_truncated_tree", "recovered_file_invalidation_failed", "recovered_stuck_repo", "recoverstuckpreparing_failed", "recoverstuckremoving_failed", "redis_client_error", "redis_rate_limit_gate_written", "rejected_upstream_download_destination", "removal_failed", "removal_recovery_failed", "removecache_save_failed", "removed_cache_for_unused_repository", "removing_cache", "removing_repository", "repo_claimed", "repository_cache_removal_failed", "repository_expiration_failed", "repository_expired", "repository_removal_failed", "repository_removed", "request_cancelled", "request_completed", "request_slow", "requeued_failed_removal", "requeued_interrupted_removal", "reset", "retired_tree_cleanup_deferred", "retired_tree_cleanup_failed", "running_daily_stats_snapshot", "s3_body_stream_error", "send_failed", "server_started", "source_stream_failed_cache_write_discarded", "staged_tree_cleanup_failed", "staged_tree_completion_deferred", "streamer_fetch_failed", "streamer_started", "streamer_startup_failed", "streamer_zip_fetch_failed", "temporary_storage_cleanup_deferred", "token_refresh_failed_backing_off", "up_to_date", "update_queued", "verify_failed", "waiting_for_rate_limit_gate", "webhook_log", "webhook_processing_failed", "write_failed", "zip_stream_failed"], record.event) { out.event = record.event }
if is_string(record.release) && match(string!(record.release), r'^[a-f0-9]{7,40}$') { out.release = record.release }
if is_string(record.instance) && match(string!(record.instance), r'^[a-f0-9-]{36}$') { out.instance = record.instance }
if includes(["repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "commit_not_specified", "conf_end_date_invalid", "conf_end_date_missing", "conf_id_missing", "conf_id_used", "conf_name_missing", "conf_not_activated", "conf_not_found", "conf_start_date_invalid", "conf_start_date_missing", "conference_not_found", "connection_changed", "download_not_enabled", "expiration_limit_reached", "file_listing_too_large", "file_not_accessible", "file_not_found", "file_not_supported", "file_too_big", "folder_not_supported", "gistId_already_used", "gistId_not_specified", "gist_expired", "gist_not_found", "gist_not_ready", "github_app_access_required", "github_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "invalid_path", "invalid_plan", "invalid_preserve_files_format", "invalid_project_name", "invalid_pullRequestId", "invalid_repo", "invalid_repoId", "invalid_request", "invalid_settings", "invalid_signature", "invalid_sort", "invalid_status", "invalid_terms_format", "invalid_token_id", "invalid_token_options", "is_removed", "not_authorized", "not_connected", "options_not_provided", "page_not_activated", "page_not_supported_on_different_branch", "path_not_defined", "path_not_specified", "pullRequestId_already_used", "pullRequestId_is_not_a_number", "pullRequestId_not_specified", "pull_request_expired", "pull_request_not_found", "pull_request_not_ready", "token_refresh_failed", "quota_exceeded", "quota_repository_limit", "quota_storage_limit", "rate_limited", "readme_not_available", "repoId_already_used", "repoId_not_defined", "repoUrl_not_defined", "repo_access_limited", "repo_empty", "repo_not_accessible", "repo_not_found", "repo_saml_enforcement", "repository_archived", "repository_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "repository_not_ready", "repository_not_specified", "repository_tree_incomplete", "repository_tree_too_large", "s3_config_not_provided", "source_not_provided", "storage_delete_failed", "storage_write_size_mismatch", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed"], record.errorCode) { out.errorCode = record.errorCode }
if includes(["repo_renamed", "preparation_interrupted", "commit_not_found", "zip_not_available", "ABORT_ERR", "ECONNREFUSED", "ECONNRESET", "ENOTFOUND", "EPIPE", "ETIMEDOUT", "billing_address_missing", "billing_city_missing", "billing_country_missing", "billing_email_missing", "billing_missing", "billing_name_missing", "billing_zip_missing", "branch_not_found", "branch_not_specified", "cache_busy", "cache_miss", "cannot_coauthor_self", "commit_not_specified", "conf_end_date_invalid", "conf_end_date_missing", "conf_id_missing", "conf_id_used", "conf_name_missing", "conf_not_activated", "conf_not_found", "conf_start_date_invalid", "conf_start_date_missing", "conference_not_found", "connection_changed", "download_not_enabled", "expiration_limit_reached", "file_listing_too_large", "file_not_accessible", "file_not_found", "file_not_supported", "file_too_big", "folder_not_supported", "gistId_already_used", "gistId_not_specified", "gist_expired", "gist_not_found", "gist_not_ready", "github_app_access_required", "github_app_reconnect_required", "github_identity_mismatch", "github_rate_limit_exceeded", "github_token_invalid", "github_user_not_found", "invalid_commit_format", "invalid_cursor", "invalid_file_path", "invalid_gistId", "invalid_path", "invalid_plan", "invalid_preserve_files_format", "invalid_project_name", "invalid_pullRequestId", "invalid_repo", "invalid_repoId", "invalid_request", "invalid_settings", "invalid_signature", "invalid_sort", "invalid_status", "invalid_terms_format", "invalid_token_id", "invalid_token_options", "is_removed", "not_authorized", "not_connected", "options_not_provided", "page_not_activated", "page_not_supported_on_different_branch", "path_not_defined", "path_not_specified", "pullRequestId_already_used", "pullRequestId_is_not_a_number", "pullRequestId_not_specified", "pull_request_expired", "pull_request_not_found", "pull_request_not_ready", "token_refresh_failed", "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", "zip_unsafe_entry_path", "quota_exceeded", "quota_repository_limit", "quota_storage_limit", "rate_limited", "readme_not_available", "repoId_already_used", "repoId_not_defined", "repoUrl_not_defined", "repo_access_limited", "repo_empty", "repo_not_accessible", "repo_not_found", "repo_saml_enforcement", "repository_archived", "repository_changed", "repository_expired", "repository_job_cancelled", "repository_not_found", "repository_not_ready", "repository_not_specified", "repository_tree_incomplete", "repository_tree_too_large", "s3_config_not_provided", "source_not_provided", "storage_delete_failed", "storage_write_size_mismatch", "submodule_not_available", "terms_not_specified", "token_expired", "token_limit_reached", "unable_to_connect_user", "unable_to_download", "upstream_error", "upstream_timeout", "user_not_found", "username_not_defined", "webhook_processing_failed"], record.errorCode) { out.errorCode = record.errorCode }
if includes(["admin", "anonymized-file", "auth", "billing", "dailyStats", "file-tree", "fs", "gh-stream", "gist", "github", "github-app-webhook", "owner-notifications", "process", "pull-request", "queue", "queue:cache", "queue:download", "queue:remove", "repository", "repository-public", "requests", "route", "route:repo", "s3", "schedule", "server", "streamer", "temporary-storage", "token-auth", "user", "zip-stream"], record.module) { out.module = record.module }
if includes(["protocol", "credentials", "port", "host"], record.reason) { out.reason = record.reason }
if includes(["parse", "find_grant_owners", "reconcile_grant", "persist_installation_block", "reconcile_installation"], record.phase) { out.phase = record.phase }
@@ -59,7 +59,7 @@ for_each(["requestId", "jobId", "deliveryId", "hopId", "parentHopId", "deploymen
value = get(record, [key]) ?? null
if is_string(value) && match(string!(value), r'^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$') { out = set!(out, [key], value) }
}
for_each(["quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode", "droppedLogsInterval", "stage_transfer_ms", "stage_transfer_count", "stage_transfer_open", "stage_database_ms", "stage_database_count", "stage_database_open", "expectedBytes", "measuredMs", "unattributedMs", "overlapMs", "stage_repository_count", "stage_repository_open", "stage_credential_resolution_count", "stage_credential_resolution_open", "stage_upstream_count", "stage_upstream_open", "stage_cache_lookup_count", "stage_cache_lookup_open", "stage_cache_fill_count", "stage_cache_fill_open", "stage_worker_wait_count", "stage_worker_wait_open", "stage_anonymize_count", "stage_anonymize_open", "stage_streamer_headers_count", "stage_streamer_headers_open", "status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond", "attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed", "oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus", "stage_repository_ms", "stage_credential_resolution_ms", "stage_upstream_ms", "stage_cache_lookup_ms", "stage_cache_fill_ms", "stage_worker_wait_ms", "stage_anonymize_ms", "stage_streamer_headers_ms"]) -> |_index, key| {
for_each(["memoryUsedBytes", "memoryFileCacheBytes", "memoryWorkingSetBytes", "memoryWorkingSetRatio", "quotaUsedRepositories", "quotaRepositoryLimit", "quotaUsedBytes", "quotaRequestedBytes", "quotaProjectedBytes", "quotaStorageLimit", "restartMs", "exitCode", "droppedLogsInterval", "stage_transfer_ms", "stage_transfer_count", "stage_transfer_open", "stage_database_ms", "stage_database_count", "stage_database_open", "expectedBytes", "measuredMs", "unattributedMs", "overlapMs", "stage_repository_count", "stage_repository_open", "stage_credential_resolution_count", "stage_credential_resolution_open", "stage_upstream_count", "stage_upstream_open", "stage_cache_lookup_count", "stage_cache_lookup_open", "stage_cache_fill_count", "stage_cache_fill_open", "stage_worker_wait_count", "stage_worker_wait_open", "stage_anonymize_count", "stage_anonymize_open", "stage_streamer_headers_count", "stage_streamer_headers_open", "status", "httpStatus", "ms", "firstByteMs", "responseMs", "bytes", "bytesPerSecond", "attempt", "rss", "memoryLimitBytes", "memoryRatio", "uptime", "activeRequests", "waiting", "active", "delayed", "failed", "oldestWaitingMs", "droppedLogs", "loopP95Ms", "upstreamStatus", "stage_repository_ms", "stage_credential_resolution_ms", "stage_upstream_ms", "stage_cache_lookup_ms", "stage_cache_fill_ms", "stage_worker_wait_ms", "stage_anonymize_ms", "stage_streamer_headers_ms"]) -> |_index, key| {
value = get(record, [key]) ?? null
if is_integer(value) || is_float(value) { out = set!(out, [key], value) }
}
@@ -79,7 +79,7 @@ if includes(["/", "other", "/dashboard", "/anonymize", "/healthcheck", "/api/hea
}
}
# BEGIN GENERATED DIAGNOSTICS
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-pool.ts":["<anonymous>","anonymizeOnWorker","cancel","exited","failed","finish","getAnonymizationPoolStats","message","pump","release","releaseSpool","reserveSpool"],"build/core/anonymization-pool.js":["Line truncated
source_functions = {"src/cli/index.ts":["<anonymous>","generateRandomFileName","main"],"build/cli/index.js":["<anonymous>","generateRandomFileName","main"],"src/config.ts":["<anonymous>"],"build/config.js":["<anonymous>"],"src/core/AnonymizedFile.ts":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"build/core/AnonymizedFile.js":["<anonymous>","anonymizedContent","assertContentFile","cancel","content","defaultMaskCandidateRegex","escapeRegex","extension","forwardHeaders","getFileInfo","handleStreamError","isFileSupported","isImage","originalPath","probe","recoverTruncatedFile","send","sha","size","streamerErrorToAnonymous","visibleFile"],"src/core/AnonymousError.ts":["<anonymous>","detail","toString","url"],"build/core/AnonymousError.js":["<anonymous>","detail","toString","url"],"src/core/Conference.ts":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"build/core/Conference.js":["<anonymous>","expire","isExpired","remove","repositories","toJSON","updateStatus"],"src/core/Gist.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/Gist.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","downloadWithAccess","expire","getAccess","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/GitHubUtils.ts":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"build/core/GitHubUtils.js":["<anonymous>","abortableGateLookup","cancelled","checkToken","ensureRedisGateClient","getRedisGateResetAt","getToken","getTokenGateResetAt","octokit","rateLimitDetail","resolveRepositoryToken","run","setRedisGate","setRedisGateFromWorker","setTokenGate","waitForTokenGate"],"src/core/PullRequest.ts":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"build/core/PullRequest.js":["<anonymous>","anonymize","check","conference","content","countView","download","downloadContent","expire","getToken","markExpired","remove","resetSate","toJSON","updateIfNeeded","updateStatus"],"src/core/Repository.ts":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"build/core/Repository.js":["<anonymous>","anonymize","anonymizeTreeRecursive","anonymizedFiles","assertNotArchived","buildPathIndex","check","checkRefreshWrite","cleanupRetiredFileTrees","cleanupStagedFileTree","clearRows","completeRecoveredFileMetadata","computeSize","conference","countView","current","ensureFileTree","expire","fileSnapshotFilter","files","findAnonymizedPath","generateAnonymizeTransformer","getToken","hasEmptyTree","indexPaths","insertBatch","invalidateFileMetadata","isReady","markCachePresent","markExpired","pathKey","readFiles","refresh","refreshFilter","refreshIfNeeded","remove","removeCache","resetSate","searchFiles","snapshotValue","submoduleMounts","toJSON","updateIfNeeded","updateProgressMessage","updateRetiringPathIndex","updateStatus","zip"],"src/core/User.ts":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"build/core/User.js":["<anonymous>","getAccessToken","getGists","getGitHubRepositories","getPullRequests","getRepositories","markListExpired","quotaRepositories","repositoryMembership","toJSON"],"src/core/anonymization-errors.ts":["<anonymous>","anonymizationErrorCode","data"],"build/core/anonymization-errors.js":["<anonymous>","anonymizationErrorCode","data"],"src/core/anonymization-pool.ts":["<anonymous>","anonymizeOLine truncated
for_each(["errorType", "causeType"]) -> |_index, key| {
value = get(record, [key]) ?? null
if includes(["Error","TypeError","RangeError","ReferenceError","SyntaxError","URIError","EvalError","AggregateError","AnonymousError","HTTPError","RequestError","MongoServerError","MongoNetworkError","MongoServerSelectionError","ValidationError","TimeoutError","AbortError","UnknownError"], value) { out = set!(out, [key], value) }
+1
View File
@@ -69,6 +69,7 @@
"invalid_path": "The provided path is invalid or missing.",
"path_not_specified": "A file path must be specified.",
"path_not_defined": "The file path has not been resolved yet.",
"zip_unsafe_entry_path": "This repository contains a filename that cannot be safely included in a ZIP archive. Rename filenames containing backslashes or unsafe path components in the source repository and update the anonymization.",
"invalid_file_path": "The requested file path is not valid.",
"invalid_request": "The request is missing required fields or is malformed.",
"invalid_project_name": "Use a project name of up to 100 characters without line breaks or control characters.",
+11
View File
@@ -133,6 +133,17 @@ const sleep = ms => new Promise(resolve=>setTimeout(resolve,ms));
for(const [key,value] of Object.entries(quotaFields)) {assert.equal(quotaView.events[0][key],value);assert.equal(redisQuota.raw[0][key],value);}
assert.equal(quotaView.events[0].errorCode,'quota_storage_limit');
console.log('PASS quota denial reason and exact numeric admission snapshot through collector and both safe admin APIs');
const workerEvidenceId = randomUUID();
const workerEvidenceRecords = ["anonymization_deadline_exceeded","anonymization_queue_timeout","zip_unsafe_entry_path"].map(code =>
logRecord('error','zip-stream',[new Error(code),{requestId:workerEvidenceId,memoryUsedBytes:750,memoryFileCacheBytes:450,memoryWorkingSetBytes:350,memoryWorkingSetRatio:350/768}]));
const workerEvidenceOutput = execFileSync('docker',['run','--rm','-i','--network','none','--memory','256m',vectorImage,'vrl','-i','/dev/stdin',fs.readFileSync('deploy/logging/sanitize.vrl','utf8')+'\nencode_json(.)'],{encoding:'utf8',input:workerEvidenceRecords.map(record=>JSON.stringify({file:'/host/docker/fixture/log.json',message:JSON.stringify({attrs:{tag:'api'},log:JSON.stringify(record)})})).join('\n')+'\n'}).trim().split('\n').map(line=>JSON.parse(JSON.parse(line)));
assert.deepEqual(workerEvidenceOutput.map(row=>row.errorCode),workerEvidenceRecords.map(row=>row.errorCode));
assert((await fetch(process.env.ADMIN_LOG_URL+'/insert/jsonline?_time_field=timestamp',{method:'POST',body:workerEvidenceOutput.map(JSON.stringify).join('\n'),headers:{'Content-Type':'application/stream+json'}})).ok);await sleep(2000);
const workerEvidenceView=await investigateLogs(logOptions({kind:'requestId',id:workerEvidenceId},true),true);
assert.equal(workerEvidenceView.events.length,3);
for(const row of workerEvidenceView.events) {assert.equal(row.memoryUsedBytes,750);assert.equal(row.memoryWorkingSetBytes,350);}
for(const row of workerEvidenceRecords) assert.equal(safeRedisLog({ts:row.timestamp,level:'error',module:'zip-stream',raw:[row]}).raw[0].memoryWorkingSetBytes,350);
console.log('PASS worker/ZIP failure codes and memory breakdown through collector and both admin APIs');
docker('stop',name);
const unavailable=await investigateLogs(logOptions({})); assert.equal(unavailable.state,'unreachable');
delete process.env.ADMIN_LOG_URL;
+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;
+46
View File
@@ -0,0 +1,46 @@
const { expect } = require("chai");
require("ts-node/register/transpile-only");
const { anonymizationErrorCode } = require("../src/core/anonymization-errors");
const { memoryBreakdown } = require("../src/core/log-memory");
const { logRecord } = require("../src/core/log-record");
describe("bounded anonymization failure evidence", () => {
it("retains recognized failure causes and never forwards source text or paths", () => {
for (const [error, expected] of [
[new Error("anonymized_output_too_large"), "anonymized_output_too_large"],
[Object.assign(new Error("private file"), {code:"ENOSPC"}), "anonymization_storage_full"],
[Object.assign(new Error("private pattern"), {code:"ERR_SCRIPT_EXECUTION_TIMEOUT"}), "anonymization_deadline_exceeded"],
[new Error("/private/source/token"), "anonymization_worker_failed"],
[Object.defineProperty({}, "message", {get(){throw new Error("getter invoked");}}), "anonymization_worker_failed"],
]) {
const code = anonymizationErrorCode(error);
expect(code).to.equal(expected);
expect(logRecord("error", "zip-stream", [new Error(code)]).errorCode).to.equal(code);
}
});
it("retains a queue timeout and unsafe ZIP code separately from cancellation", () => {
for (const code of ["anonymization_queue_timeout", "anonymization_cancelled", "zip_unsafe_entry_path"]) {
expect(logRecord("error", "zip-stream", [new Error(code)]).errorCode).to.equal(code);
}
});
it("preserves a bounded cause through an actual worker without exposing a private filesystem path", async function () {
this.timeout(15000);
const { Worker } = require("worker_threads");
const { once } = require("events");
const worker = new Worker(require("path").resolve("src/core/anonymization.worker.ts"), {
execArgv:["-r",require.resolve("ts-node/register/transpile-only")],
});
try {
const received = once(worker, "message");
worker.postMessage({input:"/nonexistent/private-repository/secret.txt",output:"/nonexistent/output",options:{terms:[]},maxOutput:100,context:{mask:"XXXX",hostname:"test.invalid"}});
const [result] = await received;
expect(result).to.deep.equal({error:"anonymization_io_failed"});
} finally { await worker.terminate(); }
});
it("separates reclaimable cache from working set without hiding total pressure", () => {
expect(memoryBreakdown(750, 768, "file 450\ninactive_file 400\n")).to.deep.equal({
memoryFileCacheBytes:450,memoryWorkingSetBytes:350,memoryWorkingSetRatio:350/768,
});
expect(memoryBreakdown(750,768,"total_cache 450\ntotal_inactive_file 400")).to.deep.equal(memoryBreakdown(750,768,"file 450\ninactive_file 400"));
expect(memoryBreakdown(750,768,"")).to.deep.equal({});
});
});
+23
View File
@@ -58,6 +58,29 @@ describe("ZIP stream errors", function () {
});
}
it("rejects backslash archive entries with a specific safe error, without emitting their contents", async function () {
const input = await fixture();
// Replace both ZIP filename headers without changing their byte lengths.
const name = Buffer.from("repo/README.md");
for (let at = input.indexOf(name); at !== -1; at = input.indexOf(name, at + name.length)) input[at + 5] = 92;
const previous = got.stream;
const response = new PassThrough();
const chunks = [], errors = [];
response.on("data", chunk => chunks.push(chunk));
response.on("error", error => errors.push(error));
const closed = new Promise(resolve => response.once("close", resolve));
try {
got.stream = () => Readable.from([input]);
await streamAnonymizedZip({
repoId:"test", organization:"owner", repoName:"public", commit:"abc",
getToken:()=>"", anonymizerOptions:{terms:["private"]},
}, response);
await closed;
expect(errors.map(error => error.message)).to.deep.equal(["zip_unsafe_entry_path"]);
expect(Buffer.concat(chunks).includes(Buffer.from("private source content"))).to.equal(false);
} finally { got.stream = previous; response.destroy(); }
});
it("aborts a download on an asynchronous anonymization timeout without crashing", async function () {
const input = await fixture();
const previous = { stream: got.stream, zip: GitHubDownload.prototype.getZipUrl, flush: AnonymizeTransformer.prototype._flush };