Repository navigation
fix(backend): declare single-field collection-group indexes and bring Firestore index debt to zero - #20161
Conversation
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. |
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.
9 issues found across 29 files
Confidence score: 3/5
- In
backend/scripts/reconcile_firestore_indexes.py, field provisioning and composite readiness each get a full timeout, so a slow provisioning step can push the workflow past its 240-minute job limit before readiness completes — use a shared overall deadline. - In
backend/scripts/firestore_field_indexes.py, existing Firestore vector or search field indexes are rejected or omitted from patches, risking reconciliation failure or loss of those configurations — preserve these modes. - In
backend/database/feedback.py,list_report_datesnow orders bydate, which excludes reports without that field and can hide older reports from results — include or otherwise account for documents missingdate. - In
backend/tests/support/firestore_conversation_profiles.py,discover_callersmisses annotated aliases, allowing a new caller to bypass the witness completeness gate — handleast.AnnAssignaliases.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/tests/support/firestore_query_drivers.py">
<violation number="1" location="backend/tests/support/firestore_query_drivers.py:670">
P3: `visit` double-counts references: a single `worker.fn(...)` call record the target twice (once via `Call.func`, once when the recursion revisits the `Attribute`/`Name` child) and also emits a separate key for the base module name. The `references` counter becomes inflated and inconsistent between call forms (qualified=2, bare-name=1), so the documented count is meaningless and any future count-based assertion on the guardrail's output will be unpredictable. Count each reference expression exactly once (e.g., handle `Call`/`Name`/`Attribute` in one pass and skip already-visited nodes, or only count `Call.func`/args/keywords like `discover_callers`).</violation>
</file>
<file name="backend/scripts/reconcile_firestore_indexes.py">
<violation number="1" location="backend/scripts/reconcile_firestore_indexes.py:920">
P2: `reconcile` gives field provisioning the full timeout, then starts composite readiness with another full timeout. A field operation that consumes 10,800 seconds can exceed the workflow's 240-minute job limit before the second wait finishes; use one shared deadline or pass the remaining budget.</violation>
</file>
<file name="backend/tests/support/firestore_shape_recorder.py">
<violation number="1" location="backend/tests/support/firestore_shape_recorder.py:212">
P3: The newly added `path_template` key is part of the signature identity but the `signature()` docstring's "includes" list was not updated. Add "path template" to that enumeration so the documented and actual identity stay in sync.</violation>
</file>
<file name="backend/database/feedback.py">
<violation number="1" location="backend/database/feedback.py:397">
P3: The docstring above `list_report_dates` still describes the old behavior: "Document ids are ISO dates, so ordering by document id is the same as ordering by date." The query now orders by the `date` field, not `__name__`, so the comment no longer describes what the code does. Reword it to say the query orders by the persisted `date` field.</violation>
<violation number="2" location="backend/database/feedback.py:397">
P2: Firestore `order_by('date')` excludes any document that does not contain the `date` field, whereas the previous `__name__` ordering returned every document. Reports written before the `date` field existed, or written by any path that does not set it, would silently disappear from the admin report-dates listing without erroring. The PR description itself notes historical production coverage is unverified — confirm/backfill the field on existing `feedback_reports` documents (or keep `__name__` ordering) before shipping this.</violation>
</file>
<file name="backend/tests/unit/test_reconcile_firestore_field_exemptions.py">
<violation number="1" location="backend/tests/unit/test_reconcile_firestore_field_exemptions.py:68">
P3: Both parametrized overrides now raise inside `firestore_field_indexes.expected_field_requirements` (which `expected_field_exemptions` calls first), so the exemption tool's own 'only supports ttl=false with indexes=' branch is dead. The combined regex `ttl=false|collection-group` lets each case pass even when it is rejected by the wrong path — the old dead-branch message also contains 'ttl=false', so case 1 would still match without the shared validator ever running, and either case matches the other case's substring. Assert one expected message per case so a regression in either validation path is pinpointed.</violation>
</file>
<file name="backend/AGENTS.md">
<violation number="1" location="backend/AGENTS.md:153">
P3: `indexes=[]` exemptions are intentionally non-serving, but this says the workflow succeeds only when they “serve”; describe the prod check as requiring them to be applied/disabled, and qualify that development skips it.</violation>
</file>
<file name="backend/tests/support/firestore_conversation_profiles.py">
<violation number="1" location="backend/tests/support/firestore_conversation_profiles.py:174">
P2: `discover_callers` misses annotated aliases, so a new caller can bypass the witness completeness gate. Handle `ast.AnnAssign` aliases alongside `ast.Assign` before resolving calls.</violation>
</file>
<file name="backend/scripts/firestore_field_indexes.py">
<violation number="1" location="backend/scripts/firestore_field_indexes.py:42">
P2: The shared reconciler cannot preserve existing Firestore `vectorConfig` or `searchConfig` field indexes: validation rejects those modes, and patch construction would omit them. Preserve these non-serving modes in the validated patch rather than blocking or deleting them.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| return | ||
| if provision_missing: | ||
| provision_missing_indexes(expected=expected, project=project, database=database, runner=runner) | ||
| field_indexes.provision_field_requirements( |
There was a problem hiding this comment.
P2: reconcile gives field provisioning the full timeout, then starts composite readiness with another full timeout. A field operation that consumes 10,800 seconds can exceed the workflow's 240-minute job limit before the second wait finishes; use one shared deadline or pass the remaining budget.
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 920:
<comment>`reconcile` gives field provisioning the full timeout, then starts composite readiness with another full timeout. A field operation that consumes 10,800 seconds can exceed the workflow's 240-minute job limit before the second wait finishes; use one shared deadline or pass the remaining budget.</comment>
<file context>
@@ -748,31 +889,53 @@ def reconcile(
return
if provision_missing:
provision_missing_indexes(expected=expected, project=project, database=database, runner=runner)
+ field_indexes.provision_field_requirements(
+ requirements=field_requirements,
+ project=project,
</file context>
| get_firestore_client() | ||
| .collection(FEEDBACK_REPORTS_COLLECTION) | ||
| .order_by(_DOCUMENT_ID_FIELD, direction='DESCENDING') | ||
| .order_by('date', direction='DESCENDING') |
There was a problem hiding this comment.
P2: Firestore order_by('date') excludes any document that does not contain the date field, whereas the previous __name__ ordering returned every document. Reports written before the date field existed, or written by any path that does not set it, would silently disappear from the admin report-dates listing without erroring. The PR description itself notes historical production coverage is unverified — confirm/backfill the field on existing feedback_reports documents (or keep __name__ ordering) before shipping this.
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/database/feedback.py, line 397:
<comment>Firestore `order_by('date')` excludes any document that does not contain the `date` field, whereas the previous `__name__` ordering returned every document. Reports written before the `date` field existed, or written by any path that does not set it, would silently disappear from the admin report-dates listing without erroring. The PR description itself notes historical production coverage is unverified — confirm/backfill the field on existing `feedback_reports` documents (or keep `__name__` ordering) before shipping this.</comment>
<file context>
@@ -394,7 +394,7 @@ def list_report_dates(limit: int = 30) -> List[str]:
get_firestore_client()
.collection(FEEDBACK_REPORTS_COLLECTION)
- .order_by(_DOCUMENT_ID_FIELD, direction='DESCENDING')
+ .order_by('date', direction='DESCENDING')
.limit(limit)
.stream()
</file context>
| if isinstance(node, ast.Assign) and resolve(node.value) in targets: | ||
| for target in node.targets: | ||
| if isinstance(target, ast.Name): | ||
| imports[target.id] = resolve(node.value) |
There was a problem hiding this comment.
P2: discover_callers misses annotated aliases, so a new caller can bypass the witness completeness gate. Handle ast.AnnAssign aliases alongside ast.Assign before resolving calls.
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/support/firestore_conversation_profiles.py, line 174:
<comment>`discover_callers` misses annotated aliases, so a new caller can bypass the witness completeness gate. Handle `ast.AnnAssign` aliases alongside `ast.Assign` before resolving calls.</comment>
<file context>
@@ -171,7 +171,7 @@ def resolve(node):
for node in ast.walk(tree):
- if isinstance(node, ast.Assign) and resolve(node.value) in TARGETS:
+ if isinstance(node, ast.Assign) and resolve(node.value) in targets:
for target in node.targets:
if isinstance(target, ast.Name):
</file context>
| if isinstance(node, ast.Assign) and resolve(node.value) in targets: | |
| for target in node.targets: | |
| if isinstance(target, ast.Name): | |
| imports[target.id] = resolve(node.value) | |
| assignment_targets = [] | |
| if isinstance(node, ast.Assign): | |
| assignment_targets = node.targets | |
| value = node.value | |
| elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): | |
| assignment_targets = [node.target] | |
| value = node.value | |
| else: | |
| continue | |
| if value is not None and resolve(value) in targets: | |
| for target in assignment_targets: | |
| if isinstance(target, ast.Name): | |
| imports[target.id] = resolve(value) |
| _OVERRIDE_KEYS = {'collectionGroup', 'fieldPath', 'ttl', 'indexes'} | ||
| _INDEX_KEYS = {'queryScope', 'order', 'arrayConfig'} | ||
| _LIVE_INDEX_KEYS = {'queryScope', 'apiScope', 'fields', 'name', 'state'} | ||
| _LIVE_FIELD_KEYS = {'fieldPath', 'order', 'arrayConfig'} |
There was a problem hiding this comment.
P2: The shared reconciler cannot preserve existing Firestore vectorConfig or searchConfig field indexes: validation rejects those modes, and patch construction would omit them. Preserve these non-serving modes in the validated patch rather than blocking or deleting them.
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_field_indexes.py, line 42:
<comment>The shared reconciler cannot preserve existing Firestore `vectorConfig` or `searchConfig` field indexes: validation rejects those modes, and patch construction would omit them. Preserve these non-serving modes in the validated patch rather than blocking or deleting them.</comment>
<file context>
@@ -0,0 +1,689 @@
+_OVERRIDE_KEYS = {'collectionGroup', 'fieldPath', 'ttl', 'indexes'}
+_INDEX_KEYS = {'queryScope', 'order', 'arrayConfig'}
+_LIVE_INDEX_KEYS = {'queryScope', 'apiScope', 'fields', 'name', 'state'}
+_LIVE_FIELD_KEYS = {'fieldPath', 'order', 'arrayConfig'}
+_OPERATION_RESOURCE = re.compile(
+ r'^projects/(?P<project>[^/]+)/databases/(?P<database>[^/]+)/operations/(?P<operation>[^/]+)$'
</file context>
| def visit(node, owners=()): | ||
| if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): | ||
| owners = (*owners, node) | ||
| if isinstance(node, (ast.Call, ast.Name, ast.Attribute)): |
There was a problem hiding this comment.
P3: visit double-counts references: a single worker.fn(...) call record the target twice (once via Call.func, once when the recursion revisits the Attribute/Name child) and also emits a separate key for the base module name. The references counter becomes inflated and inconsistent between call forms (qualified=2, bare-name=1), so the documented count is meaningless and any future count-based assertion on the guardrail's output will be unpredictable. Count each reference expression exactly once (e.g., handle Call/Name/Attribute in one pass and skip already-visited nodes, or only count Call.func/args/keywords like discover_callers).
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/support/firestore_query_drivers.py, line 670:
<comment>`visit` double-counts references: a single `worker.fn(...)` call record the target twice (once via `Call.func`, once when the recursion revisits the `Attribute`/`Name` child) and also emits a separate key for the base module name. The `references` counter becomes inflated and inconsistent between call forms (qualified=2, bare-name=1), so the documented count is meaningless and any future count-based assertion on the guardrail's output will be unpredictable. Count each reference expression exactly once (e.g., handle `Call`/`Name`/`Attribute` in one pass and skip already-visited nodes, or only count `Call.func`/args/keywords like `discover_callers`).</comment>
<file context>
@@ -605,6 +611,108 @@ def discover_query_functions(database_root: str | Path) -> list[dict[str, Any]]:
+ def visit(node, owners=()):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
+ owners = (*owners, node)
+ if isinstance(node, (ast.Call, ast.Name, ast.Attribute)):
+ references = []
+ if isinstance(node, ast.Call):
</file context>
| identity = { | ||
| 'collection_group': self.collection_group, | ||
| 'scope': self.scope, | ||
| 'path_template': self.document_path_template, |
There was a problem hiding this comment.
P3: The newly added path_template key is part of the signature identity but the signature() docstring's "includes" list was not updated. Add "path template" to that enumeration so the documented and actual identity stay in sync.
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/support/firestore_shape_recorder.py, line 212:
<comment>The newly added `path_template` key is part of the signature identity but the `signature()` docstring's "includes" list was not updated. Add "path template" to that enumeration so the documented and actual identity stay in sync.</comment>
<file context>
@@ -207,6 +209,7 @@ def signature(self) -> str:
identity = {
'collection_group': self.collection_group,
'scope': self.scope,
+ 'path_template': self.document_path_template,
'filters': [{'field': f.field, 'operator': f.operator} for f in self.filters],
'filter_tree': _filter_tree_skeleton(self.filter_tree),
</file context>
| get_firestore_client() | ||
| .collection(FEEDBACK_REPORTS_COLLECTION) | ||
| .order_by(_DOCUMENT_ID_FIELD, direction='DESCENDING') | ||
| .order_by('date', direction='DESCENDING') |
There was a problem hiding this comment.
P3: The docstring above list_report_dates still describes the old behavior: "Document ids are ISO dates, so ordering by document id is the same as ordering by date." The query now orders by the date field, not __name__, so the comment no longer describes what the code does. Reword it to say the query orders by the persisted date field.
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/database/feedback.py, line 397:
<comment>The docstring above `list_report_dates` still describes the old behavior: "Document ids are ISO dates, so ordering by document id is the same as ordering by date." The query now orders by the `date` field, not `__name__`, so the comment no longer describes what the code does. Reword it to say the query orders by the persisted `date` field.</comment>
<file context>
@@ -394,7 +394,7 @@ def list_report_dates(limit: int = 30) -> List[str]:
get_firestore_client()
.collection(FEEDBACK_REPORTS_COLLECTION)
- .order_by(_DOCUMENT_ID_FIELD, direction='DESCENDING')
+ .order_by('date', direction='DESCENDING')
.limit(limit)
.stream()
</file context>
| ) | ||
| def test_reconciler_rejects_overrides_that_are_not_index_exemptions(override): | ||
| with pytest.raises(ValueError, match='only supports ttl=false with indexes='): | ||
| with pytest.raises(ValueError, match='ttl=false|collection-group'): |
There was a problem hiding this comment.
P3: Both parametrized overrides now raise inside firestore_field_indexes.expected_field_requirements (which expected_field_exemptions calls first), so the exemption tool's own 'only supports ttl=false with indexes=' branch is dead. The combined regex ttl=false|collection-group lets each case pass even when it is rejected by the wrong path — the old dead-branch message also contains 'ttl=false', so case 1 would still match without the shared validator ever running, and either case matches the other case's substring. Assert one expected message per case so a regression in either validation path is pinpointed.
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_field_exemptions.py, line 68:
<comment>Both parametrized overrides now raise inside `firestore_field_indexes.expected_field_requirements` (which `expected_field_exemptions` calls first), so the exemption tool's own 'only supports ttl=false with indexes=' branch is dead. The combined regex `ttl=false|collection-group` lets each case pass even when it is rejected by the wrong path — the old dead-branch message also contains 'ttl=false', so case 1 would still match without the shared validator ever running, and either case matches the other case's substring. Assert one expected message per case so a regression in either validation path is pinpointed.</comment>
<file context>
@@ -65,10 +65,31 @@ def test_expected_exemptions_are_the_manifest_empty_index_overrides():
)
def test_reconciler_rejects_overrides_that_are_not_index_exemptions(override):
- with pytest.raises(ValueError, match='only supports ttl=false with indexes='):
+ with pytest.raises(ValueError, match='ttl=false|collection-group'):
field_reconciler.expected_field_exemptions({'fieldOverrides': [override]})
</file context>
| Subscription plan contract: edit `config/plan_catalog.json`, then run `python scripts/generate_plan_catalog.py`; runtime code imports `config.plan_catalog`, never JSON or a copied plan set. Before review run `python scripts/generate_plan_catalog.py --check --base-ref origin/main`. Current Stripe amounts are import-blocked; follow `.github/agent-docs/plan-source-of-truth.md` and never publish or rebind a Price from an ordinary code-change workflow. | ||
|
|
||
| Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes after a manifest merge, then fails visibly if generated field exemptions are not serving. Single-field exemptions are a separate manual `field-exemptions` operation, prod-environment protected and exact-confirmed with `APPLY_FIRESTORE_FIELD_EXEMPTIONS`; it disables only the generated fields and verifies them afterward. Composite reconciliation remains create-only, so undeclared live composites are warnings rather than deletions. | ||
| Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes and additive collection-group field requirements (union-preserving; READY-gated) after a manifest merge, then fails until generated field exemptions serve. Destructive `indexes=[]` exemptions stay manual `field-exemptions`, prod-protected, exact-confirmed via `APPLY_FIRESTORE_FIELD_EXEMPTIONS`, disabling and verifying only generated fields. Composite reconciliation stays create-only; undeclared live composites warn, never delete. |
There was a problem hiding this comment.
P3: indexes=[] exemptions are intentionally non-serving, but this says the workflow succeeds only when they “serve”; describe the prod check as requiring them to be applied/disabled, and qualify that development skips it.
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/AGENTS.md, line 153:
<comment>`indexes=[]` exemptions are intentionally non-serving, but this says the workflow succeeds only when they “serve”; describe the prod check as requiring them to be applied/disabled, and qualify that development skips it.</comment>
<file context>
@@ -150,7 +150,7 @@ Backend runtime env contract: keep `backend/deploy/runtime_env.yaml` aligned wit
Subscription plan contract: edit `config/plan_catalog.json`, then run `python scripts/generate_plan_catalog.py`; runtime code imports `config.plan_catalog`, never JSON or a copied plan set. Before review run `python scripts/generate_plan_catalog.py --check --base-ref origin/main`. Current Stripe amounts are import-blocked; follow `.github/agent-docs/plan-source-of-truth.md` and never publish or rebind a Price from an ordinary code-change workflow.
-Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes after a manifest merge, then fails visibly if generated field exemptions are not serving. Single-field exemptions are a separate manual `field-exemptions` operation, prod-environment protected and exact-confirmed with `APPLY_FIRESTORE_FIELD_EXEMPTIONS`; it disables only the generated fields and verifies them afterward. Composite reconciliation remains create-only, so undeclared live composites are warnings rather than deletions.
+Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes and additive collection-group field requirements (union-preserving; READY-gated) after a manifest merge, then fails until generated field exemptions serve. Destructive `indexes=[]` exemptions stay manual `field-exemptions`, prod-protected, exact-confirmed via `APPLY_FIRESTORE_FIELD_EXEMPTIONS`, disabling and verifying only generated fields. Composite reconciliation stays create-only; undeclared live composites warn, never delete.
Update this map for inter-service call changes. For audio, transcription, conversation lifecycle (including advisory cross-device overlap links), speakers, or listen/pusher WebSocket changes, update `backend/docs/listen_pusher_pipeline.mdx` in the same PR; it owns the overlap env/wire contract.
</file context>
| Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes and additive collection-group field requirements (union-preserving; READY-gated) after a manifest merge, then fails until generated field exemptions serve. Destructive `indexes=[]` exemptions stay manual `field-exemptions`, prod-protected, exact-confirmed via `APPLY_FIRESTORE_FIELD_EXEMPTIONS`, disabling and verifying only generated fields. Composite reconciliation stays create-only; undeclared live composites warn, never delete. | |
| Firestore index boundary: backend deploy workflows run `reconcile_firestore_indexes.py --check-only` against `RUNTIME_GCP_PROJECT_ID` in an isolated approved-source job using dedicated read-only credentials. Auto-dev deploys accept only a first-attempt successful same-repository `Release Eligibility` proof for `main` whose `head_sha` still equals freshly fetched and checked-out `main`, then use that admitted SHA for every source-derived step; manual **deploy** mode accepts only an exact main SHA with the same successful proof. Traffic-only repair leaves that input empty and stays source-independent because it changes no source-derived runtime state. A failed gate writes and locally revalidates a short-lived, redacted create-only proposal before upload; backend deployment must never mutate the serving schema. `gcp_firestore_indexes.yml` automatically creates missing composite indexes and additive collection-group field requirements (union-preserving; READY-gated) after a manifest merge; its prod lane then fails until generated field exemptions are applied and verified. Destructive `indexes=[]` exemptions stay manual `field-exemptions`, prod-protected, exact-confirmed via `APPLY_FIRESTORE_FIELD_EXEMPTIONS`, disabling and verifying only generated fields. Composite reconciliation stays create-only; undeclared live composites warn, never delete. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Failure-Class: FC-undeclared-serving-query-index
Declare single-field COLLECTION_GROUP requirements in the Firestore registry, generate additive
fieldOverrides, and bring the serving-query guard to zero unserved shapes and zero unresolved uncertainties without a checked-in debt ledger. Keep the five existingindexes: []exemptions on their deliberately separate destructive, manual-only apply path.Production inventory versus missing requirements
Source: owner-provided read-only
gcloud firestore indexes fields list --project=based-hardware --format=jsonsnapshot, 2026-10-01 (.agent-brief/prod-field-overrides.json). No GCP operation was run for this PR.The first nine field configurations are adoption, not production mutations when their declared group modes are already READY. The five missing configurations are additive requirements. Generated additive entries retain COLLECTION ASCENDING/DESCENDING/CONTAINS; reconciliation never treats a narrower, already-serving collection configuration as permission to replace it.
What happens to queue sampling today
main._periodic_listen_finalization_reconcileinvokespublish_all_queue_oldest_ready_ageson the database executor after the finalization reconciliation work (default interval: 300 seconds)._sample_status_pageissues COLLECTION_GROUP status equality reads.sample_store_wide_oldest_ready_agescatches each exception, including FailedPrecondition, and omits the queue key.publish_sampled_queue_oldest_ready_agesskips missing keys. Consequently the failing queues get no new age observation and the outer periodic error log is not reached. A never-published series remains absent; a previously published gauge can retain its stale value. This is a source-path finding against the supplied field inventory, not a live production telemetry measurement.Union-preserving field updates
Firestore field updates replace the complete index configuration; supplying only the new group mode would delete omitted existing indexes. Local gcloud GA help explicitly confirms that repeated
--indexflags overwrite the list and omitted indexes are deleted. That installed GA command exposes order/array-config but no query-scope key, so this implementation shares the existing JIT QA Firestore Admin REST field-update seam rather than invent an unsupported CLI flag.For a missing requirement, resolve the live effective configuration, including ancestor defaults, re-read immediately before mutation, and PATCH
indexConfigwith the union of live modes and required additions. Preserve unrelated group modes and collection defaults; strip server-output metadata, never touch TTL, and fail closed on malformed, foreign, cyclic, unsupported, or unsafe transitioning configurations. Batch modes for the same field into one replacement. Already-ready fields are no-ops. Wait for the operation and final readiness.--dry-runand--check-onlynever mutate. The redacted readiness proposal includes missing/blocking field requirements and is locally validated against the exact source manifest.The JIT QA operator uses the same registry requirements and additive implementation instead of a QA-only conversations.status special case. The oracle captures effective field configs and raw field inventory alongside composite inventory.
Caller-bound profiles and race-proof guards
The guard is a property of the combined source tree, not equality to a regenerated global snapshot. This removes the stale-ledger and stale-whole-function-hash failure modes from back-to-back unrelated merges; it does not waive genuine query-domain or index changes.
Feedback root collection and ordering
The oracle preserves root-versus-subcollection identity in hydration and deduplication, querying real roots read-only with limit(1) only in
based-hardware-dev/jit-qa. Production root probes are refused even with the existing production read-only opt-in.list_report_datesorders by persisteddate DESCand still returns document IDs with the same limit.save_reportis the sole in-tree writer and persists mandatoryFeedbackReport.dateunder the identical document ID. Hermetic equivalence tests cover shuffled insertion, month/year boundaries, limits, empty collections, and replacement saves. Historical production documents were not inspected: the coordinator must confirm historical date-field coverage before promoting this helper change, or request that the root-path-only repair be retained until an isolated oracle proves the original name-only query served.Deploy path and approvals
Merge changes
firestore.indexes.json, automatically queuing.github/workflows/gcp_firestore_indexes.yml. The existing production GitHub Environment required-reviewer approval covers the additive field migration. After approval, the existing step order is dry-run, provision missing and wait for READY, then the production-only unapplied-exemption check. The same reconciler now adds the five missing group field indexes before that final exemption check; an exemption warning/failure does not undo the additive repair. Automatic development reconciliation also receives the declarations. The separate field-exemption operation remains manual-only, prod protected, and exact-confirmed with APPLY_FIRESTORE_FIELD_EXEMPTIONS.Backend deployment still uses read-only
--check-onlyand now requires the group field configurations as well as composites to be READY. This PR does not create indexes, deploy, or merge anything.Verification
From
backend/:PYTHON=.venv/bin/python bash test-preflight.sh: 18 checks passed, 0 failed.backend/.venv/bin/python backend/scripts/generate_firestore_indexes.py: generated manifest matches the registry (default check mode).backend/.venv/bin/python backend/scripts/firestore_query_coverage.py --check-ratchet: passes; QUERY_SPECS and the AST registration baseline are unchanged. AST registration debt is not the runtime unserved-shape guard and is not claimed to be zero here.BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/focused-review-files.txt bash test.shfrombackend/: 411 passed, 0 failed (356 shape-guard, 34 conversation-witness, 21 candidate/memory/vector-wiring tests). This covers the last sentinel correction and the unrelated-body-edit regression.OMI_PR_BODY_FILE=/Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/pr-body.md make preflight: 34 selected checks passed. After committing and mergingorigin/main(c0cffbc1b6b2) without conflicts,scripts/pr-preflight --lane local --pr-body-file /Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/pr-body.mdalso passes all 34 selected checks against committed HEAD. The 90-day failure-class guard-artifact ratchet reports its existing shallow-history SKIP; that historical window remains a full-history CI check, not locally verified.BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/post-merge-files.txt bash test.shfrombackend/: 494 passed, 0 failed (shape guard, conversation/candidate/memory witnesses, workflow contracts, and backend release-vector contracts). Generator, formatter, and diff whitespace checks pass; no test timing allowlist, marker, or threshold was relaxed.git diff --name-only origin/maincontains only this PR's 29 files.BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/same-module-wiring-files.txt bash test.shfrombackend/: 23 passed, 0 failed. Only the existingtick → leasebinding is non-serving internal wiring; future scheduler references inside that same module also require both declared branch indexes and a serving profile.Coordinator oracle confirmation plan
based-hardware-dev/jit-qaunder its existing confirmation boundary.index-oracleoperation against isolated JIT QA, retaining export/report hashes, composite inventory, raw/effective field inventory, and root identity.Product invariants affected
None.
Product invariants affected: None
Line count
Line-Count-Exception: backend/database/firestore_index_registry.py | 2052 -> 2109 | the registry remains the single declaration point for serving-query schema; typed additive field requirements must stay beside generated composite and exemption declarations
Generated with Devin
🤖 Generated with Claude Code