Repository navigation
feat(memory): operator tool to restore memories archived by the stale dev planner (dry-run default) - #23334
feat(memory): operator tool to restore memories archived by the stale dev planner (dry-run default)#23334Git-on-my-level wants to merge 1 commit into
Conversation
Dry-run-first operator tool re-applying incident-archived memory_items as short_term-visible decisions through the canonical apply ledger (apply_long_term_patch_firestore) with the remediation=stale-planner-2026-10-22 audit marker, reversible via --revert. Per-user COLLECTION-scope scan with read budget, keyset cursor, legal-hold/deletion-gate/deleted-user exclusions, and payload-free count-only output. Registers the two memory_items query drivers and regenerates the composite-index manifest. Prod writes remain gated on the plan's explicit GO. Co-Authored-By: GLM-5.3 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b7ce058204
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| remediation = (item.promotion or {}).get("remediation") or {} | ||
| if remediation.get("marker") != MARKER or remediation.get("reverted_at") is not None: | ||
| scan.exclusions["marker_stale"] += 1 | ||
| continue | ||
| scan.matched.append(item) |
There was a problem hiding this comment.
Fence reverts to the exact restored revision
If a user edits or reviews a memory after --apply but before an operator runs --revert, the normal mutation path preserves the unknown promotion.remediation field while advancing the item revision. This selector checks only the marker and reverted_at, so it accepts that newer user-authored revision, and _apply_row then successfully archives it using its current revision. Record the committed restore revision or commit ID in the marker and require an exact match before reverting, so rollback cannot hide post-remediation user changes.
Useful? React with 👍 / 👎.
| if item.updated_at is not None and item.updated_at > processed_at: | ||
| return "edited_after_processing" |
There was a problem hiding this comment.
Do not reject the planner's own timestamp update
For rows produced by the affected planner, promotion.processed_at is the now passed into apply_consolidation_decision, while the canonical apply layer independently stamps updated_at with a later datetime.now() when it materializes the same commit. Consequently, even an untouched incident row normally has updated_at > processed_at and is classified as edited_after_processing, so the dry run and apply can exclude the entire remediation cohort. Use a revision/commit fence or otherwise distinguish later user mutations from the timestamp written by the original consolidation commit.
Useful? React with 👍 / 👎.
| route = promotion.get("route") | ||
| rationale = str(promotion.get("rationale") or "") | ||
| if route != "review": | ||
| if route != "archive" or RETRY_EXHAUSTED_RATIONALE_MARKER not in rationale: | ||
| return "route_not_incident" |
There was a problem hiding this comment.
Require the failure rationale for review routes
A successful consolidation is also allowed to choose route="review" for genuinely uncertain memories, but this branch accepts every such row without checking the retry-exhausted rationale. The default window even begins before the change that removed the planner lane, so healthy review decisions within the window can enter the cohort; after the timestamp exclusion is corrected, --apply would make those intentionally archived items default-visible. Require the incident rationale or another failure-specific audit field for review routes as well.
Useful? React with 👍 / 👎.
| for item in scan.matched: | ||
| if max_writes is not None and report.writes_committed + report.writes_idempotent >= max_writes: | ||
| report.writes_stopped_early = True | ||
| break | ||
| report.writes_attempted += 1 |
There was a problem hiding this comment.
Count failed attempts against the write budget
When an apply attempt fails, writes_committed + writes_idempotent does not increase, so --max-writes places no bound on subsequent transaction attempts. In particular, production permits an unscoped fleet run when --max-writes 1; if candidates repeatedly fail because of stale revisions, missing evidence, or another apply error, the tool can attempt every matched row instead of stopping after one. Enforce the safety budget against writes_attempted (before incrementing it), regardless of each attempt's outcome.
Useful? React with 👍 / 👎.
| result = apply_long_term_patch_firestore( | ||
| uid=item.uid, | ||
| operation_id=operation.operation_id, | ||
| patch_payload=patch_payload, | ||
| proposed_operation=operation, | ||
| db_client=db_client, |
There was a problem hiding this comment.
Enable the canonical intake gate for documented writes
In a clean operator shell following the module's documented prod-operator command, no code loads a backend environment or sets MEMORY_ENABLED=on. This call therefore reaches require_canonical_intake_enabled(), whose unset default is off, and every restore or revert fails with canonical memory intake is globally paused. Make the required intake setting an explicit, validated write-mode prerequisite (without silently bypassing an intentional pause), and include it in the operator invocation.
Useful? React with 👍 / 👎.
| progress_handle = progress_file.open("a", encoding="utf-8") if progress_file is not None else None | ||
| user_match_counts: List[int] = [] | ||
| try: | ||
| for user_id in _iter_user_ids( | ||
| db_client=db_client, uid=uid, users_from=users_from, page_size=page_size, ledger=ledger |
There was a problem hiding this comment.
Resume after the last completed user
--progress-file is opened only for append and is never read, so restarting a truncated run begins again at the first user. With a fixed --max-reads budget, the rerun can repeatedly spend that budget rescanning the same already-processed prefix and never reach users beyond the previous cutoff, despite the option being advertised for resume. Persist and consume a user/keyset checkpoint, or remove the resume claim and require an explicitly reduced --users-from cohort.
Useful? React with 👍 / 👎.
| except Exception as exc: # noqa: BLE001 - one row never aborts the run | ||
| report.writes_failed += 1 | ||
| report.errors.append(sanitize(str(exc))[:300]) |
There was a problem hiding this comment.
Keep validation payloads out of the JSON report
If an authoritative item or evidence document becomes malformed between scanning and applying, apply_long_term_patch_firestore can raise a Pydantic validation error whose string includes input_value, including memory content. Passing that string through sanitize() only masks token-like values and emails, so ordinary prose can be stored in report.errors and printed to stdout, violating the tool's no-memory-text output guarantee. Special-case validation errors with sanitize_validation_error() or report only a bounded exception type/error code.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
7 issues found across 4 files
Confidence score: 2/5
- In
restore_stale_planner_archives.py, every valid--applyor--revertrun crashes becauseosis not imported. Add the import so the write modes can reach their safety checks. - The selector in
restore_stale_planner_archives.pycan restore unrelated manual-review outcomes, not just retry-exhausted rows. Require the retry-exhausted rationale for review rows too. - A read-budget stop during user-ID pagination in
restore_stale_planner_archives.pyescapes as a traceback instead of returning the promised truncated report and exit code 1. CatchReadBudgetExceededwhile advancing the iterator. - The apply and revert tests in
test_restore_stale_planner_archives.pybypass the CLI safety gates, so those protections are not verified. Addmain-level tests for the marker, credentials and tier, write budget, and production scope.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/scripts/restore_stale_planner_archives.py">
<violation number="1" location="backend/scripts/restore_stale_planner_archives.py:266">
P1: The selector restores every `route="review"` archive in the window, regardless of rationale, so unrelated manual-review outcomes can be resurrected. Require the retry-exhausted rationale for review rows too.</violation>
<violation number="2" location="backend/scripts/restore_stale_planner_archives.py:593">
P2: A read-budget stop during user-ID pagination escapes the loop and produces a traceback rather than the truncated report and exit code 1 promised by the tool. Catch `ReadBudgetExceeded` around iterator advancement (or have `_iter_user_ids` communicate exhaustion) and mark the report truncated.</violation>
<violation number="3" location="backend/scripts/restore_stale_planner_archives.py:713">
P2: Malformed `--from-iso` or `--to-iso` values terminate with a traceback or status 1 instead of the documented usage status 2. Catch the parser exceptions at the CLI boundary and return 2 with the validation message.</violation>
<violation number="4" location="backend/scripts/restore_stale_planner_archives.py:726">
P1: Every valid `--apply` or `--revert` invocation crashes with `NameError: os is not defined` while checking the credential gates. Add the missing `os` import before using the write modes.</violation>
</file>
<file name="backend/tests/unit/test_restore_stale_planner_archives.py">
<violation number="1" location="backend/tests/unit/test_restore_stale_planner_archives.py:39">
P2: The fixture snapshots `touched` after installation, so teardown preserves the stubs in `sys.modules` rather than restoring the prior state. Snapshot all touched names before installing them, or use the repository's fresh-module isolation helper.</violation>
<violation number="2" location="backend/tests/unit/test_restore_stale_planner_archives.py:360">
P2: The apply and revert tests bypass the CLI safety gates entirely. Add tests invoking `main` that reject a missing or incorrect marker, missing credentials/tier, invalid write budget, and unscoped production writes.</violation>
<violation number="3" location="backend/tests/unit/test_restore_stale_planner_archives.py:457">
P2: This destructive-gate test becomes time-dependent after the fixed `NOW` timestamp passes the six-hour staleness threshold. Use a timestamp relative to the actual current time, or inject the clock used by the gate check.</violation>
</file>
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
| print(f"--{mode} requires a positive --max-writes budget", file=sys.stderr) | ||
| return 2 | ||
| required_tier = PROJECTS[args.project] | ||
| if os.environ.get("GCP_AGENT_TIER") != required_tier or not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"): |
There was a problem hiding this comment.
P1: Every valid --apply or --revert invocation crashes with NameError: os is not defined while checking the credential gates. Add the missing os import before using the write modes.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/restore_stale_planner_archives.py, line 726:
<comment>Every valid `--apply` or `--revert` invocation crashes with `NameError: os is not defined` while checking the credential gates. Add the missing `os` import before using the write modes.</comment>
<file context>
@@ -0,0 +1,760 @@
+ print(f"--{mode} requires a positive --max-writes budget", file=sys.stderr)
+ return 2
+ required_tier = PROJECTS[args.project]
+ if os.environ.get("GCP_AGENT_TIER") != required_tier or not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
+ print("Select the matching GCP operator tier before writing.", file=sys.stderr)
+ return 2
</file context>
| if route != "review": | ||
| if route != "archive" or RETRY_EXHAUSTED_RATIONALE_MARKER not in rationale: | ||
| return "route_not_incident" |
There was a problem hiding this comment.
P1: The selector restores every route="review" archive in the window, regardless of rationale, so unrelated manual-review outcomes can be resurrected. Require the retry-exhausted rationale for review rows too.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/restore_stale_planner_archives.py, line 266:
<comment>The selector restores every `route="review"` archive in the window, regardless of rationale, so unrelated manual-review outcomes can be resurrected. Require the retry-exhausted rationale for review rows too.</comment>
<file context>
@@ -0,0 +1,760 @@
+ return "processed_by_mismatch"
+ route = promotion.get("route")
+ rationale = str(promotion.get("rationale") or "")
+ if route != "review":
+ if route != "archive" or RETRY_EXHAUSTED_RATIONALE_MARKER not in rationale:
+ return "route_not_incident"
</file context>
| if route != "review": | |
| if route != "archive" or RETRY_EXHAUSTED_RATIONALE_MARKER not in rationale: | |
| return "route_not_incident" | |
| if route not in {"review", "archive"} or RETRY_EXHAUSTED_RATIONALE_MARKER not in rationale: | |
| return "route_not_incident" |
| def main(argv: Optional[List[str]] = None) -> int: | ||
| args = _build_parser().parse_args(argv) | ||
| mode = "apply" if args.apply else "revert" if args.revert else "dry-run" | ||
| window_from = _coerce_utc(args.from_iso, "--from-iso") |
There was a problem hiding this comment.
P2: Malformed --from-iso or --to-iso values terminate with a traceback or status 1 instead of the documented usage status 2. Catch the parser exceptions at the CLI boundary and return 2 with the validation message.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/restore_stale_planner_archives.py, line 713:
<comment>Malformed `--from-iso` or `--to-iso` values terminate with a traceback or status 1 instead of the documented usage status 2. Catch the parser exceptions at the CLI boundary and return 2 with the validation message.</comment>
<file context>
@@ -0,0 +1,760 @@
+def main(argv: Optional[List[str]] = None) -> int:
+ args = _build_parser().parse_args(argv)
+ mode = "apply" if args.apply else "revert" if args.revert else "dry-run"
+ window_from = _coerce_utc(args.from_iso, "--from-iso")
+ window_to = _coerce_utc(args.to_iso, "--to-iso")
+ if window_from >= window_to:
</file context>
| progress_handle = progress_file.open("a", encoding="utf-8") if progress_file is not None else None | ||
| user_match_counts: List[int] = [] | ||
| try: | ||
| for user_id in _iter_user_ids( |
There was a problem hiding this comment.
P2: A read-budget stop during user-ID pagination escapes the loop and produces a traceback rather than the truncated report and exit code 1 promised by the tool. Catch ReadBudgetExceeded around iterator advancement (or have _iter_user_ids communicate exhaustion) and mark the report truncated.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/scripts/restore_stale_planner_archives.py, line 593:
<comment>A read-budget stop during user-ID pagination escapes the loop and produces a traceback rather than the truncated report and exit code 1 promised by the tool. Catch `ReadBudgetExceeded` around iterator advancement (or have `_iter_user_ids` communicate exhaustion) and mark the report truncated.</comment>
<file context>
@@ -0,0 +1,760 @@
+ progress_handle = progress_file.open("a", encoding="utf-8") if progress_file is not None else None
+ user_match_counts: List[int] = []
+ try:
+ for user_id in _iter_user_ids(
+ db_client=db_client, uid=uid, users_from=users_from, page_size=page_size, ledger=ledger
+ ):
</file context>
| "kind": "explicit_memory_deletion", | ||
| "token": "tok", | ||
| "state": "running", | ||
| "started_at": NOW - timedelta(minutes=5), |
There was a problem hiding this comment.
P2: This destructive-gate test becomes time-dependent after the fixed NOW timestamp passes the six-hour staleness threshold. Use a timestamp relative to the actual current time, or inject the clock used by the gate check.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_restore_stale_planner_archives.py, line 457:
<comment>This destructive-gate test becomes time-dependent after the fixed `NOW` timestamp passes the six-hour staleness threshold. Use a timestamp relative to the actual current time, or inject the clock used by the gate check.</comment>
<file context>
@@ -0,0 +1,592 @@
+ "kind": "explicit_memory_deletion",
+ "token": "tok",
+ "state": "running",
+ "started_at": NOW - timedelta(minutes=5),
+ "finished_at": None,
+ }
</file context>
| "started_at": NOW - timedelta(minutes=5), | |
| "started_at": datetime.now(timezone.utc) - timedelta(minutes=5), |
| def _restore_tool_import_isolation(): | ||
| saved = snapshot_sys_modules(CONSOLIDATION_APPLY_STUB_MODULE_NAMES) | ||
| touched = install_consolidation_apply_stubs() | ||
| saved.update(snapshot_sys_modules(touched)) |
There was a problem hiding this comment.
P2: The fixture snapshots touched after installation, so teardown preserves the stubs in sys.modules rather than restoring the prior state. Snapshot all touched names before installing them, or use the repository's fresh-module isolation helper.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_restore_stale_planner_archives.py, line 39:
<comment>The fixture snapshots `touched` after installation, so teardown preserves the stubs in `sys.modules` rather than restoring the prior state. Snapshot all touched names before installing them, or use the repository's fresh-module isolation helper.</comment>
<file context>
@@ -0,0 +1,592 @@
+def _restore_tool_import_isolation():
+ saved = snapshot_sys_modules(CONSOLIDATION_APPLY_STUB_MODULE_NAMES)
+ touched = install_consolidation_apply_stubs()
+ saved.update(snapshot_sys_modules(touched))
+ ensure_utils_memory_packages_importable()
+ for stale_module in ("database.memory_apply_store", "utils.memory.memory_system"):
</file context>
| return _ScanDb(docs) | ||
|
|
||
|
|
||
| def _run(db: _ScanDb, mode: str = "dry-run", **overrides): |
There was a problem hiding this comment.
P2: The apply and revert tests bypass the CLI safety gates entirely. Add tests invoking main that reject a missing or incorrect marker, missing credentials/tier, invalid write budget, and unscoped production writes.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_restore_stale_planner_archives.py, line 360:
<comment>The apply and revert tests bypass the CLI safety gates entirely. Add tests invoking `main` that reject a missing or incorrect marker, missing credentials/tier, invalid write budget, and unscoped production writes.</comment>
<file context>
@@ -0,0 +1,592 @@
+ return _ScanDb(docs)
+
+
+def _run(db: _ScanDb, mode: str = "dry-run", **overrides):
+ tool = restore_tool
+ kwargs: Dict[str, Any] = dict(
</file context>
|
Folded into #24602 (the consolidation of this batch onto the age-gate survivor branch |
|
Hey @Git-on-my-level 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
Summary
This is an operator tool to restore memories that a stale dev job archived in prod. Only the read-only dry run is intended before David's GO.
The dev Cloud Scheduler job
memory-maintenance-hourlyranmemory-maintenance-job:fb9bba4(2026-10-06, predating #21480) against the shared prod customer project. After dbb7387 removed the gatewaymemory_conflictlane (~10-19), every planner batch failed, and_escalate_to_terminal_reviewsettled items asroute=review→tier=archive, hidden from default reads. The job was paused ~18:25Z 2026-10-22, and its in-flight execution was cancelled. Plan:dream-ops/remediation/PLAN-restore-stale-planner-archives.md.backend/scripts/restore_stale_planner_archives.py:--dry-run, read-only. It prints one JSON object of counts only: rows per day, a per-user bucket histogram, exclusions by reason, and the reads used. No uids, memory ids or text.processed_by=canonical_batched_consolidation, plusroute=review, orroute=archivewith the planner's retry-exhausted rationale (recovered from the pre-retirement planner), plustier=archive,status=active, andprocessed_atin a CLI window. It excludes rows edited after processing, rows with a user review, already-marked rows, deleted users, legal holds and live destructive gates (all fail closed).--applyrequires the exact--marker remediation=stale-planner-2026-10-22, a--max-writesbudget, a matchingGCP_AGENT_TIERplus credentials, and--uidor--users-fromfor prod. It restorestarget_tier=short_termthroughapply_long_term_patch_firestore, the same fenced ledger path as the legacy-backfill tier transition, with revision/content-hash/generation fences, the destructive-gate recheck,memory_commitsjournaling and projection/vector outbox events. It also writes an audit marker.--revertre-archives only marked rows.--uidgives a single-account canary.firestore.indexes.json). These indexes must be built in prod (index reconcile) before even the dry run can run.Verification
test_restore_stale_planner_archives.py: dry-run read-only, selector match/exclude, destructive-gate exclusion, idempotent ledger apply plus marker, write and read budget stops, revert-only-marked, the apply→revert round trip, and no user identification in any output.make preflight: 34 checks.backend/test.shwithnice -n 19 taskpolicy -b.Nothing has been run against any real project.
Line count
Line-Count-Exception: backend/database/firestore_index_registry.py | 2232 -> 2277 | declarative index registry entries for the tool's two new query drivers; a registry grows by design
Product invariants affected
none
Failure class
Failure-Class: none
🤖 Generated with Claude Code