Exercise 3: The Non-Terminating Recursive CTE Failure Mode — Possible Solution ==================================================================== WHAT CAUSES A RECURSIVE CTE TO NEVER TERMINATE ------------------------------ Per this chapter's own warn-box, "if the recursive term doesn't actually converge — a cyclic manager_id relationship (A reports to B, who reports back to A), or a bug in the termination logic — a recursive CTE can loop indefinitely." A recursive CTE stops naturally once a pass through the recursive term finds no new rows to add. If the underlying data contains a cycle (employee A's manager is B, and employee B's manager is A), the recursive term keeps "finding" rows that lead back into the same cycle indefinitely — there's no natural point where the query legitimately runs out of new rows to add, because the relationship loops back on itself forever. WHY THIS IS A DIFFERENT FAILURE MODE THAN AN ORDINARY QUERY BUG ------------------------------ Per this chapter, "this isn't an ordinary query bug: an incorrect join returns wrong-but-finite output; a non-terminating recursive CTE can hang or exhaust memory." A typical incorrect query — a wrong JOIN condition, a missing WHERE clause — still finishes executing; it just returns the WRONG rows, which can be caught, inspected, and debugged by looking at the (finite) output. A non-terminating recursive CTE never finishes executing at all — there's no output to inspect, because the query keeps running, consuming growing memory and CPU resources, until it's manually killed or the system runs out of resources. This is a resource-exhaustion/availability problem, not a correctness problem — a genuinely more serious category of failure than simply getting the wrong answer. WHY POSTGRES DOESN'T CATCH THIS AUTOMATICALLY BY DEFAULT ------------------------------ Per this chapter, "Postgres doesn't detect cycles automatically by default (a CYCLE clause exists in newer Postgres versions specifically for explicit cycle detection)." Without opting into that explicit CYCLE clause, Postgres has no built-in safeguard against this scenario — the responsibility falls on the query author to either know their data can't contain cycles, or to test the recursive CTE against genuinely cyclic test data before relying on it in a real, production setting. WHY THIS WORKS AS AN ANSWER ------------------------------ It identifies the specific cause (a cycle in the underlying data or a termination-logic bug) using the chapter's own example, and explains precisely why this differs from an ordinary query bug — a resource- exhaustion failure with no finite output to debug, rather than a correctness failure with wrong-but-inspectable output.