Repository navigation
ci(deploy): require Firestore index readiness on every lane that ships backend code - #20221
Conversation
Bind every querying image lane to its deployed source manifest and retain workflow-owned, read-only control code for older-release rollbacks. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <[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: 61122085a6
ℹ️ 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".
| - name: Checkout admitted Firestore source | ||
| uses: actions/checkout@v7 | ||
| with: | ||
| ref: ${{ inputs.source_sha }} | ||
| path: .github/firestore-source |
There was a problem hiding this comment.
Keep gate checkouts out of Docker build contexts
Every lane that later builds with context . leaves this full repository checkout under $GITHUB_WORKSPACE/.github/firestore-source, while callers also leave a full control checkout under .github/firestore-workflow; the root .dockerignore excludes neither directory. Since the tracked tree is roughly 760 MiB, these shallow clones and their worktrees add multiple GiB to runner storage and to contexts used by steps such as gcp_daily_memory_sweep_job.yml's context: ., making deployment builds substantially more likely to exhaust disk or time out. Use sparse checkout for the few manifest/registry/control files and/or exclude both directories in .dockerignore before any image build.
Useful? React with 👍 / 👎.
| - name: Verify serving Firestore indexes | ||
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | ||
| with: | ||
| source_sha: ${{ needs.admit.outputs.source_sha }} | ||
| project_id: ${{ env.QA_PROJECT }} | ||
| database: ${{ env.QA_FIRESTORE_DATABASE }} | ||
| credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }} |
There was a problem hiding this comment.
Create the JIT database before checking its indexes
On the first run against a clean QA project, this build job and provision run in parallel, but the database is only created later by provision's Create or verify the isolated named Firestore database step. The readiness action can therefore query based-hardware-dev/jit-qa before it exists, fail without producing a missing-index proposal, and prevent image publication even if the sibling job subsequently creates the database. Add a database-bootstrap/preflight dependency ahead of this job while retaining the required readiness check before the build and publication steps.
AGENTS.md reference: .github/AGENTS.md:L33-L33
Useful? React with 👍 / 👎.
| TAGGED_DIGEST="$(gcloud container images describe "${EXPECTED_REPOSITORY}:${RELEASE_SHA:0:7}" --format='value(image_summary.digest)')" | ||
| if [[ "$CANDIDATE_IMAGE" != "${EXPECTED_REPOSITORY}@${TAGGED_DIGEST}" ]]; then | ||
| echo "candidate_image does not equal the digest of ${EXPECTED_REPOSITORY}:${RELEASE_SHA:0:7}." >&2 |
There was a problem hiding this comment.
Derive the cutover tag with the deployer's abbreviation
The canonical backend deploy tags images with git rev-parse --short=7 HEAD, where 7 is a minimum and Git lengthens an ambiguous prefix; this repository already contains commit pairs for which that command returns eight characters. For such a release, looking up the fixed ${RELEASE_SHA:0:7} tag fails or resolves a different mutable registry tag even though the supplied candidate digest is the image produced by the deploy workflow, blocking both cutover stages. Compute the tag with the same git rev-parse --short=7 "$RELEASE_SHA" command used by the deploy action; the duplicate lookup in activate needs the same correction.
AGENTS.md reference: .github/AGENTS.md:L33-L33
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
20 issues found across 41 files
Confidence score: 2/5
check_backend_deploy_source_admission.pyand the dev deploy workflows can allow a deployment without checking that customer-data indexes inbased-hardwareare READY. Add the conditional readiness gate and enforce it invalidate_firestore_gate_steps.- In
jit_qa_cloud_run.yml, the readiness gate runs beforeprovisioncreatesjit-qa, so first runs and runs after database removal fail before provisioning can proceed. Run the gate after the database is available. - In
firestore-readiness/action.yml, caller-controlledproject_idanddatabasevalues can trigger shell command expansion despite the surrounding double quotes. Pass these values safely as environment variables or arguments before running the gate. firestore_workflow_policy.pycan miss templated or variable image references, letting a deploy-only job ship an image without producing the shipment needed for readiness checks. Resolve those references from workflow outputs or cover them with an explicit policy check.
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=".github/workflows/jit_qa_cloud_run.yml">
<violation number="1" location=".github/workflows/jit_qa_cloud_run.yml:114">
P1: This gate runs in `build` before the parallel `provision` job creates `jit-qa`. On a first run or after the database is removed, the readiness inventory fails on the missing database, so `build` exits before provisioning can bootstrap it and the workflow cannot ship; make the gate depend on a database-bootstrap step that completes before `build` (or otherwise serialize provisioning before this gate).</violation>
</file>
<file name=".github/actions/firestore-readiness/action.yml">
<violation number="1" location=".github/actions/firestore-readiness/action.yml:130">
P1: These action inputs are interpolated into the Bash script, so double quotes do not prevent `$()` or backtick expansion. A caller-controlled `project_id` or `database` can execute commands in the gate with the read-only credential available; pass both values through step `env` and expand the environment variables instead in both script invocations.</violation>
</file>
<file name=".github/workflows/gcp_backend_auto_dev.yml">
<violation number="1" location=".github/workflows/gcp_backend_auto_dev.yml:233">
P1: This lane gates only the compute/runtime project, so a deployment can pass while a required customer-data index is missing in `based-hardware`. Add the conditional customer-data readiness gate used by the other development lanes, with the same `source_sha` and a distinct proposal suffix, before deployment proceeds.</violation>
</file>
<file name=".github/scripts/check-direct-backend-production-admission.py">
<violation number="1" location=".github/scripts/check-direct-backend-production-admission.py:141">
P3: CONTROL_CHECKOUT must match the workflow block byte-for-byte, including 8/10-space indentation and `with:` key order. Any harmless reformat of the gate checkout (reordered keys, an added token/fetch-depth line, different indentation) makes `text.count(CONTROL_CHECKOUT)` return 0 and fails validation with the misleading "must not check out a second source" message. Match the required fragments individually, as check_backend_deploy_source_admission.py does for the same checkout, instead of duplicating the whole block.</violation>
<violation number="2" location=".github/scripts/check-direct-backend-production-admission.py:141">
P2: Deleting the gate-control checkout entirely from one of these three workflows passes validation: with only the source checkout left, `text.count("uses: actions/checkout@v7") == 1` and `text.count(CONTROL_CHECKOUT) == 0`, so `source_checkouts == 1`. This script is the only guard in `.github/scripts/` that references gcp_backend_listen_helm.yml, gcp_backend_pusher.yml, and gcp_llm_gateway.yml, so nothing else would keep the Firestore gate on those lanes. Require the control block to exist as well as limiting source checkouts.</violation>
</file>
<file name=".github/workflows/backend-unit-tests.yml">
<violation number="1" location=".github/workflows/backend-unit-tests.yml:49">
P3: `'.github/workflows/**'` subsumes the ~30 explicitly enumerated workflow patterns in both the push and pull_request sections, so those entries are now dead weight that will silently drift. More materially, the pattern is broader than the PR's goal of "every lane that ships backend code": any edit to an unrelated workflow (e.g. `desktop-checks.yml`, `repo-checks.yml`, or a future non-backend workflow) now triggers `backend-unit-shard`, and on every push to `main` that job runs `run-unit-ci.sh --all` (the full ~20-minute sharded suite) even when no backend code changed. ci-budget.yaml was updated for the extra runs, so the cost is known, but the trigger set could instead enumerate the concrete workflows and actions this PR gates (the new ones such as `gcp_backend_listen_helm.yml` are covered by the other `+` patterns already).</violation>
</file>
<file name=".github/scripts/check_backend_deploy_source_admission.py">
<violation number="1" location=".github/scripts/check_backend_deploy_source_admission.py:176">
P1: `validate_firestore_gate_steps` only enforces the runtime-project gate, so both backend deploy workflows can pass without checking the customer-data Firestore project required for development lanes. Require the conditional `based-hardware` gate with the same admitted SHA and credentials before accepting these workflows.</violation>
</file>
<file name="backend/scripts/firestore_workflow_policy.py">
<violation number="1" location="backend/scripts/firestore_workflow_policy.py:222">
P1: This regex misses templated or variable image references, so a deploy-only job can ship a backend image without producing a shipment for the readiness check. Resolve image/service variables from workflow outputs or conservatively treat unresolved deploy image references as backend shipments instead of requiring a same-job build.</violation>
<violation number="2" location="backend/scripts/firestore_workflow_policy.py:528">
P3: `_parse_docker_build()` doesn't handle the attached short form `-f<path>` that docker accepts, so `docker build -fbackend/Dockerfile.jit_qa_typesense ...` resolves the dockerfile to `<context>/Dockerfile` and bypasses the JIT QA exclusion. Match `-f` with an attached value as well.</violation>
</file>
<file name=".github/scripts/test_check_release_rings.py">
<violation number="1" location=".github/scripts/test_check_release_rings.py:47">
P3: This readiness-action staging block is a verbatim copy of the identical block just added to `_stage_release_sources()`, and the whole staging body of this test now duplicates that helper (same workflow, composite action, readiness action, same destinations). Future staging changes will have to be applied in both places and can silently diverge. Replace the body with a call to `self._stage_release_sources()` and keep the assertion.</violation>
</file>
<file name=".github/workflows/gcp_backend.yml">
<violation number="1" location=".github/workflows/gcp_backend.yml:308">
P1: The development manual lane checks only `based-hardware-dev` and can deploy code whose customer-data Firestore indexes are not READY in `based-hardware`. Add the paired customer-data gate, conditioned on `vars.RUNTIME_GCP_PROJECT_ID != 'based-hardware'`, using the same admitted SHA and credentials.</violation>
</file>
<file name=".github/workflows/gcp_frame_request_retention_job.yml">
<violation number="1" location=".github/workflows/gcp_frame_request_retention_job.yml:70">
P2: The serving readiness gate does not verify that the read-only credential belongs to `${{ vars.RUNTIME_GCP_PROJECT_ID }}`. A credential selected from another GCP project can therefore authenticate and query the explicit runtime project, masking a project-binding mistake; enable `verify_credential_project` for this serving check.</violation>
</file>
<file name=".github/workflows/gcp_memory_maintenance_job.yml">
<violation number="1" location=".github/workflows/gcp_memory_maintenance_job.yml:84">
P2: These gate checkouts remain in the workspace and are included in the later Docker `context: .`, adding two full repository worktrees to every build context. Remove the temporary gate worktrees before the image build, or stage them outside the workspace, to avoid large transfers, runner disk pressure, and slower deployments.</violation>
</file>
<file name=".github/scripts/test_check_direct_backend_production_admission.py">
<violation number="1" location=".github/scripts/test_check_direct_backend_production_admission.py:40">
P2: `replace_all` only makes the fresh_origin test pass by mutating every fetch occurrence, so the test no longer guards a single-weakened-site regression. With `gcp_backend_listen_helm.yml` now containing three `git fetch --no-tags origin +refs/heads/main:refs/remotes/origin/main` sites (source admission, selected image, rollback), the checker's presence check `ORIGIN_MAIN_FETCH not in text` passes while any one site is intact: mutating or removing only the canonical source-admission fetch yields `validate() == []`, and the test never exercises that case. The stated guarantee "each ... source admission mutation" now holds only when all three are weakened, masking a silent drop of one production-source freshness gate in the exact kind of missed lane this PR is closing. Mirror the count-exact checks from the same checker (`text.count(HEAD_IDENTITY) != 1`, `image_authorities == [IMAGE_IDENTITY]`) and require the fetch per production doorway (or loop the mutation over each occurrence index), so each fetch site is independently verified.</violation>
</file>
<file name=".github/workflows/desktop_backend_prod.yml">
<violation number="1" location=".github/workflows/desktop_backend_prod.yml:181">
P2: This gate blocks valid historical `release_sha` deployments that predate the Firestore manifest and registry, because the composite checks out that exact source and fails before it can evaluate readiness. Add a legacy requirements path or explicitly route pre-registry releases through a compatible admission path before enabling this gate.</violation>
</file>
<file name=".github/scripts/check_release_rings.py">
<violation number="1" location=".github/scripts/check_release_rings.py:62">
P2: This raw substring check treats a commented-out `uses` line as active, allowing this guard to pass when the Firestore readiness step no longer runs. Match an active workflow line instead of searching the whole file.</violation>
</file>
<file name="backend/scripts/reconcile_firestore_indexes.py">
<violation number="1" location="backend/scripts/reconcile_firestore_indexes.py:919">
P3: This guard fires for `--dry-run --source-root` and `--provision-missing --source-root`, but the message claims `--validate-proposal` is valid here, and that mode never reaches `reconcile()` (main() routes it to `validate_schema_proposal()` and returns earlier). Either support `--source-root` with read-only `--dry-run`, or restrict to check-only and say so accurately.</violation>
</file>
<file name=".github/workflows/gcp_backend_listen_helm.yml">
<violation number="1" location=".github/workflows/gcp_backend_listen_helm.yml:216">
P2: `git rev-parse` now requires the currently serving image’s commit to exist in the initial runtime checkout. A chart-only deploy or rollback of an image from a deleted or unreachable branch fails before the readiness composite; resolve or fetch the selected SHA independently of the chosen branch.</violation>
</file>
<file name="backend/tests/unit/test_reconcile_firestore_indexes.py">
<violation number="1" location="backend/tests/unit/test_reconcile_firestore_indexes.py:1508">
P3: `_stub_gcloud` interpolates the JSON payload directly into a single-quoted shell literal (`printf '%s' '{live}'`), but `json.dumps` escapes apostrophes as `\'` inside the JSON, so any live index data containing a single quote terminates the shell string early and yields a broken (or command-injecting) stub. Current test fixtures avoid quotes, so this passes today, but it breaks silently the moment a collection group or index name is extended with one. Emit the payload through a quoted heredoc, which is safe for quotes and backslashes.</violation>
</file>
<file name=".github/scripts/test_check_backend_deploy_source_admission.py">
<violation number="1" location=".github/scripts/test_check_backend_deploy_source_admission.py:535">
P3: `test_readiness_gate_and_control_checkout_reject_fail_open_conditions` asserts only `self.assertTrue(CHECKER.validate(root))`, so it passes when *any* error is emitted rather than the specific fail-closed contract violation. Every other test in this file pins an exact contract message with `assertIn`, and a mutation that produced an unrelated error would let this test pass even if the fail-open guard for these steps regressed. Assert that the error mentions "must not be conditionally skipped or tolerated" (or the exact per-step label).</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| ref: ${{ github.workflow_sha }} | ||
| path: .github/firestore-workflow | ||
| persist-credentials: false | ||
| - name: Verify serving Firestore indexes |
There was a problem hiding this comment.
P1: This gate runs in build before the parallel provision job creates jit-qa. On a first run or after the database is removed, the readiness inventory fails on the missing database, so build exits before provisioning can bootstrap it and the workflow cannot ship; make the gate depend on a database-bootstrap step that completes before build (or otherwise serialize provisioning before this gate).
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 .github/workflows/jit_qa_cloud_run.yml, line 114:
<comment>This gate runs in `build` before the parallel `provision` job creates `jit-qa`. On a first run or after the database is removed, the readiness inventory fails on the missing database, so `build` exits before provisioning can bootstrap it and the workflow cannot ship; make the gate depend on a database-bootstrap step that completes before `build` (or otherwise serialize provisioning before this gate).</comment>
<file context>
@@ -105,6 +105,19 @@ jobs:
+ ref: ${{ github.workflow_sha }}
+ path: .github/firestore-workflow
+ persist-credentials: false
+ - name: Verify serving Firestore indexes
+ uses: ./.github/firestore-workflow/.github/actions/firestore-readiness
+ with:
</file context>
| if ! python3 "${FIRESTORE_WORKFLOW_ROOT}/backend/scripts/reconcile_firestore_indexes.py" \ | ||
| --manifest "${FIRESTORE_SOURCE_ROOT}/firestore.indexes.json" \ | ||
| --source-root "${FIRESTORE_SOURCE_ROOT}" \ | ||
| --project "${{ inputs.project_id }}" \ |
There was a problem hiding this comment.
P1: These action inputs are interpolated into the Bash script, so double quotes do not prevent $() or backtick expansion. A caller-controlled project_id or database can execute commands in the gate with the read-only credential available; pass both values through step env and expand the environment variables instead in both script invocations.
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 .github/actions/firestore-readiness/action.yml, line 130:
<comment>These action inputs are interpolated into the Bash script, so double quotes do not prevent `$()` or backtick expansion. A caller-controlled `project_id` or `database` can execute commands in the gate with the read-only credential available; pass both values through step `env` and expand the environment variables instead in both script invocations.</comment>
<file context>
@@ -0,0 +1,169 @@
+ if ! python3 "${FIRESTORE_WORKFLOW_ROOT}/backend/scripts/reconcile_firestore_indexes.py" \
+ --manifest "${FIRESTORE_SOURCE_ROOT}/firestore.indexes.json" \
+ --source-root "${FIRESTORE_SOURCE_ROOT}" \
+ --project "${{ inputs.project_id }}" \
+ --database "${{ inputs.database }}" \
+ --check-only \
</file context>
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | ||
| with: | ||
| name: firestore-schema-proposal-${{ github.run_id }}-${{ github.run_attempt }} | ||
| path: ${{ env.FIRESTORE_PROPOSAL_PATH }} | ||
| if-no-files-found: error | ||
| retention-days: 1 | ||
| source_sha: ${{ steps.admitted_source.outputs.admitted_sha }} | ||
| project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }} | ||
| credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }} | ||
| verify_credential_project: 'true' |
There was a problem hiding this comment.
P1: This lane gates only the compute/runtime project, so a deployment can pass while a required customer-data index is missing in based-hardware. Add the conditional customer-data readiness gate used by the other development lanes, with the same source_sha and a distinct proposal suffix, before deployment proceeds.
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 .github/workflows/gcp_backend_auto_dev.yml, line 233:
<comment>This lane gates only the compute/runtime project, so a deployment can pass while a required customer-data index is missing in `based-hardware`. Add the conditional customer-data readiness gate used by the other development lanes, with the same `source_sha` and a distinct proposal suffix, before deployment proceeds.</comment>
<file context>
@@ -222,65 +222,20 @@ jobs:
- uses: actions/upload-artifact@v7
- env:
- FIRESTORE_PROPOSAL_PATH: ${{ runner.temp }}/firestore-schema-proposal-${{ github.run_id }}-${{ github.run_attempt }}.json
+ uses: ./.github/firestore-workflow/.github/actions/firestore-readiness
with:
- name: firestore-schema-proposal-${{ github.run_id }}-${{ github.run_attempt }}
</file context>
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | |
| with: | |
| name: firestore-schema-proposal-${{ github.run_id }}-${{ github.run_attempt }} | |
| path: ${{ env.FIRESTORE_PROPOSAL_PATH }} | |
| if-no-files-found: error | |
| retention-days: 1 | |
| source_sha: ${{ steps.admitted_source.outputs.admitted_sha }} | |
| project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }} | |
| credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }} | |
| verify_credential_project: 'true' | |
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | |
| with: | |
| source_sha: ${{ steps.admitted_source.outputs.admitted_sha }} | |
| project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }} | |
| credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }} | |
| verify_credential_project: 'true' | |
| - name: Verify customer-data Firestore indexes | |
| if: ${{ vars.RUNTIME_GCP_PROJECT_ID != 'based-hardware' }} | |
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | |
| with: | |
| source_sha: ${{ steps.admitted_source.outputs.admitted_sha }} | |
| project_id: based-hardware | |
| credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }} | |
| artifact_suffix: -customer-data |
| for fragment, message in ( | ||
| (f"uses: {FIRESTORE_GATE_USES}", f"{label} must run the shared Firestore readiness composite"), | ||
| (f"source_sha: {source_sha_binding}", f"{label} must bind the gate to the admitted source SHA"), | ||
| ("project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }}", f"{label} must target the runtime project"), |
There was a problem hiding this comment.
P1: validate_firestore_gate_steps only enforces the runtime-project gate, so both backend deploy workflows can pass without checking the customer-data Firestore project required for development lanes. Require the conditional based-hardware gate with the same admitted SHA and credentials before accepting these workflows.
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 .github/scripts/check_backend_deploy_source_admission.py, line 176:
<comment>`validate_firestore_gate_steps` only enforces the runtime-project gate, so both backend deploy workflows can pass without checking the customer-data Firestore project required for development lanes. Require the conditional `based-hardware` gate with the same admitted SHA and credentials before accepting these workflows.</comment>
<file context>
@@ -133,6 +138,79 @@ def validate_fail_closed_step(errors: list[str], step: str, label: str) -> None:
+ for fragment, message in (
+ (f"uses: {FIRESTORE_GATE_USES}", f"{label} must run the shared Firestore readiness composite"),
+ (f"source_sha: {source_sha_binding}", f"{label} must bind the gate to the admitted source SHA"),
+ ("project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }}", f"{label} must target the runtime project"),
+ (
+ "credentials_json: ${{ secrets.GCP_FIRESTORE_READONLY_CREDENTIALS }}",
</file context>
| } | ||
|
|
||
| _DOCKERFILE_FLAG = re.compile(r'(?:--file|--dockerfile|-f|file:)\s*=?["\']?([^\s"\']*Dockerfile[^\s"\']*)') | ||
| _GCR_IMAGE = re.compile(r'gcr\.io/[A-Za-z0-9_.${} /-]+?/([A-Za-z0-9_-]+)(?=[@:\s]|$)') |
There was a problem hiding this comment.
P1: This regex misses templated or variable image references, so a deploy-only job can ship a backend image without producing a shipment for the readiness check. Resolve image/service variables from workflow outputs or conservatively treat unresolved deploy image references as backend shipments instead of requiring a same-job build.
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/firestore_workflow_policy.py, line 222:
<comment>This regex misses templated or variable image references, so a deploy-only job can ship a backend image without producing a shipment for the readiness check. Resolve image/service variables from workflow outputs or conservatively treat unresolved deploy image references as backend shipments instead of requiring a same-job build.</comment>
<file context>
@@ -176,3 +183,931 @@ def has_direct_firestore_mutation(run: str) -> bool:
+}
+
+_DOCKERFILE_FLAG = re.compile(r'(?:--file|--dockerfile|-f|file:)\s*=?["\']?([^\s"\']*Dockerfile[^\s"\']*)')
+_GCR_IMAGE = re.compile(r'gcr\.io/[A-Za-z0-9_.${} /-]+?/([A-Za-z0-9_-]+)(?=[@:\s]|$)')
+_RUN_DEPLOY = re.compile(r'gcloud\s+run\s+(?:deploy|jobs\s+(?:deploy|update))\s+["\']?([^\s"\']+)')
+_TRAFFIC_ONLY = re.compile(r'gcloud\s+run\s+(?:services\s+)?update-traffic\b')
</file context>
| destination = self.tmp_path / checker.DEPLOY_BACKEND_STACK_ACTION | ||
| destination.parent.mkdir(parents=True, exist_ok=True) | ||
| shutil.copy2(composite_action, destination) | ||
| readiness_action = self._real_root / checker.FIRESTORE_READINESS_ACTION |
There was a problem hiding this comment.
P3: This readiness-action staging block is a verbatim copy of the identical block just added to _stage_release_sources(), and the whole staging body of this test now duplicates that helper (same workflow, composite action, readiness action, same destinations). Future staging changes will have to be applied in both places and can silently diverge. Replace the body with a call to self._stage_release_sources() and keep the assertion.
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 .github/scripts/test_check_release_rings.py, line 47:
<comment>This readiness-action staging block is a verbatim copy of the identical block just added to `_stage_release_sources()`, and the whole staging body of this test now duplicates that helper (same workflow, composite action, readiness action, same destinations). Future staging changes will have to be applied in both places and can silently diverge. Replace the body with a call to `self._stage_release_sources()` and keep the assertion.</comment>
<file context>
@@ -44,6 +44,11 @@ def _stage_release_sources(self) -> None:
destination = self.tmp_path / checker.DEPLOY_BACKEND_STACK_ACTION
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(composite_action, destination)
+ readiness_action = self._real_root / checker.FIRESTORE_READINESS_ACTION
+ if readiness_action.exists():
+ destination = self.tmp_path / checker.FIRESTORE_READINESS_ACTION
</file context>
| if sum((check_only, dry_run, provision_missing)) > 1: | ||
| raise ValueError('--check-only, --dry-run, and --provision-missing cannot be combined') | ||
| if source_root is not None and not check_only: | ||
| raise ValueError('--source-root is only valid with --check-only or --validate-proposal') |
There was a problem hiding this comment.
P3: This guard fires for --dry-run --source-root and --provision-missing --source-root, but the message claims --validate-proposal is valid here, and that mode never reaches reconcile() (main() routes it to validate_schema_proposal() and returns earlier). Either support --source-root with read-only --dry-run, or restrict to check-only and say so accurately.
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/reconcile_firestore_indexes.py, line 919:
<comment>This guard fires for `--dry-run --source-root` and `--provision-missing --source-root`, but the message claims `--validate-proposal` is valid here, and that mode never reaches `reconcile()` (main() routes it to `validate_schema_proposal()` and returns earlier). Either support `--source-root` with read-only `--dry-run`, or restrict to check-only and say so accurately.</comment>
<file context>
@@ -865,14 +915,16 @@ def reconcile(
if sum((check_only, dry_run, provision_missing)) > 1:
raise ValueError('--check-only, --dry-run, and --provision-missing cannot be combined')
+ if source_root is not None and not check_only:
+ raise ValueError('--source-root is only valid with --check-only or --validate-proposal')
if check_only:
if proposal_output is None or not source_commit:
</file context>
| raise ValueError('--source-root is only valid with --check-only or --validate-proposal') | |
| raise ValueError('--source-root is only valid with --check-only') |
| token = tokens[index] | ||
| if token == '--push': | ||
| pushed = True | ||
| elif token in ('-f', '--file', '--dockerfile'): |
There was a problem hiding this comment.
P3: _parse_docker_build() doesn't handle the attached short form -f<path> that docker accepts, so docker build -fbackend/Dockerfile.jit_qa_typesense ... resolves the dockerfile to <context>/Dockerfile and bypasses the JIT QA exclusion. Match -f with an attached value as well.
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/firestore_workflow_policy.py, line 528:
<comment>`_parse_docker_build()` doesn't handle the attached short form `-f<path>` that docker accepts, so `docker build -fbackend/Dockerfile.jit_qa_typesense ...` resolves the dockerfile to `<context>/Dockerfile` and bypasses the JIT QA exclusion. Match `-f` with an attached value as well.</comment>
<file context>
@@ -176,3 +183,931 @@ def has_direct_firestore_mutation(run: str) -> bool:
+ token = tokens[index]
+ if token == '--push':
+ pushed = True
+ elif token in ('-f', '--file', '--dockerfile'):
+ if index + 1 < len(tokens):
+ file_ref = tokens[index + 1]
</file context>
| stub.write_text( | ||
| '#!/bin/bash\n' | ||
| 'if [[ "$*" == *"indexes composite"*"list"* ]]; then\n' | ||
| f" printf '%s' '{live}'\n" |
There was a problem hiding this comment.
P3: _stub_gcloud interpolates the JSON payload directly into a single-quoted shell literal (printf '%s' '{live}'), but json.dumps escapes apostrophes as \' inside the JSON, so any live index data containing a single quote terminates the shell string early and yields a broken (or command-injecting) stub. Current test fixtures avoid quotes, so this passes today, but it breaks silently the moment a collection group or index name is extended with one. Emit the payload through a quoted heredoc, which is safe for quotes and backslashes.
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_reconcile_firestore_indexes.py, line 1508:
<comment>`_stub_gcloud` interpolates the JSON payload directly into a single-quoted shell literal (`printf '%s' '{live}'`), but `json.dumps` escapes apostrophes as `\'` inside the JSON, so any live index data containing a single quote terminates the shell string early and yields a broken (or command-injecting) stub. Current test fixtures avoid quotes, so this passes today, but it breaks silently the moment a collection group or index name is extended with one. Emit the payload through a quoted heredoc, which is safe for quotes and backslashes.</comment>
<file context>
@@ -1133,3 +1138,476 @@ def request(method, url, payload):
+ stub.write_text(
+ '#!/bin/bash\n'
+ 'if [[ "$*" == *"indexes composite"*"list"* ]]; then\n'
+ f" printf '%s' '{live}'\n"
+ 'elif [[ "$*" == *"print-access-token"* ]]; then\n'
+ ' echo stub-token\n'
</file context>
| f" - name: {step_name}\n", | ||
| f" - name: {step_name}\n{condition_line}\n", | ||
| ) | ||
| self.assertTrue( |
There was a problem hiding this comment.
P3: test_readiness_gate_and_control_checkout_reject_fail_open_conditions asserts only self.assertTrue(CHECKER.validate(root)), so it passes when any error is emitted rather than the specific fail-closed contract violation. Every other test in this file pins an exact contract message with assertIn, and a mutation that produced an unrelated error would let this test pass even if the fail-open guard for these steps regressed. Assert that the error mentions "must not be conditionally skipped or tolerated" (or the exact per-step label).
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 .github/scripts/test_check_backend_deploy_source_admission.py, line 535:
<comment>`test_readiness_gate_and_control_checkout_reject_fail_open_conditions` asserts only `self.assertTrue(CHECKER.validate(root))`, so it passes when *any* error is emitted rather than the specific fail-closed contract violation. Every other test in this file pins an exact contract message with `assertIn`, and a mutation that produced an unrelated error would let this test pass even if the fail-open guard for these steps regressed. Assert that the error mentions "must not be conditionally skipped or tolerated" (or the exact per-step label).</comment>
<file context>
@@ -494,6 +518,25 @@ def test_auto_workflow_scopes_admission_steps_to_readiness_and_rejects_duplicate
+ f" - name: {step_name}\n",
+ f" - name: {step_name}\n{condition_line}\n",
+ )
+ self.assertTrue(
+ CHECKER.validate(root),
+ f"{relative} accepted {condition_line.strip()} on {step_name}",
</file context>
Check one runtime target, preserve listen replay and cutover boundaries, and tolerate old manifests and transient read failures without changing writes. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d7f66dcdcc
ℹ️ 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".
| uses: ./.github/firestore-workflow/.github/actions/firestore-readiness | ||
| with: | ||
| source_sha: ${{ steps.candidate-identity.outputs.source_sha }} | ||
| project_id: ${{ vars.RUNTIME_GCP_PROJECT_ID }} |
There was a problem hiding this comment.
Gate the customer-data Firestore project
In the development desktop lane, this checks vars.RUNTIME_GCP_PROJECT_ID (based-hardware-dev), but the revision deployed later in this same workflow explicitly sets OMI_FIRESTORE_DATA_PLANE_PROJECT=based-hardware. When a backend/query change triggers auto-deploy while its production index rollout is still awaiting approval or building, the dev-project check can pass and the candidate can serve customer-data queries against based-hardware without the required index, causing those requests to fail. Run readiness against the declared data-plane project as well as the compute project when they differ.
Useful? React with 👍 / 👎.
| result = subprocess.run( | ||
| [sys.executable, '-c', _SOURCE_ROOT_REGISTRY_SNIPPET, str(source_root / 'backend')], | ||
| check=False, |
There was a problem hiding this comment.
Validate source registries before exposing credentials
In development workflows that accept a caller-selected source branch, such as gcp_notifications_job.yml, this subprocess imports and executes database.firestore_index_registry from that branch after the composite has created the read-only service-account credential file. Because subprocess.run inherits CLOUDSDK_AUTH_CREDENTIAL_FILE_OVERRIDE and the rest of the environment, branch-controlled module-level code can read and exfiltrate the persistent credential even though the workflow definition and environment approval come from an allowed ref. Regenerate or validate the source manifest before authentication, or parse it without executing source-controlled Python in a credentialed process.
AGENTS.md reference: .github/AGENTS.md:L23-L23
Useful? React with 👍 / 👎.
| if pattern is _CUTOVER and workflow_name == _CUTOVER_WORKFLOW: | ||
| continue |
There was a problem hiding this comment.
Require readiness for sync-ledger cutovers
This exemption makes the new coverage check deliberately ignore sync_ledger_fence_cutover.yml, even though that workflow invokes the cutover script to create and promote new backend-sync and backend-sync-backfill revisions. Its candidate_image validation accepts any immutable digest and does not enforce that it came from a gated repository or bind it to a source manifest, so an operator can ship query code whose indexes are not ready while this policy reports complete coverage. Remove the exemption and gate the source corresponding to the candidate digest before either cutover stage mutates Cloud Run.
Useful? React with 👍 / 👎.
CodeQL flagged the project-segment alternation as ambiguous and the bare substring host checks; the alternatives are now disjoint and the host check is an anchored pattern. Co-Authored-By: Claude Opus 5.5 <[email protected]>
main (BasedHardware#20221) requires every lane that ships a backend image to verify serving Firestore indexes first. Add the same checked-out-SHA resolution, immutable gate-control checkout, and readiness step the other job workflows use, pin the deploy environment to prod/development, and register the lane's source binding in the workflow contract test. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
github.workflow_sha; requirements come from each lane's exact deployed source. Both extra checkouts are sparse. Each gate checks one runtime target (or isolated JIT QA project/database), never a second customer-data project.skip_eligibility_proofdoes not skip readiness.Failure-Class: FC-workflow-control-source-identity
Product invariants affected: None
INV-DATA-1: deployment admission only; no change to customer-data authority or canonical writes.
INV-MEM-4: read-only maintenance-job admission; no change to canonical promotion authority, maintenance flags, or memory writes.
Lane inventory
runtimemeansvars.RUNTIME_GCP_PROJECT_ID/(default). All direct gates passsecrets.GCP_FIRESTORE_READONLY_CREDENTIALSfrom the existingprod/developmentjob. Static bindings are verified; the prior independent review confirmed secret-name presence in both environments. Secret payloads, principals, IAM grants, and live inventories were not inspected in this round.gcp_backend.ymlfirestore_readiness; deploy needs successrelease_shagcp_backend_auto_dev.ymlfirestore_readiness; credential-project match retainedgcp_backend_listen_helm.ymlimage_taggcp_backend_pusher.ymlgcp_backend_pusher_auto_deploy.ymlgithub.shagcp_llm_gateway.ymlrelease_shain proddesktop_backend_prod.ymldesktop_backend_auto_dev.ymlgcp_daily_memory_sweep_job.ymlgcp_daily_memory_sweep_job_auto_dev.ymlgcp_memory_maintenance_job.ymlgcp_memory_maintenance_job_auto_dev.ymlgithub.shagcp_notifications_job.ymlgcp_frame_request_retention_job.ymlrelease_shagcp_day3_reengagement_email_job.ymlgcp_day3_reengagement_email_job_auto_dev.ymljit_qa_cloud_run.ymlenv.QA_PROJECT/env.QA_FIRESTORE_DATABASE(based-hardware-dev/jit-qa)jit_qa_typesense_projection.ymlprove; bootstrap is upstream Typesense onlybased-hardware-dev/jit-qasync_ledger_fence_cutover.ymlIncident paths and builder proof
Listen's kept running tag and Helm rollback remain upstream logic: these images already served in that environment, indexes are create-only, and rollback must not gain failure modes. Only an explicit image tag gains a defense-in-depth gate. It writes the manifest SHA after existing commit/prod-ancestry validation; kept-tag and rollback paths do not resolve old source or request Firestore credentials.
Cutover is restored completely to
origin/main, including its inputs, stage/activate logic, and CI-budget inventory: no required source SHA, mutable-tag digest binding, or new readiness calls. The discovery policy documents the consumes only images from gated builders; never builds class and asserts the builder inventory. The only workflows publishing togcr.io/${{ vars.GCP_PROJECT_ID }}/backendaregcp_backend.ymlandgcp_backend_auto_dev.yml, throughdeploy-backend-stack(latest, short-SHA, and registry build cache). Both require their existing readiness job before the deploy action. Listen also consumes this repository; its explicit-tag gate remains extra defense.Important existing limitation: upstream cutover validates a generic immutable digest, not the
gcr.io/<project>/backendrepository. Its transitive readiness argument therefore assumes the operator selects a backend image from those builders; it is not an enforced arbitrary-image provenance guarantee. This rework does not change that operator boundary.Inference-only GPU images, plugins/web images, external monitoring Helm charts, and traffic-only repair paths remain excluded for their documented source/operation class. No notifications/frame-retention auto-dev workflow is invented. Pusher's valid modes are Pusher and LLM gateway, not a third backend builder.
Verification
f86f72b6f3), required five-fileBACKEND_UNIT_TEST_FILE_LIST=... bash test.sh: 418 passed (89 workflow contracts, 107 reconciler, 49 field-index, 37 release-vector, 136 runtime-validator).bash backend/scripts/pre-deploy-check.sh: 269 passed, plus its 33 admission unittest fixtures. Incident-path suites: 34 passed.make preflightand draft-bodyscripts/pr-preflight: 57 checks passed each; final committed/post-merge PR preflight also passed 57 checks. Test preflight: 18 passed, using the existing Python 3.11 venv (system Python is 3.14).Evidence is retained under git-ignored
.agent-brief/(test-sh-postmerge.log,admission-tests-final.log,pre-deploy-postmerge.log,make-preflight-final.log,pr-preflight-postmerge.log, andsparse-proof/). No workflow dispatch, deployment, GCP call, runtime API request, or schema mutation was performed.Sparse/clean-tree audit: cone mode includes root
firestore.indexes.json; controls include only the readiness action, backend scripts/database and cone ancestor files. Real-git scratch checkout plus system Python exercises the reconciler up to a local fake gcloud sentinel, without pip or cloud access. Gated jobs/composites have no dirty-tree checks,git add -A, broadhashFiles, or root-contextCOPY . .. Existing diffs use explicit revisions; Dockerfiles copy named backend paths (and one named.github/scriptsfile). Old source.gitignorefiles therefore need no cleanup machinery.32aaba5faf: registry-reference patterns in the discovery policy are linear and anchored (CodeQL); contract tests 89 passed.Next real-run checks (coordinator)
Automatic development coverage: Pusher, desktop-backend, and maintenance run on eligible main pushes; central backend, daily sweep, and day3 run after their existing eligibility/supersession admission. Listen chart-only pushes keep the served tag and are exempt. JIT QA stays manual.
For every direct gate, check the full requirement-source SHA and correct single target, then
Firestore index readiness passed: <N> composite indexes and <M> field overrides READYbefore publication/rollout/job update. Missing/non-READY requirements must stop shipment, name requirements, referencebackend/docs/runbooks/firestore-missing-index.md, and upload only a successfully revalidated, bounded, redacted, one-hour proposal (one-day retention). Extra live indexes are non-blocking; no gate writes indexes. On listen's next explicit-tag deploy verify the gate precedes config/secret/Helm mutation; on kept-tag/rollback verify no new gate runs. Cutover retains its existing operator/backend-builder contract.Owner decisions
based-hardwarereadiness. Cross-project credential grants are unverified, and that dependency could turn automatic dev deployments red for roughly an hour after an index PR. This PR checks only each lane's runtime target, including central auto-dev.Current main was merged into this branch, never rebased. No unrelated formatter changes, test-selector changes, or missing-index-alert changes are included. Do not merge this PR in this round.
🤖 Generated with Claude Code