xai / grok-4.7-efficient / high / high effort preferred over deepseek / deepseek-flash / none / unknown effort · clear win.
Primary judge: Sol 6.1, requested Low. Effective provider effort and internal attempts were not verified. A close win is still a scored preference; it does not establish a material defect.
Reviewed public evidence
Task goal
Trace inspection filtering and matching from frontend request through backend predicate construction. Identify a concrete parity or data-integrity risk (including nulls, ranges, or combined filters) where the visible result set can diverge from intended semantics; show the precise path and propose a minimal correction and boundary regression cases.
xai / grok-4.7-efficient / high / high effort answer
The sequential SQL match and the Python mirror disagree on whitespace-only operators, so the same inspection can merge on one path and insert a duplicate on the other. The supplied frontend hook never builds a filter or match predicate.
**Conclusion.** `find_existing_inspection` and `InspectionKeys.matches_row` are documented as the same strict match, but a stored `performed_by` of only spaces is missing in Python and present in SQL. Confidence is high: both predicates and the intended rule are in `inspection_match.py`.
Intended rule: operator agrees case- and whitespace-insensitively, or is missing on either side. `normalize_operator` (lines 48–55) defines missing as null, `''`, or whitespace-only after `strip()`, and the comment says that definition was extracted so the bulk and sequential paths cannot drift. `matches_row` (lines 129–134) uses it: if the row operator normalizes to `None`, it returns `True`.
The sequential predicate does not:
```244:249:[REDACTED: private project name]/backend/app/services/inspection_match.py
AND (
performed_by IS NULL
OR performed_by = ''
OR CAST(:op AS text) IS NULL
OR LOWER(TRIM(performed_by)) = LOWER(TRIM(CAST(:op AS text)))
)
```
Incoming operator is normalized before bind (line 213), so a whitespace-only *request* becomes NULL and both sides accept. The column side is not normalized. `performed_by = ' '` fails `IS NULL` and `= ''`. `TRIM` yields `''`, which is not equal to a real operator, so SQL returns no row. `matches_row` treats that column as missing and accepts.
Trigger: same `municipality_id`, `project_id`, `asset_id`, UTC date, and `camera_direction`; `deleted_at` null; stored `performed_by = ' '`; incoming operator `'Alice'`. Sequential path returns `None` and inserts another canonical row. Chunk filtering and in-chunk dedup via `matches_row` treat them as one inspection. Visible identity of the inspection set then depends on which path ran.
Minimal correction: treat trimmed-empty `performed_by` as missing, matching `normalize_operator` for ordinary spaces (the equality branch already uses `TRIM`):
```sql
AND (
performed_by IS NULL
OR TRIM(performed_by) = ''
OR CAST(:op AS text) IS NULL
OR LOWER(TRIM(performed_by)) = LOWER(TRIM(CAST(:op AS text)))
)
```
Boundary cases (both paths must agree):
- `' '` vs `'Alice'` → match (fails today in SQL only)
- `' '` vs null → match
- `''` vs `'Alice'` → match
- null vs `'Alice'` → match
- `'Alice'` vs `' alice '` → match
- `'Alice'` vs `'[REDACTED: person name]'` → no match
- `'Alice'` vs null → match
- `'\tAlice'` vs `'Alice'` → still diverges after the minimal fix: Python `strip()` removes tabs and other Unicode whitespace; PostgreSQL `TRIM` removes only U+0020 spaces
**Filter path (separate, same packet).** `useInspectionData.ts` only loads review-boot and `inspection.json`. It does not send `InspectionFilterSpec`. Predicate construction is `apply_inspection_filters`. A second result-set footgun is in that function, not on a frontend request: empty `asset_id_in` is forced to `sa_false()` because the same file says `in_([])` silently drops the clause (lines 144–150), but empty `asset_type_ids` is passed straight to `Asset.asset_type_id.in_(...)` (lines 141–142). An empty type list therefore drops the type constraint and returns every inspection allowed by the other predicates, instead of none. Guard it the same way as `asset_id_in`. Viewport bounds are inclusive and reject null centroids; an inverted or antimeridian box (`min_lon > max_lon`) is unsatisfiable. Whether callers can send that box is outside this packet.
**Alternatives discarded.** Direction null-safety in the sequential SQL (`IS NOT DISTINCT FROM`) matches Python `!=` for `None`. The hazard is only if `hard_key` (which includes nullable `direction`) is later used in SQL tuple `IN`, where `NULL = NULL` is unknown. That caller is not in the packet. `inspection_type_id` omitted from the key is documented intent, not drift. Naive `astimezone(timezone.utc)` versus `parse_inspection_datetime`’s `replace(tzinfo=UTC)` can shift the date, but only if a naive value reaches `inspection_candidate_keys` / `matches_row`; those callers are outside the packet. `project_id` winning over `in_project` is explicit `if/elif`, not an accidental widen. Review-pack trim checks in the hook are consistent with each other and are not filter predicates.
**Missing evidence.** `InspectionFilterSpec`, the `/inspections/query` router, the bulk `hard_key` probe, and the SQLAlchemy version are outside the packet. Consequence: empty `asset_type_ids` is a definite clause-drop if `[]` reaches `apply_inspection_filters`, but this snapshot cannot show that the API accepts `[]`. The operator divergence does not depend on those files.
**Next action.** Add one differential case, stored `performed_by = ' '` against incoming `'Alice'`, asserting `find_existing_inspection` and `matches_row` both match; then change the SQL empty check to `TRIM(performed_by) = ''`. Separately, mirror the `asset_id_in` empty-list `sa_false()` guard for `asset_type_ids`.deepseek / deepseek-flash / none / unknown effort answer
# Inspection filter/matching parity and data-integrity analysis
## 1. Conclusion with supporting evidence
**Two concrete divergences are established by the supplied evidence: (A) a boundary/range risk in `viewport_bbox` centroid filtering, and (B) a combined-filter null/range semantic hole in the inspection datetime match soft-time rule. A stronger candidate — a frontend/backend filter parity gap — is not established by this packet, because the frontend file (`useInspectionData.ts`) contains no list-filter request path at all.**
### Finding A — Viewport bbox uses inclusive comparisons with no range validation (data-integrity risk)
Location: `inspection_filter_pipeline.py:181-190`.
```python
if spec.viewport_bbox is not None:
bbox = spec.viewport_bbox
stmt = (
stmt.where(Asset.centroid_lng.is_not(None))
.where(Asset.centroid_lat.is_not(None))
.where(Asset.centroid_lng >= bbox.min_lon)
.where(Asset.centroid_lng <= bbox.max_lon)
.where(Asset.centroid_lat >= bbox.min_lat)
.where(Asset.centroid_lat <= bbox.max_lat)
)
```
Observations grounded in the packet:
- Nulls are handled correctly: both centroid coordinates must be non-null (`is_not(None)`), so null-centroid assets are excluded rather than matching. That is sound and is **not** a defect.
- The comparisons are inclusive on all four sides (`>=`/`<=`). A point exactly on `min_lon`/`max_lon`/`min_lat`/`max_lat` is included.
- There is **no validation** that `min_lon <= max_lon` or `min_lat <= max_lat`. If a caller supplies an inverted or degenerate box (e.g. a drag gesture that produces `min_lon > max_lon`, or antimeridian-crossing longitudes), the conjunction is unsatisfiable and the result set is silently empty — the visible result diverges from "the region the user selected." The pipeline builds the predicate without any guard or warning; `warnings` is not appended to here.
- Bounding-box edges are shared with adjacent tiles/regions. Because the filter is inclusive, a feature exactly on a shared edge is returned by **both** neighboring viewports. That is an intended-looking convention but is a genuine boundary-duplication risk when results from adjacent viewports are combined/counted.
The precise divergence path: frontend sends a bbox → `InspectionFilterSpec.viewport_bbox` → `apply_inspection_filters` step 9 → six `WHERE` clauses → empty set on inverted/degenerate input, or edge-double-count on shared edges. The pipeline does not distinguish "no assets in region" from "region is malformed."
### Finding B — Soft time-match rule accepts any time when one side is midnight, including back-to-back same-day inspections (data-integrity/merge risk)
Locations: `inspection_match.py:121-127` (Python) and `inspection_match.py:233-242` (SQL).
Both sides implement the same rule: a time match fails **only** when both sides carry a non-midnight time that differs. Consequently:
- If a stored row is midnight-UTC (date-only source) and an incoming record has a real time-of-day, they match regardless of time.
- If the incoming record is midnight-UTC, it matches any stored time on the same date.
The docstring (`lines 182-188`) states this is deliberate so date-only and full-timestamp sources merge. But the stated guard — "guards against back-to-back same-day inspections of the same asset by the same operator" (`lines 186-188`) — is only effective when **both** rows carry non-midnight times. Two inspections of the same asset on the same date by the same operator where the incoming record is midnight-UTC will **merge into one canonical row** even though they are physically distinct. This is a range/boundary semantics gap: the match treats midnight as a wildcard, not as a value, so the "same inspection" predicate is not antisymmetric across sources.
Additionally, `matches_row` (`lines 122-127`) is stated at `lines 99-110` to be a 1:1 mirror of the SQL predicate that "the differential test asserts the two agree on real rows." The packet contains a subtle parity hazard worth flagging as a **hypothesis, not a confirmed defect**: the Python uses `self.time_of_day is not None` (which is set to `None` only when the candidate's wall-clock is exactly midnight — `lines 155-162`) while the SQL independently compares `((:dt) AT TIME ZONE 'UTC')::time = TIME '00:00:00'`. These are equivalent by construction, so parity holds **provided** `inspection_candidate_keys` is the only constructor of `InspectionKeys`. If any caller constructs `InspectionKeys` directly with an inconsistent `time_of_day`, Python and SQL will diverge. The packet does not show such a caller; flagged as an unconfirmed risk.
## 2. Alternatives / discarded hypotheses / likely false positives
- **"`asset_id_in == []` silently drops the clause"** — *Already handled.* `lines 146-150` explicitly emit `sa_false()` for the empty-list sentinel, with a comment calling out SQLAlchemy's `in_([])` behavior. Not a defect.
- **"`asset_id_in=None` vs `[]` confusion"** — None means "no narrowing," `[]` means "match nothing." Semantics are correct and distinct.
- **"`nl_filter_group` compiles leniently and widens results"** — *Explicitly fixed.* `lines 56-88` document that inspections now use `compile_transient_condition_group`, which is strict/fail-closed (raises `UnknownFieldError`/`UnsafeFilterValue`), replacing the old `literal(True)` widening. Not a defect.
- **"Project narrowing has a null bug"** — `lines 133-138`: `project_id` set → equality; `in_project is True` → `is_not(None)`; `False` → `is_(None)`. `is True`/`is False` identity checks correctly avoid the truthiness trap of a nullable tri-state. Sound.
- **"Frontend/backend filter parity gap"** — **Not established.** `useInspectionData.ts` fetches `/review-pack/${inspectionId}/inspection.json` and `/inspections/${id}/review-boot` (`lines 21-23, 80`). It contains **no** list-query, no filter-spec construction, no bbox/filter params, and no inspection-list request. The declared frontend hook is a review-pack boot/loader, not the inspection-list filter path. There is therefore no visible frontend filter logic in this packet that can be compared against the backend predicate construction. Any claim of FE/BE filter divergence here would be invented; the real FE filter source is not in scope.
## 3. Missing evidence / dependencies and consequence
- The FE list-filter path is absent (see above). The dependencies list marks `../api/client`, `../api/queryKeys`, `../types/reviewData` as outside the packet; none of these carry the filter spec either. **Consequence:** I cannot confirm or deny the frontend half of the parity question. The backend predicate construction is analyzable; the frontend request construction is not.
- `InspectionFilterSpec` (`app.schemas.inspection_filter_spec.py`) is outside the packet. **Consequence:** I cannot verify whether `viewport_bbox` fields are validated (`min_lon <= max_lon`) at the schema boundary, nor confirm `asset_id_in`/`in_project` types. Finding A's severity depends on this; the pipeline itself applies no guard regardless.
- `observation_parent_filters.constrain_parent_by_observation_filters` and `filter_compiler.compile_filters` are outside the packet. **Consequence:** I cannot audit the combined `saved_filter_ids` + `observation_filter_ids` composition (the "combined filters" arm of the question) for null/range handling; only their call order (`lines 152-174`) is visible.
- `Asset.centroid_lng/lat` column types and SRID/antimeridian handling are outside the packet. **Consequence:** the antimeridian-edge case in Finding A is plausible but unverified.
- `entity_ingest._create_canonical_subject` (referenced at `inspection_match.py:32`) is outside the packet. **Consequence:** I cannot confirm the insert path uses identical normalization to `inspection_candidate_keys`, which Finding B's merge risk depends on.
## 4. Minimal corrections and boundary regression cases
**Finding A (bbox):**
- Minimal correction: add a guard in step 9 before building the clauses — if `bbox.min_lon > bbox.max_lon` or `bbox.min_lat > bbox.max_lat`, return the `sa_false()` sentinel (or raise a 422 at the schema layer) rather than emitting an unsatisfiable conjunction, and append a structured warning. Prefer schema-level validation in `InspectionFilterSpec` so callers get a 422.
- Regression cases: (i) `min_lon == max_lon` and `min_lat == max_lat` (point box) returns exactly features at that point; (ii) inverted `min_lon > max_lon` returns empty **with a warning**, not a silent empty; (iii) feature exactly on `min_lon`/`max_lon`/`min_lat`/`max_lat` is included (pins inclusive convention); (iv) asset with `centroid_lng IS NULL` is excluded; (v) antimeridian-crossing box behavior is documented/decided.
**Finding B (datetime match):**
- Minimal correction: decide and document whether a midnight-UTC candidate is a wildcard or a literal time. If back-to-back same-day inspections must never merge, add a tie-breaker (e.g. require equal operator **and** treat midnight as a value when the stored row is non-midnight), or include `inspection_type_id`/a source discriminator. At minimum, keep `matches_row` and the SQL predicate change-coupled by adding a regression test that authors a midnight-UTC candidate and a non-midnight stored row for the same asset/date/operator and asserts the intended outcome on both paths.
- Regression cases: (i) stored non-midnight `08:00`, candidate midnight, same asset/date/operator → assert agreement between `matches_row` and SQL; (ii) stored `08:00`, candidate `09:00`, same asset/date/operator → must NOT match (guard holds); (iii) stored midnight, candidate midnight → matches; (iv) `camera_direction` null vs null and null vs `'N'` (`IS NOT DISTINCT FROM`) both covered; (v) operator `''`/whitespace-only collapses to `None` on both `normalize_operator` and the SQL `performed_by = ''` branch.
**Finding B, parity hypothesis:** add a constructor-level test asserting `InspectionKeys(time_of_day=...)` is only produced via `inspection_candidate_keys`, so the Python/SQL mirror cannot be broken by direct construction.
## Confidence
- Finding A (inclusive bbox, null handling, missing range validation): **high** for what the code does; **medium** for severity, because schema-level validation is outside the packet.
- Finding B (midnight-as-wildcard merge risk): **high** that the rule accepts cross-time matches when one side is midnight; **medium** that this produces an unintended merge in practice, because the insert path is outside the packet.
- FE/BE filter-parity gap: **cannot be established** from this packet; the declared FE file is a review-pack loader, not a list-filter path.
- `matches_row`/SQL drift: **unconfirmed risk only**.Primary judge's stated reason
A provides a directly actionable, source-demonstrated parity repair and a reproducer, whereas B's main recommendations depend on unestablished requirements or alter deliberate matching semantics. This is a clear task-relevant advantage, not merely a forced slight preference, despite A's incorrect secondary finding. Actual duplicate insertion and user-visible effects remain conditional on callers outside the packet.
This reason is the judge's assessment. No independent factual-defect finding is asserted by this record.
Battle wave: 1a629e2d-f9fa-4128-8962-e007165c19b0. Pair: brp1_d0fb36dbc2f9181c64b29248faa38c134770ddd8faccbd44ff05f90bf1826649. A separate independent review is required before calling a concern a verified factual defect. Judge disagreement is not recorded here.