Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(ingestion): stop one file from hanging or exhausting the parse (#4738)

Raghav Chamadiyaf36f2d90595b
diff --git a/packages/core/src/repowise/core/analysis/health/sql_complexity.py b/packages/core/src/repowise/core/analysis/health/sql_complexity.py
index fc813b781..da55d166b 100644
--- a/packages/core/src/repowise/core/analysis/health/sql_complexity.py
+++ b/packages/core/src/repowise/core/analysis/health/sql_complexity.py
@@ -25,7 +25,6 @@ none of it may move the surfaced defect score.
from __future__ import annotations
-import logging
import re
from typing import Any
@@ -177,13 +176,13 @@ def _statement_smells(text: str, dialect: str | None) -> list[PerfHit]:
if "{{" in text or "{%" in text:
return []
try:
- import sqlglot
from sqlglot import exp
except ImportError:
return []
- logging.getLogger("sqlglot").setLevel(logging.ERROR)
+ from repowise.core.ingestion.sql_parse import parse_sql
+
try:
- statements = sqlglot.parse(text, read=dialect, error_level=sqlglot.ErrorLevel.IGNORE)
+ statements = parse_sql(text, dialect=dialect)
except Exception:
return []
diff --git a/packages/core/src/repowise/core/ingestion/special_handlers.py b/packages/core/src/repowise/core/ingestion/special_handlers.py
index 2e14a3b2c..b22e61d55 100644
--- a/packages/core/src/repowise/core/ingestion/special_handlers.py
+++ b/packages/core/src/repowise/core/ingestion/special_handlers.py
@@ -393,23 +393,14 @@ def _parse_sql(file_info: FileInfo, source: bytes) -> ParsedFile:
def _extract_sql_symbols(file_info: FileInfo, text: str) -> tuple[list[Symbol], list[str]]:
try:
- import sqlglot
from sqlglot import exp
except ImportError:
return [], ["sqlglot not installed"]
- # sqlglot warns per statement it falls back to a generic Command for
- # (procedural bodies, vendor syntax); routine here, so keep it quiet.
- import logging
-
- logging.getLogger("sqlglot").setLevel(logging.ERROR)
+ from .sql_parse import parse_sql
try:
- statements = sqlglot.parse(
- text,
- read=_sql_dialect_for(file_info),
- error_level=sqlglot.ErrorLevel.IGNORE,
- )
+ statements = parse_sql(text, dialect=_sql_dialect_for(file_info))
except Exception as exc:
# Tokenizer errors and dialect-specific syntax sqlglot can't
# recover from: degrade the file to passthrough behaviour.
diff --git a/packages/core/src/repowise/core/ingestion/sql_parse.py b/packages/core/src/repowise/core/ingestion/sql_parse.py
new file mode 100644
index 000000000..3e0bce139
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/sql_parse.py
@@ -0,0 +1,128 @@
+"""One guarded entry point for every ``sqlglot.parse`` call in repowise.
+
+sqlglot's parser can loop forever, allocating a node per pass, on statements
+it cannot consume: ``COPY t FROM :'f';`` (a psql variable), ``COPY t FROM -;``
+or a column constraint typo such as ``id3 INTEGER NOT NUL`` never return,
+under every error level and dialect. A thread cannot be stopped, so each
+statement gets a node budget instead: a parse that builds far more nodes than
+the statement has tokens is not making progress, and that statement alone is
+dropped (``None``, like any statement sqlglot cannot read) while the rest of
+the file parses as before.
+
+psql backslash meta-commands (``\\set``, ``\\copy``, ``\\gset``) are client
+syntax, not SQL, and run to the end of their line. Their tokens are dropped
+before parsing so they do not swallow the statement that follows them.
+"""
+
+from __future__ import annotations
+
+import logging
+from functools import lru_cache
+from typing import Any
+
+__all__ = ["drop_psql_meta_commands", "parse_sql"]
+
+# Nodes one statement may build: a fixed floor plus a multiple of its tokens.
+# Across the 22k statements of the postgres regression suite the most any
+# statement built was 2.15 nodes per token and 471 in total, so this leaves a
+# 10x margin, and a stuck loop still passes it within a few milliseconds.
+_NODE_BUDGET_FLOOR = 1_000
+_NODES_PER_TOKEN = 20
+
+
+class _NodeBudgetError(Exception):
+ """Raised inside the parser when a statement exhausts its node budget."""
+
+
+def drop_psql_meta_commands(text: str, tokens: list[Any]) -> list[Any]:
+ """*tokens* minus each psql meta-command: a backslash token to the end of its line.
+
+ The tokenizer has already read string literals and comments, so a
+ backslash inside one is part of that token and never starts a command.
+ ``\\g``, ``\\gset``, ``\\gexec`` and the like send the query buffer, so
+ they end a statement just as ``;`` does.
+ """
+ from sqlglot.tokens import Token, TokenType
+
+ kept: list[Any] = []
+ line_end = -1
+ for tok in tokens:
+ if tok.start < line_end:
+ continue
+ if tok.token_type == TokenType.BACKSLASH:
+ line_end = text.find("\n", tok.start)
+ if line_end == -1:
+ line_end = len(text)
+ if text.startswith("g", tok.start + 1):
+ kept.append(
+ Token(TokenType.SEMICOLON, ";", tok.line, tok.col, tok.start, tok.start)
+ )
+ continue
+ kept.append(tok)
+ return kept
+
+
+@lru_cache(maxsize=32)
+def _budgeted(parser_class: type) -> type:
+ """*parser_class* with a per-statement cap on the nodes it may build."""
+
+ class BudgetedParser(parser_class):
+ _node_budget = 0
+ _in_statement = False
+
+ def expression(self, exp_class: Any, comments: Any = None, **kwargs: Any) -> Any:
+ self._node_budget -= 1
+ if self._node_budget < 0:
+ raise _NodeBudgetError
+ return super().expression(exp_class, comments, **kwargs)
+
+ def _parse_statement(self) -> Any:
+ # Procedural bodies parse nested statements; only the top level
+ # (one ``;``-separated chunk) sets the budget, so a loop that
+ # re-enters here cannot refill it.
+ if self._in_statement:
+ return super()._parse_statement()
+ self._in_statement = True
+ self._node_budget = _NODE_BUDGET_FLOOR + _NODES_PER_TOKEN * len(self._tokens)
+ try:
+ return super()._parse_statement()
+ except _NodeBudgetError:
+ # Consume the rest of this statement so the next one starts clean.
+ while self._curr:
+ self._advance()
+ return None
+ finally:
+ self._in_statement = False
+
+ return BudgetedParser
+
+
+def parse_sql(
+ text: str,
+ *,
+ dialect: str | None = None,
+ error_level: Any = None,
+ psql_meta_commands: bool = True,
+) -> list[Any]:
+ """``sqlglot.parse`` with a per-statement node budget.
+
+ Raises ``ImportError`` when sqlglot is missing and whatever sqlglot raises
+ otherwise, so each caller keeps its own degrade path. *error_level*
+ defaults to ``ErrorLevel.IGNORE``. A statement over budget comes back as
+ ``None``. *psql_meta_commands* drops psql's backslash commands first; it
+ is for ``.sql`` files, not SQL embedded in code, where a stray backslash
+ should still fail the parse.
+ """
+ import sqlglot
+ from sqlglot.dialects.dialect import Dialect
+
+ # sqlglot warns per statement it falls back to a generic Command for
+ # (procedural bodies, vendor syntax); routine here, so keep it quiet.
+ logging.getLogger("sqlglot").setLevel(logging.ERROR)
+ level = sqlglot.ErrorLevel.IGNORE if error_level is None else error_level
+ sql_dialect = Dialect.get_or_raise(dialect)
+ tokens = sql_dialect.tokenize(text)
+ if psql_meta_commands and "\\" in text:
+ tokens = drop_psql_meta_commands(text, tokens)
+ parser = _budgeted(sql_dialect.parser_class)(dialect=sql_dialect, error_level=level)
+ return parser.parse(tokens, text)
diff --git a/packages/core/src/repowise/core/pipeline/incremental/graph.py b/packages/core/src/repowise/core/pipeline/incremental/graph.py
index d97d61913..5109805b1 100644
--- a/packages/core/src/repowise/core/pipeline/incremental/graph.py
+++ b/packages/core/src/repowise/core/pipeline/incremental/graph.py
@@ -36,24 +36,32 @@ def _parse_misses(
to_parse: list,
parse_cache: Any,
timings: PhaseTimings | None,
+ log: LogFn = _noop_log,
) -> dict[int, Any]:
- """Parse the parse-cache misses and merge them over the cached hits by index."""
- from repowise.core.ingestion import ASTParser
- from repowise.core.pipeline.phases.ingestion import _cache_parsed
+ """Parse the parse-cache misses and merge them over the cached hits by index.
+
+ Misses go through init's deadline pool, so one file that never finishes
+ parsing costs this update one deadline instead of hanging it. An update
+ whose files are all cached starts no pool.
+ """
+ from repowise.core.pipeline.phases.ingestion import (
+ _cache_parsed,
+ parse_guarded,
+ report_parse_failures,
+ )
- parser: Any = None # constructed lazily — every-file-cached updates skip query compilation
merged: dict[int, Any] = dict(cached_hits)
with timed(timings, "rebuild.parse"):
- for idx, (fi, source), content_hash in to_parse:
- try:
- if parser is None:
- parser = ASTParser()
- parsed = parser.parse_file(fi, source)
- except Exception:
- continue
- merged[idx] = parsed
- if content_hash:
- _cache_parsed(parse_cache, parsed, content_hash)
+ results = parse_guarded(to_parse)
+ for (idx, _item, content_hash), parsed in zip(to_parse, results, strict=True):
+ if isinstance(parsed, tuple | BaseException):
+ continue
+ merged[idx] = parsed
+ if content_hash:
+ _cache_parsed(parse_cache, parsed, content_hash)
+ message = report_parse_failures(to_parse, results)
+ if message:
+ log(f"[yellow]{message}[/yellow]")
return merged
@@ -235,11 +243,10 @@ pass reads the sources.
file_info.path for file_info in file_infos
}
- # Parse the misses in process and serially: on the update path they are
- # change-sized. (Ceiling: a wiped/stale cache re-parses everything on one
- # core; routing large miss counts through init's process pool would lift
- # it, at the cost of Windows spawn overhead on every routine update.)
- merged = _parse_misses(cached_hits, to_parse, parse_cache, timings)
+ # Misses go through init's deadline pool. An update pays one pool start
+ # (about a second on Windows) when anything changed, in exchange for a
+ # file that never finishes parsing costing one deadline instead of the run.
+ merged = _parse_misses(cached_hits, to_parse, parse_cache, timings, log)
skipped = len(file_infos) - len(fi_and_bytes) # unreadable files
# Opened here and closed after build(): graph construction is the add_file
diff --git a/packages/core/src/repowise/core/pipeline/parse_pool.py b/packages/core/src/repowise/core/pipeline/parse_pool.py
new file mode 100644
index 000000000..30c19911d
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/parse_pool.py
@@ -0,0 +1,306 @@
+"""A spawn process pool where no single file can stall or exhaust the parse.
+
+Every task gets a deadline (``REPOWISE_PARSE_TIMEOUT_S``). A thread cannot be
+killed, so a task past its deadline is stopped by killing the pool's worker
+processes: the late task is recorded as :class:`ParseTimeoutError`, the other
+tasks that were in flight go back to the front of the queue, and a fresh pool
+carries on. A worker that dies on its own (a native crash, an out-of-memory
+kill) breaks the pool too. Its in-flight tasks are then retried one at a time,
+so the one that crashes alone is recorded as :class:`ParseWorkerCrashError` and
+the rest finish normally.
+
+On Linux each worker's data segment is also capped
+(``REPOWISE_PARSE_WORKER_MEMORY_MB``), so a runaway allocation becomes a
+``MemoryError`` for that file instead of memory pressure on the host. Other
+platforms have no per-process cap that covers ``mmap``; the deadline is their
+only bound.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import multiprocessing
+import os
+import time
+from collections import deque
+from collections.abc import Callable
+from concurrent.futures import FIRST_COMPLETED, Future, ProcessPoolExecutor, wait
+from concurrent.futures.process import BrokenProcessPool
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+__all__ = [
+ "PENDING",
+ "ParseTimeoutError",
+ "ParseWorkerCrashError",
+ "parse_timeout_s",
+ "run_with_deadline",
+]
+
+# Force ``spawn`` for the parse pool instead of the POSIX default ``fork``.
+# A workspace init generates docs for one repo (which imports and connects
+# LanceDB) before ingesting the next, and ``lance`` is not fork-safe — it
+# registers an ``os.register_at_fork`` hook that resets its native async
+# runtime in the child but can still deadlock. Forking the parse workers
+# after LanceDB is live is exactly what hung multi-repo inits at "Parsing
+# files" (issue #678). ``spawn`` starts clean workers that never inherit the
+# runtime; it is already the default on Windows/macOS.
+MP_SPAWN = multiprocessing.get_context("spawn")
+
+_TIMEOUT_ENV = "REPOWISE_PARSE_TIMEOUT_S"
+# Normal files parse in well under a second, and the traverser caps parsed
+# sources at 2 MB, so a minute is far past any legitimate parse even on a slow,
+# shared CPU. It still stops a looping parser before it can grow without bound.
+_DEFAULT_TIMEOUT_S = 60.0
+
+_MEMORY_ENV = "REPOWISE_PARSE_WORKER_MEMORY_MB"
+# A worker holds ~50 MB of grammars plus one file's tree; 2 GB is an order of
+# magnitude above the largest parse and still bounded on a small host.
+_DEFAULT_MEMORY_MB = 2048
+
+
+# How long a fresh pool may take to run a no-op before it counts as unusable.
+_STARTUP_TIMEOUT_S = 120
+
+
+class ParseTimeoutError(Exception):
+ """A file's parse ran past the deadline; its worker was killed."""
+
+
+class ParseWorkerCrashError(Exception):
+ """A file's worker process died while parsing it, even when run alone."""
+
+
+class _Pending:
+ def __repr__(self) -> str:
+ return "PENDING"
+
+
+# Placeholder in a results list for a task that has no outcome yet.
+PENDING: Any = _Pending()
+
+
+def _env_number(name: str, default: float) -> float:
+ """A non-negative number from *name*; unset or empty means *default*."""
+ raw = os.environ.get(name)
+ if not raw:
+ return default
+ try:
+ value = float(raw)
+ except ValueError:
+ value = -1.0
+ if value < 0:
+ logger.warning("invalid_parse_pool_env", name=name, value=raw)
+ return default
+ return value
+
+
+def parse_timeout_s() -> float | None:
+ """Per-file parse deadline in seconds; ``REPOWISE_PARSE_TIMEOUT_S=0`` turns it off."""
+ value = _env_number(_TIMEOUT_ENV, _DEFAULT_TIMEOUT_S)
+ return value or None
+
+
+def _worker_memory_bytes() -> int:
+ """Per-worker data-segment cap; ``REPOWISE_PARSE_WORKER_MEMORY_MB=0`` turns it off."""
+ return int(_env_number(_MEMORY_ENV, _DEFAULT_MEMORY_MB) * 1024 * 1024)
+
+
+def _limit_worker_memory(limit_bytes: int) -> None:
+ """Pool initializer: cap this worker's data segment where the OS enforces it.
+
+ ``RLIMIT_DATA`` rather than ``RLIMIT_AS``: since Linux 4.7 it counts the
+ private writable mappings malloc and Python's arenas live in, but not the
+ address space that shared libraries and guard reservations take, so a
+ normal worker is nowhere near it. Never raises: a worker without the cap
+ still parses.
+ """
+ if not limit_bytes:
+ return
+ try:
+ import resource
+ except ImportError: # Windows has no rlimits
+ return
+ # Platforms without RLIMIT_DATA, or a hard limit we may not raise, leave
+ # the worker uncapped.
+ with contextlib.suppress(AttributeError, ValueError, OSError):
+ _soft, hard = resource.getrlimit(resource.RLIMIT_DATA)
+ if hard != resource.RLIM_INFINITY:
+ limit_bytes = min(limit_bytes, hard)
+ resource.setrlimit(resource.RLIMIT_DATA, (limit_bytes, hard))
+
+
+def _new_pool(workers: int) -> ProcessPoolExecutor:
+ return ProcessPoolExecutor(
+ max_workers=workers,
+ mp_context=MP_SPAWN,
+ initializer=_limit_worker_memory,
+ initargs=(_worker_memory_bytes(),),
+ )
+
+
+def _kill_pool(pool: ProcessPoolExecutor) -> None:
+ """Stop *pool* now, including a worker stuck in a task."""
+ # ``kill_workers`` is 3.14+; before that the process map is the only handle.
+ procs = list((getattr(pool, "_processes", None) or {}).values())
+ for proc in procs:
+ with contextlib.suppress(Exception):
+ proc.kill()
+ pool.shutdown(wait=False, cancel_futures=True)
+ for proc in procs:
+ with contextlib.suppress(Exception):
+ proc.join(timeout=5)
+
+
+class _Run:
+ """State of one :func:`run_with_deadline` call across pool rebuilds."""
+
+ def __init__(
+ self,
+ fn: Callable[[Any], Any],
+ items: list[Any],
+ results: list[Any],
+ timeout: float | None,
+ on_done: Callable[[int, Any], None] | None,
+ ) -> None:
+ self.fn = fn
+ self.items = items
+ self.results = results
+ self.timeout = timeout
+ self.on_done = on_done
+ self.queue: deque[int] = deque(i for i, r in enumerate(results) if r is PENDING)
+ # Tasks that were in flight when a worker died, retried one at a time.
+ self.suspects: deque[int] = deque()
+ self.pool_has_run = False
+
+ def finish(self, idx: int, result: Any) -> None:
+ self.results[idx] = result
+ if self.on_done is not None:
+ self.on_done(idx, result)
+
+ def wait_budget(self, in_flight: dict[Future, tuple[int, float]]) -> float | None:
+ if self.timeout is None:
+ return None
+ oldest = min(started for _idx, started in in_flight.values())
+ return max(0.05, oldest + self.timeout - time.monotonic())
+
+ def expire(self, in_flight: dict[Future, tuple[int, float]]) -> bool:
+ """Record every task past its deadline; True when any was."""
+ if self.timeout is None:
+ return False
+ now = time.monotonic()
+ late = [f for f, (_i, started) in in_flight.items() if now - started >= self.timeout]
+ for fut in late:
+ idx, _started = in_flight.pop(fut)
+ self.finish(idx, ParseTimeoutError(f"parse timed out after {self.timeout:g}s"))
+ return bool(late)
+
+ def collect(self, done: set[Future], in_flight: dict[Future, tuple[int, float]]) -> bool:
+ """Record finished tasks; True when the pool broke under one of them."""
+ broken = False
+ for fut in done:
+ exc = fut.exception()
+ if isinstance(exc, BrokenProcessPool):
+ broken = True
+ continue
+ idx, _started = in_flight.pop(fut)
+ self.finish(idx, exc if exc is not None else fut.result())
+ return broken
+
+ def requeue(self, in_flight: dict[Future, tuple[int, float]], *, suspect: bool) -> None:
+ """Send unfinished in-flight tasks back to the front of their queue."""
+ target = self.suspects if suspect else self.queue
+ target.extendleft(sorted((i for i, _s in in_flight.values()), reverse=True))
+ in_flight.clear()
+
+ def dispatch(
+ self,
+ pool: ProcessPoolExecutor,
+ queue: deque[int],
+ in_flight: dict[Future, tuple[int, float]],
+ limit: int,
+ ) -> None:
+ # In flight never exceeds the worker count, so every in-flight task is
+ # running and its clock is its own parse time.
+ while queue and len(in_flight) < limit:
+ idx = queue.popleft()
+ in_flight[pool.submit(self.fn, self.items[idx])] = (idx, time.monotonic())
+
+ def start(self, pool: ProcessPoolExecutor) -> None:
+ """Run a no-op in *pool*; raise when it cannot, so the caller falls back.
+
+ A pool that cannot start (spawn or import failure) is the
+ environment's fault, not a file's. Suspects are the exception: they
+ were in flight when a worker died, so they never go to an in-process
+ fallback, where a native crash would take the whole run down.
+ """
+ try:
+ pool.submit(os.getpid).result(timeout=_STARTUP_TIMEOUT_S)
+ except Exception:
+ if self.pool_has_run:
+ while self.suspects:
+ self.finish(self.suspects.popleft(), ParseWorkerCrashError("parse worker crashed"))
+ raise
+ self.pool_has_run = True
+
+ def round(self, workers: int) -> None:
+ """Run tasks in one pool until the queue drains or the pool must go."""
+ solo = bool(self.suspects)
+ queue = self.suspects if solo else self.queue
+ limit = 1 if solo else workers
+ pool = _new_pool(limit)
+ in_flight: dict[Future, tuple[int, float]] = {}
+ clean = False
+ try:
+ self.start(pool)
+ while queue or in_flight:
+ self.dispatch(pool, queue, in_flight, limit)
+ done, _ = wait(in_flight, self.wait_budget(in_flight), FIRST_COMPLETED)
+ if self.collect(done, in_flight):
+ self.on_broken(in_flight, solo)
+ return
+ if self.expire(in_flight):
+ self.requeue(in_flight, suspect=solo)
+ return
+ clean = True
+ finally:
+ if clean:
+ pool.shutdown(wait=True)
+ else:
+ _kill_pool(pool)
+
+ def on_broken(self, in_flight: dict[Future, tuple[int, float]], solo: bool) -> None:
+ if solo:
+ # Alone in its pool, so this task is the one that killed it.
+ (idx, _started) = next(iter(in_flight.values()))
+ in_flight.clear()
+ self.finish(idx, ParseWorkerCrashError("parse worker crashed"))
+ else:
+ self.requeue(in_flight, suspect=True)
+
+
+def run_with_deadline(
+ fn: Callable[[Any], Any],
+ items: list[Any],
+ workers: int,
+ results: list[Any],
+ *,
+ timeout: float | None,
+ on_done: Callable[[int, Any], None] | None = None,
+) -> None:
+ """Run ``fn(item)`` for each :data:`PENDING` slot of *results* in a spawn pool.
+
+ Fills *results* in place, aligned with *items*: the return value, the
+ exception the task raised, or a :class:`ParseTimeoutError` /
+ :class:`ParseWorkerCrashError` instance. ``on_done(index, result)`` runs in
+ the calling thread as each task resolves. A pool that cannot start raises,
+ with every slot it did not resolve left :data:`PENDING` for the caller's
+ fallback; slots that timed out or crashed are resolved, so a fallback
+ never runs those files again.
+ """
+ run = _Run(fn, items, results, timeout, on_done)
+ while run.queue or run.suspects:
+ run.round(workers)
diff --git a/packages/core/src/repowise/core/pipeline/phases/ingestion.py b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
index 1d61db884..02ec475b8 100644
--- a/packages/core/src/repowise/core/pipeline/phases/ingestion.py
+++ b/packages/core/src/repowise/core/pipeline/phases/ingestion.py
@@ -8,17 +8,24 @@ from __future__ import annotations
import asyncio
import contextlib
-import multiprocessing
import os
import time
from collections import Counter
-from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
+from collections.abc import Callable
+from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Any
import structlog
+from repowise.core.pipeline.parse_pool import (
+ PENDING,
+ ParseTimeoutError,
+ ParseWorkerCrashError,
+ parse_timeout_s,
+ run_with_deadline,
+)
from repowise.core.pipeline.progress import ProgressCallback, emit_item, emit_warning
from ._common import _phase_done
@@ -250,16 +257,8 @@ def _emit_traversal_summary(
# Process-pool worker (module-level — must be picklable)
# ---------------------------------------------------------------------------
-# Force ``spawn`` for the parse pool instead of the POSIX default ``fork``.
-# A workspace init generates docs for one repo (which imports and connects
-# LanceDB) before ingesting the next, and ``lance`` is not fork-safe — it
-# registers an ``os.register_at_fork`` hook that resets its native async
-# runtime in the child but can still deadlock. Forking the parse workers
-# after LanceDB is live is exactly what hung multi-repo inits at "Parsing
-# files" (issue #678). ``spawn`` starts clean workers that never inherit the
-# runtime; it is already the default on Windows/macOS, so ``_parse_one`` and
-# its picklable args are known to work under it.
-_MP_SPAWN = multiprocessing.get_context("spawn")
+# The pool itself (spawn context, per-file deadline, worker memory cap) lives in
+# ``pipeline/parse_pool.py``; this module decides how many workers and what runs.
# Upper bound on the parse pool, independent of how many cores the host has.
#
@@ -345,6 +344,10 @@ def _parse_one(path_and_fi_and_bytes: tuple) -> Any:
_WORKER_PARSER = ASTParser()
return _WORKER_PARSER.parse_file(fi, source)
+ except MemoryError:
+ # Raised, not folded into an error tuple: the parent reports it as a
+ # file it gave up on (see ``report_parse_failures``).
+ raise
except Exception as exc:
return (fi.abs_path, str(exc))
@@ -522,47 +525,89 @@ async def _traverse_stage(
return traverser, file_infos, repo_structure
-async def _parse_in_pool(
- to_parse: list[tuple], workers: int, progress: ProgressCallback | None
-) -> list[Any]:
- """Parse cache misses in the spawn process pool; results in *to_parse* order."""
- loop = asyncio.get_running_loop()
- with ProcessPoolExecutor(max_workers=workers, mp_context=_MP_SPAWN) as pool:
- tasks = [loop.run_in_executor(pool, _parse_one, item) for _idx, item, _h in to_parse]
- # Tick per finished worker: ``asyncio.gather`` alone holds every event
- # until the last file is done, which on large repos looked like a hang
- # at ``0/N``. Done-callbacks keep gather's ordered results intact.
- if progress is not None:
-
- def _parse_tick(path: str) -> Any:
- def _tick(_fut: Any) -> None:
- progress.on_item_done("parse")
- emit_item(progress, "parse", path)
-
- return _tick
-
- for fut, (_idx, (fi, _src), _h) in zip(tasks, to_parse, strict=True):
- fut.add_done_callback(_parse_tick(fi.path))
- return await asyncio.gather(*tasks, return_exceptions=True)
-
+def _parse_in_process(
+ to_parse: list[tuple], results: list[Any], on_done: Callable[[int], None] | None
+) -> None:
+ """Sequential in-process parse of every slot still ``PENDING``.
-async def _parse_in_process(to_parse: list[tuple], progress: ProgressCallback | None) -> list[Any]:
- """Sequential in-process parse, the fallback when the pool is unavailable."""
+ The fallback when the pool cannot start. It has no deadline (a thread
+ cannot be stopped), but files the pool already timed out or crashed on
+ are resolved and never reach it.
+ """
from repowise.core.ingestion import ASTParser
- parse_results: list[Any] = []
- fallback_parser = ASTParser()
+ parser: Any = None
for i, (_idx, (fi, source), _h) in enumerate(to_parse):
+ if results[i] is not PENDING:
+ continue
try:
- parse_results.append(fallback_parser.parse_file(fi, source))
+ if parser is None:
+ parser = ASTParser()
+ results[i] = parser.parse_file(fi, source)
except Exception as exc:
- parse_results.append((fi.abs_path, str(exc)))
- if progress:
- progress.on_item_done("parse")
- emit_item(progress, "parse", fi.path)
- if i % 50 == 49:
- await asyncio.sleep(0)
- return parse_results
+ results[i] = (fi.abs_path, str(exc))
+ if on_done is not None:
+ on_done(i)
+
+
+def parse_guarded(
+ to_parse: list[tuple],
+ *,
+ on_done: Callable[[int], None] | None = None,
+ on_fallback: Callable[[Exception], None] | None = None,
+) -> list[Any]:
+ """Parse ``(idx, (FileInfo, bytes), hash)`` triples; results in *to_parse* order.
+
+ Runs in the deadline pool (see ``parse_pool``), falling back to one
+ in-process parser for whatever is left when the pool cannot start. Each
+ result is a ``ParsedFile``, an ``(abs_path, error)`` tuple or an
+ exception. ``on_done(i)`` fires once per file, from the calling thread.
+ """
+ if not to_parse:
+ return []
+ results: list[Any] = [PENDING] * len(to_parse)
+ workers = parse_pool_workers(len(to_parse))
+ pool_done = None if on_done is None else (lambda i, _result: on_done(i))
+ try:
+ run_with_deadline(
+ _parse_one,
+ [item for _idx, item, _h in to_parse],
+ workers,
+ results,
+ timeout=parse_timeout_s(),
+ on_done=pool_done,
+ )
+ except Exception as pool_exc:
+ if on_fallback is not None:
+ on_fallback(pool_exc)
+ else:
+ logger.warning("parse_pool_unavailable", error=str(pool_exc))
+ _parse_in_process(to_parse, results, on_done)
+ return results
+
+
+def report_parse_failures(to_parse: list[tuple], results: list[Any]) -> str | None:
+ """Log each file the pool gave up on; one sentence naming them, or None.
+
+ Ordinary parse errors stay at debug (they are routine); a timeout, a
+ crashed worker or a worker out of memory means a file is missing from the
+ index for a reason the user can act on, such as excluding it.
+ """
+ failed: list[tuple[str, str]] = []
+ for (_idx, (fi, _src), _h), result in zip(to_parse, results, strict=True):
+ if isinstance(result, ParseTimeoutError | ParseWorkerCrashError | MemoryError):
+ reason = str(result) or "parse ran out of memory"
+ logger.warning("parse_file_abandoned", path=fi.path, reason=reason)
+ failed.append((fi.path, reason))
+ if not failed:
+ return None
+ shown = ", ".join(f"{path} ({reason})" for path, reason in failed[:5])
+ more = f" and {len(failed) - 5} more" if len(failed) > 5 else ""
+ return (
+ f"Skipped {len(failed)} file(s) the parser could not finish: {shown}{more}. "
+ "The rest of the index is complete; exclude these files, or raise "
+ "REPOWISE_PARSE_TIMEOUT_S if they are just slow."
+ )
async def _parse_misses(
@@ -572,23 +617,41 @@ async def _parse_misses(
fallback_event: str,
warn_on_fallback: bool,
) -> list[Any]:
- workers = parse_pool_workers(len(to_parse))
if not to_parse:
return []
- try:
- return await _parse_in_pool(to_parse, workers, progress)
- except Exception as pool_exc:
+ loop = asyncio.get_running_loop()
+ on_done = None
+ if progress is not None:
+
+ def _tick(i: int) -> None:
+ progress.on_item_done("parse")
+ emit_item(progress, "parse", to_parse[i][1][0].path)
+
+ # Ticks come from the parse thread; hop to the loop like the old
+ # executor done-callbacks did, so progress is only touched there.
+ def on_done(i: int) -> None:
+ loop.call_soon_threadsafe(_tick, i)
+
+ def on_fallback(pool_exc: Exception) -> None:
logger.warning(fallback_event, error=str(pool_exc))
if warn_on_fallback:
# Said out loud, not only logged: the index is still correct, but
# one process instead of up to eight makes a large repo several
# times slower for a reason nothing on screen explained.
- emit_warning(
+ loop.call_soon_threadsafe(
+ emit_warning,
progress,
f"Parallel parsing unavailable ({pool_exc}); "
"falling back to a single process, which is much slower.",
)
- return await _parse_in_process(to_parse, progress)
+
+ results = await asyncio.to_thread(
+ parse_guarded, to_parse, on_done=on_done, on_fallback=on_fallback
+ )
+ message = report_parse_failures(to_parse, results)
+ if message:
+ emit_warning(progress, message)
+ return results
def _merge_parse_results(
diff --git a/packages/core/src/repowise/core/pipeline/reparse.py b/packages/core/src/repowise/core/pipeline/reparse.py
index 5ec0eb2cf..e1c4a3282 100644
--- a/packages/core/src/repowise/core/pipeline/reparse.py
+++ b/packages/core/src/repowise/core/pipeline/reparse.py
@@ -33,7 +33,13 @@ def reparse_repo(
the original index — a fast index built with ``--include-submodules`` must
not drop submodule files from the docs re-parse.
"""
- from repowise.core.ingestion import ASTParser, FileTraverser
+ from repowise.core.ingestion import FileTraverser
+ from repowise.core.pipeline.phases.ingestion import (
+ _collect_parsed,
+ _read_sources,
+ parse_guarded,
+ report_parse_failures,
+ )
traverser = FileTraverser(
repo_path,
@@ -44,15 +50,12 @@ def reparse_repo(
file_infos = list(traverser.traverse())
repo_structure = traverser.get_repo_structure()
- parser = ASTParser()
- parsed_files: list[Any] = []
- source_map: dict[str, bytes] = {}
- for fi in file_infos:
- try:
- source = Path(fi.abs_path).read_bytes()
- parsed = parser.parse_file(fi, source)
- parsed_files.append(parsed)
- source_map[fi.path] = source
- except Exception:
- pass # unreadable / unparseable files are skipped, as in init
+ # Same deadline pool as init, so a file that never finishes parsing is
+ # skipped here too instead of hanging the re-parse.
+ fi_and_bytes = _read_sources(file_infos, None)
+ to_parse = [(idx, item, "") for idx, item in enumerate(fi_and_bytes)]
+ results = parse_guarded(to_parse)
+ report_parse_failures(to_parse, results) # logs each file it gave up on
+ # Unreadable / unparseable files are skipped, as in init.
+ parsed_files, source_map = _collect_parsed(fi_and_bytes, dict(enumerate(results)))
return parsed_files, source_map, repo_structure
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/ddl.py b/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
index 7257c9fb0..ecc7ff4fc 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/ddl.py
@@ -9,7 +9,6 @@ asserts ownership (the repo evolves that table), marked ``schema: alter``.
from __future__ import annotations
-import logging
from typing import TYPE_CHECKING
from repowise.core.workspace.origins import ContractOrigin
@@ -43,14 +42,13 @@ class DdlDialect:
def extract(self, ctx: ScanContext) -> list[Contract]:
try:
- import sqlglot
from sqlglot import exp
except ImportError:
return []
- logging.getLogger("sqlglot").setLevel(logging.ERROR)
+ from repowise.core.ingestion.sql_parse import parse_sql
try:
- statements = sqlglot.parse(ctx.content, error_level=sqlglot.ErrorLevel.IGNORE)
+ statements = parse_sql(ctx.content)
except Exception:
return []
diff --git a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py
index 7eb1842ad..138c98c51 100644
--- a/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py
+++ b/packages/core/src/repowise/core/workspace/extractors/data/sql_strings.py
@@ -15,7 +15,6 @@ Precision rules (this is where the false links would come from):
from __future__ import annotations
-import logging
import re
from typing import TYPE_CHECKING
@@ -188,9 +187,12 @@ class SqlStringsDialect:
from sqlglot import exp
except ImportError:
return None
- logging.getLogger("sqlglot").setLevel(logging.ERROR)
+ from repowise.core.ingestion.sql_parse import parse_sql
+
try:
- statements = sqlglot.parse(literal, error_level=sqlglot.ErrorLevel.RAISE)
+ statements = parse_sql(
+ literal, error_level=sqlglot.ErrorLevel.RAISE, psql_meta_commands=False
+ )
except Exception:
return None
found: list[tuple[str, str]] = []
diff --git a/tests/unit/cli/test_commands.py b/tests/unit/cli/test_commands.py
index 2cabadc03..e019bdad0 100644
--- a/tests/unit/cli/test_commands.py
+++ b/tests/unit/cli/test_commands.py
@@ -441,6 +441,14 @@ class TestBuildRepoGraph:
return real_parse(self, fi, source)
monkeypatch.setattr(ASTParser, "parse_file", _maybe_raise)
+ # The patch above cannot reach a spawned parse worker, so run the
+ # pool's in-process fallback, where it applies.
+ from repowise.core.pipeline.phases import ingestion as ing
+
+ def _no_pool(*_args, **_kwargs):
+ raise OSError("no pool in this test")
+
+ monkeypatch.setattr(ing, "run_with_deadline", _no_pool)
printed: list[str] = []
diff --git a/tests/unit/ingestion/test_sql_parse_guard.py b/tests/unit/ingestion/test_sql_parse_guard.py
new file mode 100644
index 000000000..050ea0892
--- /dev/null
+++ b/tests/unit/ingestion/test_sql_parse_guard.py
@@ -0,0 +1,143 @@
+"""sqlglot must never hang a parse: the guarded ``parse_sql`` entry point.
+
+sqlglot loops forever, allocating as it goes, on some statements it cannot
+consume (psql ``COPY ... FROM :'var'``, a ``NOT NUL`` constraint typo). The
+postgres regression suite is full of them. Every parse here runs in a child
+process with a timeout, so a regression fails the test instead of hanging the
+suite.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+import sys
+
+import pytest
+
+_TIMEOUT_S = 60
+
+# Excerpt of postgres src/test/regress/sql/copy.sql (PostgreSQL License), which
+# hung the parser outright, plus the constraint typo from errors.sql.
+_REGRESS_EXCERPT = r"""--
+-- COPY
+--
+
+-- directory paths are passed to us in environment variables
+\getenv abs_srcdir PG_ABS_SRCDIR
+\getenv abs_builddir PG_ABS_BUILDDIR
+
+create temp table copytest (
+ style text,
+ test text,
+ filler int);
+
+insert into copytest values('DOS',E'abc\r\ndef',1);
+insert into copytest values(E'esc\\ape',E'a\\r\\\r\\\n\\nb',4);
+
+\set filename :abs_builddir '/results/copytest.csv'
+copy copytest to :'filename' csv;
+
+create table copytest2 (style text, test text, filler int);
+
+copy copytest2 from :'filename' csv quote '''' escape E'\\';
+
+-- with a tab
+CREATE TABLE foo
+ (id INT4 UNIQUE NOT NULL, id2 TEXT NOT NULL PRIMARY KEY,
+ id3 INTEGER NOT NUL,
+ id4 INT4 UNIQUE NOT NULL, id5 TEXT UNIQUE NOT NULL);
+
+CREATE VIEW after_the_typo AS SELECT style FROM copytest2;
+"""
+
+_SCRIPT = r"""
+import json, sys
+from datetime import datetime
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.special_handlers import parse_special
+
+source = sys.stdin.read()
+fi = FileInfo(path="copy.sql", abs_path="/repo/copy.sql", language="sql", size_bytes=len(source),
+ git_hash="", last_modified=datetime.now(), is_test=False, is_config=False,
+ is_api_contract=False, is_entry_point=False)
+parsed = parse_special(fi, source.encode(), "sql")
+print(json.dumps({"symbols": [[s.name, s.start_line] for s in parsed.symbols],
+ "errors": parsed.parse_errors}))
+"""
+
+
+def _parse_in_child(source: str) -> dict:
+ try:
+ done = subprocess.run(
+ [sys.executable, "-c", _SCRIPT],
+ input=source,
+ capture_output=True,
+ text=True,
+ timeout=_TIMEOUT_S,
+ check=False,
+ )
+ except subprocess.TimeoutExpired:
+ pytest.fail(f"SQL parse did not finish within {_TIMEOUT_S}s")
+ assert done.returncode == 0, done.stderr
+ return json.loads(done.stdout.strip().splitlines()[-1])
+
+
+ "source",
+ [
+ "COPY t FROM :'f';",
+ "COPY t TO :'f';",
+ "COPY t FROM -;",
+ "COPY (SELECT 1) TO :'f';",
+ "CREATE TABLE foo (id INT4, id3 INTEGER NOT NUL, id4 INT4);",
+ ],
+)
+def test_statements_that_hang_sqlglot_finish(source: str) -> None:
+ assert _parse_in_child(source) == {"symbols": [], "errors": []}
+
+
+def test_regress_excerpt_keeps_every_other_symbol() -> None:
+ result = _parse_in_child(_REGRESS_EXCERPT)
+ assert result["errors"] == []
+ # The hanging COPY statements and the ``NOT NUL`` table are dropped; the
+ # statements after them still parse, with their own line numbers.
+ assert result["symbols"] == [
+ ["copytest", 9],
+ ["copytest2", 20],
+ ["after_the_typo", 30],
+ ]
+
+
+def test_meta_command_does_not_swallow_the_next_statement() -> None:
+ from repowise.core.ingestion.sql_parse import parse_sql
+
+ statements = parse_sql("\\set x 1\nCREATE TABLE after_meta (b int);")
+ assert [s.this.this.name for s in statements if s is not None] == ["after_meta"]
+
+
+def test_backslash_inside_a_string_is_not_a_meta_command() -> None:
+ from repowise.core.ingestion.sql_parse import parse_sql
+
+ statements = parse_sql("INSERT INTO t VALUES ('a\\b');\nCREATE TABLE kept (a int);")
+ assert [type(s).__name__ for s in statements] == ["Insert", "Create"]
+
+
+def test_gset_ends_the_statement_like_a_semicolon() -> None:
+ from repowise.core.ingestion.sql_parse import parse_sql
+
+ statements = parse_sql("SELECT 1 AS x \\gset\nCREATE TABLE kept (a int);")
+ assert [type(s).__name__ for s in statements] == ["Select", "Create"]
+
+
+def test_embedded_sql_keeps_a_stray_backslash_an_error() -> None:
+ import sqlglot
+
+ from repowise.core.ingestion.sql_parse import parse_sql
+
+ with pytest.raises(sqlglot.errors.ParseError):
+ parse_sql(
+ "DELETE FROM users \\ WHERE 1",
+ error_level=sqlglot.ErrorLevel.RAISE,
+ psql_meta_commands=False,
+ )
diff --git a/tests/unit/pipeline/test_ingestion_file_order.py b/tests/unit/pipeline/test_ingestion_file_order.py
index 1974fae07..9bf1de52f 100644
--- a/tests/unit/pipeline/test_ingestion_file_order.py
+++ b/tests/unit/pipeline/test_ingestion_file_order.py
@@ -13,6 +13,7 @@ import time
import pytest
from repowise.core.ingestion import FileTraverser
+from repowise.core.pipeline import parse_pool
from repowise.core.pipeline.phases import ingestion as ing
_FILES = 6
@@ -47,13 +48,13 @@ def walk_order(monkeypatch, repo):
@pytest.fixture
def single_worker_pool(monkeypatch):
- real = ing.ProcessPoolExecutor
+ real = parse_pool.ProcessPoolExecutor
def one(*args, **kwargs):
kwargs["max_workers"] = 1
return real(*args, **kwargs)
- monkeypatch.setattr(ing, "ProcessPoolExecutor", one)
+ monkeypatch.setattr(parse_pool, "ProcessPoolExecutor", one)
async def test_full_ingestion_keeps_walk_order(repo, walk_order, single_worker_pool):
diff --git a/tests/unit/pipeline/test_parse_guarded.py b/tests/unit/pipeline/test_parse_guarded.py
new file mode 100644
index 000000000..54a5a40e6
--- /dev/null
+++ b/tests/unit/pipeline/test_parse_guarded.py
@@ -0,0 +1,115 @@
+"""``parse_guarded``: pool results, the in-process fallback, and skipped-file reporting.
+
+The pool is replaced by in-process fakes here, so every branch is measurable
+in this process; ``test_parse_pool_deadline.py`` drives real spawn pools.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.pipeline.parse_pool import PENDING, ParseTimeoutError, ParseWorkerCrashError
+from repowise.core.pipeline.phases import ingestion as ing
+
+
+def _fi(path: str, root: str = "/repo") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"{root}/{path}",
+ language="python",
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _to_parse(*names: str) -> list[tuple]:
+ return [(i, (_fi(n), f"def f_{i}():\n return {i}\n".encode()), "") for i, n in enumerate(names)]
+
+
+def test_pool_failure_falls_back_for_pending_slots_only(monkeypatch) -> None:
+ from_pool = object()
+
+ def pool_dies_after_one(_fn, _items, _workers, results, **_kw):
+ results[0] = from_pool
+ raise OSError("spawn failed")
+
+ monkeypatch.setattr(ing, "run_with_deadline", pool_dies_after_one)
+ fallbacks: list[Exception] = []
+ done: list[int] = []
+ results = ing.parse_guarded(
+ _to_parse("a.py", "b.py", "c.py"), on_done=done.append, on_fallback=fallbacks.append
+ )
+
+ assert results[0] is from_pool, "a slot the pool resolved is not parsed again"
+ assert all(isinstance(r, ParsedFile) for r in results[1:])
+ assert PENDING not in results
+ assert [str(e) for e in fallbacks] == ["spawn failed"]
+ assert done == [1, 2], "only the fallback's own files tick"
+
+
+def test_timeouts_and_crashes_come_back_and_are_named(monkeypatch) -> None:
+ def pool(_fn, _items, _workers, results, **_kw):
+ results[0] = ParseTimeoutError("parse timed out after 60s")
+ results[1] = ParseWorkerCrashError("parse worker crashed")
+ results[2] = "parsed"
+
+ monkeypatch.setattr(ing, "run_with_deadline", pool)
+ to_parse = _to_parse("slow.sql", "crash.sql", "fine.py")
+ results = ing.parse_guarded(to_parse)
+
+ assert isinstance(results[0], ParseTimeoutError)
+ assert isinstance(results[1], ParseWorkerCrashError)
+ message = ing.report_parse_failures(to_parse, results)
+ assert message is not None
+ assert "slow.sql (parse timed out after 60s)" in message
+ assert "crash.sql (parse worker crashed)" in message
+ assert "fine.py" not in message
+ # Neither reaches the parsed set; both are logged, not silently dropped.
+ parsed, _sources = ing._collect_parsed(
+ [item for _i, item, _h in to_parse], dict(enumerate(results))
+ )
+ assert parsed == ["parsed"]
+
+
+def test_nothing_to_parse_starts_no_pool(monkeypatch) -> None:
+ def no_pool(*_a, **_kw):
+ raise AssertionError("a pool was started for zero files")
+
+ monkeypatch.setattr(ing, "run_with_deadline", no_pool)
+ assert ing.parse_guarded([]) == []
+
+
+def small_repo(tmp_path: Path) -> Path:
+ for name in ("good_a.py", "bad.py", "good_b.py"):
+ (tmp_path / name).write_text(f"def {name[:-3]}():\n return 1\n", encoding="utf-8")
+ return tmp_path
+
+
+def test_reparse_repo_skips_the_file_that_fails(monkeypatch, small_repo: Path) -> None:
+ from repowise.core.ingestion import ASTParser
+ from repowise.core.pipeline.reparse import reparse_repo
+
+ def pool(_fn, items, _workers, results, **_kw):
+ parser = ASTParser()
+ for i, (fi, source) in enumerate(items):
+ if fi.path.endswith("bad.py"):
+ results[i] = ParseTimeoutError("parse timed out after 60s")
+ else:
+ results[i] = parser.parse_file(fi, source)
+
+ monkeypatch.setattr(ing, "run_with_deadline", pool)
+ parsed, source_map, _structure = reparse_repo(small_repo, [])
+
+ paths = sorted(p.file_info.path for p in parsed)
+ assert paths == ["good_a.py", "good_b.py"]
+ assert sorted(source_map) == ["good_a.py", "good_b.py"]
diff --git a/tests/unit/pipeline/test_parse_pool_deadline.py b/tests/unit/pipeline/test_parse_pool_deadline.py
new file mode 100644
index 000000000..71632d0a0
--- /dev/null
+++ b/tests/unit/pipeline/test_parse_pool_deadline.py
@@ -0,0 +1,154 @@
+"""No single file may stall or exhaust the parse pool.
+
+These run real spawn pools, so the task functions live at module level where a
+child process can import them.
+"""
+
+from __future__ import annotations
+
+import os
+import sys
+import time
+
+import pytest
+
+from repowise.core.pipeline import parse_pool
+from repowise.core.pipeline.parse_pool import (
+ PENDING,
+ ParseTimeoutError,
+ ParseWorkerCrashError,
+ run_with_deadline,
+)
+
+
+def _task(item: str) -> str:
+ if item == "hang":
+ while True:
+ time.sleep(1)
+ if item == "crash":
+ os._exit(3)
+ if item == "boom":
+ raise ValueError("boom")
+ if item == "allocate":
+ return str(len(bytearray(4 * 1024**3)))
+ return item.upper()
+
+
+def _run(items: list[str], *, workers: int = 2, timeout: float | None = 5.0) -> list:
+ results = [PENDING] * len(items)
+ seen: list[int] = []
+ run_with_deadline(
+ _task, items, workers, results, timeout=timeout, on_done=lambda i, _r: seen.append(i)
+ )
+ assert sorted(seen) == list(range(len(items))), "every task reports done exactly once"
+ return results
+
+
+def test_a_hung_task_times_out_and_the_rest_finish() -> None:
+ items = ["a", "hang", "b", "c", "hang", "d", "e"]
+ started = time.monotonic()
+ results = _run(items)
+ elapsed = time.monotonic() - started
+
+ assert [r for i, r in enumerate(results) if items[i] != "hang"] == ["A", "B", "C", "D", "E"]
+ for i, item in enumerate(items):
+ if item == "hang":
+ assert isinstance(results[i], ParseTimeoutError)
+ assert str(results[i]) == "parse timed out after 5s"
+ # Two workers, two hung tasks: one deadline each at most, plus spawn time.
+ assert elapsed < 60
+
+
+def test_every_worker_hung_at_once_still_finishes() -> None:
+ results = _run(["hang", "hang", "a", "b"], workers=2, timeout=3.0)
+ assert isinstance(results[0], ParseTimeoutError)
+ assert isinstance(results[1], ParseTimeoutError)
+ assert results[2:] == ["A", "B"]
+
+
+def test_a_crashing_task_is_isolated() -> None:
+ results = _run(["a", "b", "crash", "c", "d"], workers=2)
+ assert results[:2] == ["A", "B"]
+ assert isinstance(results[2], ParseWorkerCrashError)
+ assert results[3:] == ["C", "D"]
+
+
+def test_a_pool_that_cannot_start_raises_for_the_fallback(monkeypatch) -> None:
+ from concurrent.futures import ProcessPoolExecutor
+ from concurrent.futures.process import BrokenProcessPool
+
+ def dead_pool(workers: int) -> ProcessPoolExecutor:
+ return ProcessPoolExecutor(
+ max_workers=workers, mp_context=parse_pool.MP_SPAWN, initializer=os._exit, initargs=(1,)
+ )
+
+ monkeypatch.setattr(parse_pool, "_new_pool", dead_pool)
+ results = [PENDING, PENDING]
+ with pytest.raises(BrokenProcessPool):
+ run_with_deadline(_task, ["a", "b"], 2, results, timeout=5.0)
+ # No file is blamed: every slot is left for the in-process fallback.
+ assert results == [PENDING, PENDING]
+
+
+def test_resolved_slots_are_left_alone() -> None:
+ results = ["done", PENDING]
+ run_with_deadline(_task, ["hang", "x"], 1, results, timeout=5.0)
+ assert results == ["done", "X"]
+
+
+def test_a_task_exception_is_its_result() -> None:
+ results = _run(["a", "boom", "b"], timeout=None)
+ assert results[0] == "A"
+ assert isinstance(results[1], ValueError)
+ assert results[2] == "B"
+
+
[email protected](not sys.platform.startswith("linux"), reason="RLIMIT_DATA is enforced on Linux")
+def test_a_runaway_allocation_is_a_memory_error_for_that_file(monkeypatch) -> None:
+ monkeypatch.setenv("REPOWISE_PARSE_WORKER_MEMORY_MB", "512")
+ results = _run(["a", "allocate", "b"])
+ assert results[0] == "A"
+ assert isinstance(results[1], MemoryError)
+ assert results[2] == "B"
+
+
+ ("raw", "expected"),
+ [(None, 60.0), ("", 60.0), ("15", 15.0), ("0.5", 0.5), ("0", None), ("-3", 60.0), ("x", 60.0)],
+)
+def test_parse_timeout_env(monkeypatch, raw: str | None, expected: float | None) -> None:
+ if raw is None:
+ monkeypatch.delenv("REPOWISE_PARSE_TIMEOUT_S", raising=False)
+ else:
+ monkeypatch.setenv("REPOWISE_PARSE_TIMEOUT_S", raw)
+ assert parse_pool.parse_timeout_s() == expected
+
+
+def test_report_names_the_skipped_files() -> None:
+ from datetime import datetime
+
+ from repowise.core.ingestion.models import FileInfo
+ from repowise.core.pipeline.phases.ingestion import report_parse_failures
+
+ def fi(path: str) -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="sql",
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+ to_parse = [(0, (fi("ok.sql"), b""), ""), (1, (fi("slow.sql"), b""), "")]
+ assert report_parse_failures(to_parse, ["parsed", ("x", "syntax")]) is None
+ message = report_parse_failures(
+ to_parse, ["parsed", ParseTimeoutError("parse timed out after 60s")]
+ )
+ assert message is not None
+ assert "slow.sql (parse timed out after 60s)" in message
+ assert "REPOWISE_PARSE_TIMEOUT_S" in message
diff --git a/tests/unit/pipeline/test_parse_pool_rounds.py b/tests/unit/pipeline/test_parse_pool_rounds.py
new file mode 100644
index 000000000..447f6a883
--- /dev/null
+++ b/tests/unit/pipeline/test_parse_pool_rounds.py
@@ -0,0 +1,148 @@
+"""``run_with_deadline``'s scheduling, driven in-process with a fake executor.
+
+The fake resolves futures from timer threads, so deadlines, requeues and
+crash isolation run in this process where coverage and timing can see them.
+``test_parse_pool_deadline.py`` covers the same behaviour with real workers.
+"""
+
+from __future__ import annotations
+
+import os
+import threading
+from concurrent.futures import Future
+from concurrent.futures.process import BrokenProcessPool
+
+import pytest
+
+from repowise.core.pipeline import parse_pool
+from repowise.core.pipeline.parse_pool import (
+ PENDING,
+ ParseTimeoutError,
+ ParseWorkerCrashError,
+ run_with_deadline,
+)
+
+
+def _upper(item: str) -> str:
+ return item.upper()
+
+
+class _FakePool:
+ """An executor whose tasks behave by item name.
+
+ ``hang`` never finishes; ``crash`` breaks the pool, failing every
+ unfinished future with ``BrokenProcessPool``; ``victim`` never finishes in
+ the first pool built and finishes normally in later ones; ``slow``
+ finishes after a short delay; anything else finishes right away.
+ """
+
+ def __init__(self, generation: int) -> None:
+ self.generation = generation
+ self.pending: list[Future] = []
+ self.killed = False
+
+ def submit(self, fn, item=None):
+ fut: Future = Future()
+ if fn is os.getpid:
+ fut.set_result(0)
+ return fut
+ self.pending.append(fut)
+ if item == "hang" or (item == "victim" and self.generation == 0):
+ return fut
+ if item == "crash":
+ for other in self.pending:
+ if not other.done():
+ other.set_exception(BrokenProcessPool("worker died"))
+ return fut
+ delay = 0.3 if item == "slow" else 0.01
+ threading.Timer(delay, self._finish, (fut, fn, item)).start()
+ return fut
+
+ @staticmethod
+ def _finish(fut: Future, fn, item) -> None:
+ if not fut.done():
+ fut.set_result(fn(item))
+
+ def shutdown(self, wait: bool = True, cancel_futures: bool = False) -> None:
+ self.killed = not wait
+
+
+def pools(monkeypatch) -> list[tuple[int, _FakePool]]:
+ built: list[tuple[int, _FakePool]] = []
+
+ def new_pool(workers: int) -> _FakePool:
+ pool = _FakePool(len(built))
+ built.append((workers, pool))
+ return pool
+
+ monkeypatch.setattr(parse_pool, "_new_pool", new_pool)
+ return built
+
+
+def _run(items: list[str], workers: int, timeout: float | None) -> list:
+ results = [PENDING] * len(items)
+ run_with_deadline(_upper, items, workers, results, timeout=timeout)
+ return results
+
+
+def test_timeout_requeues_the_other_in_flight_task(pools) -> None:
+ # ``victim`` is still running in the first pool when ``hang`` expires, so
+ # it is requeued, not blamed, and finishes in the replacement pool.
+ results = _run(["hang", "a", "victim", "b"], workers=2, timeout=0.5)
+
+ assert isinstance(results[0], ParseTimeoutError)
+ assert str(results[0]) == "parse timed out after 0.5s"
+ assert results[1:] == ["A", "VICTIM", "B"]
+ assert len(pools) == 2
+ assert pools[0][1].killed, "the pool holding the stuck task is killed, not awaited"
+
+
+def test_crash_is_blamed_only_after_a_one_at_a_time_retry(pools) -> None:
+ results = _run(["slow", "crash", "c"], workers=2, timeout=5.0)
+
+ assert results[0] == "SLOW", "the task that was in flight beside the crash is retried"
+ assert isinstance(results[1], ParseWorkerCrashError)
+ assert results[2] == "C"
+ # The shared pool breaks; a one-worker pool runs the two suspects in turn
+ # until ``crash`` breaks it alone; a fresh shared pool finishes the rest.
+ assert [workers for workers, _pool in pools] == [2, 1, 2]
+
+
+def test_no_deadline_waits_for_a_slow_task(pools) -> None:
+ results = _run(["slow", "a"], workers=1, timeout=None)
+ assert results == ["SLOW", "A"]
+ assert len(pools) == 1
+
+
+def test_zero_timeout_env_means_no_deadline(monkeypatch, pools) -> None:
+ monkeypatch.setenv("REPOWISE_PARSE_TIMEOUT_S", "0")
+ results = _run(["slow"], workers=1, timeout=parse_pool.parse_timeout_s())
+ assert results == ["SLOW"]
+
+
+def test_a_failed_probe_after_a_crash_never_sends_suspects_to_the_fallback(
+ monkeypatch, pools
+) -> None:
+ real_new_pool = parse_pool._new_pool
+
+ class _NoStart(_FakePool):
+ def submit(self, fn, item=None):
+ if fn is os.getpid:
+ raise OSError("cannot spawn")
+ return super().submit(fn, item)
+
+ def new_pool(workers: int):
+ pool = real_new_pool(workers)
+ return pool if len(pools) == 1 else _NoStart(pool.generation)
+
+ monkeypatch.setattr(parse_pool, "_new_pool", new_pool)
+ results = [PENDING] * 3
+ with pytest.raises(OSError, match="cannot spawn"):
+ run_with_deadline(_upper, ["slow", "crash", "c"], 2, results, timeout=5.0)
+
+ # Both suspects are resolved as crashes; only the never-started file is
+ # left for the in-process fallback.
+ assert isinstance(results[0], ParseWorkerCrashError)
+ assert isinstance(results[1], ParseWorkerCrashError)
+ assert results[2] is PENDING
diff --git a/tests/unit/pipeline/test_parse_pool_workers.py b/tests/unit/pipeline/test_parse_pool_workers.py
index 0c2851bd4..4d9ff6da0 100644
--- a/tests/unit/pipeline/test_parse_pool_workers.py
+++ b/tests/unit/pipeline/test_parse_pool_workers.py
@@ -10,6 +10,7 @@ import sys
import pytest
+from repowise.core.pipeline import parse_pool
from repowise.core.pipeline.phases import ingestion as ing
@@ -130,7 +131,7 @@ class TestBothCallSitesAreBounded:
def test_pool_uses_the_shared_helper(self):
import inspect
- src = inspect.getsource(ing._parse_misses)
+ src = inspect.getsource(ing.parse_guarded)
assert "parse_pool_workers(" in src, "the parse pool must be sized via the shared helper"
assert "os.cpu_count()" not in src, "the pool must not be sized from the host core count"
@@ -156,7 +157,7 @@ class TestBothCallSitesAreBounded:
(tmp_path / f"mod_{i}.py").write_text(f"def f_{i}(x):\n return x + {i}\n")
seen: list[int | None] = []
- real = ing.ProcessPoolExecutor
+ real = parse_pool.ProcessPoolExecutor
def recording(*args, **kwargs):
seen.append(kwargs.get("max_workers"))
@@ -166,7 +167,7 @@ class TestBothCallSitesAreBounded:
kwargs["max_workers"] = 1
return real(*args, **kwargs)
- monkeypatch.setattr(ing, "ProcessPoolExecutor", recording)
+ monkeypatch.setattr(parse_pool, "ProcessPoolExecutor", recording)
parsed, *_ = await ing._run_ingestion(
tmp_path,
diff --git a/tests/unit/workspace/test_ddl_guarded_parse.py b/tests/unit/workspace/test_ddl_guarded_parse.py
new file mode 100644
index 000000000..7b35eb35d
--- /dev/null
+++ b/tests/unit/workspace/test_ddl_guarded_parse.py
@@ -0,0 +1,30 @@
+"""DDL contracts parse through the guarded ``parse_sql``.
+
+A psql meta-command or a statement sqlglot cannot finish must not cost the
+tables declared after it.
+"""
+
+from __future__ import annotations
+
+from repowise.core.workspace.extractors.base import ScanContext
+from repowise.core.workspace.extractors.data.ddl import DdlDialect
+
+
+def _tables(content: str) -> list[str]:
+ ctx = ScanContext("svc", "schema.sql", ".sql", content)
+ return [c.contract_id for c in DdlDialect().extract(ctx)]
+
+
+def test_a_psql_set_line_does_not_swallow_the_next_table() -> None:
+ content = "\\set ON_ERROR_STOP on\nCREATE TABLE orders (id INT, total NUMERIC);\n"
+ assert _tables(content) == ["data::orders"]
+
+
+def test_a_table_after_an_over_budget_statement_is_still_found() -> None:
+ # Both statements before ``orders`` loop forever in unguarded sqlglot.
+ content = (
+ "COPY staging FROM :'datafile';\n"
+ "CREATE TABLE broken (id INT, flag INTEGER NOT NUL);\n"
+ "CREATE TABLE orders (id INT, total NUMERIC);\n"
+ )
+ assert _tables(content) == ["data::orders"]