Blackholes

The blackholes plugin permanently removes or replaces field values in history, including transaction history and configured backups. Use it to remove leaked secrets or personal data that ordinary deletion leaves in history. History retention controls how much history a database keeps. Enable blackholes in the plugins option when you open the database. See plugin selection for the open options.

Warning

Execution permanently changes history and backups. Review the preview and obtain approval before you execute.

Definitions

A blackhole is a stored definition of the blackholes kind. Write it with patch_definition like a query or mutation. For example, store the following definition with kind blackholes and path keys/leaked. It has a query and a patch, like a mutation:

edn255 B
{:query {:find  [?e]
         :where [
           [?e "kind" "apiKey"]
           [?e "owner" ?keyOwner]
           ["=" ?keyOwner ?owner]]}
 :patch {:?e {:secret nil
              :token  ["hash" ["list" ?seed ?value]]
              :note   "redacted"}}}

This definition selects every API key belonging to the supplied owner and names three fields on each selected entity. The query binds ?keyOwner from stored facts and compares it with the required input ?owner. The input has no default. Preview and execution fail if ?owner is omitted. The preview request below supplies owner 7.

The query selects rows from the current state by default. Temporal query clauses can select records from earlier history, including records already deleted from current state. Ordering, distinct results, aggregation and limits keep their usual query meaning. After aggregation, each patch target must still bind an individual entity. Each patch key is a ?variable that the query binds to an entity. Each field in a target is one of these:

ValueEffect on every assertion of the field
nullTurns the assertion into a retraction. The field disappears from current and historical records.
An expressionReplaces the assertion's value with the expression result. A literal such as redacted is a constant expression.

An assertion is a stored fact that gives the field a value. Existing retractions stay unchanged. Transactions keep their numbers and commit times, and other fields and entities do not change.

The definition is checked when you store it. The query and expressions must compile. Each patch target must be a query variable. After macro expansion, each expression input must be a query variable or one of the reserved inputs listed below. Patch fields in the reserved stardust/ namespace, generated _ targets and #_tx targets are refused. A refused definition reports invalid_definition.

Definition writes replace each supplied top-level member in full, including nested null values. For example, an update to query must supply the complete query. Other top-level members remain unchanged. A top-level null removes that member. Inside patch, null erases the selected field or entity throughout history.

A null at the entity position erases every historical field of that entity. For example, store this definition with kind blackholes and path people/erase:

edn148 B
{:query {:find  [?e]
         :where [
           [?e "kind" "person"]
           ["=" ?e ?entity]]}
 :patch {:?e nil}
 :links {:incoming "remove"}}

Supply ?entity as an entity link in both preview and execution. The query selects entities explicitly. An outgoing link does not select its destination, regardless of the field name. To erase another entity, select it in the query and name it in the patch. Temporal query clauses can select entities already deleted from current state.

Without links {incoming remove}, an incoming reference to an erased entity refuses planning with incoming_links. With this option, every historical reference to an erased entity is removed. A field containing only that link becomes a retraction. In a map or an ordered list, only the matching reference is removed; other members and empty containers remain. The source entity stays. A self-link or a link between two selected entities does not cause further selection. References in protected system fields refuse planning with protected_link.

Selecting the same entity for whole-entity erasure and a field patch reports conflicting_targets. Preview includes the expanded scope in affected, and its digest covers that scope before execution.

Replacement expressions

An expression is evaluated once for each historical assertion. It receives these inputs:

VariableValue
?valueThe original typed value.
?entityThe numeric entity ID.
?fieldThe field name.
?transactionThe assertion's transaction ID.
?seedA private random seed for the whole operation.
Other ?variablesThe row's bindings from the query.

The reserved names take precedence over query variables with the same name. The plugin expands stored callables before it identifies the query variables an expression reads. Variables in unused macro arguments do not need row bindings. The approval digest covers the expanded expression and its row bindings.

Preview

preview selects and plans a definition without changing anything. It uses the current database transaction as its cutoff. The request is a native object. This example uses DUST:

edn61 B
{:blackhole  "keys/leaked"
 :parameters {:?owner {:#link 7}}}
MemberValueMeaning
blackholeTextThe definition path.
parametersObjectOptional. Merged over the query's declared parameters, as for a stored query run.

Preview results use these members. Public results omit empty collections.

MemberMeaning
digestA SHA-256 value {#sha256 ...} identifying what execution may change.
targetsThe number of selected entity fields.
matchedThe number of assertions the operation rewrites.
replacementsThe number of assertions replaced.
removalsThe number of assertions turned into retractions.
confirmThe text execute must repeat.
samplesUp to ten records with entity, field, transaction and replacement.
affectedMaps of erased entities and rewritten fields, including incoming-reference cleanup. See audit metadata.

The digest covers the definition and its authored revision, the effective parameters, the cutoff, every selected entity field with its expanded expression and row bindings, and the original assertions. It does not depend on sample replacements or seeds.

Two rows can select the same entity field. They form one target when they agree: both remove the field, or both apply the same expression to the same row bindings. Rows that disagree are refused with invalid_argument and the code conflicting_targets.

Each preview generates one temporary seed and returns samples from it. Another preview can return different samples with the same approval digest. Preview does not keep operation state between calls, so preview and execution can run in different processes.

Limits and errors

ResourceLimit
Selected entity fields100,000 in one operation.
Rewritten assertions1,048,576 in one operation.
Authored program64 KiB.
Expanded program64 KiB.
Evaluation work10,000,000 counted expression operations in one operation.
Evaluation CPUFive seconds of thread CPU time in one operation.
Whole-entity and incoming-reference selection10,000,000 history rows and five seconds of thread CPU time per expansion.
Definition copies, selection bindings, expression state and planned replacementsThe database memory budget.

Repeated planning shares the same work and CPU limits. These failures change no history:

StatusCodeCause
invalid_argumentinvalid_requestThe request is malformed.
invalid_argumentinvalid_parametersThe parameters do not fit the query.
invalid_argumentinvalid_definitionThe stored definition is not a valid blackhole.
invalid_argumentinvalid_queryThe query cannot run.
invalid_argumenttarget_not_entityA patch variable bound something other than an entity.
invalid_argumentunbound_variableAn expression reads a variable a row does not bind.
invalid_argumentconflicting_targetsTwo rows give one entity field different changes.
invalid_argumentincoming_linksAn entity selected for erasure has incoming references, but the definition omits links {incoming remove}.
invalid_argumentprotected_linkA protected system field references an entity selected for erasure.
invalid_argumentinvalid_targetA selected entity is not a data entity.
invalid_argumentinvalid_expressionAn expression is invalid or exceeds its size limit.
not_foundnot_foundNo definition has the path.
not_foundno_matchThe selection has no assertion to rewrite.
evaluation_failedexpression_failedEvaluation fails.
evaluation_failedwork_limitEvaluation exceeds its work or CPU limit.
out_of_memoryexhaustedThe operation exceeds a limit or cannot allocate the memory it needs.

Error messages do not include expression diagnostics that could disclose original values or the private seed.

Execute

execute repeats the preview's blackhole and parameters. It also requires these members:

MemberValue
digestThe SHA-256 value {#sha256 ...} from the approved preview.
confirmThe exact confirmation text from that preview.
actorNonblank text identifying who requested the operation.
reasonNonblank text explaining the operation.

Copy digest and confirm from your actual preview. The digest below is only an example:

edn262 B
{:blackhole  "keys/leaked"
 :parameters {:?owner {:#link 7}}
 :digest     {:#sha256 "5b0fd4a1c6e9b2d8a37c0e41f9d5a6b8c3e7f20914d6a85b7c1e0f3a9d24b6c8"}
 :confirm    "PERMANENTLY REWRITE HISTORY AND BACKUPS"
 :actor      "ops"
 :reason     "Erasure request 2291"}

Execution blocks other writes, then selects and plans the definition again with a fresh 256-bit cryptographic seed. Callers cannot supply the seed, and every expression in the operation uses the same one. The plugin discards it when the operation finishes. Execution applies the rewrite only if the new digest matches the approved one. Editing the definition, changing the parameters, or any commit since the preview causes conflict. Obtain a new preview and approval before trying again.

Every selected entity field changes in one transaction. Queries and indexes read the rewritten history. Subscriptions receive an incomplete change notification and read the database again. An index that covers a selected field but cannot repair itself rejects execution with unavailable and the code index_unsupported. On macOS, execution is refused while the filesystem plugin has a mount configured. The macOS mount cannot expire files that are already open, so execute reports unsupported with the code mounted_removal_unsupported and changes nothing. To execute, reopen the database without the filesystem plugin.

The execution result contains these members:

MemberMeaning
stagecomplete, or recovering if the rewrite committed but backup or recovery-record cleanup remains.
transactionThe rewrite transaction ID. Its metadata contains the immutable audit.
cutoffThe approved transaction cutoff.
targetsThe number of selected entity fields.
matchedThe number of assertions rewritten.
replacementsThe number of assertions replaced.
removalsThe number of assertions turned into retractions.
requestDigestA SHA-256 value {#sha256 ...} identifying the targets with their expressions and row bindings.
effectDigestA SHA-256 value {#sha256 ...} identifying the changes to the assertions.

Execution results contain no samples or seed. The replacement values remain readable in the rewritten records. An expression that returns the original value or exposes the seed can disclose sensitive information. Choose expressions that remove the information you need to erase.

An output allocation failure can occur after the rewrite commits. Read the audit or reopen the database before retrying.

Backup recovery

With the backups plugin enabled, every target must be reachable and match local history before execution begins. Otherwise, execute reports unavailable and changes nothing. The operation completes these steps:

  1. The rewrite, its transaction audit, the rebuilt indexes and a recovery record commit together.
  2. Every target replaces its history from the first changed transaction with the rewritten history.
  3. The recovery record is deleted.

A failure before the first step leaves history unchanged. After that commit, cancellation, closing the database or a crash cannot undo the rewrite. A result with stage recovering confirms that the local rewrite and audit committed but recovery work remains. Until the database reopens, another execute reports unavailable with the code recovery_pending. The next database open resumes recovery before comparing local history with the targets. Opening fails while a required target is unreachable. While the backups plugin is disabled, recovery waits and status reports recovering true. Enable backups and reopen the database to finish recovery. See backup status for target progress and whether new writes are allowed.

Keep every recorded target configured with its original name and storage namespace until recovery finishes. Removing, renaming or redirecting a target prevents recovery. Restore its original configuration and reopen the database. Recovery copies the committed replacements without evaluating the expressions again. It needs no execution seed.

Audit and status

Each execution writes one immutable stardust/blackhole metadata object on its own transaction. The audit commits atomically with the rewrite. Recovery does not create or change it. Only the plugin can write this reserved field. Explicit patches cannot target transactions; incoming-reference cleanup can remove links from ordinary user transaction metadata.

The object contains definition, definitionDigest, actor, reason, cutoff, matched, requestDigest, effectDigest and affected. definition links to the named definition; definitionDigest identifies its authored source at execution. All digest fields are native SHA-256 values, written as {#sha256 ...} in DUST. affected.entities maps erased entity IDs to true. affected.fields maps each rewritten field name to a map of affected entity IDs, also with values of true. Whole-entity erasures appear in entities; their fields are not repeated in fields. Public results omit empty groups, as with other empty object members. Recovery progress is separate from transaction metadata.

For example, this scope erases entity 101 and removes incoming references from entity 200's manager field:

edn80 B
{:affected {:entities {:101 true}
            :fields   {:manager {:200 true}}}}

The plugin does not copy removed values or invocation parameters into the audit. Keep sensitive information out of the actor and reason text you supply.

audit lists these metadata objects with their transaction IDs in ascending transaction order. Its optional request accepts after and limit. The limit is from 1 to 1000. status reports enabled, audits, recovering and backups.

Removal limits

A blackhole changes readable history in this database and its configured backup targets. Later writes can store the fields or the same values again. Removing a field that references a binary payload does not delete that shared payload.

Removal does not overwrite freed disk pages or erase versions kept by a storage provider. Independent database copies and external snapshots require separate cleanup. Bytes already delivered to an application cannot be recalled.

Reopen mounted snapshots affected by a rewrite. Discard staged saves based on the old history and read the records again.

Operations

OperationReturnsSummary
Blackholes::previewdocumentblackholes.preview(request) selects and plans a stored blackhole definition and returns an owned document with the digest to approve.
Blackholes::executedocumentblackholes.execute(request) permanently rewrites the approved history and returns an owned completion record.
Blackholes::auditdocumentblackholes.audit(options) returns an owned array document of transaction audits in ascending transaction order.
Blackholes::statusdocumentblackholes.status() returns an owned document describing the runtime.

Blackholes::preview

rust61 B
pub fn preview(&self, request: &Document) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe blackholes owner for this operation. Keep it alive during the call.
request&DocumentBorrowed for the callRequiredThe borrowed preview request: {blackhole [parameters]}.

Errors

StatusWhen
Status::INVALID_ARGUMENTthe request is malformed, the parameters do not fit the query, a selected target is a reserved field or not a data entity, or rows disagree about one entity field
Status::NOT_FOUNDno definition has the path (code not_found), or the selection has no assertion to rewrite (code no_match)
Status::EVALUATION_FAILEDa replacement expression fails or exceeds its work limit. History stays unchanged
Status::UNAVAILABLEthe database does not enable the blackholes plugin
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

See preview for the request and result fields.

Examples

Store a blackhole definition and preview it

rust312 B
let definition = stardust::parse("{query {find [?e] where [[?e name Ada]]} patch {?e {name null}}}", Format::DUST)?;
db.patch_definition("blackholes", "people/erase-ada", &definition)?;
let request = stardust::parse("{blackhole people/erase-ada}", Format::DUST)?;
let result = db.blackholes().preview(&request)?;
Result / 318 B
{:value {:digest       {:#sha256 "86211f7c4ae01a9d52d96abe12afb871ea4b92f1ed181d0c4c17307e622a5837"}
         :targets      1
         :matched      1
         :replacements 0
         :removals     1
         :confirm      "PERMANENTLY REWRITE HISTORY AND BACKUPS"
         :affected     {:fields {:name {:1 true}}}}}

C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release

Blackholes::execute

rust61 B
pub fn execute(&self, request: &Document) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe blackholes owner for this operation. Keep it alive during the call.
request&DocumentBorrowed for the callRequiredThe borrowed execute request: {blackhole [parameters] digest confirm actor reason}.

Errors

StatusWhen
Status::INVALID_ARGUMENTthe request is malformed, confirm is wrong, the parameters do not fit the query, a selected target is a reserved field or not a data entity, or rows disagree about one entity field
Status::NOT_FOUNDno definition has the path (code not_found), or the selection has no assertion to rewrite (code no_match)
Status::CONFLICTthe definition, parameters, selection or history changed since the preview, or the digest names another request
Status::EVALUATION_FAILEDa replacement expression fails or exceeds its work limit. History stays unchanged
Status::UNAVAILABLEthe database does not enable the blackholes plugin, an earlier execution is still recovering, an index covers a selected field and cannot be repaired, or a backup target cannot take the blackhole
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

Obtain approval before execution. The plugin cannot undo a committed rewrite. An output allocation failure can occur after commit. Read the audit or reopen before retrying. See execution.

Examples

Execute a blackhole with the approved preview

rust932 B
#[derive(serde::Deserialize)]
struct Approval {
    digest: std::collections::BTreeMap<String, String>,
    confirm: String,
}
#[derive(serde::Serialize)]
struct Request<'a> {
    blackhole: &'a str,
    digest: &'a std::collections::BTreeMap<String, String>,
    confirm: &'a str,
    actor: &'a str,
    reason: &'a str,
}
let definition = stardust::parse("{query {find [?e] where [[?e name Ada]]} patch {?e {name null}}}", Format::DUST)?;
db.patch_definition("blackholes", "people/erase-ada", &definition)?;
let target = stardust::parse("{blackhole people/erase-ada}", Format::DUST)?;
let preview = db.blackholes().preview(&target)?;
let approval: Approval = stardust::decode(&preview)?;
let request = stardust::encode(&Request {
    blackhole: "people/erase-ada",
    digest: &approval.digest,
    confirm: &approval.confirm,
    actor: "ops",
    reason: "Erasure request",
})?;
let result = db.blackholes().execute(&request)?;
Result / 396 B
{:value {:stage         "complete"
         :transaction   8
         :cutoff        7
         :targets       1
         :matched       1
         :replacements  0
         :removals      1
         :requestDigest {:#sha256 "e134b2bd24fdec9a42d42adc6feb37666f56b9e26468bff4a4bb7980d9ba9f61"}
         :effectDigest  {:#sha256 "17604fa78ccf3e6dcf202ef94ecda279d1e96f052fd709eafd52fc030aaf0196"}}}

C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release

Blackholes::audit

rust67 B
pub fn audit(&self, options: Option<&Document>) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe blackholes owner for this operation. Keep it alive during the call.
optionsOption<&Document>Borrowed for the callAbsent selects operation defaultsThe borrowed options, or none: {[after] [limit]}.

Errors

StatusWhen
Status::INVALID_ARGUMENToptions is not an object, or an option is invalid or unsupported
Status::UNAVAILABLEthe database does not enable the blackholes plugin
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Notes

The plugin does not copy removed values or invocation parameters into the audit. Keep sensitive information out of actor and reason. See the audit.

Examples

List Blackholes audit records

rust113 B
let options = stardust::parse("{limit 100}", Format::DUST)?;
let result = db.blackholes().audit(Some(&options))?;
Result / 11 B
{:value []}

C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release

Blackholes::status

rust40 B
pub fn status(&self) -> Result<Document>

Parameters

ParameterTypeOwnershipDefaultMeaning
self&SelfBorrowed for the callRequiredThe blackholes owner for this operation. Keep it alive during the call.

Errors

StatusWhen
Status::UNAVAILABLEthe database does not enable the blackholes plugin
Status::CLOSEDthe database is closed
Status::OUT_OF_MEMORYnative memory is exhausted

Examples

Check Blackholes status

rust39 B
let result = db.blackholes().status()?;
Result / 104 B
{:value {:enabled    true
         :audits     0
         :recovering false
         :backups    false}}

C exports: stardust_db_plugin_call, stardust_result_take_document, stardust_result_error, stardust_result_release