Skip to content

Latest commit

 

History

History
259 lines (175 loc) · 38.2 KB

errors.en.md

File metadata and controls

259 lines (175 loc) · 38.2 KB

English · 中文

Centralized Error Definitions

This document defines where mega2 error types live, how they map onto interfaces, and the rules for extending them. The goal is for project-defined errors to be defined only under crate::common::errors, so that the API, Vault, and business modules do not each maintain their own error enums.

Goals

  • All project-defined error types are defined in src/common/errors/.
  • Business code returns MegaError or a domain error type where possible, with automatic conversion through From.
  • The HTTP layer uses ApiError for all status code and response body mapping.
  • The Vault subsystem keeps using RvError, but it is now a type from the libvault crate (2026-08-21, plan-20260820 VLT-02): common::errors only re-exports it with pub use libvault::errors::RvError and no longer carries its own definition.
  • The old crate::api::error and crate::vault::errors namespaces no longer provide compatibility re-exports.

Current Structure

src/common/errors/
├── mod.rs      # MegaError, MegaResult, BuckError, PathPolicyError, ProtocolError, GitLFSError, DiffParseError
├── api.rs      # ApiError, map_ceres_error
├── policy.rs   # ContextError, SaturnContextError
└── vault.rs    # VaultError, VaultResult (defined in this repo) + RvError (re-export of libvault::errors::RvError)

Recommended public import path:

use crate::common::errors::{
    ApiError, BuckError, ContextError, DiffParseError, GitLFSError, MegaError, MegaResult,
    PathPolicyError, ProtocolError, RvError, SaturnContextError, VaultError, VaultResult,
};

Type Responsibilities

Type Responsibility Used in
MegaError Main application error type; carries config, IO, DB, Redis, object storage, Git, Buck, and other errors. CLI, service, storage, business modules
MegaResult Return alias for CLI/command execution, currently Result<(), MegaError>. commands/*, cli.rs
ApiError HTTP API response error; maps MegaError, anyhow::Error, or legacy [code:xxx] text to a status code and response body. src/api/**
ProtocolError Git HTTP/SSH protocol-layer error; owns the protocol response status and message. src/contract/git_protocol/*, server
RvError The libvault library's own error enum (re-exported, not defined in this repo). Response status mapping and PartialEq behavior come from upstream. src/contract/vault/**
VaultError / VaultResult Errors from Vault integration startup, initialization, key files, runtime tokens, and API operations. src/contract/vault/integration/**
ContextError Errors from Cedar policy context building, schema, policy, validation, and JSON. src/contract/policy/context.rs
SaturnContextError Errors from building Cedar authorization requests and from authorization denials. src/contract/policy/context.rs
BuckError Buck session/upload business errors; wrapped as MegaError::Buck and mapped by ApiError to an exact HTTP status. Buck service/router
TracesError Stable traces error codes. Wrapped as MegaError::Traces; ApiError and ProtocolError::Traces read the same HTTP status table. The public text is the stable code only, with no object key or body. Codes and statuses: unauthenticated 401, unknown_scope 404, invalid_parameter 400, invalid_cursor 400, unsupported_schema 409, invalid_capture 409, object_integrity 409, trace_history_in_code 409, response_budget 413, query_timeout 503, search_unavailable 503. A 503 still shows the code to the client. The MTR-19 search service maps a PostgreSQL statement timeout (57014) and lock timeout (55P03) to query_timeout 503, and an index that is not ready to search_unavailable 503; neither pretends to be "no hits". The MTR-43 unified response budget rejects an over-budget response as a whole with response_budget 413 instead of truncating JSON bytes, so the error response itself is still valid JSON. traces callers; defined in common::errors
PathPolicyError Monorepo path creation / write policy errors (stable codes MONO_PATH_*), used bare or wrapped as MegaError::PathPolicy; ApiError maps them to 400/409 and outputs the text verbatim. ceres::pack::path_policy; product writes, path provisioning, receive-pack (plan-20260923 FU-06 / FU-07 / FU-10)
GitLFSError Git LFS handling errors. LFS router/handler
DiffParseError Unified diff parse errors for code review re-anchoring. src/jupiter/utils/code_review_reanchor.rs

Import Rules

New and existing business code must import error types directly from crate::common::errors:

use crate::common::errors::{ApiError, MegaError, RvError};

Do not add crate::api::error::* or any other module-level error facade. src/api and src/contract only consume the shared error types and no longer hold error definitions. (The top-level crate::vault was removed together with the vendored module; library errors come from libvault::errors.)

Boundaries

Structs whose names contain Error but that serve as API payloads/schemas are not error definitions under this scheme, for example:

  • LogErrorResponse
  • ObjectError
  • QueueError

These are public response data models and stay in api_model, ceres::model, or the module that holds the protocol DTO. Only types actually used as the error in Result<T, E>, that implement std::error::Error/thiserror::Error, or that carry internal failure semantics belong in common::errors.

Extension Rules

When adding an error:

  1. First check whether an existing MegaError variant can be reused.
  2. When domain semantics are needed, add a domain error enum in src/common/errors/mod.rs and wrap it in MegaError.
  3. When an HTTP status is needed, handle it in the ApiError From mapping; do not hand-write HTTP statuses in the business layer.
  4. When Vault semantics are needed, extend this repo's VaultError; do not extend RvError, which belongs to the libvault crate and is only re-exported here. The Readonly* variants for read-only bootstrap were added this way (plan-20260820 VLT-02/VLT-04).
  5. Do not add local thiserror::Error enums in API/router, Vault tooling, contract, or storage modules; local parse errors also belong in common::errors.
  6. String fallbacks (such as MegaError::Other and [code:xxx]) are only for compatibility or transition; new logic should prefer structured variants.

Status Codes for Authorization Denials (UN-23)

Guarded /api/v1/cl operations return 403 when authorization is denied, and declare that response explicitly in OpenAPI.

  • 403 = known principal without permission (authorization denied).
  • 401 = authentication failure (a required extractor cannot get a session), and must not stand in for an authorization denial. The two mean different things and clients handle them differently (sign in again vs. request access).
  • Review explicit CL reuse precheck and service-layer row-lock recheck (BRH-24 / BRH-26): when review-mode product writes (create-entry / edit/save) pass mode=TryReuse(Some(link)), router precheck returns 404 (ApiError::not_found) if the target CL does not exist, and 403 (ApiError::forbidden, before entering the service layer with zero object writes) if the CL belongs to another user, is not Open, or (for edit/save) has a mismatched build_repo_path. Inside the service layer, after resolving the authoritative build_repo_path and before calling put_objects or writing DB object rows, a single DB transaction (SET LOCAL lock_timeout = '5s') locks the CL row via SELECT ... FOR UPDATE: if concurrent close/disappearance, ownership mismatch, or authoritative build_repo_path conflict (including create-entry with missing parent directories) is detected, it intentionally differs from router 403 and returns 409 (Conflict); if lock wait hits PostgreSQL SQLSTATE 55P03, it returns 503 (Service Unavailable, retryable). Because ApiHandler trait signatures return the external crate type git_internal::errors::GitError, the service layer follows Extension Rule 6's compatibility boundary exception by using internal [code:409] / [code:503] prefixes, which ApiError::from maps to HTTP status codes and strips before emitting the response; both rejections roll back the transaction with zero object-storage or DB writes. push_policy=trunk skips both precheck and row-lock recheck.

The mapping key is {method, path} (src/contract/policy/guard/guarded_endpoints.json): different methods on the same path can be different actions. For example, GET /cl/{link}/reviewers is a read (viewRepo), while POST/DELETE on the same path are writes (editChangeList). An operation whose {method,path} is not registered is treated as unprotected and does not inherit the action of another method on the same path.

503 for "Authorization Undecidable" on the Merge Surface (UN-25)

[code:503] maps to 503 Service Unavailable. Previously, any unregistered code fell through to 500, which could not be told apart from a real bug and was not retryable by contract.

  • 503 = cannot decide right now, retryable: when authorization data is unavailable (snapshot not built / dirty / storage read failed), the merge surface can neither allow the request nor treat it as "change rejected".
  • 500 = server defect; retrying from the client is pointless.
  • 403 = known principal without permission (UN-23).

POST /cl/{link}/merge declares both 403 and 503 in OpenAPI (the legacy anonymous merge endpoint was deleted in BRH-08 and returns 404).

Queued items in the same situation are frozen rather than failed. The frozen row is written to push_queue (kind=merge) and reuses the existing terminal state Failed + SystemError (no new enum, no migration, and the existing retry entry points keep working). It keeps requester (the authorization principal re-evaluated on retry), and error_message states the condition for retrying. The freeze path also emits an in-process error log event=merge_queue_authz_frozen (fields cl_link / requester / reason). Alerting makes no external call, so there is no path by which an alerting failure can affect the freeze transaction. The event name stays unchanged (for stable alert queries).

Status Codes for the CL Commits Read Endpoint (MC-05, plan-20260827)

GET /api/v1/cl/{link}/commits (plan-20260827 MC-05, DEP-01 frozen contract) adds no new error type and reuses existing mappings:

  • 404 = unknown link: MegaError::NotFound, mapped through ApiError typed matching. The handler first looks up the CL row to establish existence, then reads the list; passing through the empty list from get_cl_commits as-is would confuse an unknown link with a CL that has no data.
  • 200 + empty list = CL exists but has no list data (existing CLs are not backfilled; mega_cl_commits has no rows).
  • 403 = authorization denied: declared in OpenAPI. The Cedar guard mapping (GET /cl/{link}/commits registered in guarded_endpoints.json) lands with MC-07 and ships together with the endpoint through REL-MC-01 (MC-08). Before that, under the UN-23 rule the path is in the intermediate "unregistered means unprotected" state, which is why the family is released atomically.

PathPolicyError: Monorepo Path Policy (plan-20260923)

PathPolicyError (src/common/errors/mod.rs) is the domain error for the path "create / write" policy, wrapped as MegaError::PathPolicy(#[from]). The wrapper uses #[error("{0}")], so the text passes through verbatim with no Other error: prefix. NotAllowed and Invalid are decided by ceres::pack::path_policy: creation classification goes through the single classifier classify_creation_path, and the ImportRepo namespace guard for product writes goes through check_write_operands (ADR-FU-06). (Rules: plan/plan-20260923.md ADR-FU-04. Callers reuse in_import_namespace, is_import_dir_ancestor, and not_allowed from the same module and must not copy the checks.) Uninitialized and Conflict are produced by callers based on tree state. Client JSON path entry points first go through strict_creation_path_input (rejects NUL and \, and requires the raw input to already be a canonical path).

Variant Code HTTP (ApiError) Meaning
NotAllowed { path, allowed_roots, import_dir } MONO_PATH_NOT_ALLOWED 400 The target path is not under any root_dirs, or is under import_dir (import takes precedence: ImportRepos are created by push)
Uninitialized { path } MONO_PATH_UNINITIALIZED 409 A path under a valid root that has not been provisioned yet; the message names mega2 path provision --server <url> <path> and POST /api/v1/path/provision
Invalid { path, reason } MONO_PATH_INVALID 400 The path is not canonical (relative, . / .. segments, repeated or trailing slashes), contains NUL / \ / other control characters (strict JSON entry point), or is the root / (decided by the classification primitive; a product write landing on / returns NotAllowed, see ADR-FU-06), or its first segment is the reserved view name .view / .filter (path provisioning and product writes)
Conflict { path, component } MONO_PATH_CONFLICT 409 A component on the path already exists and is not a directory

Text format (the same text on the Git and API surfaces): Display = "<CODE>: <human-readable message>", always a single line. Paths appear in quoted, escaped form (the path in the Uninitialized provisioning command is escaped but not quoted), and control characters (newline, NUL, and so on) in other parts such as root names and reasons are escaped as \n / \0, so the text fits in a Git ng line and cannot forge multi-line output. When a product write returns through GitError, MegaError::PathPolicy becomes [code:400|409] <text> (PathPolicyError::http_status), and ApiError sets the status from it and strips the marker. A bare PathPolicyError and MegaError::PathPolicy are mapped by type and output verbatim ([code:…] is no longer parsed out of the text, so that string appearing in a path does not truncate the message). The err_message is the original text on all three channels. The Git report-status ng line and the API err_message both carry this original text, and clients can branch on the code before the colon. The codes are a public contract; renaming one requires a minor version and an update to this section. NotAllowed only lists the allowed roots (/<name>, sorted) and the ImportRepo directory. No variant includes the config file path, base_dir, database / Redis / object storage addresses, or credentials.

Entry points: product writes (create / edit-save / delete / move, FU-06), the path provisioning API and CLI (FU-07, FU-08), and the first trunk receive-pack push (FU-10).

When it appears on the Git surface (trunk receive-pack, FU-10; the decision is described in "Path policy for creation" in refactoring/trunk-push.md): only when a push creates a path, that is, old_id is zero, the target path has no main row, has no tombstone, and does not resolve to a directory in the root tree. The first push and an identical retry get the same text.

  • Path outside the roots → MONO_PATH_NOT_ALLOWED, regardless of the pushed history.
  • Under an allowed root, with an orphan pushed chain (history starts from nothing, or the known history of another path is pushed as-is) → MONO_PATH_UNINITIALIZED.
  • Non-canonical raw URL path (such as /project//x) → MONO_PATH_INVALID: the protocol layer only strips the trailing .git (normalize_repo_path in contract/git_protocol/path.rs); normalization happens only in ImportRepo dispatch, and Monorepo dispatch uses the raw path (DEFER-FU-18). Common clients strip trailing slashes themselves and are not affected.
  • MONO_PATH_CONFLICT does not appear on the Git surface (creation on a file path: see DEFER-FU-19).

The report-status line is ng refs/heads/main <text>; git push shows ! [remote rejected] <src> -> main (<text>), and Libra shows remote rejected ref update for 'refs/heads/main': <text> (Libra truncates long text). For the steps on the user side, see user guide section 2.5.

MegaError::OrphanChain: Orphan Chain Rejection (plan-20260923)

MegaError::OrphanChain (FU-09, ADR-FU-07): the orphan rejection when a new-branch push (old_id is zero) follows the first-parent chain through the pack to a parentless root. The first push and an identical retry return the same error. The display text keeps the historical wording Other error: Can not init directory under monorepo directory!, and the Git ng line is unchanged. It is typed only so that callers (the FU-10 trunk first-push classification) can identify it precisely through push_chain::is_orphan_chain_error instead of matching text. It does not prove that the history is unreferenced (a chain with a known tip that reaches a root returns it too; see refactoring/trunk-push.md). In trunk mode, when the push targets a path still to be created (no main row, no tombstone, not resolvable in the root tree), it is mapped to MONO_PATH_UNINITIALIZED (FU-10), so the client sees the path policy code.

ImportRepoError: ImportRepo Refs and Lifecycle (plan-20260923)

ImportRepoError (src/common/errors/mod.rs) is the ImportRepo domain error, wrapped as MegaError::ImportRepo(#[from]). The wrapper uses #[error("{0}")], so the text passes through verbatim. Display = "<CODE>: <human-readable message>", always a single line (control characters in paths, ref names, and ids appear escaped), and the same text goes into the Git ng line and the API err_message. ApiError maps the status by type and outputs the text verbatim; the GitError channel carries a [code:…] marker. The full error domain is defined once in FU-12, and each code is registered here by the card that first exposes it to users (plan/plan-20260923.md ADR-FU-03 item 2):

Variant Code HTTP (ApiError) Meaning
StaleRef { ref_name, expected } IMPORT_REPO_STALE_REF 409 A ref update in an ImportRepo push failed the server-side CAS (ADR-FU-08 item 2): on Create the ref already exists; on Update / Delete it no longer points to the old_id the client claimed (another push or API write happened after the advertisement). fetch and push again
PathOccupied { path } IMPORT_REPO_PATH_OCCUPIED 409 The mount location of an ImportRepo push is occupied by content that does not belong to that repository (ADR-FU-08 item 1): the path is a plain directory or file in the Monorepo root tree and has no mount provenance record for the repository (existing mounts are lazily backfilled under the "only .gitkeep and the repository already has branches" rule and are not covered here). The root tree is unchanged; import to a different path, or have an operator clean up the occupying content
Removed { path } IMPORT_REPO_REMOVED 409 The ImportRepo was cleaned up (detached, ADR-FU-09 item 5) while a push or product API write (edit save, tag create / delete) was in progress. The rejected write lands no rows (no object rows, tags, branch refs, or file_path, and the leaf is not remounted). Edit save writes object rows and the default branch ref in two transactions; if a detach happens between them, the committed object rows are left for the sweeper to delete. Pushing again re-imports with a new repo_id. On the Git surface it is the original text of the ng line; on the API surface POST /api/v1/edit/save, POST /api/v1/tags, and DELETE /api/v1/tags/{name} return 409
PathInvalid { path, reason } IMPORT_REPO_PATH_INVALID 400 The path is not a valid ImportRepo leaf (ADR-FU-08 item 7, ADR-FU-10 item 1). Protocol dispatch, after TP-08 normalization and before any lookup or registration, rejects for paths entering the ImportRepo branch (absolute paths with import_dir as a component prefix) import_dir itself, non-canonical forms, and paths containing NUL (SSH relative forms such as third-party still take the Monorepo branch, plan DEFER-FU-37). The strict entry points of the cleanup API and operator CLI (since FU-20 / FU-21) additionally reject \, .., repeated slashes, and trailing slashes (reason explains why; when the input can be normalized but is not canonical, it gives the canonical form to use, did you mean …). No rows, refs, or objects are written and the root tree is unchanged. The HTTP cleanup endpoint returns it before authentication; the operator CLI mega2 import-repo remove prints it before connecting to the database, Redis, and object storage (exit code 1)
HasChildren { path } IMPORT_REPO_HAS_CHILDREN 409 Other registered ImportRepos still exist under the cleanup target (repo_path LIKE escape_like(P) || '/%', bound parameter; alias rows whose canonical form equals P do not count, ADR-FU-10 item 3). Rejected by the write-free precheck at the entry point (not queued, no ledger or audit writes) or by the re-check inside the B3 lock (writes a Failed queue row); rows, refs, objects, and the root tree are unchanged. The text does not name the child repositories. When a full page of 64 rows is all target aliases, it is conservatively treated as having children (plan DEFER-FU-10). Clean up the child repositories first. Exposed through POST /api/v1/import-repo/remove since FU-20; also printed by mega2 import-repo remove (exit code 1)
CleanupNotFound { path, cleanup_id } IMPORT_REPO_CLEANUP_NOT_FOUND 404 The cleanup_id of a resume request does not exist or belongs to another path. Both cases have the same text and echo only the request's own path and id (no cleanup "<id>" for "<path>"), so the ledger of other paths does not leak; no writes, never detaches. Exposed through the same endpoint since FU-20; also printed by mega2 import-repo remove --cleanup-id (exit code 1)

When it appears (ImportRepo pushes under import_dir; ADR-FU-08 items 1, 4, 5): tag commands are independent per ref, and a failed tag gets an ng line starting with IMPORT_REPO_STALE_REF. Branch commands in the same push are applied as one batch in the same B3 transaction; if any branch CAS fails, the whole batch rolls back, every branch gets ng, and no branch advances. Each branch's ng line is the original IMPORT_REPO_STALE_REF text of the stale command (since FU-13, a branch batch containing only deletions also goes through the write queue and only writes refs, skipping the materialization precheck and mount ownership check) (Create hitting an existing ref gives IMPORT_REPO_STALE_REF: "<ref>" already exists; fetch and push again). When the mount location does not belong to the repository, the result is the original IMPORT_REPO_PATH_OCCUPIED text: a first push hitting a plain directory or file, or a later push hitting a leaf that has no provenance record and does not match the existing-mount rule (for example an existing parent mount whose leaf already contains nested child repositories; see plan DEFER-FU-23). Since FU-13, write-queue failures are no longer wrapped as attach B3 did not complete successfully: {Debug}: the client text is reconstructed from the mount path and this push's branch commands into the typed errors above. Rejections from the materialization precheck keep their details as Other error: ImportRepo attach failed: <details> (I3 ancestor / descendant / target already materialized). Other unclassified failures return only Other error: ImportRepo attach failed (push_queue id <N>); retry the push, and the cause stays only in the queue row (push_queue.error_message, which may contain storage internals; it is not exposed or logged). An unfinished round gives Other error: ImportRepo attach for push_queue id <N> did not complete; retry the push, an abandoned wait gives Other error: attach wait abandoned for push_queue id <N>, and refs still not in effect after a replay give Other error: ImportRepo attach replayed push_queue id <N> but the refs did not move; retry the push (these fallback texts are MegaError::Other, and the ng line carries the Other error: prefix) (in v0.40.1, queued branch batch failures were still Debug-wrapped).

When it appears (write-path liveness fences and leaf validation since FU-18; ADR-FU-08 item 7, ADR-FU-09 items 2, 5):

  • IMPORT_REPO_REMOVED: after unpack ok, receive-pack gives each tag its own ng refs/tags/<t> IMPORT_REPO_REMOVED: …. Every branch in a branch batch gets an ng line with the same original text, regardless of which fence rejected it (the unpack batch, the file_path step, B3 attach, or a replay of a completed deletion-only round). The git client shows ! [remote rejected] main -> main (IMPORT_REPO_REMOVED: …). Product API: POST /api/v1/edit/save returns 409 when it hits the fence while writing object rows (since FU-18, zero object rows). Since FU-19, when the repository is detached only after the request has been dispatched to the ImportRepo handler, the following also return 409: the pre-read of POST /api/v1/edit/save (liveness is re-checked when it fails because the row was deleted) and its default branch ref write, POST /api/v1/tags (for an annotated tag, the git_tag row and ref in one transaction; for a lightweight tag, the ref), and DELETE /api/v1/tags/{name} (ref and git_tag row in one transaction). The body is {"req_result":false,"data":null,"err_message":"IMPORT_REPO_REMOVED: …"} and the request writes no import_refs / git_tag rows (if edit save hits a detach after the object batch commits and before the ref write, the committed object rows are deleted by the sweeper). Requests for which the detach committed before dispatch are handled by the Monorepo handler instead (edit/save gives 400 MONO_PATH_NOT_ALLOWED; see the error mapping in refactoring/directory-entry-api.md). The write-queue row is Failed, with failure_type AttachFailure and the same original text in error_message.
  • IMPORT_REPO_PATH_INVALID: HTTP v0/v1 info/refs (both services), git-receive-pack and git-upload-pack POST, and v2 ls-refs / fetch return 400 with body {"req_result":false,"data":null,"err_message":"IMPORT_REPO_PATH_INVALID: …"}, and the git client shows The requested URL returned error: 400. The v2 info/refs GET does not dispatch and still returns 200. Authentication and push permission 401 / 403 come before it. HTTP /third-party.git still gives the existing Repository third-party.git is not supported. Upload-pack on import_dir changes from 404 Repository not found. to 400. Over SSH, when it is hit during exec the channel closes with no typed line; during the receive-data phase the server writes an error: Invalid Input: IMPORT_REPO_PATH_INVALID: … line without pkt-line framing, and the git client only shows protocol error: bad line length character: erro (the existing way SSH errors are written). SSH git-receive-pack '/third-party.git' is rejected as well (previously it registered an import_dir row). Since BRH-12, POST /api/v1/repo/clone under the review policy enforces admin authentication/authorization first (returning 401 for anonymous callers and 403 for non-admins before reaching this path logic); for authorized admins, it drops report-status so the former does not reach the client and the latter shows up as 500 (DEFER-FU-29).

When it appears (the cleanup endpoint POST /api/v1/import-repo/remove since FU-20, ADR-FU-10):

  • Decision order: plain-text rejections from axum extractors (400 / 413 / 415 / 422, not CommonResult) → 400 IMPORT_REPO_PATH_INVALID (before authentication, the reverse of the Git surface) → fixed-body 401 authentication required / 403 forbidden (not codes from this domain, and the path is not echoed; push_auth=none or unconfigured always gives 403) → 404 IMPORT_REPO_CLEANUP_NOT_FOUND / 409 IMPORT_REPO_HAS_CHILDREN (only for authorized callers; no ledger, audit, ref, object, or root tree writes, except that a 409 from the re-check inside the write-queue lock leaves one Failed queue row).
  • Examples: {"req_result":false,"data":null,"err_message":"IMPORT_REPO_HAS_CHILDREN: \"/third-party/p\" contains other ImportRepos; remove them first"}, {"req_result":false,"data":null,"err_message":"IMPORT_REPO_CLEANUP_NOT_FOUND: no cleanup \"12\" for \"/third-party/p\""}.
  • 500 Internal server error is retryable (write queue paused / hard-stopped / full, detach round not finished, storage error; plan DEFER-FU-42). A resume retry with cleanup_id is safe against re-imports; a retry with only path (no cleanup_id) detaches whatever repository is live at that time. For the request, outcome semantics, and client protocol, see "ImportRepo leaf cleanup" in refactoring/directory-entry-api.md.
  • The operator CLI mega2 import-repo remove (since FU-21) writes the original text of errors from this domain to stderr, prints no outcome line, and exits with code 1. For outcome lines, other exit codes, and resuming, see section 2.6 of the user guide.

MegaError::ViewUnavailable / ViewPackRejected: View Protocol Errors (plan-20261002)

MegaError::ViewUnavailable { filter_id: String, reason: ViewUnavailableReason } and MegaError::ViewPackRejected(String) are the view precheck errors of Git upload-pack. For the former, ViewUnavailableReason is WarmingUp, RootChainHalted, or DefinitionCorrupt, displayed as warming up, root chain halted, or definition corrupt; the latter's string is a validated protocol message. Both variants map as-is to the corresponding ProtocolError variants and do not go through the GitError channel, which would collapse the error type.

ViewUnavailable answers over HTTP with 503 and a fixed 30-second Retry-After; ViewPackRejected answers over HTTP with 200, application/x-git-upload-pack-result, and a body of a single ERR <message>\n pkt-line. The full response table for the four kinds of view errors is in history-projection design §6.1 "Error contract"; the precheck call sites are in the protocol refactoring notes.

Review LFS Fallback Upload Error Contract (BRH-25 / BRH-30 / BRH-32 / BRH-29)

Under push_policy=review, mega2-hosted fallback LFS uploads (POST /info/lfs/objects/batch, PUT /info/lfs/objects/{oid}, and PUT /api/v1/lfs/objects/{oid}) return application/vnd.git-lfs+json error responses under the following contract (with zero object-storage writes):

Surface & Status Condition Notes
Batch object-level ObjectError { code: 422 } Unstored new object with size > 32 MiB (33554432 bytes) on review fallback Rejected before inserting an lfs_objects row or issuing a Redis upload grant (zero orphan metadata, zero grant keys); the message states the 32 MiB fallback cap and directs operators to configure s3compatible presigned uploads for larger objects. Already-stored large objects continue succeeding idempotently (BRH-29)
PUT 401 Unauthorized Missing, invalid, expired, or OID-mismatched X-Mega-LFS-Upload-Grant Strictly reserved for upload grant verification failures (BRH-25); rejected before reading the request body, independent of the object-storage backend
PUT 415 Unsupported Media Type Any non-identity (trimmed, ASCII case-insensitive) or non-UTF-8 Content-Encoding header The review branch bypasses RequestDecompressionLayer for PUT /api/v1/lfs/objects/{oid}, and both aliases uniformly reject compressed uploads after grant verification and before reading the body (without WWW-Authenticate; clients must upload raw uncompressed bytes per the Git LFS basic transfer spec, BRH-30)
PUT 400 Bad Request grant.size > 32 MiB (pre-upgrade or anomalous oversize grant, guiding to s3compatible presigned uploads, BRH-29), grant.size < 0, invalid or mismatched Content-Length != grant.size, or chunked/h2c upload ending at EOF with fewer than grant.size bytes No WWW-Authenticate; oversize grants and mismatched Content-Length are rejected before reading any body bytes (411 is intentionally not returned so libra's Transfer-Encoding: chunked and headerless h2c uploads stay compatible, BRH-32 / BRH-29)
PUT 413 Payload Too Large Chunked or headerless h2c upload exceeds grant.size cumulative bytes Aborts immediately before appending the overflowing chunk and stops polling further frames; no WWW-Authenticate, zero object-storage writes (BRH-32)

storage-only (push_policy=trunk) deployments are not affected by these review-only restrictions.

Review-Mode MST/2 Configuration Validation Error (BRH-21)

When [mst2] is enabled (mst2.enabled = true) under push_policy=review, Config::validate (enforced on both config validate CLI and AppContext::new startup) requires a non-empty mst2.auth_token. Omitting it fails with the existing MegaError::Other variant ("mst2.auth_token is required when mst2.enabled is true in review mode"), naming only the config field without echoing any secret material. storage-only (push_policy=trunk) retains the unauthenticated lab mode when mst2.auth_token is unset.

Response Safety

  • ApiError only exposes 4xx details to clients.
  • 5xx always returns Internal server error; internal details go only to logs.
  • Sensitive values such as secrets, tokens, passwords, and API keys must not be written into error messages.
  • Errors involving config, Vault, or credential resolution should use redacted paths or field names.

Verification Requirements

When changing error definitions, error mappings, or error path migrations, run:

cargo +nightly fmt --all --check
cargo clippy --all-targets --all-features -- -D warnings
source .env.test && cargo test --all

and, depending on the scope of the change, also:

cargo build
cargo build --tests

plan-20260905 (Trunk Direct Push)

This plan adds no user-visible MegaError enum variant. StaleMonorepoRootRef existed before the plan. The protocol rejections of TP-15/17/19 (trunk chain length, token path prefix, B0 non-main branch) use existing MegaError::Other strings and register no new type here. The LFS review-only 404 string from TP-18 at the time was removed by plan-20260909.md (no new error type).

plan-20260909 (Storage-only LFS)

N/A: this plan adds no MegaError variant. Trunk LFS rejections keep the existing HTTP statuses (401/403) and lfs_auth_challenge, and register no new error type.

plan-20260907 (git-internal 0.9.0 / BLAKE3)

N/A: no new user-visible MegaError enum variant. Cross-kind / wrong-width IDs, invalid Buck sha1:+64 hex, and unimplemented LFS BLAKE3 business paths use the existing fail-closed text and register no new type here.

plan-20260901 (FastCDC Media + receive-pack / Import Reliability)

N/A: no new user-visible MegaError enum variant. Media HTTP uses domain error mapping to 400/404/409/500 (see docs/refactoring/fastcdc-media.md); MegaError::is_retryable_db_serialization is only used to classify internal retries in batch insert and does not change the public error surface.

plan-20260911 (Storage-only Agent Capture, Retired)

Historical record: /api/v1/agent-capture was removed by MTR-26/MTR-28. The route is no longer mounted, and the loader rejects the old [agent_capture] config. Agent session history is now uploaded through scoped traces Git and queried through /api/v1/traces (see refactoring/traces.md). The content below only describes the behavior while that interface was in service.

N/A: no new user-visible MegaError enum variant. /api/v1/agent-capture used a fixed HTTP envelope { "error": { "code", "message" } } at the time (unauthorized / not_found / conflict / bad_request / payload_too_large / missing_raw) and registered no new MegaError type.

plan-20260912 (Storage-only Post-commit Outbound Events)

N/A: no new user-visible MegaError enum variant. [storage_events] config/startup errors reuse MegaError::Other (enabled in review mode, missing installation_id, duplicate target id, invalid id, non-HTTPS URL, timeout out of range, invalid HMAC encoding, unknown event literal, filter set over the limit, non-canonical path, unpaired agent filters). A projection over 16 KiB or invalid metadata is recorded as dropped and must not map back to the HTTP status of the already committed write.

WH-11 startup secret binding uses the same error class: a SecretRef shape/namespace error in a target's secret_ref (vault://secret/config/<profile>/storage_events/targets/<id>/hmac#<field>) fails both in config validate and at service startup. When enabled, a vault resolution failure (missing secret/field, non-string field) or an invalid hex:<even-hex> encoding also fails startup. Redaction guarantee: error text does not contain the SecretRef URI (resolver errors are fixed as vault://secret/***#***) and never contains the decrypted value; diagnostics only name the field path (such as storage_events.targets[0].secret_ref) and the required namespace template.

WH-14 adds two more MegaError::Other config errors of the same kind. Both run in enabled and disabled modes (following the contract that "disabled still validates structure and only skips fetching from vault"):

  • [storage_events] shutdown_grace_seconds must be 0..=10: ADR-WH-03 requires a bounded drain; 0 is valid (abort in-flight tasks immediately), and the upper bound is part of the contract. Previously the field only appeared in the unknown-field allowlist and the reload restart registry, with no range check.
  • [[storage_events.targets]] oci_repositories contains an invalid OCI repository name: filter entries must be canonical distribution remoteNames, using the same check as inbound /v2 (single implementation in src/common/oci_name.rs, case-sensitive, no folding). A name the router can never produce can never match, which would be a silently dead subscription, so it fails closed.

Neither diagnostic echoes the target url, secret_ref, or any secret; they only name the field path and the rule.