Skip to content

Retention, purge and the consistency sweep ​

The platform never deletes a row: every StoredFile is soft-deletable by construction, and the global filter hides what was marked. Keeping a file forever, though, is a legal obligation turned inside out — privacy law requires erasing data once its purpose is over. GrydFiles reconciles the two with the tombstone: the record follows the framework's rules and stays, and what is actually destroyed is the object in the bucket, which is not an entity.

This page describes how long a file lives, the three ways it dies, and the weekly job that checks the records and the bucket still agree.

How long a file lives ​

The retention comes with the upload, declared by the consumer or inherited from the profile. The module does not know that a tax document is kept for five years — the consumer does. What the module guarantees is that the question was asked and the answer is on the record.

ModeDies when
UntilReleasedNothing references it and the grace period has run out since the last reference was released.
RetainUntilretainUntil has passed and nothing references it and the grace period has run out since the last release — all three, always. The date is a floor, not a death date: a document still in use does not go because the date passed (RN-GF-14).
PermanentNever by a job (RN-GF-09), and never by an ordinary manual purge. Only the act of erasure kills it — over the route with purge-permanent:files on top of purge:files, in process by two different authors.

The date is a floor for the people too (RN-GF-25). A manual purge before retainUntil, or of a Permanent file, is 409 FILE_RETENTION_NOT_EXPIRED_CONFLICT unless it is the act of erasure; the data subject's request is what passes, marked and on the trail.

The grace period is GrydFiles:PurgeGracePeriodDays (30 by default), in both modes a job purges. It counts from lastReferenceReleasedAt, the date denormalised on the record next to referenceCount — never from an aggregation over the reference table (D8). A file nobody ever referenced counts from its verdict (scannedAt) instead: without a release to count from, an upload its consumer forgot to link would otherwise stay in the bucket forever, and nobody would ever look.

A legal hold freezes every purge — the retention job, the quarantine expiry and the manual route, including an erasure request from the data subject. It is per holder (RN-GF-27): the platform holds through the retention route and each registered consumer through its own port, one hold each, with its author, the kind of author, the reason and the date. legalHold on the record is derived — on while any holder has one — and legalHolders lists who: the refused purge answers FILE_LEGAL_HOLD_CONFLICT (409) with the same list, because each holder lifts only its own.

Changing retention after the upload ​

PUT /files/{id}/retention only tightens custody:

  • retainUntil moves forward. A date that is not later than the current one answers FILE_RETENTION_SHORTENED_UNPROCESSABLE (422) and changes nothing. Shortening custody by API is how evidence gets destroyed by accident; when it is legitimate, the path is an explicit purge, which leaves an author and a reason. Only a RetainUntil file has a date to extend — sending one for the other modes is a 400 with no code.
  • legalHold: true places the platform's hold, for retain:files, with a reason (required, at most 200 characters, a 400 with no code without one). It adds to the consumers' holds and never replaces them; placing it again changes nothing and keeps the first author and reason.
  • legalHold: false lifts the platform's hold — the one change that loosens custody — and needs release-hold:files on top of retain:files (a tenant permission on no role template, ADR 0011 D10), a reason, and a durable audit trail: with the default NullAuditStore it answers FILE_AUDIT_TRAIL_UNAVAILABLE (503) and the hold stays. The line goes to the trail in the same transaction as the change; placing a hold does too, but is never refused for want of a trail, because a hold only ever protects content. A file held only by consumers answers FILE_OWNER_SCOPE_FORBIDDEN (403) with their scopes in errors: no permission lifts another holder's hold. Touching the hold without a user answers FILE_CALLER_UNAUTHORIZED (401); on the route the author is always the authenticated user.

A consumer places and lifts its own hold in process, through IFileStore<TScope> (PlaceLegalHoldAsync, ReleaseLegalHoldAsync): the holder is the marker's scope, no module permission is checked, and the replay after the consumer's commit — which runs with no user and no tenant — passes the tenant and a DeclaredFileAuthor. The author is recorded as declared, with the scope that declared it and the executor that called, in the hold and in the trail; with a user in the context the declared author, if any, has to be that user. Lifting a hold the scope does not have succeeds without effect. A product file's hold is placed without a trail line (counted in gryd_files.audit_trail.unreachable, act=legal-hold) and its lifting answers FILE_AUDIT_TRAIL_UNAVAILABLE (503) until the Core outbox takes a message without a tenant.

Every refusal is decided before anything changes, so a request carrying a date and a hold never applies half of itself. A tombstone answers FILE_PURGED_CONFLICT, and a product file (no tenant) needs the platform permission retain:product-files for any change, the lifting of its platform hold included. QuarantineRetentionDays is global to the module and has no field here.

The three ways a file dies ​

PathSelectsReason on the tombstonepurgedBy · purgeAuthorKind
POST /files/{id}/purgethe file named, if Available and past its retentionthe reason the caller wrotethe caller · Authenticated
POST /files/{id}/purge with erasure: true, or PurgeAsync of a consumerthe file named — Available, Infected or Failed, retention or notthe reason the caller wrotethe executor · Authenticated, or Declared in process — Erasure
RetentionPurgeJob (nightly, 04:00)Available files whose mode says they are duejob:retencaonull · Job
ConsistencySweepJob (weekly, Sunday 05:00)Infected files past QuarantineRetentionDays (365) and past retainUntil, never held nor Permanentjob:quarentena-vencidanull · Job

purgedBy is null exactly when the author kind is Job and the reason starts with job: (D16, RN-GF-10). An author a consumer declares in process is Declared, with purgeDeclaredScope and purgeServiceExecutor. The purge and its trail line commit together. A product file is not purged yet: the route answers FILE_AUDIT_TRAIL_UNAVAILABLE (503) and the jobs leave it, counted in gryd_files.audit_trail.unreachable, until the Core outbox takes a message without a tenant (why).

Both jobs ask one rule, PurgeEligibility (RN-GF-15): no legal hold, never Permanent, the date passed in RetainUntil, and then, for Available, no active reference and the grace over; for Infected, the quarantine window over. The rule is an expression: the database translates it to select candidates, and the same expression, compiled, is asked again of each record under its lock. Whichever deadline comes last wins. The trail that cannot reach a product file is not part of the rule: it is checked after it, under the same lock. The manual route refuses a reason that borrows the prefix, one that is empty, and one longer than the 200 characters the tombstone keeps.

The manual route ​

POST /files/{id}/purge needs purge:files; a Permanent file needs purge-permanent:files on top of it, and a product file the platform permission purge:product-files instead (ADR 0011, D10). Without erasure: true it also refuses by the floor: retainUntil ahead, or Permanent, is FILE_RETENTION_NOT_EXPIRED_CONFLICT (409) with the date in the message — an ordinary purge is a decision about a file whose retention is over. It refuses with the record's own holds:

  • FILE_LEGAL_HOLD_CONFLICT (409) while the file is held — releasing it is a different route and a different authority;
  • FILE_STILL_REFERENCED_CONFLICT (409) while a reference row of the file is active, listing the ownerScope values holding it. A count above zero with no active row is refused too, and settled by the nightly reconciliation.

redactFileName: true takes originalFileName off the tombstone as well — for the erasure whose object is the name itself, and the audit entry says the name was redacted. Without it, a person's purge keeps the name: it is the only tombstone that does (see What survives). There is no DELETE /files/{id}: destroying content has a reason and a permission of its own, and the easiest verb of the API would be an invitation to an accident.

The retention job ​

The selection reads stored_files alone, over the (status, referenceCount, lastReferenceReleasedAt) index, and pages by id so a candidate skipped in one run cannot keep a run from ending. Each candidate is then purged in its own transaction, under a FOR UPDATE SKIP LOCKED lock on the record: two overlapping runs take disjoint work and neither ever waits. Under the lock the record is read again with its reference rows, and the rule is asked again — a reference added, a hold placed or a window extended since the selection is honoured, and a count of zero over an active row is skipped and logged, never trusted.

Across tenants, one record at a time in its own (RN-GF-08). The page of candidates is the one read made with the tenant filter off — it is asked in a system scope that is closed before any file is touched, and the scope audit trail records it, one line per page. Each candidate is then locked, read, destroyed and written in the tenant it belongs to, with the filter on, exactly as a request of that tenant would; a product file (no tenant) is treated in the global scope. The same holds for the quarantine expiry, the reconciliation, the expired-upload sweep, the stalled-scan requeue and the archive re-scan: none of them keeps the system scope open for its effects, and none calls storage or the queue with the filter off.

It runs an hour after the reference reconciliation, so the pair it selects by has just been returned to what the rows say. Hangfire's [DisableConcurrentExecution] is not used: Hangfire schedules RecurringJobExecutionAdapter<TJob>, so a filter on the job class would never be read.

What survives ​

The tombstone keeps the digest, the size, the type, the profile, the dates, the scan result, the rejection code, the location where the object was, and who purged it and why. The original name leaves every tombstone nobody asked for — every job: reason and the size rejection (rejeicao:tamanho-divergente) — because a file name carries personal data often enough and, once the bytes are gone, answers nothing the digest and the dates do not (RN-GF-21). A manual purge keeps it unless the request says redactFileName. For quarantined content the signature name and the whole scan history stay forever: what expires is the binary, never the evidence of the incident.

The object and the row ​

Every record owns its own object — the same content uploaded twice is two records and two objects — so the record's retention decides when both die. The tombstone keeps the location, so it still answers where the file was.

An upload that never reaches the scan has its object under _transit/: the expiry sweep deletes it with the reservation, and the scan deletes it after copying a confirmed one. A bucket lifecycle rule on that prefix (one day) is the backstop for what a late PUT on a still-valid URL recreates — see Antivirus service.

Every purge goes through FilePurger: it confirms the aggregate would accept the tombstone, deletes the record's object, treats an object already gone as success (which is what makes a re-run after a crash converge), and only then writes the tombstone. The object goes first and the tombstone second — never the other way round (RN-GF-10) — and a storage failure stops both.

The consistency sweep ​

The state of a file is the record's, not the object's. That is what makes the module safe, and it is exactly why the two have to be compared: silent drift between them is how a file module loses the trust of whoever depends on it. ConsistencySweepJob asks the bucket about every record that owns a location and reports two kinds of inconsistency:

KindMeaning
Missing objectA live record — Scanning, Failed, Available or Infected — whose object is gone. Content vanished outside the purge.
Object outliving its purgeA tombstone whose object is still there. The purge did not complete.

It reports and never repairs — an automatic correction would hide the cause. Pending reservations are left out because their object may not exist yet. A run that finds anything logs one error naming the files (never a key or a bucket) and moves gryd_files.consistency_sweep.alerts; a clean run makes no noise. Records storage could not be asked about are counted as unverified, not as defects.

The sweep is weekly because it costs one existence check per record, tombstones included, and that grows with the history. The reference reconciliation is not part of it: it is SQL over the database alone, runs nightly on its own schedule, and is described on the references page.

Not covered: an object with no record at all, such as a blob left behind by a deletion that failed. No row knows that key; finding it would take a sweep of the bucket against the table.

Metrics ​

All in the GrydFiles.Sweeps meter:

InstrumentUnit
gryd_files.retention_purge.purgedrecords
gryd_files.retention_purge.objects_deletedobjects
gryd_files.retention_purge.bytes_freedbytes
gryd_files.quarantine_expiry.purgedrecords
gryd_files.quarantine_expiry.bytes_freedbytes
gryd_files.consistency_sweep.checkedrecords
gryd_files.consistency_sweep.missing_objectsrecords
gryd_files.consistency_sweep.objects_outliving_purgerecords
gryd_files.consistency_sweep.unverifiedrecords
gryd_files.consistency_sweep.alertsalerts
gryd_files.sweep.candidate_unreadable (sweep = purge, consistency, reconciliation, expired-upload, stalled-requeue, archive-rescan)records

Fewer objects deleted than records purged means a re-run found the object already gone — a crash between the deletion and the tombstone.


The decisions behind this page are in ADR 0010; the contract is in the specification.

Released under the MIT License.