Skip to content

fix(ci): harden notifications-job deploy contract for prod render - #9296

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/notifications-job-deploy-contract
Jul 9, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/notifications-job-deploy-contract

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Summary

Follow-up to #9295 review feedback before any prod notifications-job deploy:

  • Pass CLOUD_RUN_VPC_NETWORK / CLOUD_RUN_VPC_SUBNET into the render step (same as gcp_backend.yml). Prod network flags are env_var-backed; without them render_backend_runtime_env.py exits before notifications_job_* outputs are emitted.
  • Derive the immutable image short SHA from git rev-parse --short=7 HEAD after checkout so the tag matches the branch input, not a divergent GITHUB_SHA workflow-file ref.

Why

Test plan

  • pytest backend/tests/unit/test_render_backend_runtime_env.py (8 passed), including regression that prod render requires VPC vars and workflow source assertions
  • validate-backend-runtime-env.py --env dev|prod --check-workflows
  • CI on this PR

Notes

  • No memory flag / cohort / prod enablement changes.
  • Safe to land independently of whitelist dogfood; required before relying on prod notifications-job deploys.

Made with Cursor

Review in cubic

Pass VPC GitHub vars into the runtime-env renderer (required for prod
network flags) and tag images from checked-out HEAD so branch-input
deploys match the built commit.

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.

No issues found across 2 files

Confidence score: 5/5

  • Automated review surfaced no issues in the provided summaries.
  • No files require special attention.

You’re at about 94% 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].

Re-trigger cubic

@Git-on-my-level
Git-on-my-level merged commit 4826b1a into main Jul 9, 2026
20 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/notifications-job-deploy-contract branch July 9, 2026 02:59
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.
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