Files
brain-of-reese/tests/e2e/test_extensionless_import.py
T
ducoterra 2ac37455f0
Build and Push Containers / build-and-push-app (push) Successful in 1m45s
Build and Push Containers / build-and-push-db (push) Successful in 14s
phase: 167_api_payload_diet
All gates green. Final report:

**Verified (phase 167 final pass — all 6 tasks already in `complete/`)**
- Live re-measure of the headline criterion on the **1,000-doc live-replica corpus** (restored `data/bor_live_kb_replica.dump.sql` into a scratch DB `bor_audit`, alembic 0011→0027, dropped after; the shared dev DB was never touched): `GET /api/docs/tree` default depth=1 = **8,474 identity → 1,128 B with `Content-Encoding: gzip`** (< 40 KB bar; ~2 MB defect fixed), repeat load **304 / 0 bytes**; depth=8 265,147→23,515; node drill 20,844→1,065; `/api/docs` 246,366→45,104; `/api/documents/content` 892,124→60,776 (`LOOK`, accepted-with-why). Reproduces `AUDIT.md` to within 1 byte.
- Transport contracts proven live: `POST /api/chat` **no** `Content-Encoding` + frames arriving live + budget line `… enc=identity duration_ms=7380 stream=1`; HTML still `no-cache` with the `?v=` rewrite (and gzipped); A20 headers on 200 **and** 304; ETag identical across identity/gzip; `depth=0|9|abc`→422; anonymous tree/node→403; unknown folder/source→404 `unknown node`.

**Gates (all 100% green)**
- `uv run pytest` → **3980 passed**; `uv run pytest --cov=app --cov-report=term-missing` → **TOTAL 99%** (`compression.py`, `http_cache.py`, `response_budget.py` 100%; `api/docs.py` 99%, one defensive dedupe line).
- `uv run ruff check .` → All checks passed; `uv run pyright` → 0 errors.
- Phase + regression E2E **in isolation** (`--junitxml`, exit codes): `test_kb_tree_lazy_load` 11, `test_kb_tree` 8, `test_kb_tree_nav` 4, `test_navbar_refresh` 7, `test_document_dates` 6, `test_git_source_dates` 4, `test_sync_summary_visibility` 3, `test_table_ux_polish` 6, `test_sources_midstream_bug` 6, `test_ls_tree_drilldown` 3, `test_smoke` 3 — **0 failures/errors** (the earlier `-q -q` run had simply suppressed pytest's summary line).

**Documentation** — README.md + AGENTS.md reviewed in full (1,436 / 80 lines):
- Fixed (pre-existing, phase-167-exposed): README *Caching & deploys* claimed "One Starlette middleware (`app/core/caching.py`) applies the rule" while the section now describes three transport layers → rewritten to name caching/compression/http_cache, the real outermost→innermost order, and why `bytes=` is uncompressed.
- AGENTS.md rule 5 (UI Structure Check) gained the phase-167 clause: a lazily-drilled level keeps the current level rendered, its in-flight `role="status"` / `role="alert"`+Retry row lives in the same bounded scroll panel, and stat cards read server `totals` (never a walk of a depth-limited tree).
- Cross-checked and consistent: every `BOR_*` in `.env.example` is in the README table, every `Settings` field is documented, all 15 README-cited API routes exist in the app, no stale "one fetch / drill client-side" claim remains anywhere.

**Notable decisions / deviations**
- `compression.py` adds a documented `_RebufferSmallResponses` seam beyond the D1 sketch (the caching layer's `BaseHTTPMiddleware` re-framing otherwise defeats Starlette's `minimum_size` exemption and inflates tiny responses) — integration-pinned, math still Starlette's.
- A node-route **404 = vanished folder → honest reset to top level** (per `00_phase.md` D4/D6), not task-06's "alert + Retry"; 500 shows alert+Retry with the level preserved — both pinned, nothing weakened.
- Retrieval battery not measurable (shared E2E DB holds no corpus), but `git diff --name-only -- app/rag` is empty, so retrieval is unchanged by construction. `AUDIT.md` left byte-identical (it lives under `todo/`, off-limits to this pass); no git index/history commands run.

**Next pending phase:** none — `167_api_payload_diet` is the only entry in `.agents/phases/todo/`; the harness moves it to `complete/` and commits.
2026-10-08 21:23:49 -04:00

247 lines
11 KiB
Python

"""Phase 102 E2E (Playwright): extensionless files (``Dockerfile``,
``Containerfile``) sync when their name is a ``BOR_IMPORT_EXTENSIONS``
token — import → chunks → mock ``lite`` summary → drill-down tree →
viewer badge, plus the negative control and the anonymous gate.
The owner's defect: files without extensions never got synced, so
``Dockerfile`` / ``Containerfile`` were skipped even with
``dockerfile,containerfile`` in the env. Phase 102's rule: a suffix-less
file imports iff its lowercased FULL filename equals a token (exact
name, case-insensitive), the import ``formats=`` counter keys it by the
matched token, and the viewer badge is truthful (``dockerfile``, not
the generic ``text``).
The subject is the extensionless scope (``import_extensions=
"md,dockerfile,containerfile"``); the story-dedicated fixture
(``tests/fixtures/extensionless_kb/``) is seeded in-process against the
deterministic mock LLM — the phase-02/56 seeding-thread pattern — with
``Dockerfile`` / ``Containerfile`` carrying their own unique sentinels
and ``Makefile`` as the negative control (no token names it).
Run in isolation (DB must be up: ``podman compose up -d db``):
uv run pytest tests/e2e/test_extensionless_import.py -v --no-cov
DB isolation: the fixture's source name (``extensionless_kb``) is
distinctive — the suite never asserts on absolute row counts and
deletes the rows it creates in a ``finally`` (other suites' documents
stay untouched in the shared E2E database).
App-under-test scope pin (the phase-61 leak-guard pattern): the viewer
badge is rendered by the APP from its own ``get_settings().
import_extension_set`` (``GET /api/documents/content``), so the app
process must carry exactly the scope under test — a module-level
``BOR_IMPORT_EXTENSIONS`` override (process env ranks above the
operator's local gitignored ``.env`` when the ``app_server`` fixture
snapshots ``os.environ``). In isolation (AGENTS.md rule 9) the session
app is spawned by this file's first test, so the pin lands determinis-
tically.
Phase 97 adaptation: the catalog is the DRILL-DOWN TREE — the fixture's
files live at the SOURCE level (no subfolders), so a single drill
reaches every asserted row; the drill is the only change, the asserted
rows/links/modal are unchanged.
"""
from __future__ import annotations
import asyncio
import os
from collections.abc import Iterator
from pathlib import Path
from threading import Thread
from typing import Any
import pytest
from playwright.sync_api import Page, expect
from sqlalchemy import select
from app.config import Settings
from app.db import SessionLocal
from app.models import Document
from app.rag.importer import ImportSummary, import_sources
from app.rag.llm import LLMClient
from e2e.auth_helpers import login
from tests.e2e.mock_llm import TOKEN_RE
#: The app-under-test scope pin (see the module docstring) — exactly the
#: scope this suite proves, no matter what the operator's local ``.env``
#: carries. Must run before the session ``app_server`` fixture snapshots
#: ``os.environ`` (module import precedes fixture setup).
os.environ["BOR_IMPORT_EXTENSIONS"] = "md,dockerfile,containerfile"
REPO = Path(__file__).resolve().parents[2]
FIXTURES = REPO / "tests" / "fixtures" / "extensionless_kb"
SOURCE = FIXTURES.name # "extensionless_kb" — distinctive, never asserted by count
DOCKER_REL = "Dockerfile"
CONTAINER_REL = "Containerfile"
NOTES_REL = "notes.md"
MAKE_REL = "Makefile" # negative control — no token in the scope under test
DOCKER_SENTINEL = "DOCKERFILE-PROBE-SENTINEL-7a3e"
async def _import_fixtures(mock_port: int, extensions: str) -> ImportSummary:
kwargs: dict[str, Any] = {
"_env_file": None,
"llm_base_url": f"http://127.0.0.1:{mock_port}/v1",
"import_extensions": extensions,
}
settings = Settings(**kwargs) # pyright: ignore[reportCallIssue]
return await import_sources([FIXTURES], LLMClient(settings))
def _run_in_thread(coro: Any) -> Any:
"""Run a coroutine on a worker thread.
Playwright's sync API keeps an asyncio loop running on the test
thread, so ``asyncio.run`` cannot be called directly from a test
body.
"""
box: dict[str, Any] = {}
def runner() -> None:
try:
box["value"] = asyncio.run(coro)
except BaseException as e: # noqa: BLE001 — re-raised on the test thread
box["error"] = e
t = Thread(target=runner)
t.start()
t.join()
if "error" in box:
raise box["error"]
return box["value"]
def _delete_source_rows() -> None:
"""Delete every row of this suite's distinctive source (chunks
cascade with the document rows)."""
with SessionLocal() as db:
for doc in db.scalars(select(Document).where(Document.source == SOURCE)).all():
db.delete(doc)
db.commit()
def _drill(page: Page, *names: str) -> None:
"""Drill one level at a time (phase 97; phase 167: an UNCACHED level
costs exactly one /api/docs/tree/node fetch, a held level costs
nothing, and no click ever changes the URL): each name is the EXACT
text of the source/folder link at the current level."""
for name in names:
page.click(f'#folders-tbody a.folder-link:text-is("{name}")')
def _go_top(page: Page) -> None:
"""Back to the top level: the breadcrumb's top-level link (call
between drills only — the breadcrumb is hidden at the top)."""
page.locator("#kb-crumb a.kb-crumb-link").first.click()
def _summary_lines(path: str) -> tuple[str, str]:
"""(digest line, pointer line) of the stored phase-30 summary for a
fixture file — mirrors the mock ``SUMMARY_MODE`` branch (first 24
tokens of the document content) plus the code pointer line (the
``test_summary_in_viewer.py`` house helper)."""
content = (FIXTURES / path).read_text(encoding="utf-8")
digest = " ".join(TOKEN_RE.findall(content.lower())[:24])
expected = f"This document covers {digest}.\nSource: {SOURCE}/{path}"
digest_line, pointer_line = expected.split("\n", 1)
return digest_line, pointer_line
@pytest.fixture(autouse=True)
def extensionless_kb(mock_llm: int, db_ready: None) -> Iterator[ImportSummary]:
"""Seed the fixture with the extensionless scope
(``md,dockerfile,containerfile``) for one test and delete every row
it creates afterwards (DB isolation — see the module docstring)."""
_delete_source_rows() # idempotent: leftovers from a crashed run
summary = _run_in_thread(_import_fixtures(mock_llm, "md,dockerfile,containerfile"))
try:
yield summary
finally:
_delete_source_rows()
def test_admin_tree_lists_name_token_files_and_viewer_badge(
page: Page, app_url: str, extensionless_kb: ImportSummary
) -> None:
# The seed saw exactly the three in-scope files in their formats —
# the two extensionless build files walked by name token, chunked,
# and summarized; the Makefile negative control stayed out.
assert extensionless_kb.formats == {"dockerfile": 1, "containerfile": 1, "md": 1}
assert "unknown" not in extensionless_kb.formats
assert (extensionless_kb.added, extensionless_kb.errors) == (3, 0)
login(page, app_url) # phase 16: the catalog is admin-only
# All three fixture files live at the SOURCE level (no subfolders —
# one drill reaches them, phase 97).
_drill(page, SOURCE)
for name in (DOCKER_REL, CONTAINER_REL, NOTES_REL):
expect(page.locator("#docs-tbody tr", has_text=name)).to_have_count(1)
# The negative control: no token names Makefile exactly — absent.
expect(page.locator("#docs-tbody tr", has_text=MAKE_REL)).to_have_count(0)
# The Dockerfile row's path link opens the SAME-PAGE modal and its
# meta row shows the D3 badge (``dockerfile`` — not the generic
# ``text`` fallback) + the source badge + the stem title.
row = page.locator("#docs-tbody tr", has_text=DOCKER_REL)
link = row.locator("td:nth-child(2) a.doc-link")
expect(link).to_have_count(1)
expect(link).to_have_attribute("title", DOCKER_REL)
before = len(page.context.pages)
link.click()
assert len(page.context.pages) == before, "clicking a row link must not open a new tab"
expect(page.locator("#doc-modal-meta .doc-source-badge")).to_have_text(SOURCE)
expect(page.locator("#doc-modal-meta .format-badge")).to_have_text("dockerfile")
expect(page.locator("#doc-modal-title")).to_have_text(DOCKER_REL)
# Non-markdown content renders as escaped monospace text in a pre —
# the sentinel proves it is THIS document's content.
pre = page.locator("#doc-modal-content pre.doc-raw")
expect(pre).to_have_count(1)
expect(pre).to_contain_text(DOCKER_SENTINEL)
# The phase-30 summary line renders above the content (house
# assertion style — test_summary_in_viewer.py): the deterministic
# mock digest + the code pointer line, in the labeled panel.
digest_line, pointer_line = _summary_lines(DOCKER_REL)
panel = page.locator("#doc-modal .doc-summary")
expect(panel).to_have_count(1)
expect(panel).to_be_visible()
expect(panel).to_have_attribute("aria-label", "Summary")
expect(panel).to_contain_text(digest_line)
expect(panel).to_contain_text(pointer_line)
# Still on the Sources page: no navigation happened.
assert page.url == app_url + "/sources.html", f"navigated away: {page.url}"
def test_anonymous_sources_gate_and_no_api_docs(
page: Page, app_url: str, extensionless_kb: ImportSummary
) -> None:
"""A fresh anonymous context (function-scoped ``page`` = new
browser context, no cookies): the sign-in gate renders and the page
never calls ``/api/docs`` — the phase-16 pin, regression-checked
with the extensionless KB seeded; the API itself 403s anonymous
callers."""
api_docs_calls: list[str] = []
page.on(
"request",
lambda r: api_docs_calls.append(r.url) if "/api/docs" in r.url else None,
)
page.goto(f"{app_url}/sources.html")
# The gate, with its sign-in link — not a redirect.
gate = page.locator("#sources-gate")
expect(gate).to_be_visible()
expect(gate).to_contain_text("Sign in to view the full catalog")
expect(gate.locator("a[href='/login.html?next=/sources.html']")).to_have_count(1)
# Stat cards + table hidden…
expect(page.locator("#stat-cards")).to_be_hidden()
expect(page.locator("#docs-table")).to_be_hidden()
expect(page.locator("#sources-empty")).to_be_hidden()
# …and NO /api/docs call was ever made.
assert api_docs_calls == [], f"anonymous sources page called /api/docs: {api_docs_calls}"
# And the API gate itself: an anonymous GET /api/docs 403s (phase 16
# — the router sits behind require_admin).
assert page.request.get(f"{app_url}/api/docs").status == 403