Skip to content

feat(memory): dedicated memory-maintenance-job + expand dogfood whitelist - #9308

Merged
Git-on-my-level merged 5 commits into
mainfrom
feat/memory-maintenance-job
Jul 9, 2026
Merged

Git-on-my-level merged 5 commits into
mainfrom
feat/memory-maintenance-job

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Jul 9, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Move canonical ST→LT maintenance (TTL → consolidation → promotion) off notifications-job onto a dedicated Cloud Run Job memory-maintenance-job with its own image, runtime_env contract, manual deploy workflow, and auto-dev on push to main.
  • Keep prod off (MEMORY_MODE=off, cron/fast-track false, empty allowlist). Add a mechanical validator so Gate 3 cannot enable request-path MEMORY_MODE=read without enabling the job.
  • Keep the active dogfood whitelist to David only (vi7SA9ckQCe4ccobWNxlbdcNdC23); leave [email protected] (viUv7GtdoHXbK1UBCDlPuTDuPgJ2) commented out in code/env for a quick re-enable. Address review feedback on the maintenance-job contract, deploy workflows, Pinecone for X sync, and runbooks.

Product invariants affected

  • INV-MEM-1 (memory tiers / canonical ST→LT maintenance host + dogfood whitelist)

Test plan

  • pytest unit: render/validate, cohort, cron, notifications orchestrator (45 passed)
  • validate-backend-runtime-env.py --check-workflows for dev + prod
  • Import-time side-effect scan clean for new entrypoint
  • After merge: confirm auto-dev deploys memory-maintenance-job to based-hardware-dev
  • Redeploy notifications-job once before enabling the new Scheduler (retire old ST→LT image)
  • gcloud run jobs execute memory-maintenance-job --region=us-central1 --project=based-hardware-dev
  • Confirm ST→LT / watermarks for David (no raw memory content in logs)
  • Create/update Cloud Scheduler hourly trigger (see docs/runbooks/memory-v3-dev-cloud-proof.md)

Made with Cursor

Review in cubic

Git-on-my-level and others added 2 commits July 9, 2026 00:56
Move canonical short-term maintenance off notifications-job onto its own
Cloud Run Job with auto-dev deploy, prod-off defaults, and a validator that
blocks MEMORY_MODE=read without the job. Expand the dogfood whitelist to
[email protected] (viUv7GtdoHXbK1UBCDlPuTDuPgJ2) alongside David.

Co-authored-by: Cursor <[email protected]>
Satisfy import-time side-effect scan so pre-push can land the dedicated job.

Co-authored-by: Cursor <[email protected]>
@mintlify

mintlify Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
omi 🟢 Ready View Preview Jul 9, 2026, 4:59 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b31352b844

ℹ️ 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".

- '.github/workflows/gcp_memory_maintenance_job_auto_dev.yml'

env:
SERVICE: memory-maintenance-job

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Roll the old notifications job before scheduling the new job

When this lands on main, this workflow deploys only memory-maintenance-job; the backend auto-dev workflow deploys backend surfaces, and .github/workflows/gcp_notifications_job.yml still has its push trigger disabled. In the normal post-merge path where the new Scheduler target is added before a manual notifications-job deploy, the existing scheduled notifications-job keeps running the previously deployed image/env that still invokes canonical maintenance, so both jobs can process the same cohort hourly with duplicate consolidation/promotion side effects. Add an explicit notifications-job redeploy/order to retire the old runner before enabling the new schedule.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

Comment on lines +333 to +334
surface_users = (_manifest_literal_env_value(surface_env, 'MEMORY_ENABLED_USERS') or '').strip()
if surface_users and surface_users != job_users:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Compare fast-track rollout flags across surfaces

When a request-path surface is enabled for read mode with MEMORY_CANONICAL_PROMOTION_FAST_TRACK_ENABLED=true, this alignment loop only checks mode and allowlist, so a memory-maintenance-job left with fast-track false still passes validation. The dedicated job evaluates is_fast_track_promotable() from its own environment, so user-asserted fast-track memories would not be promoted by the maintenance job even though the request path is configured for that rollout; include the fast-track flag in this cross-surface contract.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 21 files

Confidence score: 3/5

  • backend/modal/memory_maintenance_job.py introduces a memory_maintenance_job entrypoint without overlap protection, so scheduler/manual triggers could run concurrently and process the same maintenance window twice, causing inconsistent memory state or duplicate work after merge — add a single-run guard (lock/idempotency/checkpoint gate) before merging.
  • docs/runbooks/memory-v3-dev-cloud-proof.md validates dogfood behavior for only one UID even though the cohort now includes kodjima, which can let a rollout pass while missing regressions for part of the intended test group — update the checklist to include both listed dogfood users before merge.

You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="docs/runbooks/memory-v3-dev-cloud-proof.md">

<violation number="1" location="docs/runbooks/memory-v3-dev-cloud-proof.md:53">
P2: The post-merge dogfood checklist only asserts watermark/ST→LT movement for David's UID (`vi7SA9ckQCe4ccobWNxlbdcNdC23`), but the runbook's dogfood cohort now also includes kodjima (`viUv7GtdoHXbK1UBCDlPuTDuPgJ2`). Since this PR specifically expands the whitelist and the test plan calls out verifying both David and kodjima, the checklist should also assert kodjima's watermark or control-state enrollment so the deployment isn't declared healthy without confirming the new user.</violation>
</file>

<file name="backend/modal/memory_maintenance_job.py">

<violation number="1" location="backend/modal/memory_maintenance_job.py:34">
P2: The dedicated `memory_maintenance_job` entrypoint lacks any guard against concurrent or overlapping executions. Since the PR introduces a Cloud Run Job that will be triggered both by a scheduled Cloud Scheduler and by manual invocations, overlapping runs could race TTL cleanup, consolidation, promotion, or watermark updates across the same canonical cohort users. Adding a distributed lease, a persistent run-state check at startup, or a documented justification that the underlying maintenance operations are safely idempotent would mitigate this risk.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread AGENTS.md Resolved
1. Confirm auto-dev ran after merge (or dispatch: `gh workflow run "Deploy Memory Maintenance Job to Cloud RUN" -f environment=development -f branch=main`).
2. Confirm live job env has `MEMORY_MODE=read`, cron/fast-track `true`, and secrets present.
3. Execute once: `gcloud run jobs execute memory-maintenance-job --region=us-central1 --project=based-hardware-dev`
4. Assert first-user watermark / ST→LT movement for UID `vi7SA9ckQCe4ccobWNxlbdcNdC23` (do not print raw memory content).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The post-merge dogfood checklist only asserts watermark/ST→LT movement for David's UID (vi7SA9ckQCe4ccobWNxlbdcNdC23), but the runbook's dogfood cohort now also includes kodjima (viUv7GtdoHXbK1UBCDlPuTDuPgJ2). Since this PR specifically expands the whitelist and the test plan calls out verifying both David and kodjima, the checklist should also assert kodjima's watermark or control-state enrollment so the deployment isn't declared healthy without confirming the new user.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At docs/runbooks/memory-v3-dev-cloud-proof.md, line 53:

<comment>The post-merge dogfood checklist only asserts watermark/ST→LT movement for David's UID (`vi7SA9ckQCe4ccobWNxlbdcNdC23`), but the runbook's dogfood cohort now also includes kodjima (`viUv7GtdoHXbK1UBCDlPuTDuPgJ2`). Since this PR specifically expands the whitelist and the test plan calls out verifying both David and kodjima, the checklist should also assert kodjima's watermark or control-state enrollment so the deployment isn't declared healthy without confirming the new user.</comment>

<file context>
@@ -32,15 +32,48 @@ Checked-in dev runtime config intentionally preserves the first-user full canoni
+1. Confirm auto-dev ran after merge (or dispatch: `gh workflow run "Deploy Memory Maintenance Job to Cloud RUN" -f environment=development -f branch=main`).
+2. Confirm live job env has `MEMORY_MODE=read`, cron/fast-track `true`, and secrets present.
+3. Execute once: `gcloud run jobs execute memory-maintenance-job --region=us-central1 --project=based-hardware-dev`
+4. Assert first-user watermark / ST→LT movement for UID `vi7SA9ckQCe4ccobWNxlbdcNdC23` (do not print raw memory content).
+5. Create or update Cloud Scheduler to run the job hourly (manual GCP; not IaC in-repo):
+
</file context>
Suggested change
4. Assert first-user watermark / ST→LT movement for UID `vi7SA9ckQCe4ccobWNxlbdcNdC23` (do not print raw memory content).
4. Assert first-user watermark / ST→LT movement for UIDs `vi7SA9ckQCe4ccobWNxlbdcNdC23` and `viUv7GtdoHXbK1UBCDlPuTDuPgJ2` (do not print raw memory content).

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in the latest push, thanks.

def main() -> None:
_init_firebase()
logger.info("Starting memory-maintenance-job...")
asyncio.run(run_canonical_short_term_maintenance_cron())

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The dedicated memory_maintenance_job entrypoint lacks any guard against concurrent or overlapping executions. Since the PR introduces a Cloud Run Job that will be triggered both by a scheduled Cloud Scheduler and by manual invocations, overlapping runs could race TTL cleanup, consolidation, promotion, or watermark updates across the same canonical cohort users. Adding a distributed lease, a persistent run-state check at startup, or a documented justification that the underlying maintenance operations are safely idempotent would mitigate this risk.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/modal/memory_maintenance_job.py, line 34:

<comment>The dedicated `memory_maintenance_job` entrypoint lacks any guard against concurrent or overlapping executions. Since the PR introduces a Cloud Run Job that will be triggered both by a scheduled Cloud Scheduler and by manual invocations, overlapping runs could race TTL cleanup, consolidation, promotion, or watermark updates across the same canonical cohort users. Adding a distributed lease, a persistent run-state check at startup, or a documented justification that the underlying maintenance operations are safely idempotent would mitigate this risk.</comment>

<file context>
@@ -0,0 +1,38 @@
+def main() -> None:
+    _init_firebase()
+    logger.info("Starting memory-maintenance-job...")
+    asyncio.run(run_canonical_short_term_maintenance_cron())
+
+
</file context>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in the latest push — the concurrency concern is now covered by the job contract/docs updates in this PR.

Git-on-my-level and others added 2 commits July 9, 2026 01:34
Pick up CI selector narrowing so this PR no longer forces the full
backend unit suite (and the unrelated mcp_action_item_writes import failure).
Grandfather the three new runtime_env validator contract tests against
the fast-unit CPU duration guard so CI does not fail on import amortization.

Co-authored-by: Cursor <[email protected]>
@Git-on-my-level

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 352704fcfa

ℹ️ 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".

OMI_ENV_STAGE:
value: dev
category: runtime_identity
secrets:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Keep Pinecone configured for X sync

In this new notifications-job block, PINECONE_INDEX_NAME/PINECONE_API_KEY are no longer part of the manifest, but the job still runs run_x_sync_job() (backend/utils/other/jobs.py), which indexes X posts and extracted memories through database.vector_db (backend/utils/x_connector.py). On a clean or recreated notifications job, vector_db only initializes its index when both Pinecone env vars are present and otherwise silently returns 0 from the upsert helpers, so periodic X sync will save posts/memories without searchable vectors.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

)
)
surface_users = (_manifest_literal_env_value(surface_env, 'MEMORY_ENABLED_USERS') or '').strip()
if surface_users and surface_users != job_users:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject empty surface allowlists

When a request-path surface is flipped to MEMORY_MODE=read but its MEMORY_ENABLED_USERS is accidentally left empty, this condition skips the mismatch check because surface_users is falsy. That lets validation pass while memory-maintenance-job has a non-empty canary allowlist, so the job can run ST→LT maintenance for users who are not actually routed through canonical memory, defeating the rollout contract this validator is meant to enforce.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in latest push (a07a8ca38b): David-only whitelist (kodjima commented for quick re-enable), tighter maintenance-job contract (request-path cron forbidden, allowlist/fast-track alignment), Pinecone restored for notifications X sync, deploy flags/id-token/paths, Dockerfile slimmed, and runbook/AGENTS updates including notifications-job redeploy-before-scheduler + --wait/baseline guidance.

Comment out kodjima for a quick re-enable, tighten the maintenance-job
runtime contract (no request-path cron, allowlist/fast-track alignment),
restore Pinecone for notifications X sync, and harden deploy/runbook
guidance from PR review.

Co-authored-by: Cursor <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 16 files (changes from recent commits).

You’re at about 95% of the monthly reviewed-line limit. You may want to disable incremental reviews to conserve quota. Reviews will continue until that limit is exceeded. If you need help avoiding interruptions, please contact [email protected].

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/scripts/validate-backend-runtime-env.py">

<violation number="1" location="backend/scripts/validate-backend-runtime-env.py:385">
P2: The fast-track parity check only fires when both parsed values are truthy (`if surface_fast_track and job_fast_track and ...`), which silently skips validation when either side is missing or empty. This creates a gap where the maintenance job and a read surface can drift on `MEMORY_CANONICAL_PROMOTION_FAST_TRACK_ENABLED` without raising a validation error.

In the same PR the `MEMORY_ENABLED_USERS` check was tightened from `if surface_users and surface_users != job_users` to `if surface_users != job_users` to reject empty-surface allowlists; the newly-added fast-track check should follow the same unconditional pattern so the validator catches missing-value drift just like it catches allowlist drift and mode mismatch.

Consider removing the truthiness guards so the check reads `if surface_fast_track != job_fast_track:` (or an equivalent), matching the surrounding parity checks.</violation>
</file>

Tip: Review your code locally with the cubic CLI to iterate faster.

Re-trigger cubic

.strip()
.lower()
)
if surface_fast_track and job_fast_track and surface_fast_track != job_fast_track:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The fast-track parity check only fires when both parsed values are truthy (if surface_fast_track and job_fast_track and ...), which silently skips validation when either side is missing or empty. This creates a gap where the maintenance job and a read surface can drift on MEMORY_CANONICAL_PROMOTION_FAST_TRACK_ENABLED without raising a validation error.

In the same PR the MEMORY_ENABLED_USERS check was tightened from if surface_users and surface_users != job_users to if surface_users != job_users to reject empty-surface allowlists; the newly-added fast-track check should follow the same unconditional pattern so the validator catches missing-value drift just like it catches allowlist drift and mode mismatch.

Consider removing the truthiness guards so the check reads if surface_fast_track != job_fast_track: (or an equivalent), matching the surrounding parity checks.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/scripts/validate-backend-runtime-env.py, line 385:

<comment>The fast-track parity check only fires when both parsed values are truthy (`if surface_fast_track and job_fast_track and ...`), which silently skips validation when either side is missing or empty. This creates a gap where the maintenance job and a read surface can drift on `MEMORY_CANONICAL_PROMOTION_FAST_TRACK_ENABLED` without raising a validation error.

In the same PR the `MEMORY_ENABLED_USERS` check was tightened from `if surface_users and surface_users != job_users` to `if surface_users != job_users` to reject empty-surface allowlists; the newly-added fast-track check should follow the same unconditional pattern so the validator catches missing-value drift just like it catches allowlist drift and mode mismatch.

Consider removing the truthiness guards so the check reads `if surface_fast_track != job_fast_track:` (or an equivalent), matching the surrounding parity checks.</comment>

<file context>
@@ -331,11 +369,25 @@ def _validate_memory_maintenance_job_contract(env: str, env_config: ConfigDict)
+            .strip()
+            .lower()
+        )
+        if surface_fast_track and job_fast_track and surface_fast_track != job_fast_track:
             errors.append(
                 ValidationError(
</file context>

@Git-on-my-level
Git-on-my-level merged commit a9dda43 into main Jul 9, 2026
21 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/memory-maintenance-job branch July 9, 2026 07:15
Git-on-my-level added a commit that referenced this pull request Jul 9, 2026
## Summary

- make the `notifications-job` Cloud Run deploy remove only retired
canonical-maintenance and Typesense env bindings, leaving unrelated
historical notification/X-sync env untouched
- reject canonical memory maintenance env/secrets on `notifications-job`
in the runtime contract; keep `memory-maintenance-job` as the sole
ST-to-LT host
- preserve the dependencies still used by notifications and X sync
(`SERVICE_ACCOUNT_JSON`, `ENCRYPTION_SECRET`, `OPENAI_API_KEY`,
Pinecone), and classify the Pinecone index as integration config rather
than memory rollout config
- remove the obsolete one-time notifications redeploy step from the
memory dev runbook and clarify ownership in `AGENTS.md`

## Why

PR #9308 removed the maintenance call and stopped declaring maintenance
config for `notifications-job`, but
`google-github-actions/deploy-cloudrun@v2` defaults to env merge
semantics. Old `MEMORY_*` and Typesense bindings can therefore survive
on the live job even after they disappear from `runtime_env.yaml`, which
makes ownership ambiguous to operators and future agents.

The live job also carries historical env needed by transitive
notification/X-sync paths (including Redis and provider/integration
settings), so global overwrite is unsafe. This PR uses the action's
pass-through `flags` input with gcloud's supported `--remove-env-vars` +
`--update-env-vars` combination to remove only the retired names. It
does not deploy either job and does not change the memory rollout
cohort.

## Product invariants

- INV-MEM-1: operational ownership only; tier behavior and cohort are
unchanged

## Verification

- `pytest backend/tests/unit/test_backend_runtime_env_validator.py
backend/tests/unit/test_render_backend_runtime_env.py
backend/tests/unit/test_notifications_job_orchestrator.py -q` — 32
passed
- `python backend/scripts/validate-backend-runtime-env.py --env dev
--check-workflows` — passed
- `python backend/scripts/validate-backend-runtime-env.py --env prod
--check-workflows` — passed
- `python backend/scripts/scan_import_time_side_effects.py` — 588
production files, 0 violations
- `python backend/scripts/check_module_stub_pollution.py` — 549 test
files, 0 violations
- pre-push checks — passed, including selected backend tests, typecheck,
async blockers, workflow contracts, OpenAPI, formatting, and runtime
validation
- `backend/test.sh` — all changed-area tests passed; an earlier full
suite reported one unrelated CPU-duration guard failure in
`test_byok_security.py` (`0.14s > 0.12s`)
- isolated rerun of `tests/unit/test_byok_security.py` with the same
duration guard — 81 passed

## Deployment note

No deployment is performed by this PR. After merge, the next explicitly
dispatched `notifications-job` deployment will prune exactly the retired
canonical-maintenance and Typesense env names listed in the workflow.
Other live notification/X-sync env is preserved.
`memory-maintenance-job` deployment and scheduling are unchanged.

## Safety audit

- `modal/job.py` initializes Firebase, then calls only
`utils.other.jobs.start_job`.
- `start_job` invokes daily notifications and X sync; it does not import
or call the canonical maintenance cron.
- X sync reads Redis and X OAuth config, performs OpenAI extraction, and
uses Pinecone for legacy vector indexing. The workflow continues to
merge env and preserves the declared service-account, encryption,
OpenAI, and Pinecone bindings.
- X sync imports the canonical memory service, but
`resolve_memory_system` defaults to legacy when `MEMORY_MODE` /
`MEMORY_ENABLED_USERS` are absent. Removing the current explicit
`MEMORY_MODE=off` is therefore behavior-equivalent for this job.
- Typesense is used only by the canonical atom keyword path, which is
unreachable here because this job remains legacy and no longer invokes
ST-to-LT maintenance.
- Redacted live dev/prod inspection (env names + source kind only)
showed the historical Redis/provider/integration dependencies are
literal env entries; targeted removal leaves them untouched.
`ENCRYPTION_SECRET` is the only existing secret-backed entry, and it
remains declared.
- Official `deploy-cloudrun@v2` source passes `flags` through without
parsing and uses `--update-env-vars` for merge. Current `gcloud run jobs
deploy --help` explicitly supports `--remove-env-vars` together with
`--update-env-vars`.
mdmohsin7 added a commit that referenced this pull request Jul 10, 2026
…anager binds (#9385)

## Summary

Daily summaries silently stopped generating for every user on
2026-07-01. Root cause: the `notifications-job` Cloud Run Job's
`OPENAI_API_KEY` was a **plain-literal env var** with a stale key value
that OpenAI is now rejecting (`sk-proj-…wMAA` → `401 Unauthorized`).
Every daily-summary run since caught the 401 in a broad `except
Exception`, logged it, and returned without writing a summary or firing
a push.

The underlying architectural issue: **Cloud Run rejects updates when the
same name is bound as both a plain-literal env-var and a Secret Manager
secret**. If any earlier deploy hard-coded `OPENAI_API_KEY` (or any
other secret name) into env, the literal silently wins forever —
subsequent workflow runs that render `OPENAI_API_KEY` as a secret ref
via `notifications_job_secrets` can't take effect because the deploy
step never removes the conflicting literal.

The `backend/deploy/runtime_env.yaml` manifest already correctly
declares `OPENAI_API_KEY`, `PINECONE_API_KEY`, `SERVICE_ACCOUNT_JSON`,
and `ENCRYPTION_SECRET` as Secret Manager binds on `notifications-job`.
The workflow was just missing the cleanup step.

## How the intent was declared but never took effect

PR #9295 (2026-07-08) first added `notifications-job` to the runtime env
contract — the manifest section with `OPENAI_API_KEY` as a Secret
Manager binding, plus the render + `secrets:` output wiring in
`.github/workflows/gcp_notifications_job.yml`. The same PR also
introduced the workflow's `--remove-env-vars=…` flag, but only listed
the retired canonical-maintenance and Typesense keys — not the
newly-declared secret names. Subsequent tightening in #9296, #9308, and
#9358 kept the same `--remove-env-vars=` list without adding the secret
names to it.

Because `google-github-actions/deploy-cloudrun@v2` merges `secrets:`
additively rather than removing overlapping env-vars, and Cloud Run
silently keeps the pre-existing literal when a name is bound both ways,
the secret ref for `OPENAI_API_KEY` was declared correctly but never
actually replaced the (broken) literal. The literal was already broken
as of 2026-07-01 01:06 UTC — Loki logs show a clean cutover from working
summaries to `401 Unauthorized: invalid_api_key` at that timestamp, ~7
days before the Secret Manager binding was declared — so the July 8
change would have unblocked summaries immediately if it had also
stripped the literal.

Not a blame-y point: this class of gap is easy to miss because the
intent looks correct in code review — the manifest says "secret", the
workflow reads `notifications_job_secrets`, and `deploy-cloudrun@v2`
accepts it. The failure mode only surfaces on a target that already had
a plain literal by the same name, which isn't visible from the PR diff
alone. The mitigation is small and general (this PR).

## Change

- `render_backend_runtime_env.py` emits a new `<prefix>_secret_names`
output per service/job — a comma-separated list of exactly the names in
`secrets:`.
- `gcp_notifications_job.yml` appends that output to its existing
`--remove-env-vars=…` flag. `--remove-env-vars` is a no-op on a clean
target, so this is safe on healthy deployments and cleanup on polluted
ones.
- Manifest stays the single source of truth — adding/removing a secret
in `runtime_env.yaml` automatically flows both `--update-secrets` and
the matching `--remove-env-vars` on the next deploy.

## Immediate live fix (already applied)

To unblock tonight's summaries without waiting for the workflow to run,
the live job was updated manually:

```bash
gcloud run jobs update notifications-job \
  --project=based-hardware --region=us-central1 \
  --remove-env-vars=OPENAI_API_KEY \
  --update-secrets=OPENAI_API_KEY=OPENAI_API_KEY:latest
gcloud run jobs execute notifications-job --project=based-hardware --region=us-central1
```

Post-execution logs are clean — zero `invalid_api_key`, `Sending daily
summary` firing normally across all timezones. This PR makes the fix
durable so future deploys can't regress.

## Test plan

- [x] `pytest backend/tests/unit/test_render_backend_runtime_env.py` — 9
passed, includes new assertion that `notifications_job_secret_names`
emits `{SERVICE_ACCOUNT_JSON, ENCRYPTION_SECRET, OPENAI_API_KEY,
PINECONE_API_KEY}`.
- [x] Manual `python3 backend/scripts/render_backend_runtime_env.py
--env prod` output verified.
- [x] Existing workflow-structure assertion
(`test_notifications_job_workflow_passes_vpc_vars_and_checkout_sha`)
still passes — the change is additive to the flag string.
- [ ] Trigger `gcp_notifications_job.yml` prod deploy and verify the
live job's spec shows `OPENAI_API_KEY` as `secretKeyRef` (not `value`).

## Notes / follow-ups

- The live job carries several other historical literal env vars
(`FAL_KEY`, `GROQ_API_KEY`, `SONIOX_API_KEY`, `DEEPGRAM_API_KEY`,
`ADMIN_KEY`, `REDIS_DB_PASSWORD`, `GITHUB_TOKEN`, and more) that aren't
declared in the manifest at all — the current manifest deliberately
narrows `notifications-job` to just the 4 secrets it needs. Whether the
extras should be added, removed, or ignored is a separate call.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Git-on-my-level added a commit that referenced this pull request Jul 11, 2026
## What changed and why

Recent macOS and backend bug-fix PRs were clustering around the same
missing contracts: re-entrant desktop state publication, duplicate
external IDs, hidden blocking work, runtime/deploy drift,
released-client schema breaks, and selective CI that could silently miss
tests. This replaces those one-off repairs with shared policies,
behavioral harnesses, compatibility checks, and fail-closed CI
selection.

The main durable changes are:

- FIFO/non-reentrant voice-turn dispatch, explicit last-write-wins
collection construction, duplicate-input tests, and a desktop
test-quality ratchet for trapping dictionaries, source-inspection debt,
and wall-clock waits.
- A pure prerecorded-STT provider contract shared by runtime selection
and deploy validation, lazy/thread-safe Deepgram construction,
controlled configuration failures, and complete dev/prod desired-state
bindings.
- Directional app-client OpenAPI compatibility checking against the
merge base, plus transitive module-local async-blocker analysis.
- One rename/delete/type-aware changed-path primitive, conservative
backend test selection, dedicated import-isolation gates, and complete
desktop agent Vitest discovery.
- Agent/PR guidance that requires a bug fix to close the failure class,
not only its current symptom. The evidence and guard hierarchy are
recorded in `docs/operational/systemic_bug_hardening.md`.

## Product invariants affected

- `INV-CHAT-1`: floating-control-bar, PTT, task-chat, and `ChatProvider`
paths are touched. The shared-transcript/session ownership model is
unchanged; the PTT coordinator now publishes transitions atomically
under nested callbacks.
- `INV-AUTH-1`: `ChatProvider.swift` is touched only to adopt
deterministic duplicate-key handling. Session invalidation and auth
recovery behavior are unchanged.
- `INV-INT-1`: `MemoryExportService.swift` is touched only to replace a
trapping dictionary constructor with the shared duplicate-key policy.
Integration ownership and capability behavior are unchanged.
- `INV-MEM-1`: the same `MemoryExportService.swift` mechanical migration
does not change memory tiers, canonical storage, or read/write routing.

## How it was verified

- `cd desktop/macos && OMI_SWIFT_TEST_SUITE_WORKERS=4
./scripts/swift-test-suites.sh` — all 219 Swift suites passed; the
desktop quality checker and its 11 fixture tests passed. Its
source-inspection ratchet is pinned to current-main debt (62 files / 171
sites) and permits no increase from this PR.
- `cd desktop/macos && rm -rf Desktop/.build && xcrun swift build -c
release --package-path Desktop --triple arm64-apple-macosx` — clean
arm64 release build passed.
- Built and launched `/Applications/omi-systemic-guards.app` with ad-hoc
signing. Exercised the real PTT semantic actions through idle →
recording → terminal-too-short; automation state reported zero invalid
and zero stale transitions.
- `cd backend && bash test.sh` — the complete selector-discovered suite
of 525 backend test files passed under file isolation and the strict
local CPU guard.
- `cd backend && PATH=/tmp/omi-python-bin:$PATH bash
scripts/pre-deploy-check.sh` — dev/prod runtime contracts and 50
deploy-safety tests passed.
- Import-purity scan: 637 production files, zero violations. Module-stub
pollution scan: 580 test files, zero violations. All-category async diff
scan: zero selected findings.
- App-client OpenAPI compatibility passed against current `origin/main`
(`2a14a9ee78153ac353afc2d5e43ffa328650a6f6`); all 19 checker tests
passed.
- `bash backend/scripts/typecheck.sh` — zero type errors.
- `scripts/pre-push` — all commit-aware local gates passed, including
OpenAPI/model freshness, actionlint, desktop suites, and the complete
desktop agent tool surface.
- Independent agent review found four test/wiring gaps; each was fixed
and the final review approved the updated tree.

No production deploy was performed. `backend/deploy/runtime_env.yaml`
changes checked-in desired state and will take effect only through the
normal deployment workflows.

## Tests

- `VoiceTurnCoordinatorTests` now reproduces nested effect/snapshot
callbacks and proves FIFO publication without recursion.
- `DictionaryDeduplicationTests` proves the shared collision policy; the
static checker rejects future trapping initializers and unreasoned
escapes.
- `test_prerecorded_stt_config.py`, provider tests, and
runtime-validator tests cover dynamic selectors, missing dependencies,
BYOK, fallback requirements, and dev/prod surfaces.
- `test_app_client_openapi_compatibility.py` covers request/response
directionality, status/media/security changes, enums, arrays, maps,
unions, constraints, and recursive references.
- `test_scan_async_blockers.py` covers transitive helpers, cycles, diff
scope, and safe executor offload.
- Workflow/path tests cover unknown sources, mixed direct+unmapped
changes, deleted tests, both rename sides, file-to-symlink type changes,
hook fallback, and full agent test discovery.

## Root cause and durable guard (bug fixes)

- Desktop lifecycle chain (`#9402`, `#9411`, `#9420`, `#9424`, `#9428`):
synchronous callbacks could advance a half-published transition. The
coordinator now owns a non-reentrant event queue, backed by
reducer-level behavior tests.
- Duplicate-ID crash class (`#9288` and adjacent sites): boundary data
was incorrectly assumed unique. A named collision policy replaces every
trapping production constructor, and CI rejects recurrence.
- Runtime/provider drift (`#9296`, `#9308`, `#9358`, `#9385`, `#9421`,
`#9422`): runtime choice and deploy dependencies had separate owners.
One pure provider contract now drives both, with lazy client
construction preserving import purity.
- Released-client break (`#9425`): schema freshness alone did not prove
compatibility. CI now compares contracts in the direction requests and
responses actually flow.
- False-green test selection: rename/deletion/type changes and unknown
production sources could escape intended gates, while the desktop agent
harness ran only a hand-picked subset. Selection now fails toward
broader coverage and discovers the complete suite.

## Scoped cleanups (optional)

- The backend test runner now caps nested BLAS/OpenMP pools per isolated
pytest worker, preventing oversubscription from corrupting per-test CPU
attribution while preserving explicit overrides.
- Runtime workflow validation reuses the already-parsed manifest instead
of reparsing it once per workflow.

This branch was successfully deployed

1 active deployment
staging - docs — a07a8ca3 Deployed Jul 9, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant