gendesign/tradein-mvp/backend/scripts/README.md
Light1YT 20b4a195b3 feat(tradein): Phase 2-3 of #582 — backfill houses + canonical reverse audit
Builds on Phase 1 audit infra (PR #583). Forward-geocode 4141 houses
без coords + reverse audit 4452 already-geocoded houses через Yandex
Geocoder API. Verified mismatch 870м для «Малышева 125» — наш point
в другом квартале от реального здания.

Scripts (new):
- `backfill_house_coords.py` (619 LOC) — driver:
  * Forward mode: UPDATE houses SET lat/lon когда precision ∈ {exact, number}
  * `--audit-only`: reverse геокод + distance check, flag >50м как mismatch
  * Per-row SAVEPOINT, idempotent через UNIQUE (house_id, audit_batch)
  * EKB locality bias (ll=60.6122,56.8389, spn=0.6,0.4)
  * Rate-limit 50ms между запросами, 25k/день квота Yandex покрывает 8.5k houses

- `_yandex_reverse.py` (+123 LOC) — added `forward_via_api()`,
  precision/kind в YandexReverseResult dataclass

- `audit_address_sample.sql` (-7 +47) — FIX: убрана зависимость от FDW
  `gendesign_ekb_districts_geom` (нет на проде). Простой
  `ORDER BY random()` без district stratification. Bind-param контракт
  сохранён (`:limit_per_district` * 8 = 200 default).

Tests:
- `test_backfill_house_coords.py` (510 LOC) — 20 tests: request shape,
  precision filter, UPDATE shape, backfill happy/imprecise/no_match/error,
  audit ok/mismatch/no_match, resumability, missing-key exit, mode routing
- Existing `test_audit_address_mismatch.py` still green
- 39/39 pass, ruff clean

Decisions (см. PR body):
- Precision filter = {exact, number} only (street/range/near → audit-imprecise)
- Mismatch threshold 50м (consistent с Phase 1 report)
- API-only (no Playwright fallback) — exit если key missing

Closes #582 (Phase 2-3 portion; Phase 1 was #583)
2026-05-27 11:30:25 +05:00

4.3 KiB
Raw Blame History

tradein-mvp/backend/scripts/

Ops scripts that touch the production database directly. Run via python -m scripts.<name> from the backend/ working directory after uv sync.

All scripts are idempotent / resumable where they write — re-running the same --batch label skips already-processed rows (UNIQUE constraints in target tables). Failures inside a per-row loop never roll back the outer transaction; each row is wrapped in a SAVEPOINT (db.begin_nested()) per .claude/rules/backend.md.


Address audit + backfill (issue #582)

End-to-end address quality pipeline. Three scripts, two helpers, two SQL files.

audit_address_mismatch.py — Phase 1 baseline (PR #583)

Stratified-sample audit (200 EKB houses) comparing houses.address vs Yandex Geocoder reverse lookup. Writes one row per house into address_mismatch_audit with the snapped point + canonical address + distance.

DATABASE_URL=postgresql+psycopg://... \
YANDEX_GEOCODER_API_KEY=... \
uv run python -m scripts.audit_address_mismatch \
    --batch 2026-05-25_run1 \
    --limit-per-district 25

Mode auto picks API if the key is set, otherwise Playwright (CAPTCHA-aware, 4-7s sleep between calls). API tier free is 25k req/day → 200-row sample takes ~10s with no quota concern.

Report:

psql "$DATABASE_URL" -v batch='2026-05-25_run1' \
    -f scripts/address_audit_report.sql

backfill_house_coords.py — Phase 2-3 (PR for #582)

Two modes (--audit-only flag switches between them):

Backfill (default) — forward-geocode houses.address for the ~4141 rows WHERE lat IS NULL OR lon IS NULL. Only writes back if Yandex returns precision='exact' or 'number' (skips street-only / locality matches). Each processed row gets an address_mismatch_audit entry with status backfill / imprecise / no_match / error.

DATABASE_URL=postgresql+psycopg://... \
YANDEX_GEOCODER_API_KEY=... \
uv run python -m scripts.backfill_house_coords \
    --batch 2026-05-27_backfill

Expected duration (~4141 rows, 50ms between calls, ~250ms RTT per request): 20-25 min. Expected output split (rough baseline from Phase 1 numbers):

Status Approx rows What it means
backfill ~3.3k3.7k UPDATE landed, lat/lon now populated
imprecise ~300500 Match returned but precision too low — needs review
no_match ~100300 Yandex couldn't resolve; address probably mangled
error <50 HTTP errors / timeouts — re-run picks them up

Audit-only — reverse-geocode the ~4452 houses WITH coords, write audit rows with status ok (≤50m) / mismatch (>50m) / no_match / error. Does NOT modify the houses table.

uv run python -m scripts.backfill_house_coords \
    --batch 2026-05-27_audit --audit-only

Combined budget for both phases (~8.6k requests) is well under the 25k/day Geocoder free tier.

Common ops

Canary first — run with --limit 100 and inspect the audit table before letting the full job loose:

uv run python -m scripts.backfill_house_coords \
    --batch canary_$(date +%F) --limit 100
psql "$DATABASE_URL" -c "
  SELECT audit_status, COUNT(*)
    FROM address_mismatch_audit
   WHERE audit_batch = 'canary_$(date +%F)'
   GROUP BY audit_status;
"

Resume after crash / quota hit — same --batch label, the UNIQUE (house_id, audit_batch) index skips finished rows:

uv run python -m scripts.backfill_house_coords --batch 2026-05-27_backfill
# ... interruption ...
uv run python -m scripts.backfill_house_coords --batch 2026-05-27_backfill
# logs: "resuming batch 2026-05-27_backfill: N rows already processed"

Helpers (not entry points)

  • _yandex_reverse.pyforward_via_api(), reverse_via_api(), reverse_via_playwright(), YandexReverseResult dataclass. Both API paths share _parse_api_payload because Yandex's forward/reverse envelopes have the same shape.
  • audit_address_sample.sql — random sample for the Phase 1 audit (used by audit_address_mismatch.py).
  • address_audit_report.sql — psql-driven post-run summary (p50/p75/p95 distance, top-20 outliers, per-district breakdown).