Attachment store for operators
File bytes never live in a business table. Metadata, references and the garbage collection queue are in PostgreSQL; the bytes are in a store that every node of the deployment reaches: an S3-compatible bucket, or a local path that all nodes mount from shared storage (ADR 0041). A directory that only one node can see is a single-node setup and the deployment refuses to run a second node on it.
Configure a store
Section titled “Configure a store”Stores are server configuration, never database data, and credentials never appear in it.
[attachments]write_store = "main" # where new content goesinline_max_bytes = 2048 # content up to this size is a database row (0 to 65536)max_file_bytes = 134217728 # one attachment, at most (1 MiB to 2 GiB; file_size is an Odoo integer)gc_grace_secs = 86400 # an unreferenced blob keeps its bytes this long (3600 to 30 days)stream_permits_per_node = 32 # streaming operations ONE node runs at once (1 to 1024); per node, not cluster-widestaging_max_bytes = 4294967296 # hard database staging reservations (default 4 GiB)upload_idle_timeout_secs = 30 # no new body bytes (1 to 300 seconds)upload_receive_timeout_secs = 600 # whole receive (10 to 86400), capped by upload_ttl_secs# quota_bytes = 10737418240 # optional soft storage quota (example: 10 GiB)
[attachments.stores.main]kind = "s3"bucket = "erp-files"region = "eu-west-1"prefix = "tenant-acme" # keys live under this prefix; one bucket may serve one operator# endpoint = "https://minio.internal:9000" # S3-compatible services; https, or http on a loopback address# path_style = true # most self-hosted services
# or, on shared storage mounted at the same path on every node:# [attachments.stores.main]# kind = "local"# path = "/srv/erp/attachments"# shared_filesystem = true- Credentials for
s3come from the process environment (AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN) or an instance role, never from this file. Give the application role read, write and delete on the prefix only; listing the bucket is needed only by the verification role. - An unknown key, an unknown kind, a value outside its bounds, a relative path, an
endpointthat is plainhttpoutside a loopback address, a missingwrite_store,encryption = "on"and a scan mode other thanofffail at startup naming the setting. Thepostgreskind (small sites, bytes in the database) is not built yet (the BASE-B postgres-store follow-up). - Hosting. One bucket with a prefix per database is fine for one operator. A multi-tenant host must give each tenant its own bucket, or credentials scoped to its prefix.
- Writing the Odoo parameter
ir_attachment.locationis refused: it names this configuration.
The server (erp server --config server.toml) opens the stores with AttachmentConfig::from_toml and
AttachmentRuntime::open (crate erp-blob) at start and attaches the product to every registry generation.
With no [attachments] table the server uses the default of ADR 0041 (lead ruling 3): a local store, id
main, in the directory attachments next to server.toml. The server creates the directory (mode 0700)
when it starts, so an installation needs nothing else; the directory belongs to the user that runs the
server and must be kept with the database in the backup. To place it elsewhere, or to use S3, write the
table (it goes after the plain keys of the file):
[attachments]write_store = "main"[attachments.stores.main]kind = "local"path = "/var/lib/erpforall/attachments"An invalid table, or a store that cannot be opened, stops the start with an error that names the setting. A
host that composes the ORM without a runtime answers every attachment call with UserError (HTTP 422),
Attachments are not configured: ... set attachments.write_store ....
What size a browser upload may have is a separate limit. Until the HTTP upload route exists, the chatter uploads through the thread_upload RPC call, which holds the content to
attachments.inline_max_bytes (2 KiB by default, at most 64 KiB; set it in the same table).
The database administrator can further restrict files using base.attachment_max_bytes, visible in
Settings and Technical System Parameters. Default: 134217728 bytes; floor: 1; hard bound: 2147483647.
Changes take effect on subsequent requests without restart. This value does not enlarge the inline
path or override the existing node attachments.max_file_bytes ceiling. Administrators choose the
database scope in Settings and edit Maximum attachment size (bytes) under Base, or edit the
same key in Technical → System Parameters. Clearing the Technical value restores the default.
All serving nodes must retain consistent
node ceilings; bootstrap reports the current node’s effective inline-path limit.
limits.rpc_body_bytes stays node configuration because request buffering must be bounded before
database policy is available. It counts the JSON envelope and base64 encoding, not just decoded file
bytes. Stream permits, deadlines, staging reservations and storage quotas remain independent resource
controls. Lowering the upload policy does not remove or block reading existing attachments.
Several nodes
Section titled “Several nodes”There is no node-local authority: any node links, reads and collects, and losing a node loses no file. Configure the same quota, staging, pending-count and file limits on every serving node. Drain old writers and restart all nodes together when changing these installation limits; mixed configuration generations are not a supported limit rollout. How a misconfiguration is detected:
- Node registry. More than one live node (
erp_node, ADR 0057) while alocalstore lacksshared_filesystem = truemakes uploads and the attachment schedules fail withThe attachment store <id> is a node-local directory but N nodes are live .... The flag is the operator’s statement that the path is shared storage; it is not probed. - Store identity. Each store has a random id (
.store-idin the directory, a marker object in the bucket); the database records it the first time the store is used. A node that mounts another directory or another prefix finds a different id and refuses to read or write (not retryable), so files cannot silently split across two disks even if the flag was set wrongly.
Garbage collection and cleanup
Section titled “Garbage collection and cleanup”Five job kinds run on the durable queue (see Background jobs); there is no scheduler process and no leader, any worker may claim them, and each has a singleton key so one runs at a time per database:
| Kind | What it does |
|---|---|
base.attachment_gc | Phase A: marks blobs nobody references deleting. Phase B: after the grace, removes the rows and the bytes in chunks of at most 1,000 keys. |
base.attachment_clean_staging | Removes consumed uploads and expired ones with their staged objects; adopts the digest of an expired upload so a key promoted by a rolled-back transaction is removed too. |
base.attachment_reconcile | Walks the blob table by id and queues unreferenced blobs the statement triggers missed (a restore with triggers disabled). |
base.attachment_owner_heartbeat | Every five minutes: advances this database’s owner marker in each configured store and opens the 660-second observation window when none is open. Without it no store-backed cleanup is admitted. It writes ownership state, so it needs the owner-role maintenance runner. |
base.attachment_verify | On demand (payload {"deep": true} re-hashes the bytes): reports missing, short or corrupt blobs; fails the job listing up to 20; repairs nothing. |
A blob another node is still writing is never deleted. A writer holds a shared lock on the blob
row from the link until its commit; the sweep locks rows exclusively and skips locked ones, so it never
waits for or removes content a transaction is linking. A blob nobody references is first only marked;
its bytes leave after gc_grace_secs and only if, in a second transaction, the row is still
unreferenced and unlocked. A writer that arrives in between revives the row, after proving its bytes
are present. The upload record is the write-ahead marker: it commits before the first byte reaches the
store and is removed only after an admitted cleaner has removed its staging object. Link
commit or expiry makes it eligible; neither proves that storage disappeared. A key removed whose
transaction did not commit is simply reported absent the next time.
The schedules exist after every base install and upgrade. erp db init and
erp module install|upgrade with base in the operation create the recurring row of
base.attachment_gc, base.attachment_clean_staging and base.attachment_reconcile when that kind
has no live row (any state but dead), in the operation’s own transaction. A row that exists keeps
its next run time, a running row is left alone, and a dead letter gets a fresh row next to it.
Every erp server start does the same before the node reports ready, on the owner connection
and without the store topology check (that check stays at upload and before every destructive store
call). Two nodes starting together should end with one row per kind: the creation runs under an
advisory lock (expected from the code, not tested). A start that cannot keep the
schedules stops with a short cause and does not serve.
erp_addon_base::attachments::gc::ensure_schedules(&orm) does the same in its own transaction
after the store topology check, and is idempotent across nodes.
Rows are not runs. The rows run only where a job runner claims them. The isolated maintenance runner for these kinds (ADR 0165 D5) is planned; until it is deployed, nothing collects, cleans or reconciles on its own. Do not treat the presence of the rows as attachment maintenance being operational.
With the in-app runner on (jobs_run_in_app = true), that runner leaves these rows alone: it
excludes the elevated attachment kinds (base.attachment_gc, base.attachment_clean_staging,
base.attachment_reconcile, base.attachment_verify; ADR 0165 D5, ADR 0185), so the rows stay
ready, are never claimed and nothing goes dead. Running them is planned work.
A base upgrade during a server start. erp module upgrade base while a node is starting can
abort on a serialization error when both create the schedule rows at the same moment. Nothing is
committed; run the upgrade again.
Old attachment dead letters. A dead attachment schedule row (from an earlier release or a test) is not live, so the next start creates a fresh row next to it. Discard such dead letters rather than requeue them: a requeue collides with the fresh row on the queue’s dedup index and is refused.
A backup that copies the store apart from the database must keep the sweep from removing files it has
not copied yet. gc::hold(tx, seconds, reason) writes a durable row; the sweep removes nothing while
any hold is unexpired. The tool renews it while it runs and checks at the end that it never lapsed;
gc::release_hold ends it.
Holds and the sweep are serialized by one transaction advisory lock (gc::GC_HOLD_LOCK). Both sweep
transactions take it shared before they read the holds and keep it until they commit; hold takes it
exclusive before it writes its row, so it waits for every sweep that is already running (one that
read the holds before the new row existed) to commit. When hold returns and its transaction commits,
no sweep that missed the hold is still removing keys, and every later sweep sees it. Start the backup’s
database snapshot only after the hold has committed. A hold may therefore take as long as one sweep
chunk (at most 1,000 key removals) to return. The sweep refuses to run outside READ COMMITTED (its
job kinds use it): an older snapshot could miss a hold it waited for.
Limits and what to watch
Section titled “Limits and what to watch”- A file is streamed in 64 KiB reads; an
s3upload holds one 8 MiB part; alocalupload holds the read buffer. No whole file is buffered by the store, and proving a stored file’s digest (a revive after a sweep started, deep verification) streams it the same way. - Required for
s3: a bucket lifecycle rule that aborts incomplete multipart uploads (for example after one day) on the prefix. An upload whose request is dropped mid-stream never sends the abort, and its parts stay billed and invisible to the cleaner, which only sees completed staging objects. Configure the provider’s incomplete-multipart lifecycle rule before using that backend; a durable intent alone does not identify an interrupted provider multipart session. - At most 100 pending uploads per subject (
pending_uploads_per_subject, configurable from 1 to 100); separate API keys share this allowance. Previously accepted values above 100 now fail startup. An upload expires after 24 hours, but expiry alone does not release its storage reservation. Consumed rows do not occupy a pending slot; failed zero-byte rows still do until cleanup succeeds. attachments.staging_max_bytesalways caps database staging reservations (default 4 GiB, configurable from 1 MiB through 9223372036854775807 bytes). Each subject additionally holds at most four times the applicable file limit in reservations. These byte limits are hard across nodes.- Optional
attachments.quota_bytesdeclares a soft storage quota (at least 1 MiB, at most 9223372036854775807 bytes). Omit it for no storage quota; staging limits still apply. Usage includes distinct committed content and retained external staging reservations. Inline linking clears its reservation in the same transaction; external staging stays reserved until admitted physical cleanup. Deduplicated committed content is charged once, independently of retained staging. - Quota observations use a transaction snapshot and an insert-only ledger. Concurrent new-content transactions can overshoot the soft quota by their admitted content sizes, bounded by the number of concurrent operations times their applicable file/batch bounds. Use this bound when sizing storage. Hard staging admission remains serialized in short database transactions.
- Failed receives retain their intent and reservation for fenced cleanup. Watch cleanup-pending
ir_blob_uploadrows (state 3), includingcleanup_error. No active maintenance worker means these reservations may continue refusing admission; raising limits does not repair failed cleanup. - Upload reads stop after
upload_idle_timeout_secswithout bytes, and afterupload_receive_timeout_secstotal even with continuous progress. The total deadline never exceeds intent lifetime. Timeouts release the node stream permit, retaining the cleanup marker. - Quota reads refuse admission when more than 10000 usage deltas remain. Run the admitted owner compactor; do not delete ledger rows manually. Compaction folds the actual deleted deltas into the base in one transaction. The isolated owner worker schedules compaction when explicitly enabled.
- Quota schema version 3 migrates under the lifecycle writer drain once; repeated addon sync
validates columns, constraints, capture functions and triggers instead of recreating them.
Unknown-size legacy uploads become state 3 with
reservation_unknown=trueand numeric reservation zero. This is unknown occupancy, not an empty-object claim. While one such row exists, every staged upload is refused (“temporarily unavailable”), and so is every new inline attachment content whenquota_bytesis configured; with no quota, inline attachments are still created. Only the staging cleaner (base.attachment_clean_staging) removes these rows, and only once the store is admitted: setattachment_maintenance_run_in_app = trueon a node and let the owner heartbeat complete its observation window. Count them before activation withSELECT count(*) FROM ir_blob_upload WHERE reservation_unknown. Never clear the flag manually to restore admission. Validate the migration on the deployment clone before activation and retain a recovery backup. - Watch, too: callers answered
every attachment stream of this node is in use(409, retry). That node’sstream_permits_per_nodeare all held; add nodes or raise the value (see below). - Watch: jobs of kind
base.attachment_*inerp_job(dead letters), rows ofir_blobin statedeletingthat stay (a store outage),ir_blob_uploadrows older than a day, and the size ofir_blob_gc_candidate(it should drain). - Not yet: malware scanning, encryption at rest, online migration between stores, the Odoo filestore import, database duplication that shares blobs, and automatic owner-fenced maintenance for a clone of a database sharing one prefix (see below).
Concurrency limits across nodes
Section titled “Concurrency limits across nodes”| Limit | Scope | How it is enforced | Setting |
|---|---|---|---|
| One run at a time of each attachment job kind | whole cluster | the job queue’s singleton key and lease, in PostgreSQL | none |
| A hold stops every sweep, and waits for a sweep already running | whole cluster | a PostgreSQL transaction advisory lock (gc::GC_HOLD_LOCK) | none |
| The sweep never removes content another node is linking | whole cluster | PostgreSQL row locks and the grace | gc_grace_secs |
| Pending uploads per subject | whole cluster, hard | committed intent plus short ordered advisory locks and fresh READ COMMITTED reads | pending_uploads_per_subject (1–100) |
| Staging bytes | whole database and subject, hard | durable reservations retained through failed cleanup, expiry and consumption | staging_max_bytes; subject allowance is four times the applicable file limit |
| Storage quota | whole database, soft | compacted base plus visible insert-only deltas in one snapshot | optional quota_bytes |
| Concurrent streaming operations: upload staging, proving a stored file, deep verification | each node | an in-process bound; a full node answers busy at once (409), it never queues | stream_permits_per_node (default 32) |
The streaming bound is per node: the deployment’s capacity is nodes × stream_permits_per_node, so
adding a node adds capacity. It is not a cluster-wide cap; a cap on the total requests a bucket
receives (an S3 account limit) is not built yet, so size the per-node value with the node count in
mind.
Restored copies and clones: the shared-prefix hazard
Section titled “Restored copies and clones: the shared-prefix hazard”A database restored next to its source (a staging copy, a clone for a test, a point-in-time restore)
holds the same ir_blob_store row: the same store namespace and the same store id. If it is started
with the source’s [attachments] configuration, it opens the same directory or bucket prefix,
finds the same .store-id, and passes every identity check. Its garbage collection then decides from
its own references: content the source attached after the copy was taken is unreferenced in the
copy. An unfenced worker could remove the source’s keys. The sweep and staging-cleanup library
entry points now require current ownership admission; automatic server composition remains pending.
This does not remove ADR 0041’s stopped-owner residual or replace clone isolation.
Neutralise every copy before any node or worker of it starts:
- Leave the source running; start nothing on the copy.
- Copy the source’s store to a location of the copy’s own, including the identity marker: for
local, copy the directory with its.store-idfile (for examplersync -a /srv/erp/attachments/ /srv/erp-copy/attachments/); fors3, copy every object under the prefix, the.store-idobject included, to a new prefix or bucket (for exampleaws s3 sync s3://erp-files/tenant-acme/ s3://erp-files/tenant-acme-copy/). Files the source added after the database copy was taken are harmless extras in the copy; files the source removed meanwhile are missing there (base.attachment_verifyreports them). - Point the copy’s configuration at the new location (
path, orprefix/bucket) and give its credentials no access to the source’s prefix. - Start the copy. Its sweep now removes keys only in its own location.
If the copy does not need the files, point it at a new empty location instead: the store identity check then refuses every attachment read and write there (the store id differs), which fails loudly and removes nothing.
Prerequisite for the server wiring. The work that wires AttachmentRuntime into the server
must compose the owner fence of ADR 0041 decision 5 with an isolated maintenance
runner. The delivered library checks <ns>/_owner, _contested, database identity, the observation
window and capabilities in both sweep transactions and before staging removal. Server activation
and real shared-filesystem peer admission remain prerequisites. Keep the clone procedure above.
Planned server activation contract — not an operator switch
Section titled “Planned server activation contract — not an operator switch”Streaming HTTP upload and automatic maintenance are planned; this documentation update does not activate a route or job. Before activation the implementation must compose the delivered quota reservations and hard staging caps with the complete ADR 0041 owner fence, and a separate allowlisted attachment maintenance runner. Do not widen runtime-role grants or move the general job runner onto the owner connection to work around missing maintenance. The existing clone procedure and capability limitations above still apply.
The object-store adapter now has low-level owner/CAS/contest marker operations and an explicit conditional-semantics probe. The in-memory test store implements the same operations. This does not protect scheduled cleanup by itself. The coordinator API below is delivered, but native activation remains pending. Library deletion enforcement is delivered; the clone isolation procedure above and ADR 0041’s documented residual still apply. LocalStore now supplies the low-level marker protocol on Linux and macOS. Its capability probe exercises create/CAS, no-replace rename and advisory-guard exclusion on the local filesystem. Unsupported atomic operations refuse explicitly; a capability flag alone is insufficient. The shared-filesystem flag is still not peer-probe evidence. Before future destructive activation, two-node evidence must establish both exclusive creation and the guard’s cross-node exclusion on the actual filesystem. No configuration key or CLI switch enables these planned protections in this delivery.
Local owner markers are <namespace>/_owner and _contested. The implementation uses a 30-second
.owner.lock lease and a stable .owner.guard. Keep the guard file in place: replacing or deleting
it while a process is using the namespace can split its interlock. Internal guard files are private
(mode at most 0600); owner/lease records are created with mode at most 0440 inside private
directories. The store directory and namespace must not be symlinks for owner operations.
A busy guard or live lease returns retryable unavailable. A verified expired lease is recovered without overwriting another holder. Missing OS support, malformed records, failed directory sync and failed restoration refuse advancement. A crash during initial lease creation can leave an incomplete lease; this delivery refuses it and provides no automatic repair command. Preserve artifacts and keep destructive maintenance disabled pending supported operator recovery. A put error after naming the owner can be ambiguous, so coordinator recovery must inspect the intended operation rather than retrying with invented ownership. Process-crash tests do not establish physical power-loss behavior on every filesystem.
Application jobs disabled means an admitted maintenance worker is required; a recurring schedule row alone is not evidence of running cleanup. Upload HTTP remains a separate delivery. The isolated attachment worker below is explicitly enabled per node; ordinary application jobs can remain disabled.
Upgrade base with the authorized owner-side lifecycle before publishing runtime grants. Drain
old application writers for the schema/backfill transaction. The upgrade backfills existing distinct
blobs and retained uploads once; legacy receiving rows without a size reserve the historical maximum
file size conservatively until cleanup. An over-cap database remains readable but refuses new
admission. Contract version 7 publishes append-only accounting and restricted attachment writes;
older publishers must not be restored over it. Ordinary requests cannot delete tracking/content rows
or compact usage. Schema synchronization and a focused upgrade fixture establish the additive path;
server maintenance activation still belongs to its separate delivery.
Ownership coordinator delivery boundary
Section titled “Ownership coordinator delivery boundary”The durable coordinator uses additive ir_blob_owner_identity and ir_blob_owner_state tables.
An authorized base upgrade installs them without changing existing blobs, uploads or accounting and
without inventing a heartbeat. Request roles get SELECT only; publisher contract v9 refuses missing
ownership tables or effective write privileges through PUBLIC/inherited roles. Automatic restoration
of an older publisher is refused because it could regrant writes to retained coordination state.
The native heartbeat is registered as base.attachment_owner_heartbeat and scheduled by the same
ensure_schedules call as the other attachment jobs; the served binary does not call it yet.
Server maintenance composition, request write-health enforcement and shared-filesystem peer
admission remain integration work. Sweep and staging deletion now enforce the coordinator’s
current admission state in the actual cleanup transaction. Existing configured storage is not proof that maintenance is
operational. Do not clear store markers by hand as a substitute for an audited operator claim.
Once integrated, a heartbeat advances ownership every five minutes and 600 seconds without confirmed
success makes established ownership unavailable. Failed store writes do not refresh that timestamp.
Each advancement persists its exact intended marker before the conditional write; restart recovers only
that marker. A lost conditional claim records contest-pending before publishing create-only _contested;
failed publication preserves refusal. Repeated upgrades and restarts never reset ownership identity.
Cleanup observation is durable for 660 seconds (two heartbeat intervals plus a one-minute margin). Healthy heartbeat successors preserve the original window; uncertainty or a health gap restarts it. A live clone sharing an identity can contest during this interval. ADR 0041’s residual remains when the original database is stopped or cannot reach storage throughout the interval: neutralize or rebase clones before starting jobs. The local primitives merged separately; real provider/peer proof remains an admission requirement; coordinator readiness alone never permits deletion.
Shared local filesystem peer probe
Section titled “Shared local filesystem peer probe”erp attachments probe-store --peer verifies the filesystem primitives used by local owner
fencing. Run it as an operator on two distinct hosts using their protected server configurations,
different node_name values, the same tenant database and the same registered local store. Each
configuration must declare shared_filesystem = true. The store must already be registered by the
attachment runtime; the probe does not install or upgrade the database. Upgrade base and publish
the current runtime grants before using the command. The audit store must be ready.
On the first host:
erp attachments probe-store --peer --config /etc/erp/server.toml --store main start --timeout 120The process prints a fresh session UUID and waits. On the second host, before the deadline:
erp attachments probe-store --peer --config /etc/erp/server.toml --store main join SESSION_UUIDInspect the current result with:
erp attachments probe-store --peer --config /etc/erp/server.toml --store main statusThe timeout accepts 30–300 seconds. Both processes must finish successfully. The protocol checks fresh challenge visibility, exclusive creation, advisory-guard exclusion in both directions, conditional owner publication and no-replace preservation inside a new private probe namespace. It removes only that attempt’s known artifacts and audits the result. It does not touch the real namespace’s ownership or contested markers, content or staged uploads.
Evidence is bound to the database incarnation, store namespace/fingerprint, protocol and the two node/host/mount bindings. Starting another attempt invalidates previous admission. Missing, expired, failed, incomplete or mismatched evidence refuses destructive admission. A pair does not certify additional hosts. Rerun after mount, storage, configuration or topology changes, including changes an OS mount/root identity cannot detect. Host provenance assumes trusted operators; it is not remote attestation against a privileged host administrator.
On cancellation or failure, preserve unexpected private artifacts for diagnosis and start a fresh
attempt after resolving the reported error. A cleanup or audit failure never publishes successful
new evidence. A kernel filesystem call blocked by an unavailable mount may outlast the orchestration
deadline. Do not replace or remove a real .owner.guard or _contested marker to force progress.
Audited claim --force recovery is planned.
The probe and pair-scoped admission API are delivered by PROBE, but no cleanup path reads the evidence yet: a verified probe admits no deletion today. Destructive-path integration and maintenance activation remain with CLEANUP/INTEGRATE and MAINTENANCE. Probe success alone does not satisfy owner, contest, observation-delay, hold or per-chunk checks. Same-host process fixtures do not certify an actual shared mount; this delivery has no actual two-host shared-mount certificate.
Fenced cleanup delivery boundary
Section titled “Fenced cleanup delivery boundary”An admitted cleanup transaction locks the ownership coordinator, store metadata and owner rows, then the hold lock and content/upload rows. It checks the current store owner version and contest once per store for each chunk (staging cleanup and sweep marking), and again before each store’s batch removal in the sweep. Uninitialized, recovering, stale or contested ownership refuses deletion; missing conditional capabilities refuse too. The 660-second observation wait happens between jobs, with no open cleanup transaction. Healthy heartbeats must continue throughout that wait. The scheduled heartbeat opens the window itself; on a new database store-backed cleanup starts about eleven minutes after the first healthy heartbeat, with no operator step.
A refused store is skipped, never silent. When a store is not admitted (not yet observed long
enough, owned or contested by another database, missing capabilities, unreachable), staging cleanup and
sweep marking leave that store’s rows, bytes and reservations in place and still clean inline rows and
the rows of admitted stores. Each refusal is logged at error level on target erp::attachments with
the store id and the reason (“attachment cleanup is not admitted for this store”), and the staging
cleaner counts the rows it left in skipped in its job progress. A store that stays refused keeps its
consumed staging reserved, so its uploads eventually fail with QuotaExceeded: treat a repeated
refusal as an alert.
Which store, why and since when. The progress of base.attachment_gc and
base.attachment_clean_staging (the jobs admin screen, or erp_job.progress) carries
"refused": {"<store id>": {"reason": "...", "since": <epoch seconds>}}. The reason is a fixed text
(ownership is not admitted, observation is incomplete, namespace is contested,
store binding changed, database identity changed, and so on) or store_error when the store itself
failed (its error is only in the log). since is the database time of the first refusal of an unbroken
run of refusals; a store leaves the list as soon as cleanup admits it again. A store with no due rows,
or a run skipped by an active hold, is not checked and so is not listed.
A long refusal fails the run. Once a store has been refused for longer than the 660-second
observation period, the job first commits what it could clean, then fails for retry with code
cleanup_refused and a message naming each store and its reason (last_error_code and last_error
of the job). The job is retried, not dead-lettered. While the store stays refused the job retries at
the queue’s backoff cadence (jobs.backoff_base_secs, 10 seconds by default) instead of every 15
minutes, so expect extra short runs and repeated error lines until it is fixed. What to do: look up the
store id in ir_blob_store, then act on the reason:
ownership is not admittedorobservation is incomplete: check that the heartbeat runs (below); on a new database the first eleven minutes are expected, a few retries may show then;namespace is contestedordatabase identity changed: another database (often a restored copy) uses the same store prefix; see “Restored copies and clones” above and “Audited operator recovery” below;store binding changedorstore_error: compare the store configuration withir_blob_storeand check that the store is reachable.
The heartbeat continues past a refused store. A store the heartbeat cannot advance (an active
operator recovery, a contest, a changed store binding, a superseded operation or a failing store) is
logged at error level on erp::attachments with its key and a fixed code, and the heartbeat moves on
to the next store, so one store never leaves the others without heartbeats. Its run still succeeds
and reschedules after five minutes. Its progress shows
{"after": null, "refused": {"<store key>": "<code>"}} for the last completed cycle; the codes are recovery_active, contested,
binding_changed, contest_pending, superseded, store_failed and store_invalid (the store has
no fingerprint, its recorded owner marker is unreadable, or its owner generation is exhausted: repair
the store or its configuration). After a cycle with no refused store the progress is null. A
refused store’s own cleanup stays refused (its heartbeat is stale), which the cleanup jobs report as
above. A database error fails the heartbeat run and it is retried. A changed database identity, a
configuration error or an unreadable progress value is permanent: the heartbeat row is dead-lettered
(state dead, with the cause in last_error) and nothing beats until the next erp server start,
which schedules a fresh heartbeat row. Fix the cause first. The same holds for the cleanup jobs when
their stored refused progress is unreadable.
Known limit: one failed beat can start a cleanup_refused episode. A single failed or refused
heartbeat of a store (for example one store timeout) makes that store stale, and a fresh observation
window has to complete before cleanup admits it again: up to about 960 seconds (one heartbeat interval
plus the 660-second window). Because the failure threshold is the 660-second observation period, the
cleanup jobs can report cleanup_refused for that store during part of this time and retry at the
backoff cadence. This is expected; act only when it persists past the window.
Shared local stores currently refuse destructive admission with an error saying that peer probe evidence is not read yet, including when shared_filesystem=true and including after a
verified peer probe: cleanup does not read peer evidence yet, so a recorded probe admits nothing and
the cleaners skip such a store as above. Reading the probe evidence in cleanup is a separate task. Neither the flag nor
single-node local process tests establish two-node evidence. Borrowed namespaces remain explicitly
unsupported for cleanup and their external objects are never removed.
Promotion retains staging until maintenance. Local receive failures can retain .part files under
the upload’s deterministic path. Do not remove those files or their ir_blob_upload rows manually.
A failed delete retains accounting/tracking; retry tolerates objects already removed before a lost
reply or database rollback. A consumed external upload retains its byte reservation, but no longer
occupies a pending-upload slot. Inline consumption releases its staging reservation in its business
transaction. A consumed source retained as a local hard link is conservatively counted as logical
staging occupancy, although the inode is shared.
These are library protections, not evidence of an active owner runner. Before activating schedules, maintenance composition must supply its isolated authorized connection; the heartbeat schedule supplies the observation sequence. Runtime roles keep their existing DELETE/TRUNCATE and coordinator-write denial. Provider multipart lifecycle cleanup, peer probing, operator force claim and complete borrower support remain separate obligations. Actual proof and remaining limits are in the cleanup task report.
Pending attachment schema upgrade
Section titled “Pending attachment schema upgrade”The MAIL upload package adds base infrastructure table ir_attachment_pending_guard. Upgrade
base with the schema-owner connection before publishing request grants or starting this binary.
The additive table has no seed data: pending creation registers a subject/placeholder pair on
first use; a user deletion cascades its guard rows. Existing attachments need no count backfill.
Request roles require SELECT and INSERT on this table, and UPDATE of generation only. They must
have no DELETE, TRUNCATE, identity-column UPDATE, REFERENCES, TRIGGER or MAINTAIN rights. The grant
publisher narrows those rights and startup checks effective grants, including inherited/PUBLIC
rights. Publisher contract 10 adds attachment_pending: guarded-create; older contract restoration
is refused before grant publication or release switching. Reconcile an older publisher explicitly;
never regrant blanket writes to the retained table. This introduces no maintenance schedule.
Mail RPCs accept ready staged ids while retaining bounded base64 input. HTTP staging and browser transport activation are separate packages; RPC support alone does not prove browser integration.
Audited operator recovery
Section titled “Audited operator recovery”An active _contested record stops ownership advancement and cleanup. After identifying and
isolating every competing database, select the database that must own the namespace. Use that
database’s protected server configuration and its owner connection:
erp attachments inspect --config /etc/erp/server.toml --store mainerp attachments claim --config /etc/erp/server.toml --store main --force \ --reason restore-primary --confirm '<exact Confirm token from inspect>'Inspection prints the selected database identity, namespace, observed owner and confirmation token.
restore-primary and retire-clone are the supported reason codes. A changed snapshot requires
another inspection. The command refuses a request-role connection, unavailable audit storage,
changed store binding, copied physical database identity, malformed markers or generation overflow.
The ownership coordinator must already be initialized; this command does not activate maintenance.
A heartbeat advancement that is still in flight refuses the claim: the command reports that an
advancement is in flight and asks you to let the heartbeat settle it. It is treated as in flight
while it is younger than the jobs.job_deadline_secs catalogue hard bound on the database clock (an advancement dated in the
future counts as young), or while a job of the attachment ownership singleton holds a live lease.
After both have lapsed, for example when the store kept failing and the heartbeat stopped, the
claim proceeds and its higher generation supersedes the stale advancement; completion clears it and
the heartbeat continues above the claim’s generation.
Known limit: a heartbeat retry whose job lease lapsed (for example, a node that lost the database
but still reaches the store) can keep writing until its admitted jobs.job_deadline_secs after its run started.
An old pending marker does not record that admitted limit; lowering current policy cannot shorten the
recovery wait, which conservatively uses the catalogue hard bound.
If its owner write lands after the claim’s decision but before the claim’s own owner write, every
resume of that claim reports that the ownership changed, and the claim cannot complete. No content
is deleted and cleanup stays refused. Before you force a claim after a node failure, stop the
failed node’s server process (that ends its writes at once), or wait the deadline catalogue hard bound after
the attachment ownership job last started. If a claim is
already stuck this way, the fix is tracked separately; do not delete markers or recovery rows.
The decision and its audit commit before storage mutation. Ownership is established by conditional
write, then the exact observed contest is conditionally replaced with a resolution receipt. The
receipt stays in storage as recovery evidence. A later conflict creates a new active contest; an
old retry cannot erase it. Keep all writers sharing the namespace on the compatible protocol:
drain and upgrade them before the first force claim. Upgrade base to version 1.13 to install the recovery tables. Contract v12 prevents an automatic rollback
to a publisher that could expose the retained recovery state. Contract v13 grants exactly what v12
grants and only relabels the capability owner-write, progress-read (the owner connection writes
claims, the runtime role reads progress); a restore between v12 and v13 is allowed in both directions.
An incomplete command reports its operation UUID. Inspect the durable phase and resume that exact operation after correcting the reported failure:
erp attachments status --config /etc/erp/server.toml --store main --operation '<UUID>'erp attachments claim --config /etc/erp/server.toml --store main --force --resume '<UUID>'Do not start a new claim to conceal an unknown commit outcome. Preserve _owner, _contested,
.owner.guard, lease artifacts and database decisions. Manual marker deletion and malformed-lease
repair are not supported recovery procedures. An inaccessible clone cannot be proven isolated by
this command; making that operational decision is the operator’s responsibility.
Completion resets observation. Cleanup still needs a fresh 660-second observation window, current owner/contest checks and its normal hold/borrower/peer admission. Recovery removes no attachment content, staged upload, accounting reservation or legal hold. It creates no schedules or workers.
Isolated attachment maintenance
Section titled “Isolated attachment maintenance”Set attachment_maintenance_run_in_app = true in the root of the private server TOML on nodes that
should execute attachment maintenance. It defaults to false and is independent of jobs_run_in_app.
This node setting determines execution topology before the owner pool opens. A disabled node reports
that its schedule rows do not execute cleanup. At least one ready admitted node must run maintenance.
The maintenance runner admits only the fixed native attachment handlers (including heartbeat and
usage compaction). The ordinary runtime-role runner excludes elevated kinds. Both share process and
database job slots; the owner ORM has no package/Wasm hooks and never enters an HTTP request.
Its pool capacity is the configured jobs.workers_per_db plus one control connection. Across N
maintenance nodes the connection capacity is N times that amount; actual active jobs retain the
shared durable queue limits and live-node division.
Readiness loss stops new claims; a generation change fences old owner transactions and supervision
replaces the runner. Shutdown drains it within the server deadline. Request roles retain their
DELETE/TRUNCATE/owner-state restrictions. The owner needs the blob, usage, ownership and job privileges;
missing required privileges refuse maintenance startup. Keep credentials in protected external files.
A scheduled heartbeat establishes the ownership observation window. External cleanup still requires fresh ownership, capabilities, applicable peer evidence and an absent contest on every destructive chunk. Borrowed/refused stores retain their bytes; safe inline cleanup can proceed. Metadata marking and reconcile require maintenance authority, READ COMMITTED and the hold/coordinator locks; they do not themselves authorize store deletion. The deployment clone migration and operator activation remain the designated lead’s release steps, not a consequence of merging source.
Technical policy is editable in Technical → System Parameters, with these defaults and bounds. Missing/empty values use defaults; malformed or out-of-range writes and reads fail by key. Existing TOML upload deadline values remain the fallback until an explicit database override is stored.
| Parameter | Default | Allowed range |
|---|---|---|
attachments.usage_delta_read_limit | 10000 rows | 1–10000 |
attachments.usage_compaction_batch | 1000 rows | 1–10000 |
attachments.usage_compaction_interval_secs | 30 seconds | 1–3600 |
attachments.upload_idle_timeout_secs | 30 seconds | 1–300 |
attachments.upload_receive_timeout_secs | 600 seconds | 10–86400 |
attachments.gc_interval_secs | 900 seconds | 1–86400 |
attachments.cleanup_interval_secs | 900 seconds | 1–86400 |
attachments.reconcile_interval_secs | 21600 seconds | 1–604800 |
attachments.maintenance_batch | 1000 rows | 1–1000 |
attachments.composer_retention_secs | 86400 seconds | 3600–31536000 |
Interval changes apply at a handler’s next run; existing due times are retained. An administrator may
move a job row’s due time using the ordinary job controls. No zero value means unlimited. Unknown
legacy occupancy blocks new staging, and new inline content while a quota is configured, until fenced
cleanup; a ledger backlog above the configured read window blocks soft-quota admission until scheduled
compaction. Never delete ledger rows or clear recovery flags manually. The cleaner deletes a draft
message’s attachments older than attachments.composer_retention_secs, so set it above the longest
time a user may spend writing one message.