Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
OP_STACK_DEPTH_CAP = 20
SLOW_OPS_CAP = 50

# Structural/wrapper ops whose span is a whole phase, not a unit of work — excluded
# from slow_ops so they don't crowd out the actual slow I/O calls (db/http/sink).
# Structural ops are excluded from slow_ops so they don't crowd out the
# actual slow I/O calls (db/http/sink).
_NON_LEAF_OPS = frozenset({"workflow.execute", "source.iter", "stage.run", "processor.run", "bulksink.run"})


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@

Tripwires:
* Hang: a thread on the same op for >stuck_warn_seconds (warn) or
>auto_dump_seconds (warn + dump_reason).
>auto_dump_seconds (warn + dump_reason). Whole-phase wrapper ops
(_PHASE_OPS — source.iter, workflow.execute, ...) are excluded because
their cumulative age grows monotonically on healthy long runs.
* Memory pressure: PSI avg10 over threshold; cgroup `memory.events.high`
or `.events.oom` incremented since the previous tick.
"""
Expand All @@ -30,6 +32,9 @@
from metadata.ingestion.diagnostics.config import DIAG_LOG_PREFIX, DiagnosticsConfig
from metadata.ingestion.diagnostics.samplers.memory import MemorySample, MemoryTracker

# Phase duration includes completed work; per-record processor/stage spans remain judged.
_PHASE_OPS = frozenset({"workflow.execute", "source.iter", "bulksink.run"})


@dataclass(frozen=True)
class Verdict:
Expand Down Expand Up @@ -86,6 +91,8 @@ def _judge_thread(
name_by_ident: dict[int, str],
now: float,
) -> Verdict | None:
if op_name in _PHASE_OPS:
return None
if age < self._config.stuck_warn_seconds:
return None
key = (tid, op_name)
Expand Down
128 changes: 125 additions & 3 deletions ingestion/tests/unit/diagnostics/test_watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,14 @@ def test_auto_dump_verdict_after_hang_threshold():
watchdog, registry = _make_watchdog()
tid = threading.get_ident()
started = _time.monotonic() - 1000.0
registry._stacks[tid] = [("source.iter", {"entity": "table42"}, started, 1)]
registry._stacks[tid] = [("snowflake.query", {"sql": "SELECT *"}, started, 1)]

verdicts = watchdog.check(_time.monotonic())
assert len(verdicts) == 1
verdict = verdicts[0]
assert "diag.watchdog.auto_dump" in verdict.message
assert verdict.dump_reason is not None
assert "watchdog:source.iter" in verdict.dump_reason
assert "watchdog:snowflake.query" in verdict.dump_reason


def test_redump_throttle_blocks_repeat_dump_verdicts():
Expand All @@ -85,6 +85,104 @@ def test_redump_throttle_blocks_repeat_dump_verdicts():
assert all(v.dump_reason is None for v in second)


# ---- whole-phase exclusion ----


@pytest.mark.parametrize("op_name", ["workflow.execute", "source.iter", "bulksink.run"])
def test_no_verdict_for_aged_wrapper_op_alone(op_name: str) -> None:
"""A whole-phase wrapper op whose cumulative age is past both thresholds must
not produce any verdict — its age is the phase span, not a sign of being stuck."""
watchdog, registry = _make_watchdog()
tid = threading.get_ident()
started = _time.monotonic() - 1000.0
registry._stacks[tid] = [(op_name, {}, started, 1)]
assert watchdog.check(_time.monotonic()) == []


def test_no_verdict_for_healthy_wrapper_with_intermittent_nested_progress():
"""Model a healthy long run: a wrapper frame held for the whole phase while
short nested ops come and go to represent per-record progress. No verdicts
should fire on any tick — whether the tick lands inside a nested op or after
it pops back to the wrapper."""
watchdog, registry = _make_watchdog()
tid = threading.get_ident()
# Wrapper held 1100 s — past warn (60 s) and dump (300 s) thresholds.
wrapper_started = _time.monotonic() - 1100.0
registry._stacks[tid] = [("source.iter", {"entity": "table42"}, wrapper_started, 1)]

# Tick 1: wrapper is the deepest frame — excluded, no verdicts.
assert watchdog.check(_time.monotonic()) == []

# Simulate several cycles of per-record progress: push a short nested op,
# tick inside it (small age), pop it, tick on the wrapper again (excluded).
for _ in range(3):
token = registry.push("sink.write", {"entity": "rec"})
assert watchdog.check(_time.monotonic()) == []
registry.pop(token)
assert watchdog.check(_time.monotonic()) == []


def test_no_verdict_for_healthy_workflow_execute_across_redump_window(monkeypatch: pytest.MonkeyPatch) -> None:
"""Whole-phase operations remain silent beyond the redump throttle window."""
watchdog, registry = _make_watchdog()
now = 1000.0
monkeypatch.setattr(_time, "monotonic", lambda: now)
registry.push("workflow.execute", {})

now += 400.0
assert watchdog.check(now) == []
now += watchdog._config.redump_throttle_seconds + 1.0
assert watchdog.check(now) == []


@pytest.mark.parametrize("op_name", ["processor.run", "stage.run"])
@pytest.mark.parametrize("age", [100.0, 1000.0])
def test_stuck_per_record_operation_under_wrapper_still_fires(
monkeypatch: pytest.MonkeyPatch, op_name: str, age: float
) -> None:
"""Per-record operations emit warnings and dumps even beneath phase wrappers."""
watchdog, registry = _make_watchdog()
now = 1000.0
monkeypatch.setattr(_time, "monotonic", lambda: now)
registry.push("source.iter", {})
registry.push(op_name, {"entity": "my_table"})
now += age

verdicts = watchdog.check(now)
assert len(verdicts) == 1
verdict = verdicts[0]
assert verdict.severity == logging.WARNING
assert f"op={op_name}" in verdict.message
if age < 300.0:
assert "diag.warn.stuck" in verdict.message
assert verdict.dump_reason is None
else:
assert "diag.watchdog.auto_dump" in verdict.message
assert verdict.dump_reason is not None
assert f"watchdog:{op_name}@" in verdict.dump_reason


def test_nested_stuck_op_under_wrapper_still_fires():
"""A genuinely stuck *leaf* op beneath a wrapper must still be caught —
the exclusion only skips the wrapper frame, not real work."""
watchdog, registry = _make_watchdog()
tid = threading.get_ident()
wrapper_started = _time.monotonic() - 1200.0
registry._stacks[tid] = [("source.iter", {"entity": "t"}, wrapper_started, 1)]
# Push a nested op that is itself aged past the dump threshold.
nested_started = _time.monotonic() - 1000.0
registry._stacks[tid].append(("snowflake.query", {"sql": "SELECT 1"}, nested_started, 2))

verdicts = watchdog.check(_time.monotonic())
assert len(verdicts) == 1
verdict = verdicts[0]
assert "diag.watchdog.auto_dump" in verdict.message
assert verdict.dump_reason is not None
assert "snowflake.query" in verdict.dump_reason
# The wrapper must NOT appear in the verdict — only the stuck leaf op.
assert "source.iter" not in verdict.dump_reason


# ---- handler shell: verdicts -> log + dump ----


Expand All @@ -93,7 +191,7 @@ def _make_handler_with_hung_op(started_seconds_ago: float):
registry = OperationRegistry()
memory = MemoryTracker()
tid = threading.get_ident()
registry._stacks[tid] = [("source.iter", {"entity": "t"}, _time.monotonic() - started_seconds_ago, 1)]
registry._stacks[tid] = [("snowflake.query", {"sql": "SELECT 1"}, _time.monotonic() - started_seconds_ago, 1)]
aspects = [registry, HttpTracker(), memory, TimeAccountingSampler(registry), StageProgressCollector()]
return DiagnosticsHandler(
config=config,
Expand Down Expand Up @@ -122,3 +220,27 @@ def test_handler_run_watchdog_logs_warn_without_dump_on_stuck(caplog: pytest.Log
out = "\n".join(r.getMessage() for r in caplog.records)
assert "diag.warn.stuck" in out
assert "diag.dump.begin" not in out


def test_handler_run_watchdog_no_dump_for_healthy_wrapper_op(caplog: pytest.LogCaptureFixture) -> None:
"""End-to-end: a healthy wrapper op aged past the dump threshold must not
produce any watchdog warn/dump output via the handler."""
config = DiagnosticsConfig()
registry = OperationRegistry()
memory = MemoryTracker()
tid = threading.get_ident()
registry._stacks[tid] = [("source.iter", {"entity": "t"}, _time.monotonic() - 1100.0, 1)]
aspects = [registry, HttpTracker(), memory, TimeAccountingSampler(registry), StageProgressCollector()]
handler = DiagnosticsHandler(
config=config,
aspects=aspects,
watchdog=Watchdog(registry, memory, config),
db_introspector=None,
workflow=None,
)
with caplog.at_level(logging.WARNING, logger="metadata.Diagnostics"):
handler.run_watchdog()
out = "\n".join(r.getMessage() for r in caplog.records)
assert "diag.warn.stuck" not in out
assert "diag.watchdog.auto_dump" not in out
assert "diag.dump.begin" not in out
Loading