Skip to content

Storage

Local storage is the default in generated applications. The development s3-storage feature exposes a private S3-compatible backend; it is not in published Fexu 0.2.0. It does not automatically replace local upload routes or settings.

Enable features = ["s3-storage"] on a matching development source dependency on Fexu. Provision a private bucket and restrict credentials to its Fexu media prefix. Set FEXU_S3_ACCESS_KEY and FEXU_S3_SECRET_KEY in the environment.

use fexu::storage::{
    credentials_from_env, prepare_s3, S3Limits, S3Storage, Storage,
    ACCESS_KEY_ENV, SECRET_KEY_ENV,
};

let plan = prepare_s3(
    "https://storage.example",
    "us-east-1",
    "app-media",
    ACCESS_KEY_ENV,
    SECRET_KEY_ENV,
)?;
let storage = S3Storage::new(
    &plan,
    credentials_from_env(&plan)?,
    S3Limits::default(),
    &["text/plain", "image/png"],
    None,
)?;
let file = storage.save(owner_id, "notes.txt", b"hello").await?;
let (_metadata, bytes) = storage.read_for(owner_id, owner_id, file.id).await?;

The example assumes a verified owner ID from the application session. It uses path-style S3 addressing and a regional endpoint. Private CA PEM bytes may be supplied in the final constructor argument; certificate checking remains enabled. No redirect or implicit HTTP proxy is followed. Configure the Rustls provider before construction if your application requires a different one.

The backend stores one versioned envelope per immutable owner/file UUID, including metadata and a SHA-256 digest. Do not serve raw bucket objects: they contain metadata as well as file bytes. Application downloads must enforce verified ownership and safe response headers. Existing signed-download tokens are application tokens, not S3 presigned URLs. The local HTTP routes are not automatically remote-enabled.

The default file cap is 10 MiB, up to 100 MiB; each request has a bounded timeout. A failed write may have reached storage even if its reply was lost. Automatic retries are disabled. Staged expiry is honored for reads and retain, but expired objects require explicit cleanup. Do not deploy remote staging without a reconciliation policy. No distributed owner quota, automatic orphan scan, multipart support, IAM role refresh or live AWS acceptance is claimed. The initial TLS MinIO contracts passed in PR #271. Additional CI coverage checks explicit concurrent retain/delete operations and persistence across a restart of the same disposable MinIO container. A restart is not a backup/restore or failover guarantee. Automatic expiry cleanup, distributed quotas and production lifecycle acceptance remain separate work.

Explicit expiry reconciliation

The development backend exposes cleanup_unreferenced_expired(owner, id) for an operator or application reconciliation service. Call it only after establishing that no database reference exists and preventing new references during reconciliation. It skips missing, retained and not-yet-expired objects. A conditional tombstone write fences a stale retain before physical deletion; a failed cleanup can be retried using the same immutable ID. There is no scheduled sweep, automatic account purge or database transaction. Do not write or recreate raw keys outside Fexu. Keep server clocks synchronized; bucket versioning may retain historical bytes and requires separate retention policy. The targeted cleanup contract passed in PR #273. Additional deterministic tests exercise a stale ETag after retain and resuming a cleanup from a persisted deletion marker; both tests passed in PR #274. They simulate interruption between requests, not a network fault or server crash.

Reference-aware reconciliation

Use reconcile_expired with an application implementation of ReferenceCheck and the S3 backend. The check returns Referenced, Unknown, or Unreferenced(guard). Only the last decision permits cleanup; lookup errors propagate. The guard must exclude new database references across every writer for the entire cleanup operation. This API keeps the guard alive across storage I/O but cannot prove that an application implements distributed exclusion correctly. No default database adapter, scheduled scan or automatic local cleanup is enabled. Existing local cleanup_orphans is not reference-aware; do not run it on live referenced media. The reference-aware contract passed in PR #275.

Opt-in reference ledger

ReferenceLedger provides a durable admission/retirement gate shared by SQLite and PostgreSQL writers. Explicitly initialize its table with initialize during controlled setup, then enroll only newly allocated media IDs with register. Every model reference addition and removal must call attach or detach in the same database transaction as the model write. The ledger stores a count, not a discovery scan. Missing rows are unknown; retirement is irreversible and requires zero references. ReferenceCheck commits retirement before allowing storage cleanup, so a lost connection cannot reopen admission. A retired key remains retired even if storage cleanup fails or finds a permanent or future-dated file. Only submit expired candidates that will never be reused; keep the ledger and media backups consistent. Do not enroll existing media without a separately verified reference migration. Direct writers, legacy form deletion, automatic enumeration and production integration are not covered. The ledger runtime contracts passed on both databases in PR #277.

Reference-aware model save

After validating and staging an upload, use StagedMedia::commit_referenced(&storage, &db, save) instead of the legacy commit or finish_media path. The async save closure receives the transaction, previous field bindings and replacement bindings. It must compare the current authorized model fields against the previous values under a row lock or an atomic conditional write, persist exactly the replacement values, and return an error on conflict. Do not start or commit a separate transaction. The coordinator enrolls and attaches new IDs, detaches replaced IDs, retains new bytes before committing, and never deletes old bytes. Detached IDs are candidates only, not deletion permission. On any failure, new candidate IDs are reported and no file is deleted; retained but unreferenced bytes can require manual recovery. Cancellation may leave staged or permanent orphans. Do not treat a commit error as proof of rollback. All writers must use the ledger; legacy forms/admin and automatic cleanup remain unintegrated. The SQLite and PostgreSQL model-row contract tests passed in PR #278.

Explicit orphan discovery and cleanup

ReferenceLedger::orphan_candidates(after, limit) returns up to 1,000 enrolled zero-reference IDs in deterministic owner/file order. Pass the last ID as the next cursor, and restart from the beginning on later scans. Results are not a snapshot or permission to delete; newly registered or temporarily unreferenced files can be present. Retired IDs remain visible for repeatable recovery. cleanup_abandoned(&storage, media) is an explicit operator operation for permanently abandoned IDs only, including retained files. It commits the irreversible zero-reference retirement before calling the backend delete operation. Unknown and referenced IDs are skipped. Missing and removed bytes are distinguished according to the backend's delete result; errors leave the retirement intact. Do not run this on unexpired staged uploads, in-flight saves, legacy files, or storage shared with nonparticipating writers. No background worker, automatic eligibility policy, physical inventory, durable pre-upload registration, or recovery of unknown IDs is provided. The SQLite/PostgreSQL orphan contracts passed in PR #279.

Reserved uploads

ReferenceLedger::stage_reserved generates a fresh server-side ID, commits its enrollment before calling Storage::save_reserved, and returns the stored metadata or an error containing the attempted ID. The low-level reserved write rejects collisions: local storage uses exclusive temporary creation and hard-link publication (requires filesystem hard-link support), and S3 uses conditional creation. Never reuse IDs even after deletion. Other storage implementations reject reserved writes by default. The caller must authorize the upload, exclude cleanup while writes are in flight (including uncertain remote completion), and coordinate retention and model attachment in one model transaction. The legacy StagedMedia::commit_referenced registers its own fresh IDs; use the dedicated reserved staging path below for pre-enrolled uploads. Failed writes remain discoverable as enrolled candidates when registration succeeded. No automatic cleanup, durable upload-state machine, crash-proof local metadata publication or distributed writer lease is provided. The reserved upload and collision runtime contracts passed in PR #280.

Reserved model staging

Use UploadPlan::stage_referenced(&storage, &ledger, now, ttl) and then ReservedStagedMedia::commit(&storage, save). The wrapper keeps the enrolling database connection and has no legacy abort/delete method. Use the same storage namespace for both operations. The transaction claims only enrolled zero-reference, non-retired IDs, runs the authorized compare-and-write model callback, detaches previous references and retains the new files before committing. A rollback leaves the pre-enrolled IDs discoverable. A retired ID cannot reach the model callback. Failed staging reports attempted IDs without deleting bytes. All writers must cooperate; callers must exclude cleanup during in-flight uploads and uncertain remote writes. Automatic eligibility and worker integration are not provided. SQLite/PostgreSQL model contracts passed in PR #281.

Durable upload states

Explicit ledger initialization creates a separate upload-state table without rewriting legacy enrollment rows. Reserved uploads atomically enroll the ID and record Uploading before storage I/O. Only a successful validated storage response advances it to Staged. The reserved model transaction changes it to Committed together with the reference claim; rollback restores Staged. Generic attach rejects tracked IDs until committed. Reference-aware retirement refuses Uploading and Staged IDs, returning Unknown (no deletion permission). Candidate enumeration is discovery only and may include protected IDs. upload_state observes state without retirement. abandon_upload explicitly transitions a settled, permanently abandoned upload to Abandoned; never call it on an uncertain or still-running write. Errors and cancellation remain protected, including ambiguous storage responses. Retirement and cleanup remain separate operations; committed uploads can become unreferenced through normal detach. Legacy IDs have no state record and retain their previous contract; do not mix old and new binaries during rollout. No automatic timeout, lease, worker or proof of remote write completion is included. The durable upload state contracts passed in PR #282.

Bounded abandoned-upload cleanup

abandoned_candidates(after, limit) selects only tracked, explicitly abandoned IDs with zero references. Uploading, staged, committed (even detached), and legacy IDs are excluded. cleanup_abandoned_page(&storage, after, limit) processes at most 1,000 candidates sequentially and returns a per-ID result, including errors without stopping the remaining page. Each deletion requires the existing durable retirement gate. Advance the cursor using the last result ID; periodically restart from the beginning to retry failures and discover new candidates. Missing results reflect backend semantics, not proof of physical erasure. Retired IDs without a receipt remain in discovery. Run only with authorized storage namespaces and cooperating writers. The SQLite/PostgreSQL page contracts passed in PR #283.

Durable cleanup receipts

Explicit ledger initialization creates a separate receipt table. Abandoned-page cleanup records the backend result (Removed or Missing) only after retirement and the storage operation; cleanup_receipt(media) reads that result. Discovery excludes IDs with receipts. Errors do not record completion; a crash after deletion but before recording leaves the retired ID eligible for retry. Concurrent workers can repeat a delete, and the first recorded result wins. These receipts describe backend responses, not proof of physical erasure: partial local files, S3 tombstones, object versions and backups may require separate reconciliation. The direct cleanup_abandoned API retains its original semantics. No automatic abandonment, scheduler, remote write settlement proof or mixed-version rollout support is supplied. The extended page contracts passed in PR #284.

Unresolved upload recovery

unresolved_uploads(after, limit) lists up to 1,000 tracked Uploading IDs in keyset order, including live writers. inspect_unresolved(&storage, media) is non-destructive and reports Present (validated readable staged metadata and payload digest), Missing, Expired, or NotUploading; backend errors propagate. Observations are not proof of remote write settlement. Only after an operator establishes that all original writes have settled may recover_settled_upload transition a readable upload from Uploading to Staged. It does not create a model reference or reconstruct a lost form plan. Missing, expired, corrupt or uncertain reads do not change state. Use the same authorized storage namespace, and explicitly abandon only after settlement and a decision not to use the file. No timeout-based abandonment, remote fencing, or automatic deletion is supplied. The extended SQLite/PostgreSQL upload contracts passed in PR #285.

Original upload intent journal

Ledger initialization creates _fexu_media_upload_intents without rewriting existing enrollment rows. New reserved uploads atomically record their original byte length, SHA-256 digest, staging deadline and sanitized filename alongside the ID and Uploading state before any storage I/O. upload_intent(media) reads these expected values. The successful storage response must match the intent and identity before advancing to Staged. Explicit settled-write recovery additionally requires the readable object's verified metadata and payload digest to match the recorded original intent; self-consistent but different bytes are rejected. Older unresolved uploads without an intent remain protected and cannot use this recovery transition. Read-only inspection continues to describe observed storage, not certify intent or settlement. Operators must still establish that every original write has settled before recovery or abandonment. The journal does not store file bytes, reconstruct form plans, establish remote fencing or authorize deletion. Use one authorized storage namespace and do not mix ledger versions. Extended SQLite/PostgreSQL contracts passed in PR #286.

Permanent S3 discard fencing

For an authorized operator who has decided to discard an unresolved upload, ReferenceLedger::abandon_unresolved_s3(&storage, media) (feature s3-storage) first commits an irreversible discard request in _fexu_media_upload_fences. upload_fence_requested(media) exposes that durable request; normal staging, recovery and ordinary abandonment refuse it. If remote I/O fails or is interrupted, the Uploading state stays protected, and the same operation can be retried. The S3 backend conditionally creates an FXF1 marker at an absent immutable key or conditionally replaces a validated existing object or expiry marker using its observed ETag. Only confirmed marker publication permits transition to Abandoned. Late conditional-create uploads cannot replace that marker; ordinary reads, retain, delete and expiry reconciliation cannot remove it. Retry is idempotent, including after an ambiguous final database commit. The marker must remain for the lifetime of the namespace: disable lifecycle expiration of these keys, exclude raw writes/deletes and non-cooperating or older binaries, and use exactly the original authorized bucket. Do not race raw destructive APIs with ledger-managed writes. This requires a backend implementing atomic conditional create/update and consistent reads; TLS MinIO contracts exercise both absent and existing keys and ledger cleanup. The marker is not proof of erasure of object versions or backups, and is intentionally never physically removed by Fexu. Local storage still requires operator-established settlement. The fencing contracts passed in PR #287.

Targeted local residue reconciliation

After establishing that all local writers have settled, an authorized operator can explicitly abandon an unresolved upload and call ReferenceLedger::cleanup_local_residue(&local_storage, media). The operation accepts only tracked Abandoned IDs without an S3 fence request, checks durable retirement before filesystem I/O, and removes only the four exact UUID paths (payload, .json, .partial, .json.tmp). It preflights all paths and rejects links, directories or other unexpected file types before deleting any. It tolerates absent files and is retryable after partial removal. Existing backend receipts are not overwritten and do not prevent explicit reconciliation. No directory-wide scan, sidecar reconstruction, timeout-based abandonment or cross-process writer exclusion is provided. Use the original trusted root, exclude concurrent filesystem changes and raw storage operations, and do not infer physical erasure from unlinking paths. SQLite/PostgreSQL contracts cover residue after receipts, preflight rejection and protected uploads; CI verification is required.

Local exclusive writer slots

Current LocalStorage writers acquire an exclusive {id}.write-lock file before publishing bytes and release it after all tracked write paths have settled. ReferenceLedger::abandon_unresolved_local(&storage, media) commits an irreversible local discard request before attempting to occupy that same slot with a permanent FXL1 marker. local_fence_requested(media) reports the request. Pending requests block normal staging, recovery and ordinary abandonment; S3 and local requests cannot be exchanged. A busy, crashed or malformed slot is never stolen automatically. Retry after a cooperating writer releases its slot; after a crash, an authorized operator must establish writer settlement before using the offline recovery operation below. Do not unlink an empty slot. Never remove a permanent marker. A confirmed marker permits Abandoned and targeted residue reconciliation preserves the marker. Requires a trusted shared filesystem supporting atomic exclusive file creation, the original root, current cooperating binaries, and no raw mutation, owner purge or legacy cleanup concurrent with ledger-managed operations. This is not a distributed lease, power-loss durability guarantee, or automatic stale-lock recovery. SQLite/PostgreSQL contracts exercise independent local handles and simulated occupied slots; real multi-process deployment acceptance remains outstanding. CI verification required.

Offline stale writer slot recovery

ReferenceLedger::recover_settled_local_discard(&storage, media) is an explicit maintenance operation, not an automatic timeout or lease. First request discard using abandon_unresolved_local; if a slot remains occupied, stop and settle every writer and competing recovery operator sharing the original trusted root before invoking recovery. The operation requires a durable local discard request and Uploading or Abandoned state, rejects S3 requests, and converts an empty regular slot in place to FXL1 without unlinking it or exposing a new writer admission window. An absent slot is exclusively created; an existing complete marker is synchronized and preserved. Unexpected contents, links and directories fail closed. Only successful marker synchronization permits the Abandoned transition; the operation is retryable. A partially written marker requires separate offline investigation; no age, PID or timeout proves settlement. No physical erasure or power-loss guarantee is supplied. SQLite/PostgreSQL tests simulate stale slots and malformed markers; actual multi-process acceptance remains outstanding. CI verification required.

Bounded cleanup worker batches

ReferenceLedger::cleanup_abandoned_batch(&storage, after, page_size, max_pages) is a bounded worker entry point for an explicitly configured scheduler. Use the original trusted storage namespace and the same ledger as all cooperating writers. It attempts at most 16 pages and 1,000 candidates, returning per-ID outcomes, a continuation cursor, an end-of-sweep flag and any page-query error. Persist or carry next_after between invocations; when reached_end is true, begin the next sweep at None so failed or newly eligible earlier IDs are revisited. A page-query failure leaves the cursor at the last completed page. Durable backend receipts suppress successfully completed IDs, including after a worker restart. Inspect individual outcomes and scan_error rather than treating a successful outer result as success of every item. No automatic abandonment, committed-ID cleanup, raw directory scan, local residue cleanup or scheduler registration is performed. A single configured worker is recommended; overlapping workers may repeat backend calls. The existing cleanup receipt is not proof of physical erasure. Extended SQLite/PostgreSQL contracts passed in PR #291.

Persistent cleanup jobs

Register fexu::jobs::StorageCleanupHandler::new(ledger, storage, page_size, max_pages)? explicitly with the worker registry or WorkerHost. storage is an Arc<dyn Storage> bound to the original trusted namespace. The job payload is an empty object; it cannot select a path, bucket, owner, media ID or abandonment policy. Enqueue with fexu::jobs::enqueue_storage_cleanup(&queue, When::every("storage-cleanup", 60)).await? (or When::now() / When::cron(...)). Initialize the ledger and apply job migrations separately before starting the worker. No schedule or worker is enabled automatically. Each invocation attempts a bounded batch, records only counts in logs, and keeps a process-local cursor across invocations; restart from the beginning is safe because durable receipts exclude completed IDs. Scan or item errors report retryable job failures; after exhausting attempts the existing queue stops that schedule until an operator retries it. A successful partial batch schedules its next normal occurrence; it does not imply the sweep is complete. Configure one trusted worker per namespace; at-least-once redelivery may repeat backend calls. The 120-second handler timeout is not a hard bound on blocking local filesystem I/O. Local residue reconciliation and automatic abandonment are not part of this handler. SQLite/PostgreSQL recurring-job contracts passed in PR #292.

Explicit cleanup admission for detached committed media

After authorizing permanent deletion and establishing that all external references and storage writes have settled, call ReferenceLedger::admit_detached_cleanup(&tx, media) in the same database transaction as removal of the final model reference (after detach), or in a fresh transaction after removal. The method atomically retires a tracked Committed ID with zero references and changes its upload state to Abandoned. It returns false for IDs that are not eligible, including already admitted, referenced, unknown, staged, uploading and legacy IDs. Roll back the entire transaction on error. After commit, attachment is permanently refused and the existing abandoned-only worker may process the ID, subject to the original trusted storage namespace and normal cleanup constraints. Rollback preserves attachment eligibility for an originally unretired ID. The method does not delete bytes, authorize users, automatically select all detached media, or implement retention/legal-hold policies. Existing detach behavior is unchanged. Applications must opt in only when permanent deletion is intended. SQLite/PostgreSQL contracts cover shared references, rollback, reattachment exclusion and subsequent cleanup; CI verification required.

Per-save detached media policy

ReservedStagedMedia::commit_with_policy(&storage, DetachedMediaPolicy::Cleanup, save) opts into cleanup admission for detached tracked committed media inside the model transaction. The default commit and legacy referenced commits retain detached files. All detach operations run before admission so shared references remain protected. The application must authorize permanent deletion and establish that external references and original storage writes have settled. Ineligible or legacy IDs remain unadmitted. No physical deletion occurs in the model transaction; the configured persistent cleanup worker handles admitted IDs after commit. A rollback also rolls back admission. The existing report lists detached IDs, not proof of cleanup eligibility or deletion. SQLite/PostgreSQL model roundtrip contracts require CI verification.

Distributed owner admission budgets

Before the first enrollment of a new owner, an authorized operator may call ReferenceLedger::configure_owner_quota(owner, max_files, max_bytes).await?. Zero is a real limit; an unconfigured owner uses the signed 64-bit maximum for both limits. All reserved uploads acquire the database owner row and charge one file and the original intent byte length in the same transaction as enrollment, before storage I/O. owner_quota(owner) returns the persisted limits and counters. Concurrent cooperating writers share the budget, and rejected admissions do not enroll IDs. Failed or ambiguous writes remain charged. The implementation is deliberately conservative: no cleanup receipt, timeout or abandonment automatically releases budget. Counters are logical reservations since deployment of this schema, not physical disk usage; old enrollments, raw storage and legacy saves are outside this accounting. Initial configuration requires a fresh owner in a namespace where every writer uses reserved admission; existing logical budgets can be resized as described below. Legacy adoption requires separate reconciliation. Do not mix older binaries or raw writers. Initialize the ledger explicitly before rollout. SQLite/PostgreSQL runtime contracts require CI verification.

Explicit settled quota release

New reserved admissions journal the exact per-ID charge in the enrollment transaction. After an authorized operator has established permanent abandonment, settlement of every writer, and removal of relevant storage residue in the original trusted namespace, ReferenceLedger::release_settled_quota(media).await? may return capacity. A durable cleanup receipt, retired zero-reference state, Abandoned upload state and an unreleased per-ID charge are required. A receipt alone is not evidence of physical absence: for local storage reconcile the known residue paths separately, and for S3 consider permanent markers, versioning and external lifecycle rules. The release changes the charge and owner counters atomically under the owner lock; repeat calls return false. Older reservations lacking a per-ID journal remain charged, including reservations made with the initial quota implementation in #295. No historical backfill is inferred. The caller must not release capacity while any writer can still publish bytes. No automatic release or physical deletion occurs in this explicit API. The SQLite/PostgreSQL contracts passed in PR #296.

Local fenced quota cleanup

For an explicitly abandoned ID, ReferenceLedger::cleanup_and_release_local_quota(&storage, media).await? combines permanent local writer fencing, retirement, reconciliation of the four managed residue paths, durable receipt recording and once-only quota release. Use only the original authorized local root with current cooperating writers; exclude raw mutation, owner purge and legacy cleanup. An empty or malformed writer slot fails closed and is never stolen. Existing receipts do not bypass physical reconciliation. A permanent FXL1 marker remains; logical quota does not account for marker overhead or backups. Live, unknown and S3-fenced IDs are ineligible. Unjournaled charges stay reserved. Retry after a cleanup or database failure; only a newly released charge returns true. This is an opt-in per-ID operation, not automatic abandonment, namespace discovery or scheduled sweeping. Remote release, historical reconciliation and real multi-process acceptance remain open. SQLite/PostgreSQL contracts passed in PR #297.

Scheduled local quota cleanup

For a ledger dedicated exclusively to one original trusted local root, explicitly register fexu::jobs::LocalQuotaCleanupHandler::new(ledger, storage, page_size, max_pages)? with an Arc<LocalStorage> and enqueue fexu::jobs::enqueue_local_quota_cleanup(&queue, When::every("local-quota-cleanup", 60)).await?. Never use a mixed-root or mixed-backend ledger: the schema does not record a namespace per charge. The empty job payload cannot select storage or IDs. The underlying cleanup_local_quota_batch attempts at most 16 pages and 1,000 journaled, unreleased, abandoned zero-reference IDs, excluding S3-fenced IDs. Unlike ordinary cleanup, existing receipts do not exclude candidates. A restart begins from the start; released journals are excluded, and failures remain eligible on a later sweep. The worker reports counts and retryable errors, and keeps a process-local continuation cursor. No schedule is enabled by default. Use current cooperating writers and exclude raw mutation, owner purge and legacy cleanup. No automatic abandonment, remote release, historical backfill or production crash acceptance is supplied. Shared SQLite/PostgreSQL job contracts passed in PR #298.

Explicit S3 fenced quota release

With s3-storage, an authorized operator may call ReferenceLedger::release_fenced_s3_quota(&storage, media).await? after the existing permanent S3 discard protocol has completed. Verify the original bucket, settlement of all destructive operations, and removal or absence of relevant historical object versions before calling. The method requires Abandoned state, a durable S3 discard request, zero references and permanent retirement; it rejects local fence requests. It reads and verifies the exact current FXF1 marker even when a cleanup receipt already exists, records a receipt if needed and releases the journaled logical charge once. Missing or unexpected markers fail closed; no marker is recreated by this method. Preserve the marker for the namespace lifetime. No raw mutation, concurrent deletion, lifecycle expiration of markers or mixed-version writers are permitted. This API does not enumerate or remove historical versions, verify bucket versioning settings or erase backups. Marker overhead is outside logical quota accounting. Ordinary abandoned S3 IDs without a durable S3 fence, automatic remote scheduling, historical reconciliation and production acceptance remain open. TLS MinIO contract passed in PR #299.

Permanent fencing of abandoned S3 media

An authorized operator can call ReferenceLedger::fence_abandoned_s3(&storage, media).await? for a tracked, explicitly abandoned S3 ID with zero references, including media previously admitted through detached-media cleanup. Use the original trusted bucket and settle all destructive operations, including ordinary delete and expiry cleanup, before fencing. Do not overlap those operations with fencing. The ledger retires the ID and durably records the S3 discard request before conditional marker publication. Unknown, protected and locally fenced IDs are ineligible. Existing cleanup receipts do not bypass fencing; absent keys receive the permanent marker and validated present objects are conditionally replaced. Failed remote operations leave a retryable request. A confirmed marker records a backend receipt and returns true, including on retry. The method does not release quota. Separately verify historical object versions and invoke release_fenced_s3_quota under its existing operator contract. Preserve markers permanently; no automatic S3 sweep or version-history verification is supplied. TLS MinIO contract passed in PR #300.

Resize existing owner quotas

An authorized operator can call ledger.resize_owner_quota(owner, max_files, max_bytes).await? to change an existing logical budget. The atomic update shares the owner row with admission and release, preserves all reservation counters, and returns false if no budget exists or either limit would fall below its reserved amount. Negative limits fail; zero is a real limit. This does not create a budget, release charges, infer physical usage or adopt historical media. Older unjournaled charges stay reserved. For initial configuration use configure_owner_quota; all writers must cooperate with reserved admission. SQLite and PostgreSQL runtime contracts passed in PR #301.

Audit owner quota accounting

An authorized operator can call ledger.audit_owner_quota(owner).await? to read the existing logical budget, unreleased journaled file and byte totals, released journal count, tracked uploads without a charge journal, and reference-ledger IDs without an upload record. All fields come from one database read statement. counters_match_journal() compares the reservation counters with unreleased charge totals only; matching totals do not certify complete enrollment or physical storage usage. A gap may reflect historical reservations or inconsistent data and must never be interpreted as automatically releasable capacity. None means no budget row, not absence of media. The audit is read-only, does not contact storage, and does not create or repair records. Historical adoption and reconciliation remain separate work. SQLite/PostgreSQL runtime contracts passed in PR #302.

Journal verified historical quota reservations

An authorized operator may call ledger.journal_historical_quota(media, expected_size).await? only after independently establishing that this exact immutable ID was already charged and never released. The original durable upload intent must exist and match the expected byte size; upload and reference records must exist. A sufficient unjournaled file and byte gap is required under the same owner lock used for admission and release. Existing journals, including released journals, cannot be replaced. The operation returns true only for a newly inserted charge and never changes the owner counters. A gap is not proof of charge attribution: do not infer it from the audit alone. Exclude legacy writers and raw database mutation, use independently verified accounting records, and keep unresolved charges reserved. After journaling, the existing settlement and cleanup rules still govern release. No storage access, bulk adoption, automatic reconciliation or physical usage inference is performed. SQLite/PostgreSQL contracts passed in PR #303.

Adopt verified legacy media into quota accounting

An authorized operator may call ledger.adopt_legacy_quota(&storage, media).await? for an existing retained file with live enrolled references but no upload record. Independently establish that this exact ID has never been charged, that all references are enrolled, and that the original trusted namespace is used. Keep legacy writers, raw mutation and destructive operations offline throughout adoption. The method reads the file and validates owner, ID, length, digest and retained status. Under the owner and reference row locks it rejects existing upload records, charge journals, original intents, cleanup receipts, discard requests and retired or unreferenced IDs. Admission, a committed upload record and the charge journal are committed together; insufficient capacity rolls back all changes. No upload intent is fabricated and no storage bytes are changed. Repeat adoption of an otherwise readable retained file returns false. Missing or corrupt files fail closed. Adopted media follow the existing explicit detached cleanup and settlement protocols. A missing owner budget may be initialized with the normal unlimited sentinel; use an existing configured budget when enforcing limits. This is per-ID adoption, not automatic discovery, physical inventory or complete migration of a legacy owner. SQLite/PostgreSQL contracts passed in PR #304.

Discover legacy quota adoption candidates

An authorized operator can call ledger.legacy_quota_candidates(owner, None, 100).await? to discover a page of referenced legacy IDs for one owner. Resume with the last returned file ID as Some(id), and repeat from None after reaching the end to revisit changes. Page sizes must be between 1 and 1,000. The query excludes retired or unreferenced IDs and IDs with upload records, charge journals, original intents, cleanup receipts or discard requests. This is read-only discovery, not a stable migration snapshot, proof of physical existence or proof that a file was never charged. Independently verify each candidate and follow the offline operator contract of adopt_legacy_quota before adoption. No storage access, automatic adoption, quota creation or repair is performed. SQLite/PostgreSQL contracts passed in PR #305.

Operator-guided legacy migration

Perform this procedure per owner during a maintenance window. Back up the database and original storage consistently before starting; verify restore separately. Stop legacy writers, raw mutations and destructive operations, and independently reconcile model references, storage namespace and historical accounting records. A database audit cannot establish those facts.

  1. Read audit_owner_quota(owner). If no budget exists, do not interpret that as zero usage. Existing legacy owners cannot use fresh-owner configuration; adoption can initialize the normal unlimited sentinel. Keep admissions offline until the intended budget is established with resize_owner_quota.
  2. For each independently verified already-charged historical upload with a matching original intent, use journal_historical_quota(media, expected_size). Keep uncertain charges reserved. Do not use adoption to resolve an unexplained gap.
  3. Enumerate legacy_quota_candidates(owner, None, 100). Verify each retained file was never charged and all references are enrolled. Call adopt_legacy_quota(&storage, media) only for verified IDs. Record successes, skipped IDs and failures in the operator's migration log. Continue using the last file ID; restart at None after interruption or at the end of a sweep. A completed adoption is excluded from the next scan.
  4. If capacity is insufficient, leave the file and references intact; decide whether to raise the budget explicitly and retry. Do not delete live media to force a migration through.
  5. Repeat the audit and discovery. Verify intended limits, counters, outstanding journals, unresolved IDs, all model references and physical inventory independently. Matching counters and an empty candidate page are necessary checks, not sufficient proof of complete migration. Retired, unreferenced, unknown, untracked, corrupt and ambiguous media require separate operator decisions. Keep admission offline if any unresolved issue compromises accounting.
  6. Resume only cooperating reserved writers after the independent checks pass. Preserve the migration log and backups. Never revert only the database or only the storage after new writes have begun.

The shared SQLite/PostgreSQL contract exercises a synthetic two-file retained legacy migration, a reconstructed ledger instance, exhausted quota, explicit resizing, duplicate rejection, final audit and unchanged bytes. All 14 checks passed in PR #306. This is not a real process-crash, physical inventory, production restore or full owner migration certification.

Offline backup and restore of local media

Treat the application database, complete local media root and the configuration that identifies the namespace as one recovery unit. Stop application writers, workers, cleanup jobs and external mutation; independently settle outstanding writes before taking a backup. Preserve all owner directories, metadata sidecars, temporary or unresolved artifacts and permanent writer fences, including FXL1 markers. A backup of live media bytes alone is insufficient. Protect backups against unauthorized access and modification.

For SQLite, close all connections before copying a quiescent database and its namespace. Include any remaining database companion files; do not copy a live SQLite database using ordinary file copying. For PostgreSQL use a supported consistent database backup procedure while application and media writers remain stopped. Restore the matching database and media snapshot to an isolated environment, with the original logical namespace and compatible framework version, before enabling any writers. Never combine unrelated snapshot times or allow the original and restored installations to write concurrently. Restoring an older snapshot cannot preserve later tombstones or quota charges; independently reconcile post-backup writes and retirement decisions before reusing a namespace.

Verify live references and content hashes, upload states, unresolved work, cleanup receipts, permanent fences, owner limits and charge journals. Audit results alone do not prove physical completeness. Test that retired IDs cannot be written again and released charges cannot be released a second time. Keep admissions and cleanup disabled if the database, bytes or namespace cannot be reconciled. Preserve recovery logs and independently verify authorization and external model references before reopening service.

The SQLite fixture copies a closed file-backed database and its entire local media directory to a separate path, removes the original fixture, reopens the restored copy, and checks live contents, committed and abandoned states, receipt and quota persistence, permanent local write-lock marker preservation, rejected late write and once-only release. This synthetic offline SQLite recovery drill passed all 14 checks in PR #316. The PostgreSQL variant uses the same fixture and assertions, with two newly created disposable databases, a real custom-format pg_dump, and a single-transaction pg_restore that stops on errors. It copies the complete local media namespace while the source fixture is offline, removes the original fixture, and verifies the restored database and media without reinitializing the ledger. CI requires the ignored PostgreSQL test to execute successfully, not merely compile. PostgreSQL verification passed all 14 checks in PR #317. These tests are not online backup tools, S3 restore tests, process-crash tests or production restore certification.

Offline recovery of S3 media

Treat the matching database and entire authorized object namespace as one recovery unit. Stop all application and cleanup writers, settle outstanding requests and preserve the exact current object envelopes, including permanent FXF1 discard markers and expiry tombstones. Do not export only files visible through the Storage API: that would omit markers. Account separately for historical object versions, lifecycle rules, permissions, encryption and bucket configuration. Restore into an isolated private namespace with equivalent conditional-create/update semantics and verified TLS; never reuse an active namespace or overlap old and restored writers. Reconcile all post-snapshot operations and historical versions independently before resuming admissions or destructive operations.

The disposable TLS MinIO test restores a closed SQLite ledger and two exact current object envelopes (one live file and one permanent discard marker) into a separate test bucket, removes the original fixture objects, and checks readable live data, upload state, receipt, fence request, exact marker bytes, rejection of a late write and once-only quota release. The SQLite/S3 recovery drill passed all 14 checks in PR #318. The PostgreSQL variant shares its fixture and verification, creates two disposable databases, closes the source pool, uses real custom-format pg_dump and single-transaction pg_restore, copies the current object envelopes, removes the original fixture, and verifies the restored ledger without reinitialization. The S3 CI job provisions PostgreSQL 16 and requires the combined test to pass; local S3-only runs may omit the separate database fixture. PostgreSQL/S3 verification passed all 14 checks in PR #319. These are bounded synthetic current-object recovery drills, not inventory/export tools, version-history backups or certification of external providers. Raw object writes and deletes are private test-only operations, not a supported application recovery API.

Local writer process termination drill

The local writer test starts a separate process of the Rust test executable and pauses it at a test-only barrier after exclusive slot acquisition and partial byte writing, before hard-link publication. A second writer cannot acquire the slot; ordinary abandonment records the discard request but cannot steal the live slot. The parent kills and reaps the child, closes and reopens the file-backed SQLite ledger, verifies the surviving partial and Uploading state, then performs explicitly settled offline discard recovery and cleanup. The permanent FXL1 marker excludes later writers and the charge is released exactly once. The SQLite variant passed all 14 checks in PR #320. The PostgreSQL variant shares the same subprocess and recovery assertions, using a disposable database and closing and reopening its connection pool after child termination. The PostgreSQL CI job requires successful execution of the ignored contract. PostgreSQL verification passed all 14 checks in PR #321. These tests terminate a local media writer, not the database server, and do not test machine power loss, filesystem durability across reboot, S3 process termination, or automatic detection of settled writers. Operators must still independently establish that all writers and other recovery operators are stopped before stale-slot recovery.

S3 writer process termination drill

The isolated TLS MinIO test starts a separate writer process using a file-backed SQLite ledger and the real reserved upload API. A test-only barrier pauses the child after successful conditional object creation, before the ledger acknowledges staging. The parent verifies the original bytes and Uploading state, kills and reaps the child, then reconnects to the ledger. Separate fixture owners exercise explicit recovery of the verified original intent to Staged and irreversible discard directly from Uploading. Both paths ultimately fence the retired ID, verify the exact permanent FXF1 marker, reject late creation and release quota exactly once. The SQLite variant passed all 14 checks in PR #322. The PostgreSQL variant shares the same subprocess and recovery assertions, using a disposable database and a separate connection pool for recovery after child termination. The S3 CI script requires successful execution of both PostgreSQL/S3 restore and writer termination contracts when the PostgreSQL fixture is configured, and requires that fixture in CI. PostgreSQL/S3 process termination verification passed all 14 checks in PR #323. These tests cover acknowledged remote writes with interrupted ledger confirmation, not ambiguous in-flight HTTP requests, database or object server failure, historical object versions or production settlement. Operators must independently verify settlement and historical versions before quota release; process exit alone does not establish remote settlement in general.

Transactional reserved form saves

Use fexu::forms::bind_media to validate authorized input without storage writes, then fexu::forms::finish_reserved_media(plan, &storage, &ledger, now, ttl, DetachedMediaPolicy::Retain, save) to stage reserved uploads and commit the model and ledger in one transaction. The async callback receives the transaction, previous field bindings and proposed bindings. It must authorize the actual model row and compare or lock its current media fields against the previous values before writing the proposed values, without committing the transaction itself. Initialize the ledger explicitly, use the same authorized namespace throughout, and require every reference writer to cooperate. Retain is the conservative policy; Cleanup requires independent deletion authorization and settlement as described above.

ReservedMediaFinishError::Stage preserves the underlying staging error and attempted candidates; ReservedMediaFinishError::Save preserves the underlying transaction failure and staged candidates. Neither is permission to delete bytes, including on an uncertain commit. Quota denial prevents the model callback from running. The older finish_media API retains its existing non-ledger contract. The new adapter is opt-in and does not automatically change generated models, forms, admin handlers or HTTP authorization. SQLite and disposable PostgreSQL tests exercise model rollback, successful commit and quota denial; all 14 checks passed in PR #324.

Scoped generated model media updates

Inside the reserved form save callback, use fexu::forms::update_media_model(tx, id, &scope, previous, bound, project, payload).await with a model implementing the generated repository contract. The adapter locks the authorized existing row on the supplied transaction, reads its current state, compares the complete projected media field set with the previous bindings, invokes the typed update DTO builder, updates through the generated transaction method, and verifies the returned media bindings against the proposed set. Missing or out-of-scope rows, stale values, duplicate projections and incorrect returned bindings fail the save. The outer reserved save coordinates rollback and candidate preservation.

The caller supplies an independently authorized query scope, a trusted projection of actual model fields (including absent values), and a DTO builder that writes the proposed media bindings without changing unauthorized fields. The projection must reflect the actual persisted owner and file IDs rather than echoing form input. This is an opt-in adapter for existing rows; it does not infer media fields from the derive, authorize unrelated fields, create models, intercept other writers or migrate admin and HTTP handlers. All writers must cooperate with the ledger. The generated-model SQLite/PostgreSQL update contract passed all 14 checks in PR #325.

Transactional generated model creation

Inside the reserved form save callback, use fexu::forms::create_media_model(tx, previous, bound, project, payload).await to create a model through its generated repository method. The helper rejects any previous nonempty media binding before invoking the DTO builder, creates the row on the supplied transaction, and verifies that the trusted projection of the returned row exactly matches the proposed media bindings. A mismatch returns an error so the outer reserved save rolls back the row and ledger claims while preserving staged candidates. Use an independently authorized owner and create permission; the caller must supply a trusted projection of actual row fields and a DTO builder that writes only authorized fields. The helper does not establish authorization, commit independently, infer media fields or enroll existing references. All writers must cooperate. The extended SQLite/PostgreSQL generated-model contracts passed all 14 checks in PR #326.

Scoped reference-aware model deletion

Use fexu::forms::delete_media_model(tx, id, &scope, previous, project, policy).await inside a caller-owned transaction on the initialized ledger database. The helper locks the scoped model row, reads its actual media bindings, rejects stale or duplicate field bindings, deletes the row through the generated repository, and detaches one reference per populated field. With DetachedMediaPolicy::Retain, detached uploads keep their existing state. With explicitly authorized Cleanup, eligible tracked committed uploads are admitted to abandoned cleanup only after all detachments, so other model references continue to protect shared files. The helper returns detached IDs, not proof of cleanup admission or physical removal. Propagate every error and roll back the entire transaction; commit only after all application operations succeed. No storage I/O or quota release occurs here.

The caller must authorize deletion, use a trusted projection covering all actual media fields (including absent ones), establish settlement and absence of external references before opting into permanent cleanup, and coordinate every writer. Cascading deletions of other rows with media references require separate coordination; this adapter does not discover or reconcile them. Commit errors may be ambiguous and do not authorize physical deletion. Extended SQLite/PostgreSQL contracts cover rollback, shared references, last-reference cleanup, retained uploads and unknown-reference failure; all 14 checks passed in PR #327.

Derived model form media binding

A model-backed FexuForm can declare separate UUID media columns with #[form(model = Document, media = "file")]. Its generated from_submit_with_media method validates scalar values with the existing form context and cross-check, then validates the explicitly supplied media fields against the separate allowlist and model contracts. Each declared media column must have exactly one application-built MediaField. Unknown, protected, non-UUID and nonwritable media columns are rejected. Required model columns cannot be made optional by the caller. Posted scalar media IDs are rejected by the scalar allowlist. Creation cannot carry previous media references. No storage writes occur during binding.

The returned typed form and UploadPlan can be passed to the existing reserved save workflow, with independently authorized owner, trusted current bindings, projection and DTO builder. Media declarations are not scalar fields; application code must build MediaField values from authorized row state and validated multipart input, enforce dynamic media access via readonly/required settings, and reject unexpected multipart parts. The helper does not automatically render media widgets, parse multipart, infer field ownership or migrate existing handlers. SQLite/PostgreSQL verification is pending CI.