Attachments
ir.attachment keeps Odoo’s metadata (name, parent record, type, URL, checksum, size, media type);
the bytes live in a store that every node of a deployment shares (ADR 0041). A table never holds a
file: it holds a reference to a blob addressed by its SHA-256, so identical files are stored once per
database. You use the functions of erp_addon_base::attachments; you never write SQL and you never
touch a path.
Operators: the store and its settings are in Attachment store for operators.
Database maximum attachment size
Section titled “Database maximum attachment size”base.attachment_max_bytes is the database-global administrator policy (ADR 0193). It is one value
shared by declared Settings and Technical System Parameters: default 134217728 bytes, inclusive
bounds 1–2147483647. Empty/absent resets to the declared default; invalid text refuses by name.
Use the Settings service or the checked parameter API; never write either storage table directly.
Technical edits advance the same Settings revision and audit as Settings edits.
The attachment service enforces this policy on decoded bytes and server-owned staged/copy sizes; caller-supplied sizes cannot grant admission. The runtime file ceiling and inline threshold still apply. Larger content uses the native staged protocol; the browser’s current base64 path remains bounded by the inline threshold. An upload-policy read does not grant generic parameter access. The attachment service rolls back consumed uploads on a size refusal; callers catching model-method errors must still use the ORM’s outer savepoint contract (ADR 0014). Future HTTP uploads must use the same policy before reservation and during receiving.
Administrators open Settings, choose the database scope, and edit Maximum attachment size (bytes) under Base. The same key appears in Technical → System Parameters; clearing its value resets it.
What is delivered
Section titled “What is delivered”The API below, the ir.attachment model, the garbage collection jobs and the access rules of the
generic ORM path are in this release. The signed-in download route is described under
Read a file in the browser; bounded composer uploads use the thread RPCs
in Chatter storage. The separate streaming-upload delivery is not complete.
Not yet: binary fields stored as attachments (the BASE-B binary-field follow-up, needs a binary value in the ORM), the
compiled parent-access rule that makes generic search follow the record (the BASE-B access follow-up),
scanning, encryption and store migration (see the design note
docs/design/m3-base-b.md section 1). Each fails with an error that names what adds it.
Stage an upload
Section titled “Stage an upload”Content above the inline threshold (2 KiB by default) never passes through memory as a whole. A caller that holds the ORM (a route, a job’s external step, a test) streams it into staging first:
use erp_addon_base::attachments::{StageRequest, Uploader};use erp_sdk::prelude::*;
async fn stage( orm: &erp_sdk::Orm, env: &erp_sdk::Env, file: &mut (dyn tokio::io::AsyncRead + Send + Unpin),) -> Result<()> { let staged = Uploader::new(orm) .stage(env, file, StageRequest::named("contract.pdf").declared("application/pdf")) .await?; // `staged.id` is bound to the subject and actor of `env`, expires in 24 hours and links once println!("{} bytes, sha1 {}, type {}", staged.size, staged.checksum, staged.mimetype); Ok(())}The row that records the upload commits before the first byte is written, so a crash leaves a row that expires and a cleaner job removes the object; nothing ever lists the store to find leftovers. The type is detected from the first 8 KiB; a declared type that is not itself active (HTML, SVG, XML, script) on active content is refused naming both types.
The intent also reserves its declared byte length, or the effective file limit when length is
unknown. Use .with_declared_length(bytes) for a known length and .with_file_limit(bytes)
for a transport limit; the configured attachment limit still caps both. Actual content cannot
exceed its reservation, including content below the inline threshold. A shorter successful file
reduces the reservation to its actual size.
For this native staging API, that admission ceiling is the node runtime configuration. The database policy is rechecked when the staged file is adopted into an attachment. A lower database policy can therefore refuse adoption of an already staged file. The future HTTP route must also consult the database policy before reserving or receiving bytes; that transport is outside this slice.
Pending count and bytes aggregate by subject across API keys and application nodes. Database staging bytes have a separate hard cap. An optional storage quota uses deduplicated committed content plus retained staging reservations. Direct inline writes participate in that quota and ledger too; copying an existing blob does not charge it again.
Receiving has separate idle and absolute bounds: upload_idle_timeout_secs defaults to 30
seconds (1–300); upload_receive_timeout_secs defaults to 600 seconds (10–86400), capped by
upload_ttl_secs. Only new body bytes reset the idle timer. Both inline probing and external
staging use this reader. A transport may tighten these deadlines. Typed UploadIdleTimeout,
UploadReceiveTimeout and UploadExpired sources distinguish their Validation errors.
Failure/cancellation leaves a durable intent for fenced maintenance; it does not synchronously
delete store objects. Its reservation remains until physical cleanup succeeds. An expired or
consumed external upload can therefore still occupy the staging byte budget. Consumed uploads
no longer occupy pending-upload slots; inline consumption releases its staging reservation. Adoption and its new-content
charge roll back with the business transaction. An admitted upload is not admitted a second time
when linked, regardless of whether it is inline or external; physical staging stays charged until
cleanup. Storage-quota errors retain a typed
erp_sdk::blob::BlobError::QuotaExceeded source; count refusal uses ResourceExhausted, and
node admission uses Lock. Transport mapping belongs to the HTTP package.
erp_sdk::Isolation is available to native composition code using BeginOptions::isolation;
normal ORM business work keeps its default isolation. attachments::gc::compact_usage is an
explicit bounded System maintenance primitive requiring READ COMMITTED. The fixed elevated base.attachment_usage_compact job schedules it through the isolated owner
runner. Enable that node explicitly as described in the attachment-store operations guide.
Attach inside your transaction
Section titled “Attach inside your transaction”use erp_addon_base::attachments::{self, AttachmentContent, NewAttachment, ParentRef, UploadId};use erp_sdk::prelude::*;
async fn attach(tx: &mut Transaction, partner: i64, upload: UploadId) -> Result<()> { let ids = attachments::create( tx, vec![ // a staged upload (any size) NewAttachment::new("contract.pdf", AttachmentContent::Upload(upload)) .on(ParentRef::new("res.partner", partner)), // bytes up to the inline threshold need no upload NewAttachment::new("note.txt", AttachmentContent::Bytes(b"hello".to_vec())) .on(ParentRef::new("res.partner", partner)), // a link to an external page (http or https) NewAttachment::new("site", AttachmentContent::Url("https://example.com".to_owned())), ], ) .await?; assert_eq!(ids.len(), 3); Ok(())}create checks write access to every parent record once per model, links the content, and inserts
the rows. Linking is one set-based step per batch: the upload is consumed (unexpired, same subject and
actor, single use), the blob row of the digest is found or inserted (a unique key on the SHA-256, so two
nodes storing the same bytes at once end with one blob and no race), and a blob that garbage collection
had marked is revived only after its bytes are proved present. A rolled-back transaction leaves the
upload usable again.
create_unique is Odoo’s: it reuses an attachment of the same content and type that the caller may
write, else creates one.
Claim a composer’s files for a record
Section titled “Claim a composer’s files for a record”A chatter composer uploads its files before the message, and so before the record that will own them, is
known. Until the HTTP upload route exists, the mail addon’s thread_upload RPC call (see
Mail, base64 content up to the inline threshold) is that route: it stores them with NewAttachment::pending_in("mail.compose.message"): the row names the
placeholder model, has no record id, and is standalone to the access rules (its creator and the system group
see it). The post path then claims them with attachments::adopt, after it has checked the right to post on the
record:
use erp_addon_base::attachments::{self, AdoptScope, AttachmentContent, NewAttachment, ParentRef};use erp_sdk::prelude::*;
async fn composer_flow(tx: &mut Transaction, ticket: i64) -> Result<()> { // the upload route: the message does not exist yet let draft = attachments::create( tx, vec![ NewAttachment::new("quote.pdf", AttachmentContent::Bytes(b"%PDF".to_vec())) .pending_in("mail.compose.message"), ], ) .await?; // the post: after the caller's post access on the record was checked attachments::adopt( tx, &[draft[0].get()], ParentRef::new("helpdesk.ticket", ticket), &["mail.compose.message"], // an internal caller may also name files already on the record AdoptScope::ComposerAndRecord, ) .await?; Ok(())}adopt accepts an id only if it is the caller’s own file in one of the placeholder models, or, with
AdoptScope::ComposerAndRecord, already on the record (not field-bound). AdoptScope::ComposerOnly is for a caller
outside the internal group (the chatter passes it for a portal user, as Odoo keeps only their own composer files): a file
already on the record is refused by name like any other. For the files already on the record ComposerAndRecord also
requires write access to the record (Access otherwise), as Odoo’s post route refuses a file the caller may not write.
adopt is not for public or shared principals until
scoped principal tokens exist: its creator test compares the caller’s user id. Anything else, a missing id included, refuses the whole call with Access, names the
ids, and moves nothing. The move is one set-based write as the system, because the right that matters is the
right to post (a portal user may post on a record they may only read, and has no right on the file table);
reattach is the call to use when the caller must hold write access to the target.
A composer file that no post ever claims is removed by the staging cleaner job after attachments.composer_retention_secs
(default 24 hours, at least one hour; CleanReport::abandoned); the cleaner only touches rows of the composer placeholder model
with no record id.
List and open
Section titled “List and open”use erp_addon_base::attachments::{self, ListOptions};use erp_sdk::blob::ByteRange;use erp_sdk::prelude::*;
async fn show(tx: &mut Transaction, partner: i64) -> Result<()> { // the chatter panel: what the caller may read of this record's files let files = attachments::for_record(tx, "res.partner", &[partner], ListOptions::default()).await?; for file in &files { let handle = attachments::open(tx, file.id).await?; // a range, streamed: nothing is loaded whole let first = ByteRange::new(0, 1024.min(handle.size()).max(1)); let part = handle.open(Some(first)).await?; drop(part); } Ok(())}open returns a BlobHandle: size, type and checksum come from the database before any byte is
fetched; open(range) streams; read_to_vec(max_bytes) refuses content above max_bytes up front and
checks the SHA-256 of what it read. Missing content is an AttachmentContentMissing internal error,
never an empty body (Odoo serves an empty file: ir_attachment.py:145-152).
The content route: GET|HEAD /erp/content/<id>
Section titled “The content route: GET|HEAD /erp/content/<id>”The browser reads a file by attachment id at /erp/content/<id> (Odoo’s /web/content/<id> is
served in place, so existing links keep working). Our web client’s chatter uses it for thumbnails
and ?download=true for the download link. What the route does (SPEC-BASE-175):
- it needs a signed-in browser session (
401without one; anAuthorizationheader is401for now, bearer reads come later); onlyGETandHEAD(405withAllow: GET, HEAD); - only internal users are served: a portal or public caller gets the
404(SPEC-BASE-150; portal reads come with link principals). The read check is the one of “Who may see a file” below, run under the caller’s principal in the session’s transaction before anything else. No company selection is needed in the URL: a session reads with all of the user’s allowed companies. A missing id, a refused read, a record of another company, a URL attachment and one without stored content all answer the same404; - the transaction ends before any byte is read; one byte range is
206, several, malformed or unsatisfiable ranges are416naming the reason, andIf-Rangereturns the whole file (there is noETagyet); - query keys:
download=true|falseandmimetype=application/octet-stream; anything else is400; - headers are the
attachmentclass:Content-Security-Policy: default-src 'none'; sandbox,X-Content-Type-Options: nosniff,Referrer-Policy: no-referrer,Cache-Control: private,Cross-Origin-Resource-Policy: same-origin, an RFC 6266Content-Dispositionwithfilename*. Only PNG, JPEG, GIF, WebP and PDF areinline(and not withdownload=true); HTML, SVG, XML, JavaScript and WASM are served asapplication/octet-stream; - a node with every stream permit in use answers
503withRetry-After: 1; content whose bytes are gone is500 AttachmentContentMissing <request id>(the attachment and digest are in the server log).
Native code reads the same way with attachments::content::lookup_content(tx, id): it takes the
caller’s transaction, does the check itself and returns ContentLookup::Found with a
RouteContent that stays usable after the transaction ended (open(range) takes the stream permit
and opens the bytes). There is no entry that returns bytes by id without the check. Not in this
route yet: /web/image, model/id/field paths, access_token and public files, URL-attachment
redirects.
Move, copy and unlink by record
Section titled “Move, copy and unlink by record”use erp_addon_base::attachments::{self, ParentRef};use erp_sdk::prelude::*;
async fn move_files(tx: &mut Transaction, attachment: i64, message: i64) -> Result<()> { // an activity's files move to the message when it is done attachments::reattach(tx, &[attachment], Some(ParentRef::new("mail.message", message))).await?; // a copy references the same blob: no byte is copied attachments::copy(tx, &[attachment], Some(ParentRef::new("mail.message", message))).await?; Ok(())}Deleting a record deletes its attachments, in one statement per unlink call: the composition root
registers attachments::UNLINK_HOOK (the server composition does). Deleting an attachment removes the
row only; the blob becomes a garbage candidate through a statement trigger, and the collection job
removes its bytes after the grace period if nothing references it any more.
Who may see a file
Section titled “Who may see a file”Access derives from the record the file is attached to (Odoo _compute_res_access): a record-bound
attachment is allowed when the caller may read (write, for create, write and delete) the parent; a
field-bound one needs access to that field too, except for the system group; a standalone one belongs
to its creator and the system group; a parent that no longer exists, whose model is not installed, or
that is security data is denied, and a missing attachment looks the same as a refused one. Checks are
explicit and batched, one per parent model per call.
Until the compiled parent-access rule lands, the generic ORM search and read of ir.attachment
are limited: the system group sees everything, internal users see only the attachments they created,
public and portal users see none. Use for_record and open for the record-derived view.
Treat metadata visibility, file delivery and mutation as separate checks. A record reader can download
a file uploaded by another user without being able to read that file’s generic metadata row. Conversely,
the creator’s metadata grant does not authorize downloading or moving a file after it has been bound to
a record the creator cannot access. Rebinding checks write access on both its current and proposed
parent, including a changed res_field; a refused batch leaves the binding unchanged.
The current /erp/content/<id> route requires a signed-in session even when the row has public=true.
The public content capability of SPEC-BASE-143 is separate, unimplemented behavior; the flag grants no
anonymous JSON-2 metadata access. Native multi-user acceptance for these distinctions is in
crates/erp-cli/tests/multiuser_mail_attachments.rs (partial SPEC-HUMAN-033 coverage).
The service checks the caller first (parent access and, for a binary attachment with a URL, which a
copy keeps, the serving group), then writes the rows as superuser inside a private scope. An addon’s
override of ir.attachment create or write that runs during that write, and anything it calls
in the same transaction, sees the superuser environment and inherits the scope: do its own checks
from the values, not from the environment.
Errors you will meet
Section titled “Errors you will meet”| Situation | Kind | Message starts with |
|---|---|---|
| Parent refused | Access | Sorry, you are not allowed to access this document. |
| Upload unknown, expired, used or another user’s | Validation | The upload is not usable: |
| Storage quota or a database/subject staging-byte budget is exhausted | ResourceExhausted | This file cannot be uploaded because the attachment storage limit |
| Subject pending-count cap is reached | ResourceExhausted | Too many uploads are pending. |
| Receive outlives its durable intent | Validation | The upload intent expired |
| Declared type does not match the content | Validation | declared content type |
| Bytes above the inline threshold passed in memory | Validation | Content above |
| No attachment runtime attached | UserError (422) | Attachments are not configured: |
| Several nodes, node-local store | Programming | The attachment store |
| Content missing from the store | Internal | AttachmentContentMissing: |
Every streaming permit of this node held (stream_permits_per_node, per node); retry shortly | Lock | every attachment stream of this node is in use |
| Copy of a binary attachment with a URL, without the serving group | Validation | Sorry, you are not allowed to write on this document |
adopt of a file that is not the caller’s pending file or (with ComposerAndRecord) already on the record, or that does not exist | Access | These attachments cannot be linked here: |
adopt of more than 1000 ids or a non-positive id | Validation | At most 1000 attachments are claimed / An attachment id is a positive number |
| A pending file with a parent or a field | Validation | A pending attachment belongs to a placeholder model |
Porting from Odoo
Section titled “Porting from Odoo”| Odoo | Here |
|---|---|
attachment.raw, datas, db_datas, store_fname, index_content | none: bytes are blobs; use open and Uploader; text indexing is the M5 extraction task |
ir_attachment.location | server configuration attachments.write_store; writing the parameter is refused |
_filtered_access, check | the explicit parent check inside every function above |
create_unique | create_unique |
copy | copy: shares the blob |
| file served empty when missing | an error |
XML and SVG neutered to text/plain for non-administrators | the detected type for everyone; active types are served only as downloads (HTTP route, planned) |
SHA-1 checksum as the file address | SHA-1 stays in checksum; the address is SHA-256 |
What is different from Odoo, as behaviour
Section titled “What is different from Odoo, as behaviour”- Odoo’s filestore is a directory on one node (
ir_attachment.py:99-101,_filestore), so several application servers need a shared filesystem or an add-on; here the store is shared by design (an object store, or a shared path declared by the operator), and a node that mounts another directory refuses to serve. - Odoo collects garbage by marking files in a
checklistdirectory on every write and walking it later (ir_attachment.py:161-162,224-242,265-371); here references are database rows guarded by a foreign key, unreferencing enqueues a candidate, and any node runs the collection as a leased job. - Odoo compares whole files to deduplicate because SHA-1 can collide (
:164-170); here the key is the SHA-256 and the unique index decides. - Odoo filters attachments in Python and gives up past a candidate limit (
:43-44,779-782); here the parent check is one batched call per model and there is no such ceiling in the API.
Planned streaming HTTP contract — not available yet
Section titled “Planned streaming HTTP contract — not available yet”The planned POST /erp/attachments/upload route will return
{upload_id, size, checksum, mimetype}. A native
composition adapter will stream into Uploader; the HTTP crate will not depend on the base addon.
Existing typed staging/linking APIs remain the implemented path. Chatter RPCs still use bounded
base64; their planned upload_id alternative and thread_post staged descriptors must not be called
until the HTTP/mail implementation is available.
Owner marker primitives for native composition
Section titled “Owner marker primitives for native composition”erp_blob::AttachmentStore exposes owner, put_owner, check_owner, contested,
create_contested and probe_owner. The memory store and object-store adapter implement these
low-level operations. LocalStore implements them on Linux and macOS through exclusive-create
leases, a stable OS advisory guard and atomic no-replace rename. Other platforms retain typed
unsupported defaults. An advertised capability never grants ownership admission by itself.
OwnerIdentity records the cluster identifier, database OID and database incarnation.
OwnerMarker adds a positive generation, a unique operation UUID and Unix seconds. Its strict
v1 encoding rejects extra bytes and unknown formats. OwnerVersion preserves the backend ETag
and optional version identifier; keep both in durable coordinator state. Tokens reject wildcards,
lists and header control characters. OwnerState pairs a record with the version from the same read.
Passing no expected version to put_owner means create-only. Passing the last confirmed version
means compare-and-swap; a failed precondition returns BlobError::OwnerConflict. The coordinator
must persist its intended operation before issuing the put. An existing contested marker is never
overwritten, and the store API has no operation to clear it. check_owner checks the current owner,
not an old version selected by a versioned-object query; it does not also check contest absence.
Run probe_owner against each configured backend before accepting its ownership capabilities.
It exercises create-only writes, stale and matching conditional writes, current-owner checks and
create-only contest writes in a fresh random namespace, then removes only its own probe markers. LocalStore exclusively
creates the probe namespace before it can own cleanup; an existing namespace is refused intact.
A probe failure is an error even when the advertised capability flag is true. Cleanup failures
retain the original probe error and the cleanup error in OwnerProbeCleanup; failed probe objects
may remain in that private namespace. No content or staging object is removed by the probe.
These primitives do not activate maintenance. The coordinator API below adds heartbeat health
and durable observation. Sweep and staging-cleanup primitives enforce current ownership;
shared-filesystem peer admission and native runner activation remain pending. Native composition must complete those parts before admitting destructive maintenance. The clone isolation procedure in the operator
guide remains required. The executable marker examples are in
crates/erp-blob/tests/owner_contract.rs. Object-adapter coverage uses an in-memory object store;
live S3-provider behavior remains unverified. Local process fixtures are in
crates/erp-blob/tests/local_owner_process.rs and crates/erp-blob/tests/support/local_owner.rs.
They establish local primitive behavior, not whole application/database or shared-filesystem admission.
Local owner records pair the canonical marker with a fresh publication nonce. Persist the returned opaque version unchanged; publishing the same marker again still changes its version. A single open file yields the marker and token together. The implementation syncs temporary records before naming them and syncs the namespace directory before acknowledging publication.
The local lease lasts 30 seconds and contains an acquisition nonce, advancement operation and expiry.
A verified expired lease can be moved aside; changed lease data is restored with no-replace rename.
The stable .owner.guard interlocks final validation, publication and release. A paused holder inside
that guard causes retryable refusal, even after lease expiry. A resumed stale holder cannot publish
or remove a successor’s lease. Guard/lease contention is retryable Unavailable, distinct from
OwnerConflict. Reads and writes of malformed state fail explicitly.
A failure after publication can leave the intended owner installed. Recover by reading the exact persisted intended operation through the ownership coordinator; never assume an error undid the put. A truncated lease after a process crash refuses further advancement instead of guessing expiry. Recovery artifacts remain for diagnosis when safe restoration fails. No automatic force claim or manual marker-deletion procedure is provided by this library slice.
Durable ownership coordinator
Section titled “Durable ownership coordinator”attachments::ownership implements ADR 0041’s owner protocol as explicit transaction boundaries.
An owner-side native consumer commits prepare(tx, store_key, Purpose::Heartbeat) in READ COMMITTED,
performs Prepared::execute() outside the transaction, then commits settle(tx, &prepared, attempt).
Only after that commit does it interpret Settlement. A retry retains the exact pending marker;
a successful external write with a lost database commit is recovered by exact marker equality.
A matching database identity or a larger generation alone is insufficient.
ContestPending means refusal is durable before marker publication. The consumer publishes the
create-only contest outside a transaction and commits settle_contest; a publication failure keeps
the pending refusal and its typed storage error. Contests are never cleared automatically.
HeartbeatJob provides that fenced native sequence. It is registered as
base.attachment_owner_heartbeat and gc::ensure_schedules keeps its recurring row under the shared
ownership::SINGLETON. Each beat prepares with Purpose::Observe, which opens a cleanup observation
window when none is open and keeps an open one, so scheduled cleanup is admitted 660 seconds after the
first healthy beat. Running it still needs an owner-role ORM and the privileged native-handler
allowlist of ADR 0165 D5; the runtime role cannot write ownership state and fails loudly.
gc::clean_staging and gc::sweep_mark admit each external store once per call. A store that is not
admitted is left out (its rows, bytes and reservations stay), the refusal is logged at error level with
the store and the reason, CleanReport::skipped counts the staging rows left, and
CleanReport::refused / SweepMark::refused name each refused store (RefusedStore { store_id, reason }; reason is the fixed text of the refusal, or store_error). sweep_mark returns a
SweepMark { ids, refused }; pass ids to sweep_remove. Inline rows and other stores are still
cleaned. gc::check_cleanup returns the exact refusal for one store. Shared local stores are refused
whatever the peer-probe evidence: no cleanup path reads it yet.
The heartbeat handler persists {"after": <last visited store key>, "refused": {<key>: <code>}} in
its job progress: a yielded run resumes after after, which is cleared only after a complete cycle.
A store it cannot advance is recorded with an ownership::Refusal code and skipped, so the following
stores are still beaten, and the run does not fail for it.
health(&runtime_orm, store_key) and observation open a fresh primary READ COMMITTED transaction,
close it before store I/O, and validate current store markers. No elevated connection enters these
read APIs. Health expires after 600 seconds without a confirmed heartbeat. These APIs are not yet
wired to all upload/link/revive call sites; FENCE integration retains that obligation.
Starting Purpose::Observe establishes a durable 660-second window. Healthy heartbeats update the
current owner version while preserving its anchor. Ambiguous recovery or a heartbeat gap invalidates
continuity. Waiting returns a delay to reschedule, holding no transaction or connection. Ready returns
a window identity, never permission to delete. The sweep and cleaner recheck owner/contest,
identity, observation, holds, references and capabilities at each removal chunk. Shared local
storage remains refused until maintenance integrates and verifies peer evidence. Borrowed-store sweeping remains
unsupported. Complete SPEC-UPLOAD-010 and separate-process SPEC-BASE-158 acceptance remain pending.
Shared-local peer evidence
Section titled “Shared-local peer evidence”erp_sdk::blob::peer separates actual local primitive observations (LocalPeer::step) and
successful private cleanup (PeerCleanup) from raw transcript bytes. These private-field types
have no public success constructor or deserializer. verify_transcript validates the fixed
primitive transcript; it is not an authorization token.
The native base API attachments::peer_probe stores one current attempt per store. Use owner-side
primary READ COMMITTED transactions with an OperationIdentity for every audited transition;
commit and drop each transaction before filesystem I/O or waiting. start, join, ready,
record, finalize, fail and completed support the operator CLI. finalize consumes an actual
cleanup proof and commits verified evidence with its typed audit event. The event retains the bounded node identifiers (one at start, both after join), so replacing the current row does not erase the audited pair. No API imports a success
receipt. Runtime roles receive SELECT only on ir_blob_peer_probe.
A future cleanup integration must call peer_probe::admit with the current node, automatically collected host
provenance and current physical mount binding. It rechecks the fingerprint without the runtime’s
fingerprint cache and refuses an unlisted or changed participant. This is only the peer prerequisite:
retain the ownership coordinator, contest, observation, hold, borrowed-store and per-chunk checks.
The current scope is the verified pair; additional hosts need explicit admission. Operator usage,
limits and remaining activation work are in the installation attachment-store page.
Fenced cleanup for native maintenance
Section titled “Fenced cleanup for native maintenance”Storage promotion publishes content create-only and retains its staging source. A failed local
receive may retain its deterministic .part file. Keep the committed upload intent until the
cleaner removes both forms; callers never remove staging after a failed or successful link.
External staging reservations remain charged until physical removal succeeds or absence is
confirmed. This applies to deduplicated uploads too. Inline consumption releases its reservation
transactionally; rollback restores the original ready intent and reservation.
The native maintenance consumer establishes observation with the committed prepare/execute/settle sequence above and reschedules while waiting. It must keep the heartbeat healthy during the wait. It can check admission inside its actual owner-side READ COMMITTED transaction:
use erp_addon_base::attachments::gc;use erp_sdk::{Result, Transaction};
async fn admitted(tx: &mut Transaction) -> Result<()> { gc::check_cleanup(tx, "main").await}This check holds coordinator/metadata locks until the transaction ends. It is neither a reusable
permit nor a reason to sleep inside the transaction. sweep_mark, sweep_remove and
clean_staging check again themselves. Their batch size is 1–1000. Both sweep transactions and
staging cleanup use READ COMMITTED. Roll back on any error: partial external deletion can have
happened, while database rollback retains the intent or sweep-attempt marker for an idempotent retry.
BlobError::CleanupRefused names a fixed admission reason and remains the source of an Internal
ORM error. Missing conditional or peer capabilities use OwnerCapabilityMissing; backend failures
retain their typed cause. Multipart abort failures preserve the receive error and a separately
redacted abort diagnostic in StagingAbort. Incomplete multipart sessions still require provider
lifecycle cleanup after a crash. No listing-based recovery or automatic contest clearing is added.
This library seam grants no SQL privileges and activates no schedules. A System principal on a request-role connection still cannot execute privileged cleanup. The maintenance composition must use its isolated authorized role; the general runner remains on its runtime role (ADR 0165 D5).
Bounded pending batches
Section titled “Bounded pending batches”attachments::create_pending(tx, placeholder, limit, items) creates a batch that awaits a parent
record. Check the caller’s intended operation first. Items supply no parent, field or placeholder;
the helper assigns the validated placeholder, derives the subject from the transaction principal,
and admits against the actual pending rows. Limit and batch are bounded by MAX_BATCH (1000).
An empty batch returns no ids. Invalid items or an exceeded cap create nothing.
A full cap is a Validation error with PendingLimitExceeded as its typed source. A consumer may
map that source to its own recovery message; it must propagate all other errors. A shared guard
row prevents stale repeatable-read snapshots from over-admitting: PostgreSQL returns 40001 and
normal whole-call retry obtains a fresh snapshot. Own flushed writes count. The helper’s savepoint
and guard share the business transaction; no independently committed reservation survives rollback.
Do not perform body transfer inside this operation. Direct staged posts use ordinary batch
creation and adoption in their one transaction, since no waiting file is committed.
Owner recovery API
Section titled “Owner recovery API”attachments::recovery is an owner-side operator API (ADR 0183), never an RPC shortcut. inspect
returns the validated database/store snapshot; begin commits a closed operator reason and audit
before external effects. Its Claim::id is the durable resume identifier. resume reloads that
same operation, Claim::phase reads progress, and Claim::run performs bounded resumable phases.
The ORM must have the real attachment runtime attached to its registry generation and a ready
audit store. Actual relation ownership is checked; a System environment alone does not authorize
recovery. Store primitives are low-level ports and must not be called to bypass this audit path.
An active recovery makes ordinary ownership health unavailable and refuses prepare/settlement. Errors retain their kind/source and identify incomplete operations. A successful claim invalidates old observation; it is not a deletion capability. The CLI runbook is in Attachment store for operators.
Bounded policy and owner execution
Section titled “Bounded policy and owner execution”Quota admission reads at most attachments.usage_delta_read_limit deltas plus one overflow sentinel
in one snapshot. Excess backlog and unknown legacy occupancy return typed AccountingUnavailable;
quota/pending/timeout errors retain typed causes with safe public messages. The compactor folds only
the actual DELETE RETURNING set. Its batch and interval are validated database parameters.
gc::maintenance_kinds() is the fixed exact-declaration list for native server composition. Addon
payloads, model methods and an arbitrary elevated declaration cannot join it. The owner ORM omits
package hooks. Metadata GC/reconcile calls require maintenance authority and READ COMMITTED, like
their scheduled handlers. External deletion remains separately fenced per store and chunk.