Skip to content

Commit 15e84ef

Browse files
committed
Fix review findings: lifecycle guarantees under --parallel, transform aliasing, sys.path scoping, fetch-cache keying
Addresses four verified defects from code review of the build-lifecycle change: 1. Pre-transform snapshot for main_data_context (processor.py). raw_data aliased the same list/dicts later handed to transform_data(), so an in-place transform (e.g. renaming/popping the heavy content column) mutated the "raw" context the fragments phase receives, violating the documented pre-transform contract. raw_data is now deep-copied before the transform runs (only when a transform_data function exists, so transform-less resources pay nothing). 2. Single-load/single-fetch guarantee now holds under --parallel (processor.py, builder.py). _prewarm_fetches imported its own module instance and ran fetch_data there, while the sequential loop imported a second, virgin instance that the fragments phase received — losing module-level state and double-running module import side effects. ResourceProcessor now keeps a per-build module cache keyed by resource name, so prewarm and the sequential loop share one instance; the cache is cleared in build_database's finally via clear_build_caches(). 3. Scoped, lowest-precedence sibling-import path (processor.py). The sys.path.insert(0, resources_dir) was permanent and took precedence over stdlib/site-packages, so resources/openai.py self-imported on `import openai`, and any helper named after a lazily-imported package (statistics, csv, requests, ...) shadowed it process-wide. The dir is now APPENDED for the duration of the module load only and removed in a finally block. Sibling helper modules registered in sys.modules during the load are tracked and purged at build end, so same-named helpers in different projects no longer leak between builds in one process. Sibling imports must be at module top level (documented in CLAUDE.md). 4. Build-stable fetch-cache key (async_executor.py). The cache key included the live row count, so a user migrate_schema() that changes the row count between the schema-check fetch and the insert fetch caused a cache miss and a second fetch_data invocation in the same build (double-spending API budgets / advancing checkpoints). The key is now the resource name alone; the cache is cleared between builds. Rejected one finding (builder.py:157, "context flip enables duplicate fragment insertion in dedup-pattern resources"): the non-empty main_data_context is the intended, versioned behavior of 0.8.0 — the [] context under 0.7.0 was an artifact of the duplicate fetch this release removes, never a contract. Verified against the cited pdpc project: its fetch_fragments_data is a `return []` stub that ignores context, so no duplicate insertion occurs. Adds 5 regression tests (parallel module state, in-place transform, sys.path cleanup, cross-project sibling leak, migrate_schema row-count change). Full suite: 386 passed, 5 skipped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Cuh5eJDfVowgpp22s7siE1
1 parent 710ecbe commit 15e84ef

5 files changed

Lines changed: 353 additions & 26 deletions

File tree

‎CLAUDE.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ zeeker/{cli.py,commands/{assets.py,metadata.py,helpers.py}}
3333
`async fetch_data(existing_table)` (concurrent I/O)
3434
`fetch_fragments_data(existing_fragments_table, main_data_context=None)` (main_data_context avoids duplicate API calls)
3535
`transform_data()` (optional)
36-
Sibling imports work: resource modules can `import helper` for helpers in `resources/` (dir is on sys.path during load)
36+
Sibling imports work: resource modules can `import helper` for helpers in `resources/` — import at module top level only (dir is appended to sys.path just for the load, lowest precedence, then removed; stdlib/site-packages always win name clashes)
3737
`--setup-fts` is idempotent (safe on incremental `--sync-from-s3` builds)
3838

3939
## CRITICAL: Duplicate Handling
@@ -60,7 +60,7 @@ CRITICAL: Use `float` for potential decimals, consistent types, no type mixing
6060

6161
## Fragments
6262
`--fragments`: Two tables (main: metadata, fragments: chunks). Context passing via `main_data_context` avoids duplicate API calls.
63-
**Single-fetch lifecycle**: `fetch_data()` runs ONCE per build — the resource module is loaded once and its raw fetch output is threaded to the fragments phase as `main_data_context` (no module reload, no second fetch). Resources may rely on this (no PID sentinels/marker files needed).
63+
**Single-fetch lifecycle**: `fetch_data()` runs ONCE per build — the resource module is loaded once (also under `--parallel`) and its raw fetch output (pre-`transform_data`, snapshotted) is threaded to the fragments phase as `main_data_context` (no module reload, no second fetch). Resources may rely on this (no PID sentinels/marker files needed).
6464
**`fragments_on_skip = true`** (per-resource in zeeker.toml, opt-in): run the fragments phase even when `fetch_data()` returns no new rows (steady-state builds), with `main_data_context=[]`. Default (flag absent): fragments only run when new main rows were inserted (unchanged behavior).
6565
```python
6666
def fetch_fragments_data(existing_fragments_table, main_data_context=None):

‎packages/zeeker/tests/test_build_lifecycle.py‎

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,18 @@
88
builds (fetch_data returned no new rows); flag absent preserves old behavior
99
- --setup-fts is idempotent (safe on incremental builds)
1010
- sibling imports inside resources/ work without a manual sys.path shim
11+
- the single-load/single-fetch guarantee also holds under --parallel (module
12+
state written by fetch_data reaches the fragments phase)
13+
- main_data_context is a pre-transform snapshot (in-place transform_data
14+
cannot corrupt the fragments context)
15+
- resources/ is never left on sys.path, and sibling helper modules do not
16+
leak across projects via sys.modules
17+
- fetch_data still runs once per build when migrate_schema() changes the
18+
main table's row count between the schema check and the insert
1119
"""
1220

1321
import sqlite3
22+
import sys
1423
import textwrap
1524
from pathlib import Path
1625

@@ -358,6 +367,251 @@ def fetch_data(existing_table):
358367
assert len(rows) == 1
359368

360369

370+
def test_parallel_build_preserves_module_state_for_fragments(tmp_path):
371+
"""Under --parallel (max_parallel > 1) the module must still be imported
372+
exactly once, and module-level state written by fetch_data must reach the
373+
fragments phase (regression: pre-warm used to load a second, virgin
374+
module instance)."""
375+
import_counter = tmp_path / "import_count.txt"
376+
manager = _make_project(
377+
tmp_path,
378+
"""\
379+
[resource.docs]
380+
description = "Docs"
381+
fragments = true
382+
383+
[resource.other]
384+
description = "Second resource so the parallel pre-warm engages"
385+
""",
386+
)
387+
388+
docs_code = (
389+
COUNTER_HELPERS
390+
+ f"""
391+
IMPORT_COUNTER = {str(import_counter)!r}
392+
_bump(IMPORT_COUNTER) # module-level side effect: counts imports
393+
394+
_PENDING = [] # module-level bridge: populated by fetch_data, read by fragments
395+
396+
397+
def fetch_data(existing_table):
398+
rows = [{{"id": 1, "title": "Doc", "content": "alpha beta"}}]
399+
_PENDING.extend(rows)
400+
return rows
401+
402+
403+
def fetch_fragments_data(existing_fragments_table, main_data_context=None):
404+
# Deliberately ignores main_data_context: proves the SAME module
405+
# instance that ran fetch_data is handed to the fragments phase.
406+
return [{{"parent_id": r["id"], "text": r["content"]}} for r in _PENDING]
407+
"""
408+
)
409+
(tmp_path / "resources" / "docs.py").write_text(docs_code)
410+
(tmp_path / "resources" / "other.py").write_text(
411+
"""
412+
def fetch_data(existing_table):
413+
return [{"id": 1, "value": "x"}]
414+
"""
415+
)
416+
417+
build_result = manager.build_database(max_parallel=2)
418+
assert build_result.is_valid, build_result.errors
419+
420+
assert _read_count(import_counter) == 1, (
421+
"resource module must be imported exactly once per build, " "including under --parallel"
422+
)
423+
424+
conn = sqlite3.connect(tmp_path / "test_project.db")
425+
try:
426+
frag_count = conn.execute("SELECT COUNT(*) FROM docs_fragments").fetchone()[0]
427+
finally:
428+
conn.close()
429+
assert frag_count == 1, "module-level state from fetch_data must reach the fragments phase"
430+
431+
432+
def test_inplace_transform_does_not_corrupt_fragments_context(tmp_path):
433+
"""main_data_context must be the PRE-transform data even when
434+
transform_data mutates rows in place (regression: raw_data used to alias
435+
the list handed to transform_data)."""
436+
manager = _make_project(
437+
tmp_path,
438+
"""\
439+
[resource.docs]
440+
description = "Docs"
441+
fragments = true
442+
""",
443+
)
444+
445+
resource_code = """
446+
def fetch_data(existing_table):
447+
return [{"id": 1, "title": "Doc", "content": "alpha. beta."}]
448+
449+
450+
def transform_data(data):
451+
# Common in-place pattern: rename the heavy column before insert.
452+
for item in data:
453+
item["content_text"] = item.pop("content")
454+
return data
455+
456+
457+
def fetch_fragments_data(existing_fragments_table, main_data_context=None):
458+
if not main_data_context:
459+
return []
460+
# Reads the RAW (pre-transform) field, per the documented contract.
461+
return [
462+
{"parent_id": doc["id"], "text": part.strip()}
463+
for doc in main_data_context
464+
for part in doc["content"].split(".")
465+
if part.strip()
466+
]
467+
"""
468+
(tmp_path / "resources" / "docs.py").write_text(resource_code)
469+
470+
build_result = manager.build_database()
471+
assert build_result.is_valid, build_result.errors
472+
473+
conn = sqlite3.connect(tmp_path / "test_project.db")
474+
try:
475+
cols = {row[1] for row in conn.execute("PRAGMA table_info(docs)").fetchall()}
476+
frag_count = conn.execute("SELECT COUNT(*) FROM docs_fragments").fetchone()[0]
477+
finally:
478+
conn.close()
479+
assert "content_text" in cols and "content" not in cols, "transform must apply to main table"
480+
assert frag_count == 2, "fragments must be built from the pre-transform data"
481+
482+
483+
def test_resources_dir_not_left_on_sys_path(tmp_path):
484+
"""The resources/ directory must not remain on sys.path after a build
485+
(regression: a permanent sys.path.insert(0, ...) let resources/*.py
486+
shadow stdlib/site-packages for the whole process)."""
487+
manager = _make_project(
488+
tmp_path,
489+
"""\
490+
[resource.plain]
491+
description = "Plain resource"
492+
""",
493+
)
494+
(tmp_path / "resources" / "plain.py").write_text(
495+
"""
496+
def fetch_data(existing_table):
497+
return [{"id": 1}]
498+
"""
499+
)
500+
501+
build_result = manager.build_database()
502+
assert build_result.is_valid, build_result.errors
503+
504+
assert str(tmp_path / "resources") not in sys.path
505+
506+
507+
def test_sibling_modules_do_not_leak_across_projects(tmp_path):
508+
"""Two projects with a same-named helper module must each get their own
509+
helper (regression: sibling modules stayed in sys.modules under bare
510+
names, so the second project silently reused the first's helper)."""
511+
rows = {}
512+
for label in ("one", "two"):
513+
project_dir = tmp_path / f"project_{label}"
514+
project_dir.mkdir()
515+
manager = _make_project(
516+
project_dir,
517+
"""\
518+
[resource.uses_helper]
519+
description = "Uses a same-named sibling helper"
520+
""",
521+
)
522+
(project_dir / "resources" / "leak_probe_helper_zq.py").write_text(
523+
f"""
524+
VALUE = {label!r}
525+
"""
526+
)
527+
(project_dir / "resources" / "uses_helper.py").write_text(
528+
"""
529+
import leak_probe_helper_zq
530+
531+
532+
def fetch_data(existing_table):
533+
return [{"id": 1, "value": leak_probe_helper_zq.VALUE}]
534+
"""
535+
)
536+
537+
build_result = manager.build_database()
538+
assert build_result.is_valid, build_result.errors
539+
540+
conn = sqlite3.connect(project_dir / "test_project.db")
541+
try:
542+
rows[label] = conn.execute("SELECT value FROM uses_helper").fetchone()[0]
543+
finally:
544+
conn.close()
545+
546+
assert rows == {"one": "one", "two": "two"}
547+
assert "leak_probe_helper_zq" not in sys.modules
548+
549+
550+
def test_fetch_runs_once_despite_migrate_schema_row_change(tmp_path):
551+
"""fetch_data must run exactly once per build even when migrate_schema()
552+
changes the main table's row count between the schema-check fetch and the
553+
insert fetch (regression: the fetch cache was keyed on live row count)."""
554+
fetch_counter = tmp_path / "fetch_count.txt"
555+
phase_file = tmp_path / "phase2.flag"
556+
manager = _make_project(
557+
tmp_path,
558+
"""\
559+
[resource.docs]
560+
description = "Docs"
561+
""",
562+
)
563+
564+
resource_code = (
565+
COUNTER_HELPERS
566+
+ f"""
567+
FETCH_COUNTER = {str(fetch_counter)!r}
568+
PHASE_FILE = {str(phase_file)!r}
569+
570+
571+
def fetch_data(existing_table):
572+
_bump(FETCH_COUNTER)
573+
if Path(PHASE_FILE).exists():
574+
data = [{{"id": 3, "title": "c", "extra": 1.5}}]
575+
else:
576+
data = [{{"id": 1, "title": "a"}}, {{"id": 2, "title": "b"}}]
577+
if existing_table:
578+
existing_ids = {{row["id"] for row in existing_table.rows}}
579+
data = [d for d in data if d["id"] not in existing_ids]
580+
return data
581+
582+
583+
def migrate_schema(existing_table, migration):
584+
# Migration that changes the table's row count AND adapts the schema —
585+
# the row-count change must not cause a second fetch_data invocation.
586+
existing_table.db.execute("DELETE FROM docs WHERE id = 2")
587+
existing_table.db.conn.commit()
588+
existing_table.add_column("extra", float)
589+
return True
590+
"""
591+
)
592+
(tmp_path / "resources" / "docs.py").write_text(resource_code)
593+
594+
first = manager.build_database()
595+
assert first.is_valid, first.errors
596+
assert _read_count(fetch_counter) == 1
597+
598+
phase_file.write_text("go")
599+
600+
second = manager.build_database()
601+
assert second.is_valid, second.errors
602+
assert _read_count(fetch_counter) == 2, (
603+
"each build must invoke fetch_data exactly once, even when "
604+
"migrate_schema changes the row count mid-build"
605+
)
606+
607+
conn = sqlite3.connect(tmp_path / "test_project.db")
608+
try:
609+
ids = sorted(r[0] for r in conn.execute("SELECT id FROM docs").fetchall())
610+
finally:
611+
conn.close()
612+
assert ids == [1, 3]
613+
614+
361615
def test_sibling_import_in_resources(tmp_path):
362616
"""A resource module importing a sibling helper module in resources/ must
363617
load and build without a manual sys.path shim."""

‎packages/zeeker/zeeker/core/database/async_executor.py‎

Lines changed: 17 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,10 @@ def clear_prewarmed(self) -> None:
4040
"""Drop all pre-warmed overrides. Call between builds."""
4141
self._prewarmed.clear()
4242

43+
def clear_fetch_cache(self) -> None:
44+
"""Drop all cached fetch_data results. Call between builds."""
45+
self._fetch_cache.clear()
46+
4347
def call_fetch_data(
4448
self, fetch_data_func: Callable, existing_table: Optional[Table], resource_name: str = None
4549
) -> List[Dict[str, Any]]:
@@ -113,22 +117,24 @@ async def acall_fetch_data(
113117
def _generate_cache_key(self, resource_name: str, existing_table: Optional[Table]) -> str:
114118
"""Generate cache key for fetch_data results.
115119
120+
The key is the resource name alone — stable for the duration of a
121+
build. Keying on live table state (e.g. row count) would let an
122+
intermediate step that changes the table — such as a user-supplied
123+
migrate_schema() deleting rows between the schema-check fetch and
124+
the insert fetch — miss the cache and run fetch_data a second time
125+
in the same build, double-spending side effects (API budgets,
126+
checkpoints). The cache is cleared between builds by
127+
:meth:`clear_fetch_cache`.
128+
116129
Args:
117130
resource_name: Name of the resource
118-
existing_table: sqlite-utils Table object or None
131+
existing_table: sqlite-utils Table object or None (unused; kept
132+
for signature stability)
119133
120134
Returns:
121-
Cache key string combining resource name and table state
135+
Cache key string
122136
"""
123-
if existing_table is None:
124-
return f"{resource_name}_no_table"
125-
126-
try:
127-
table_count = existing_table.count
128-
return f"{resource_name}_table_{table_count}"
129-
except Exception:
130-
# If we can't get count, use basic key
131-
return f"{resource_name}_table_exists"
137+
return resource_name
132138

133139
def call_fetch_fragments_data(
134140
self,

‎packages/zeeker/zeeker/core/database/builder.py‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -207,8 +207,10 @@ def build_database(
207207
report.fatal_error = msg
208208

209209
finally:
210-
# Prevent stale pre-warmed data from leaking into a reused builder.
211-
self.processor.async_executor.clear_prewarmed()
210+
# Prevent per-build state (pre-warmed fetches, fetch cache,
211+
# loaded resource modules, sibling helper modules in
212+
# sys.modules) from leaking into a later build in this process.
213+
self.processor.clear_build_caches()
212214

213215
report.total_duration_s = time.perf_counter() - build_started
214216
return result

0 commit comments

Comments
 (0)