forgetproof 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
forgetproof/fixer.py ADDED
@@ -0,0 +1,274 @@
1
+ """Erase residue found by the scanner, rescan, and report what changed."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import shutil
8
+ import sqlite3
9
+ import subprocess
10
+ import sys
11
+ from dataclasses import dataclass, field
12
+ from importlib import metadata
13
+ from pathlib import Path
14
+
15
+ from . import files_store, hnsw, lance_store, mem0_store, postgres, qdrant_store, safety
16
+ from ._chroma_rebuild import JOURNAL
17
+ from .report import Report
18
+ from .scanner import normalized_segments, scan
19
+ from .sqlite_residue import connect_ro, vacuum
20
+
21
+
22
+ class FixError(Exception):
23
+ pass
24
+
25
+
26
+ @dataclass
27
+ class Options:
28
+ force: bool = False # skip the open-process and free-space checks
29
+ allow_upgrade: bool = False # let chromadb migrate an older store to its own format
30
+
31
+
32
+ @dataclass
33
+ class Result:
34
+ before: Report
35
+ after: Report
36
+ actions: list[str] = field(default_factory=list)
37
+
38
+
39
+ def _dispatch_child(args: list[str]) -> None:
40
+ """What the child process does: `rebuild PATH`, `delete PATH` (values on stdin) or `migrations`."""
41
+ from . import _chroma_rebuild as m
42
+
43
+ if args[0] == "rebuild":
44
+ m.rebuild(Path(args[1]))
45
+ elif args[0] == "delete":
46
+ m.delete_containing(Path(args[1]))
47
+ else:
48
+ m.migrations()
49
+
50
+
51
+ def _mp_entry(args: list[str], input_text: str | None, out_path: str, err_path: str) -> None:
52
+ """Entry point of the child when it is a multiprocessing process (a frozen desktop app has no
53
+ separate interpreter to exec): stdio goes to files the parent reads back."""
54
+ import io
55
+
56
+ for k, v in _child_env().items():
57
+ os.environ[k] = v
58
+ sys.stdin = io.StringIO(input_text or "")
59
+ with open(out_path, "w", encoding="utf-8") as out, open(err_path, "w", encoding="utf-8") as err:
60
+ sys.stdout, sys.stderr = out, err
61
+ try:
62
+ _dispatch_child(args)
63
+ except BaseException as e: # the parent reports it as a failed child
64
+ import traceback
65
+
66
+ traceback.print_exc(file=err)
67
+ err.write(f"\n{type(e).__name__}: {e}\n")
68
+ os._exit(1)
69
+
70
+
71
+ def _run_child(*args: str, input: str | None = None) -> subprocess.CompletedProcess:
72
+ """Run a Chroma operation in a child process so chromadb's file handles and caches are fully
73
+ released before the fixer touches the files directly. Normally a fresh interpreter; in a frozen
74
+ app (PyInstaller) a spawned multiprocessing child, since there is no interpreter to exec."""
75
+ if getattr(sys, "frozen", False) or os.environ.get("FORGETPROOF_CHILD_MP") == "1":
76
+ import multiprocessing
77
+ import tempfile
78
+
79
+ ctx = multiprocessing.get_context("spawn")
80
+ with tempfile.TemporaryDirectory(prefix="forgetproof-child-") as d:
81
+ out_path, err_path = os.path.join(d, "out"), os.path.join(d, "err")
82
+ p = ctx.Process(target=_mp_entry, args=(list(args), input, out_path, err_path))
83
+ p.start()
84
+ p.join()
85
+ out = open(out_path, encoding="utf-8").read() if os.path.exists(out_path) else ""
86
+ err = open(err_path, encoding="utf-8").read() if os.path.exists(err_path) else ""
87
+ return subprocess.CompletedProcess(list(args), p.exitcode or 0, out, err)
88
+ # -c rather than -m, with the current directory dropped from sys.path before anything is
89
+ # imported: a chromadb.py in whatever directory the user runs us from must not be executed.
90
+ bootstrap = (
91
+ "import sys; sys.path[:] = [p for p in sys.path if p not in ('', '.')]; "
92
+ "from forgetproof.fixer import _dispatch_child; _dispatch_child(sys.argv[1:])"
93
+ )
94
+ return subprocess.run([sys.executable, "-c", bootstrap, *args], capture_output=True, text=True, env=_child_env(),
95
+ input=input)
96
+
97
+
98
+ def _child_env() -> dict[str, str]:
99
+ """The rebuild only copies stored embeddings; it never needs to fetch or run a model. A collection's
100
+ saved settings can name an embedding model to load, so keep model hubs offline (remote model code is
101
+ how the 2026 chromadb code-injection advisories work) and keep Chroma's usage telemetry off."""
102
+ return {
103
+ **os.environ,
104
+ "HF_HUB_OFFLINE": "1",
105
+ "TRANSFORMERS_OFFLINE": "1",
106
+ "HF_HUB_DISABLE_TELEMETRY": "1",
107
+ "ANONYMIZED_TELEMETRY": "False",
108
+ }
109
+
110
+
111
+ def _require_chromadb() -> None:
112
+ # Check from package metadata: chromadb itself only ever loads in the rebuild child process.
113
+ try:
114
+ installed = metadata.version("chromadb")
115
+ except metadata.PackageNotFoundError:
116
+ raise FixError("fixing a Chroma store needs chromadb: pip install 'forgetproof[chroma]'") from None
117
+ if int(installed.split(".")[0]) < 1:
118
+ raise FixError(
119
+ f"fixing needs chromadb 1.0 or later (installed: {installed}). Scanning works with any "
120
+ "version. To fix a store from Chroma 0.x, install chromadb>=1.0 and pass --allow-upgrade: the store "
121
+ "will then need Chroma 1.x to open."
122
+ )
123
+
124
+
125
+ def _check_chroma_version(target: Path, allow_upgrade: bool) -> None:
126
+ """Refuse to let the installed chromadb silently migrate the user's store."""
127
+ conn = connect_ro(target / "chroma.sqlite3")
128
+ try:
129
+ store = {tuple(r) for r in conn.execute("select dir, version from migrations")}
130
+ except sqlite3.Error:
131
+ store = set()
132
+ finally:
133
+ conn.close()
134
+ proc = _run_child("migrations")
135
+ if proc.returncode != 0:
136
+ raise FixError(f"could not start chromadb:\n{proc.stderr.strip()[-2000:]}")
137
+ info = json.loads(proc.stdout)
138
+ installed = {tuple(r) for r in info["migrations"]}
139
+ if store - installed:
140
+ raise FixError(
141
+ f"this store was written by a newer Chroma than the installed chromadb {info['chromadb']}. "
142
+ "Upgrade chromadb to the version your app uses, then run fix again."
143
+ )
144
+ if installed - store and not allow_upgrade:
145
+ raise FixError(
146
+ f"this store was written by an older Chroma. Fixing it with chromadb {info['chromadb']} would upgrade "
147
+ "it to that version's format, and your app's older Chroma may not open it afterwards. Install the "
148
+ "chromadb version your app uses (pip install chromadb==<version>) and run fix again, or pass "
149
+ "--allow-upgrade if your app is moving to this version anyway."
150
+ )
151
+
152
+
153
+ def preflight(target: Path, report: Report, options: Options) -> None:
154
+ if report.store == "postgres":
155
+ return # VACUUM FULL takes its own locks; fix() checks ownership and uses a lock timeout
156
+ if report.store == "files":
157
+ return # nothing is rewritten
158
+ if not options.force:
159
+ holders = safety.open_by_other_processes(target)
160
+ if holders:
161
+ raise FixError(
162
+ "the store is open in another process: " + ", ".join(holders[:5])
163
+ + ". Stop it first; rewriting files under a running app corrupts them. (--force skips this check.)"
164
+ )
165
+ need, free = safety.space_needed(target), safety.free_space(target)
166
+ if free < need:
167
+ raise FixError(f"fix needs about {need >> 20} MB free next to the store; {free >> 20} MB available. (--force skips this check.)")
168
+ if report.store == "chroma":
169
+ _require_chromadb()
170
+ _check_chroma_version(target, options.allow_upgrade)
171
+
172
+
173
+ def plan(report: Report) -> list[str]:
174
+ """What fix would do to this store, without doing it."""
175
+ if report.store == "postgres":
176
+ return postgres.plan(report)
177
+ if report.store == "mem0":
178
+ return mem0_store.plan(report)
179
+ if report.store == "qdrant":
180
+ return qdrant_store.plan(report)
181
+ if report.store == "lancedb":
182
+ return lance_store.plan(report)
183
+ if report.store == "files":
184
+ return files_store.plan(report)
185
+ if report.store != "chroma":
186
+ return [f"VACUUM {Path(report.target).name} with secure_delete on (rewrites the file without free pages)"]
187
+ target = Path(report.target)
188
+ steps = []
189
+ if (target / JOURNAL).exists():
190
+ steps.append("finish the interrupted fix recorded in " + JOURNAL)
191
+ n = report.stats.get("collections", 0)
192
+ steps.append(f"rebuild {n} collection(s) from their live records "
193
+ "(ids, documents, metadata and embeddings kept; collections get new internal IDs)")
194
+ steps.append("delete the index files the rebuild replaces, with their deleted vectors")
195
+ checks = {f.check for f in report.findings}
196
+ if checks & {"chroma.write_log", "chroma.write_log_overwritten"}:
197
+ steps.append("drop write-log entries of the replaced collections")
198
+ if "chroma.orphaned_index" in checks:
199
+ steps.append("delete index directories no collection uses: "
200
+ + next(f.location for f in report.findings if f.check == "chroma.orphaned_index"))
201
+ steps.append("zero never-used capacity in the remaining index files (sizes unchanged)")
202
+ steps.append("VACUUM chroma.sqlite3 with secure_delete on")
203
+ return steps
204
+
205
+
206
+ def _fix_chroma(target: Path) -> list[str]:
207
+ actions = []
208
+ proc = _run_child("rebuild", str(target))
209
+ if proc.returncode != 0:
210
+ raise FixError(
211
+ "rebuilding collections failed; no live data was lost, and running fix again finishes or undoes "
212
+ f"the interrupted step.\n{proc.stderr.strip()[-2000:]}"
213
+ )
214
+ actions += [line for line in proc.stderr.splitlines() if line.startswith(("rebuilt ", "recovered "))]
215
+
216
+ db = target / "chroma.sqlite3"
217
+ conn = sqlite3.connect(db)
218
+ try:
219
+ segments = {r[0] for r in conn.execute("select id from segments")}
220
+ normalized = normalized_segments(conn)
221
+ collections = {r[0] for r in conn.execute("select id from collections")}
222
+ stale = [
223
+ topic for (topic,) in conn.execute("select distinct topic from embeddings_queue")
224
+ if topic.rsplit("/", 1)[-1] not in collections
225
+ ]
226
+ for topic in stale:
227
+ conn.execute("delete from embeddings_queue where topic = ?", (topic,))
228
+ conn.commit()
229
+ finally:
230
+ conn.close()
231
+ if stale:
232
+ actions.append(f"dropped write-log entries of {len(stale)} deleted collection(s)")
233
+
234
+ for sub in sorted(p for p in target.iterdir() if p.is_dir()):
235
+ index = hnsw.read_index(sub, normalized.get(sub.name, True))
236
+ if index is None:
237
+ continue
238
+ if sub.name not in segments:
239
+ shutil.rmtree(sub)
240
+ actions.append(f"removed orphaned index {sub.name}")
241
+ elif index.leaked_bytes:
242
+ zeroed = hnsw.zero_unused(index)
243
+ actions.append(f"zeroed {zeroed} bytes of unused index capacity in {sub.name}")
244
+
245
+ vacuum(db)
246
+ actions.append("vacuumed chroma.sqlite3 (secure_delete on)")
247
+ return actions
248
+
249
+
250
+ def fix(target: Path | str, canaries: list[str], options: Options | None = None, show: bool = False) -> Result:
251
+ if postgres.is_postgres(target):
252
+ before = scan(target, canaries)
253
+ try:
254
+ actions = postgres.fix(str(target))
255
+ except postgres.PostgresError as e:
256
+ raise FixError(str(e)) from None
257
+ return Result(before, scan(target, canaries), actions)
258
+ target = Path(target).resolve()
259
+ before = scan(target, canaries, show)
260
+ preflight(target, before, options or Options())
261
+ if before.store == "chroma":
262
+ actions = _fix_chroma(target)
263
+ elif before.store == "mem0":
264
+ actions = mem0_store.fix(target)
265
+ elif before.store == "qdrant":
266
+ actions = qdrant_store.fix(target)
267
+ elif before.store == "lancedb":
268
+ actions = lance_store.fix(target)
269
+ elif before.store == "files":
270
+ actions = files_store.fix(target)
271
+ else:
272
+ vacuum(target)
273
+ actions = [f"vacuumed {target.name} (secure_delete on)"]
274
+ return Result(before, scan(target, canaries, show), actions)
forgetproof/forget.py ADDED
@@ -0,0 +1,264 @@
1
+ """forget(): erase one subject's data now, or queue it when the store can't be rewritten yet.
2
+
3
+ Postgres and SQLite can be fixed while the application is running: `fix` takes its own locks.
4
+ Chroma cannot — it must not be rewritten while the application still has it open. `forget()`
5
+ queues the request instead of failing, encrypted at rest under a local key. Call `run_queued()`
6
+ before the application reopens the store (its own next start is the natural point) to finish it.
7
+
8
+ A subject is one exact value or several (a person's name, emails and phone numbers: see
9
+ `subject.py`). `also_live=True` first removes the live records that contain one of the values —
10
+ the owner's explicit choice on their own machine, never the default — and then erases what the
11
+ store had deleted but still held. The receipt carries how many values the subject had, never the
12
+ values, and the copies report for the store, so a clean verdict is read next to the places it
13
+ doesn't cover.
14
+
15
+ A queued entry holds nothing but the encrypted subject values, the store it is for, whether live
16
+ records were to go too, and the caller's opaque correlation id if it gave one. It is deleted once
17
+ it drains *clean* — not merely once it's been tried. A subject can legitimately still be found
18
+ after `fix()`: the same value can appear in another, unrelated live record that must not be
19
+ erased. Retrying that forever won't help, so after a few attempts the entry is parked (kept, but
20
+ no longer retried automatically) instead of either looping forever or being silently dropped as
21
+ if it had succeeded.
22
+
23
+ A parked entry still holds that encrypted subject — only the local queue key, sitting right next
24
+ to it, can decrypt it — so an operator can inspect why and retry manually once resolved. A tool
25
+ built to help with erasure requests must not become an unbounded store of who asked for one, so a
26
+ parked entry isn't kept forever either: run_queued() purges one past PARK_RETENTION_DAYS on its own,
27
+ and purge_stale() does it on demand.
28
+ """
29
+
30
+ from __future__ import annotations
31
+
32
+ import json
33
+ import uuid
34
+ from collections.abc import Iterable
35
+ from dataclasses import dataclass
36
+ from datetime import datetime, timedelta, timezone
37
+ from pathlib import Path
38
+
39
+ from cryptography.fernet import Fernet
40
+
41
+ from . import keystore, postgres, receipt, safety
42
+ from .copies import copies_of
43
+ from .erase_live import erase_live
44
+ from .fixer import FixError, Options, fix
45
+ from .scanner import detect
46
+ from .subject import Subject, subject as make_subject
47
+
48
+ MAX_ATTEMPTS = 3 # how many run_queued() calls retry an entry that isn't clean yet before parking it
49
+ PARK_RETENTION_DAYS = 30 # how long a parked entry is kept before run_queued() purges it automatically
50
+ _OPEN = "open in another process"
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class Queued:
55
+ target: str
56
+ queued_at: str
57
+ correlation_id: str | None = None
58
+
59
+
60
+ def _label(target: Path | str) -> str:
61
+ return postgres.display(target) if postgres.is_postgres(target) else str(Path(target).resolve())
62
+
63
+
64
+ def _queue_dir(queue_dir: Path | str | None = None) -> Path:
65
+ d = Path(queue_dir) if queue_dir else receipt.key_path().parent / "queue"
66
+ d.mkdir(parents=True, exist_ok=True)
67
+ try:
68
+ d.chmod(0o700)
69
+ except OSError:
70
+ pass # best-effort on platforms without POSIX permissions (e.g. some Windows filesystems)
71
+ return d
72
+
73
+
74
+ def _queue_key(queue_dir: Path) -> Fernet:
75
+ return Fernet(keystore.get_or_create("queue_key", queue_dir / "queue.key", Fernet.generate_key))
76
+
77
+
78
+ def _copies(target: Path | str) -> list[dict]:
79
+ if postgres.is_postgres(target):
80
+ return []
81
+ return [c.to_dict() for c in copies_of(target)]
82
+
83
+
84
+ def _issue(target: Path | str, result, correlation_id: str | None = None, *, subject_values: int = 0,
85
+ issuer: str | None = None) -> dict:
86
+ before, after = result.before.summary(), result.after.summary()
87
+ canaries = [{"canary": c.number, "found_in": c.found_in} for c in result.after.canaries]
88
+ return receipt.issue(target, before, after, result.actions, canaries, label=_label(target),
89
+ correlation_id=correlation_id, subject_values=subject_values, copies=_copies(target),
90
+ issuer=issuer)
91
+
92
+
93
+ def _as_subject(value: str | Iterable[str] | Subject) -> Subject:
94
+ return value if isinstance(value, Subject) else make_subject(value)
95
+
96
+
97
+ def _open_elsewhere(target: Path | str, options: Options) -> bool:
98
+ """Is a file store held open by another process? (The same check fix's preflight makes; done first
99
+ here so a live deletion is never attempted on a store an application is writing to.)"""
100
+ if options.force or postgres.is_postgres(target):
101
+ return False
102
+ path = Path(target).resolve()
103
+ try:
104
+ if detect(path) == "files":
105
+ return False
106
+ except Exception:
107
+ return False
108
+ return bool(safety.open_by_other_processes(path))
109
+
110
+
111
+ def _erase(target: Path | str, subj: Subject, also_live: bool, options: Options):
112
+ """Live deletion (if asked), then fix. Raises FixError(_OPEN) without touching anything if the
113
+ store is open elsewhere."""
114
+ if also_live and _open_elsewhere(target, options):
115
+ raise FixError(f"the store is {_OPEN}")
116
+ actions = erase_live(target, subj) if also_live else []
117
+ result = fix(target, subj.needles, options)
118
+ result.actions = actions + result.actions
119
+ return result
120
+
121
+
122
+ def forget(target: Path | str, subject: str | Iterable[str] | Subject, *, also_live: bool = False,
123
+ options: Options | None = None, queue_dir: Path | str | None = None,
124
+ correlation_id: str | None = None, issuer: str | None = None) -> dict | Queued:
125
+ """Erase `subject`'s data from `target` and return a signed receipt.
126
+
127
+ If the store can't be rewritten right now (Chroma, with the application still holding it
128
+ open), the request is queued instead and a `Queued` marker is returned. Call `run_queued`
129
+ for this target before the application next opens the store to finish it.
130
+
131
+ `subject` is one value, several, or a Subject. `also_live` removes live records that contain a
132
+ value first (see erase_live.py). `correlation_id`, if given, is an opaque label the caller
133
+ supplies to tie this request to its own record of it (a case id, a ticket number) — forgetproof
134
+ never looks at it. It's carried into the eventual receipt either way, including when the
135
+ request is queued and only actually drains, in a later process, through `run_queued()`. Keep
136
+ it non-sensitive: like `target`, it's stored in the queue entry and the receipt in plaintext,
137
+ not encrypted like the subject is.
138
+ """
139
+ subj = _as_subject(subject)
140
+ options = options or Options()
141
+ try:
142
+ result = _erase(target, subj, also_live, options)
143
+ except FixError as e:
144
+ if _OPEN not in str(e):
145
+ raise
146
+ return queue(target, subj, also_live=also_live, queue_dir=queue_dir, correlation_id=correlation_id)
147
+ return _issue(target, result, correlation_id=correlation_id, subject_values=subj.count, issuer=issuer)
148
+
149
+
150
+ def queue(target: Path | str, subject: str | Iterable[str] | Subject, *, also_live: bool = False,
151
+ queue_dir: Path | str | None = None, correlation_id: str | None = None) -> Queued:
152
+ """Queue `subject` for `target` without touching the store, and return the `Queued` marker.
153
+
154
+ forget() does this itself when its own check finds the store open in another process. Call it
155
+ directly when you already know the store must not be rewritten now — a Chroma directory the
156
+ application in this very process still has open, which the check cannot see on every platform.
157
+ `run_queued` for the target drains the entry later.
158
+ """
159
+ subj = _as_subject(subject)
160
+ qd = _queue_dir(queue_dir)
161
+ token = _queue_key(qd).encrypt(json.dumps(list(subj.values)).encode())
162
+ queued_at = datetime.now(timezone.utc).isoformat(timespec="seconds")
163
+ entry = qd / f"{uuid.uuid4().hex}.json"
164
+ entry.write_text(json.dumps({"target": _label(target), "subject": token.decode(), "queued_at": queued_at,
165
+ "also_live": also_live, "correlation_id": correlation_id}))
166
+ try:
167
+ entry.chmod(0o600)
168
+ except OSError:
169
+ pass
170
+ return Queued(_label(target), queued_at, correlation_id)
171
+
172
+
173
+ def pending(target: Path | str, *, queue_dir: Path | str | None = None) -> int:
174
+ """How many forget() calls for this target will still be retried automatically.
175
+
176
+ Doesn't count entries parked by run_queued() after MAX_ATTEMPTS — those need the operator's
177
+ attention; stale_entries() reports them.
178
+ """
179
+ qd = _queue_dir(queue_dir)
180
+ label = _label(target)
181
+ return sum(1 for e in qd.glob("*.json") if json.loads(e.read_text()).get("target") == label)
182
+
183
+
184
+ def stale_entries(target: Path | str, *, queue_dir: Path | str | None = None) -> int:
185
+ """How many forget() calls for this target were parked: tried MAX_ATTEMPTS times by
186
+ run_queued() without becoming clean, so they're no longer retried automatically. Each
187
+ attempt's receipt recorded why — a value that's still genuinely live elsewhere, most often.
188
+ Purged automatically after PARK_RETENTION_DAYS; purge_stale() does it sooner on demand."""
189
+ qd = _queue_dir(queue_dir)
190
+ label = _label(target)
191
+ return sum(1 for e in qd.glob("*.failed") if json.loads(e.read_text()).get("target") == label)
192
+
193
+
194
+ def purge_stale(target: Path | str | None = None, *, older_than_days: float = PARK_RETENTION_DAYS,
195
+ queue_dir: Path | str | None = None) -> int:
196
+ """Delete parked entries older than `older_than_days` (for every target, if `target` is None).
197
+
198
+ A parked entry still holds the subject it couldn't erase, encrypted but decryptable with the
199
+ local queue key sitting beside it, so it isn't kept indefinitely. run_queued() calls this with
200
+ the default retention on every drain; call it directly to purge sooner, e.g. `older_than_days=0`.
201
+ """
202
+ qd = _queue_dir(queue_dir)
203
+ label = _label(target) if target is not None else None
204
+ cutoff = datetime.now(timezone.utc) - timedelta(days=older_than_days)
205
+ purged = 0
206
+ for entry in qd.glob("*.failed"):
207
+ data = json.loads(entry.read_text())
208
+ if label is not None and data.get("target") != label:
209
+ continue
210
+ parked_at = datetime.fromisoformat(data.get("parked_at", data["queued_at"]))
211
+ if parked_at <= cutoff:
212
+ entry.unlink()
213
+ purged += 1
214
+ return purged
215
+
216
+
217
+ def _decode_subject(plain: str) -> Subject:
218
+ """A 0.2 entry holds a JSON list of values; a 0.1 entry holds the one value as text."""
219
+ if plain.startswith("["):
220
+ try:
221
+ values = json.loads(plain)
222
+ if isinstance(values, list):
223
+ return make_subject(values)
224
+ except ValueError:
225
+ pass
226
+ return make_subject(plain)
227
+
228
+
229
+ def run_queued(target: Path | str, *, options: Options | None = None,
230
+ queue_dir: Path | str | None = None, issuer: str | None = None) -> list[dict]:
231
+ """Finish every forget() queued for `target`. Call this before the application reopens
232
+ a Chroma store, so nothing else has it open while the queued erasures run.
233
+
234
+ Each receipt is issued as its entry is drained. An entry is removed only once its receipt's
235
+ verdict is CLEAN — never merely because it was attempted — so a crash midway, or a fix that
236
+ didn't fully succeed, leaves it to retry rather than being silently treated as done. After
237
+ MAX_ATTEMPTS without a clean result, an entry is parked (kept, but excluded from future
238
+ automatic retries) instead of being retried forever; stale_entries() reports those. Parked
239
+ entries older than PARK_RETENTION_DAYS are purged as part of this call.
240
+ """
241
+ qd = _queue_dir(queue_dir)
242
+ key = _queue_key(qd)
243
+ label = _label(target)
244
+ receipts = []
245
+ for entry in sorted(qd.glob("*.json")):
246
+ data = json.loads(entry.read_text())
247
+ if data.get("target") != label:
248
+ continue
249
+ subj = _decode_subject(key.decrypt(data["subject"].encode()).decode())
250
+ result = _erase(target, subj, bool(data.get("also_live")), options or Options())
251
+ rec = _issue(target, result, correlation_id=data.get("correlation_id"), subject_values=subj.count, issuer=issuer)
252
+ receipts.append(rec)
253
+ if rec["verdict"] == "CLEAN":
254
+ entry.unlink()
255
+ continue
256
+ attempts = data.get("attempts", 0) + 1
257
+ data["attempts"] = attempts
258
+ if attempts >= MAX_ATTEMPTS:
259
+ data["parked_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
260
+ entry.rename(entry.with_suffix(".failed")).write_text(json.dumps(data))
261
+ else:
262
+ entry.write_text(json.dumps(data))
263
+ purge_stale(target, queue_dir=qd)
264
+ return receipts