Skip to content

fix(backend): declare single-field collection-group indexes and bring Firestore index debt to zero - #20161

Merged
Git-on-my-level merged 4 commits into
mainfrom
lane/idx-field-overrides
Oct 1, 2026
Merged

Git-on-my-level merged 4 commits into
mainfrom
lane/idx-field-overrides

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Oct 1, 2026 •

Copy link
Copy Markdown
Member

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 existing indexes: [] 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=json snapshot, 2026-10-01 (.agent-brief/prod-field-overrides.json). No GCP operation was run for this PR.

Collection group Field Required COLLECTION_GROUP modes Snapshot state
conversations id ASCENDING Already READY
conversations source ASCENDING Already READY
conversations status ASCENDING Already READY
fair_use_events case_ref ASCENDING, DESCENDING Already READY
fcm_tokens app_version ASCENDING, DESCENDING Already READY
fcm_tokens token ASCENDING Already READY
llm_usage date ASCENDING Already READY
memories tags CONTAINS Already READY
processing_memories created_at ASCENDING Already READY
candidate_integration_outbox status ASCENDING Missing
chat_first_proactive_intents delivery_state ASCENDING Missing
memory_outbox status ASCENDING Missing
projection_repairs status ASCENDING Missing
task_recurrence_inbox status ASCENDING Missing

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_reconcile invokes publish_all_queue_oldest_ready_ages on the database executor after the finalization reconciliation work (default interval: 300 seconds). _sample_status_page issues COLLECTION_GROUP status equality reads. sample_store_wide_oldest_ready_ages catches each exception, including FailedPrecondition, and omits the queue key. publish_sampled_queue_oldest_ready_ages skips 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 --index flags 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 indexConfig with 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-run and --check-only never 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

  • Candidate list and suggested-surface profiles require a non-null account generation; the suggested surface fixes status=None. Real route arguments are observed in tests.
  • Historical memory metadata reads have no categories or dates; the legacy scoring caller retains its fixed default profile. Actual adapter/legacy caller arguments are checked against those domains.
  • The vector-repair worker remains an explicit non-serving profile, with pending and expired-lease query coverage retained. A separate wiring sentinel prevents a scheduler/router/host registration from converting the unwired seam into serving work without both its index coverage and a serving profile.
  • Remove the known-gaps snapshot: every serving capture must be served and have no unresolved uncertainty. There is no ledger to prune after an unrelated index declaration merges.
  • Replace whole-function caller hashes with named runtime caller witnesses and fresh AST reference completeness checks. Non-query edits no longer stale a caller fingerprint. New callers or widened query arguments must acquire a witness/profile and index coverage; AST is detection only, not query-shape construction.

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_dates orders by persisted date DESC and still returns document IDs with the same limit. save_report is the sole in-tree writer and persists mandatory FeedbackReport.date under 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-only and 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/:

BACKEND_UNIT_TEST_FILE_LIST=/Volumes/Ephemeral/scratch/worktrees/omi/omi-lane-idx-field-overrides-upstream-keep-clean/.agent-brief/final-test-files.txt bash test.sh
  • All 26 requested/relevant files: 1,187 passed, 0 failed, 3 pre-existing marker deselections. The selection includes every manifest-reading test, the new runtime caller/field tests, and queue/helper-path regressions. The log contains 26 per-file summaries; this count includes the 132 oracle tests.
  • 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.
  • Final focused review rerun: 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.sh from backend/: 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 merging origin/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.md also 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.
  • Post-merge gate: 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.sh from backend/: 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/main contains only this PR's 29 files.
  • Same-module wiring hardening: 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.sh from backend/: 23 passed, 0 failed. Only the existing tick → lease binding is non-serving internal wiring; future scheduler references inside that same module also require both declared branch indexes and a serving profile.
  • The bounded pre-push gate passed on the final pushed revision, including all 34 selected PR checks, backend typecheck (0 errors; existing warnings), 15 runtime-image source-closure contracts, selected backend tests, and pinned formatting. No hooks were bypassed.
  • No live Firestore/GCP command or API request, production data inspection, index creation, deploy, or upstream PR merge was performed.

Coordinator oracle confirmation plan

  1. Review and approve the separate schema workflow only after merge; wait for all five missing production field configurations to reach READY. Do not use backend deploy as a schema writer.
  2. Use the fixed JIT QA operator to reconcile the same registry into based-hardware-dev/jit-qa under its existing confirmation boundary.
  3. Export runtime shapes from the merged source. Run the existing index-oracle operation against isolated JIT QA, retaining export/report hashes, composite inventory, raw/effective field inventory, and root identity.
  4. Require a verified empty-group planner probe, zero serving unserved outcomes, zero query errors, zero rule bugs, and no unresolved serving uncertainty. Keep explicit non-serving vector-repair findings separate; they are not deploy permission.
  5. Confirm feedback saved-date/ID coverage and latest-date equivalence before production code promotion. No live oracle or historical production verification was run by this lane.

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

Git-on-my-level and others added 2 commits October 1, 2026 18:04
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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 1, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-01T12:57:06.527089Z 59c259b New commits
ℹ️ 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" or "@codex security review".

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]>

@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.

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_dates now orders by date, which excludes reports without that field and can hide older reports from results — include or otherwise account for documents missing date.
  • In backend/tests/support/firestore_conversation_profiles.py, discover_callers misses annotated aliases, allowing a new caller to bypass the witness completeness gate — handle ast.AnnAssign aliases.
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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: 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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: 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>

Comment on lines +174 to 177
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: 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>
Suggested change
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'}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The 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)):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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')

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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'):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>

Comment thread backend/AGENTS.md
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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>
Suggested change
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.

@Git-on-my-level
Git-on-my-level merged commit 0a5bd79 into main Oct 1, 2026
54 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/idx-field-overrides branch October 1, 2026 13:02
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