{
 "src/backend/executor/execExprInterp.c": {
  "6102": {
   "func": "ExecEvalRPRNavSet",
   "reachable": false,
   "subs": [
    [
     "6102",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6102",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Line 6102 (target_pos = -1 on subtraction underflow for RPR_NAV_PREV) cannot be reached by any SQL input. The subtraction is pg_sub_s64_overflow(winstate->currentpos, offset, &target_pos). currentpos is declared int64 in execnodes.h:2612 and is a window-partition row index, always in [0, nrows-1], hence >= 0. offset is read via DatumGetInt64 (line 6077) and validated to be non-negative at lines 6079-6082 (negative -> ereport ERROR), or set to a small default (0/1) when the offset arg is absent. For currentpos >= 0 and offset >= 0, the result currentpos - offset ranges from currentpos (<= INT64_MAX, no overflow) down to 0 - INT64_MAX = -INT64_MAX = INT64_MIN + 1, which is strictly greater than INT64_MIN and therefore representable. Underflow is mathematically impossible, so pg_sub_s64_overflow always returns false and the guarded assignment on 6102 is never executed. I tried to refute this: the only way to make currentpos - offset underflow would require offset > currentpos - INT64_MIN, i.e. offset > INT64_MAX (since the most negative reachable currentpos is 0), which int64 offset cannot hold; and a negative currentpos is structurally impossible. No SQL input reaches the line.",
      "refinedTest": "No test can cover this line; it is unreachable. To exercise the surrounding live RPR_NAV_PREV path (lines 6100-6101, 6103) use a normal PREV navigation, e.g. a window with PATTERN/DEFINE referencing PREV(col) or PREV(col, n) with a non-negative offset; that drives the non-overflow path but never the 6102 assignment. If coverage of 6102 is mandatory, it cannot be obtained via SQL and the guard should instead be downgraded to an Assert (see refinedFix).",
      "refinedFix": "Keep the guard but document it as defensive, or convert to an assertion since underflow is impossible. Option A (preferred for safety/symmetry with the other arms): leave the code and add a comment such as \"currentpos >= 0 and offset >= 0, so subtraction cannot underflow; guard kept for symmetry with NEXT/FIRST/LAST\". Option B: compute target_pos = winstate->currentpos - offset; and Assert(!pg_sub_s64_overflow(winstate->currentpos, offset, &target_pos)); to express the invariant and drop the unreachable runtime branch. Note this asymmetry: the NEXT arm (6105, pg_add_s64_overflow) and FIRST arm (6110) CAN overflow for large offsets and are genuinely reachable, so only the PREV (6101-6102) overflow branch is provably dead."
     }
    ]
   ]
  },
  "6148": {
   "func": "ExecEvalRPRNavSet",
   "reachable": false,
   "subs": [
    [
     "6148",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6148",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable. Line 6148 (target_pos = -1) fires only if pg_sub_s64_overflow(inner_pos, compound_offset, &target_pos) reports underflow in the RPR_NAV_PREV_FIRST branch. Both operands are provably non-negative: inner_pos is constrained to [0, currentpos] by the guard at lines 6135-6139 (inner_pos > currentpos || inner_pos < 0 => break), and compound_offset is validated >= 0 by rpr_nav_get_compound_offset (line 6034 rejects val < 0; NULL rejected at 6027). Subtracting a non-negative from a non-negative cannot underflow int64: the most negative achievable result is 0 - INT64_MAX = -(2^63 - 1) = INT64_MIN + 1, which is still representable (INT64_MIN = -(2^63)). Underflow would require compound_offset > INT64_MAX, impossible for an int64. I attempted refutation with the largest possible outer literal (PREV(FIRST(...), 9223372036854775807) over an empty/zero-position match giving inner_pos=0): result is -INT64_MAX, no overflow, so 6148 is NOT taken (the value is simply treated as out-of-range downstream by ExecRPRNavGetSlot). The compound PREV(FIRST(...), N) syntax is real and exercised in rpr.sql (lines 560-577), so the branch is reachable structurally but the overflow=true outcome is mathematically impossible. Note the sibling pg_add branches (NEXT_FIRST line 6152, NEXT_LAST line 6187) CAN overflow and are reachable; only the two pg_sub overflow arms (6148 and 6182) are dead because both their operands are non-negative.",
      "refinedTest": "No SQL test can cover this line; it is mathematically dead. (Best refutation attempt, which still does NOT hit it: a query whose DEFINE uses PREV(FIRST(x), 9223372036854775807) such that the inner position is 0 -- e.g. a single-row-per-partition match -- yields 0 - INT64_MAX = -INT64_MAX, no underflow, branch not taken.) To make the line coverable one would have to change the type/validation so compound_offset could exceed INT64_MAX or inner_pos could be negative, neither of which the surrounding guards permit.",
      "refinedFix": "Replace the unreachable overflow handling with an Assert documenting the invariant, e.g.:\n  /* inner_pos in [0,currentpos] and compound_offset >= 0, so no underflow */\n  Assert(!pg_sub_s64_overflow(inner_pos, compound_offset, &target_pos));\n  target_pos = inner_pos - compound_offset;\nThe same simplification applies to the RPR_NAV_PREV_LAST sub-overflow arm at line 6182 (inner_pos there is also non-negative: line 6170 enforces inner_pos >= nav_match_start >= 0). Keep the pg_add_s64_overflow handling for the NEXT_FIRST/NEXT_LAST arms unchanged -- those are genuinely reachable."
     }
    ]
   ]
  },
  "6183": {
   "func": "ExecEvalRPRNavSet",
   "reachable": false,
   "subs": [
    [
     "6183",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6183",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. Line 6183 is the target_pos=-1 assignment inside the `if (pg_sub_s64_overflow(inner_pos, compound_offset, &target_pos))` branch for RPR_NAV_PREV_LAST. To reach it, inner_pos - compound_offset must underflow below INT64_MIN. But the surrounding code guarantees: (1) inner_pos = currentpos - offset where offset>=0 (validated 6079-6082), so inner_pos <= currentpos; (2) line 6170-6174 forces inner_pos >= nav_match_start, and nav_match_start is a real row position set from matchStartRow or 0 (nodeWindowAgg.c:2831, 4462), hence >= 0; so inner_pos is in [0, currentpos], a small non-negative bounded by partition size; (3) compound_offset is validated >= 0 (rpr_nav_get_compound_offset, lines 6034-6037). The minimum possible value of inner_pos - compound_offset is 0 - INT64_MAX = -(2^63-1) = INT64_MIN+1, which is within int64 range. Therefore pg_sub_s64_overflow can never return true here. Negative or NULL offsets are rejected with ereport(ERROR) before this point, so no SQL/regression input can construct an underflowing subtraction. I tried to refute by maximizing compound_offset (bigint up to INT64_MAX) against inner_pos=0, but the result is still exactly representable. Genuinely unreachable.",
      "refinedTest": "No SQL test can cover this line. The only way to exercise pg_sub_s64_overflow returning true would require inner_pos to be negative AND compound_offset near INT64_MAX simultaneously, but inner_pos is provably in [0, currentpos] after the guards at lines 6135-equivalent (6165) and 6170-6174, and compound_offset>=0. The branch is dead under all valid executor states. (Contrast: the corresponding overflow guards that ARE reachable are pg_add_s64_overflow paths such as RPR_NAV_NEXT at 6105 and RPR_NAV_NEXT_FIRST at 6152, where adding a large bigint offset to a non-negative position can genuinely overflow upward and could be tested with e.g. NEXT(x, 9223372036854775807).)",
      "refinedFix": "Replace the unreachable overflow check with an Assert documenting the invariant, e.g.:\n\nif (op->d.rpr_nav.kind == RPR_NAV_PREV_LAST)\n{\n    /*\n     * inner_pos is in [nav_match_start, currentpos] (>= 0) and\n     * compound_offset >= 0, so the subtraction cannot underflow.\n     */\n    Assert(!pg_sub_s64_overflow(inner_pos, compound_offset, &target_pos));\n    target_pos = inner_pos - compound_offset;\n}\n\nAlternatively, keep the defensive overflow branch but add a comment noting it is unreachable given inner_pos>=0 and compound_offset>=0, to document why it is intentionally untested."
     }
    ]
   ]
  },
  "6192": {
   "func": "ExecEvalRPRNavSet",
   "reachable": false,
   "subs": [
    [
     "6192-6193",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6192-6193",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. The switch at execExprInterp.c:6098 dispatches on op->d.rpr_nav.kind, an RPRNavKind enum (primnodes.h:669-680) with EXACTLY 8 members: RPR_NAV_PREV/NEXT/FIRST/LAST and the four compounds PREV_FIRST/PREV_LAST/NEXT_FIRST/NEXT_LAST. Every one of the 8 has an explicit case label (lines 6100,6104,6108,6115,6123,6124,6158,6159), so the default at 6192-6193 matches no valid enum value. The kind field is populated by the expression compiler (EEOP_RPR_NAV_SET) from a parser/planner-validated RPRNav node, never from user-controlled raw integers. I tried to refute by looking for any path that sets kind from a cast/user value or an enum value lacking a case; there is none. The default elog(ERROR) is reachable only via memory corruption or an invalid cast, neither of which any SQL or regression input can produce. This is the canonical PostgreSQL can't-happen guard for an exhaustive enum switch.",
      "refinedTest": "No SQL/regression test can drive these lines, since the planner/expression-compiler only ever emits one of the 8 enumerated kinds, all of which have explicit case labels. Reaching the default would require fabricating an out-of-range RPRNavKind, which is impossible through the parser->planner->executor pipeline. The only way to exercise it at all would be a C-level fault-injection unit test that hand-constructs an ExprEvalStep with op->d.rpr_nav.kind set to an invalid value (e.g. 99) and calls the interpreter directly; that is outside the regression framework and not warranted.",
      "refinedFix": "No source change required. Keep the default elog(ERROR) as a standard defensive guard for an exhaustive switch over an enum, consistent with PostgreSQL convention. It is intentionally non-testable."
     }
    ]
   ]
  },
  "6106": {
   "func": "ExecEvalRPRNavSet",
   "reachable": true,
   "subs": [
    [
     "6106",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6106",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "Confirmed testable and currently uncovered. Line 6106 (target_pos = -1 on RPR_NAV_NEXT overflow) fires when currentpos + offset > INT64_MAX. The offset is coerced to int8 (parse_func.c:2204) and only validated >= 0 (execExprInterp.c:6079), so INT64_MAX is a legal offset with no upper bound. The existing suite's largest NEXT offset is NEXT(val,999) over 1000 rows (rpr.sql:812), giving max ~1998 -- never overflows, so 6106 is genuinely uncovered. I empirically proved on a live RPR build that DEFINE predicates are evaluated at currentpos >= 1 (an A+ match over val < NEXT(val,1) extended through currentpos 1 and 2), so currentpos + INT64_MAX overflows there and executes 6106; target_pos becomes -1, ExecRPRNavGetSlot returns nav_null_slot, NEXT(...) yields NULL. The proposed test ran and produced correct classification output. Caveat: per-line gcov confirmation was not obtainable because the installed binary is an LTO coverage build that zeroed/mis-attributed line counts (whole function showed ##### despite executing); reliance is on the behavioral discriminator test, which is conclusive.",
      "refinedTest": "Add to rpr.sql a DEFINE using a max-int8 NEXT offset on a >=2-row, all-true-predicate match so the matcher evaluates at currentpos>=1 (forcing overflow at line 6106):\n\nSELECT val, count(*) OVER w AS grp\nFROM (VALUES (1),(2),(3)) AS t(val)\nWINDOW w AS (\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS NEXT(val, 9223372036854775807) IS NULL\n)\nORDER BY val;\n\nExpected output (verified on a live build):\n val | grp\n-----+-----\n   1 |   3\n   2 |   0\n   3 |   0\n\nThe A+ match starts at row 0 and extends through currentpos 1 and 2; at currentpos>=1, currentpos + 9223372036854775807 overflows -> line 6106 (target_pos = -1) -> NEXT returns NULL -> IS NULL TRUE -> all 3 rows in one match group (grp=3 on the first row under FINAL count). Note: the predicate is also TRUE at currentpos=0 (no overflow there, INT64_MAX is simply out of range), but extension to currentpos>=1 is what executes 6106. To also cover the PREV overflow sibling (line 6102), add a symmetric DEFINE A AS PREV(val, 9223372036854775807) IS NULL on the same data (currentpos - INT64_MAX underflows).",
      "refinedFix": ""
     }
    ]
   ]
  },
  "6153": {
   "func": "ExecEvalRPRNavSet",
   "reachable": true,
   "subs": [
    [
     "6153",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6153",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED reachable and the proposed test covers line 6153. I built and ran the RPR-instrumented binary (PostgreSQL 19beta1 from tmp_install) against a fresh cluster, executed the proposed test, and gcov reported line 6153 executed (count 4) with line 6152's overflow branch taken. Line 6153 is the overflow handler in the RPR_NAV_NEXT_FIRST case: pg_add_s64_overflow(inner_pos, compound_offset, &target_pos) -> target_pos=-1. compound_offset is the user-supplied outer offset of NEXT(FIRST(expr), N), validated only >=0 in rpr_nav_get_compound_offset (execExprInterp.c:6034), so it can be INT64_MAX. inner_pos is partition-relative [match_start..currentpos]; it is >=1 whenever a match starts at partition position >=1 OR an inner offset >=1 is used, so inner_pos + INT64_MAX overflows. Skeptical note: the proposed test with inner default offset 0 does NOT overflow on the FIRST match (match_start=0 -> inner_pos=0 -> 0+INT64_MAX=INT64_MAX, no overflow, hits success line 6152), but it DOES overflow on subsequent match attempts whose match_start>=1; with a >=5-row partition this happens, hence the proposed test still reaches 6153. The output (IS NULL = TRUE) is the same for overflow and out-of-range, so the test's pass/fail cannot by itself prove which line ran, but gcov proves coverage. Existing rpr.sql:1185 (NEXT(FIRST(val),99)) exercises this case via the success path only (99 never overflows).",
      "refinedTest": "Either form covers line 6153 on a partition with >=2 matched rows. Most robust (overflows on every match independent of match_start) -- add to src/test/regress/sql/rpr.sql near the other compound-overflow tests:\n\n-- Compound NEXT(FIRST): outer offset = INT64_MAX overflows int64 -> target -1 -> NULL\nSELECT id, val, count(*) OVER w AS cnt\nFROM rpr_nav WINDOW w AS (\n    ORDER BY id\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A B+)\n    DEFINE A AS TRUE, B AS NEXT(FIRST(val, 1), 9223372036854775807) IS NULL\n);\n\nThe inner offset 1 forces inner_pos = match_start + 1 >= 1, so inner_pos + 9223372036854775807 always overflows regardless of where the match starts. The proposed test (NEXT(FIRST(val), 9223372036854775807) IS NULL, inner default 0) also works because later match attempts have match_start >= 1, but it relies on match-restart positioning; the inner-offset-1 form is preferred for determinism. Verified via gcov: line 6153 hit count 4, line 6152 overflow branch taken 100%.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "6188": {
   "func": "ExecEvalRPRNavSet",
   "reachable": true,
   "subs": [
    [
     "6188",
     {
      "functionName": "ExecEvalRPRNavSet",
      "lines": "6188",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED testable, and the proposed test hits the exact line. Line 6188 sets target_pos = -1 when pg_add_s64_overflow overflows in the RPR_NAV_NEXT_LAST branch (inner_pos + compound_offset). Reaching it requires: (1) inner offset of LAST valid >=0; (2) inner_pos = currentpos - inner_offset not overflowing (line 6165) and inner_pos >= nav_match_start (line 6170); (3) outer offset of NEXT validated >=0 (rpr_nav_get_compound_offset); (4) inner_pos + outer_offset overflows int64. The proposed test NEXT(LAST(val), 9223372036854775807) achieves all four: LAST inner offset defaults to 0, so inner_pos = currentpos (small, non-negative, always >= nav_match_start, passes lines 6165/6170), then currentpos + INT64_MAX overflows for any currentpos >= 1, hitting line 6187-6188. I empirically verified against a live RPR build (PG19beta1, fresh temp cluster). The proposed query returned TRUE (IS NULL) for the entire matched partition starting at row 1. A control with outer offset 1 returned TRUE only at the final row (legitimate out-of-range via nav_null_slot, NOT the overflow branch) and FALSE elsewhere. This divergence proves the INT64_MAX form forces the overflow branch at 6188 rather than the ordinary out-of-range path. Existing tests (e.g. NEXT(LAST(val,99),1) at rpr.sql:1203) trip the inner clamp at line 6170 instead and never reach 6188. Note: the proposed root cause text slightly mislabels the default inner offset as currentpos-0 being driven by user offset; the LAST inner offset is the default 0, which is exactly why inner_pos stays small and valid, so the explanation holds in effect.",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql (after the existing compound tests near line 1204), using the existing rpr_nav table:\n\n-- Compound: outer offset overflow on NEXT(LAST()) -> target_pos = -1 via add overflow (covers execExprInterp.c:6188)\nSELECT id, val, count(*) OVER w AS cnt\nFROM rpr_nav WINDOW w AS (\n    ORDER BY id\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS NEXT(LAST(val), 9223372036854775807) IS NULL\n);\n\nExpected output: all 6 rows match (A+ forms a single match from row 1); the row at id=1 shows cnt=6 and rows id=2..6 show cnt=0, because NEXT(LAST(val), INT64_MAX) overflows to NULL at every row, making the DEFINE predicate uniformly TRUE. (Verified empirically.) For symmetry, the analogous PREV(LAST()) underflow path uses pg_sub_s64_overflow at line 6182-6183; if that sibling line is also uncovered, add: DEFINE A AS PREV(LAST(val), 9223372036854775807) IS NULL similarly (inner_pos = currentpos small, currentpos - INT64_MAX underflows -> -1).",
      "refinedFix": ""
     }
    ]
   ]
  }
 },
 "src/backend/commands/explain.c": {
  "3073": {
   "func": "deparse_rpr_node",
   "reachable": false,
   "subs": [
    [
     "3073",
     {
      "functionName": "deparse_rpr_node",
      "lines": "3073",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable. Line 3073 (`altEnd = limit;`) only fires when `altEnd > limit`, i.e. when rpr_alt_scope_end(idx) overshoots the inherited limit. I traced every call site of deparse_rpr_node's ALT branch and the depth invariants from rpr.c (fillRPRPatternAlt sets ALT marker at depth d, branches at d+1; finalizeRPRPattern puts FIN at depth 0; rpr_alt_scope_end uses `depth <= d`, so it stops AT the first element whose depth is <= the ALT's depth and never skips a same-or-lower-depth boundary). The three possible limits all bound the ALT's scope: (1) top-level seq passes limit=numElements; an ALT here is at depth 0 and its scope_end stops at FIN (depth 0) or a depth-0 sibling, index <= numElements-1 < limit. (2) loneAlt path (line 3054) passes limit=end with the explicit guard rpr_alt_scope_end(idx+1)==end, so altEnd==limit exactly, not >. (3) seq inside a non-loneAlt group passes limit=group END index; the END sits at depth d_group = d_alt-1 < d_alt, so scope_end stops at or before it, altEnd <= limit. Nested ALTs are flattened by flattenAltChildren/optimizeAltPattern and {1,1} groups are unwrapped, so no two ALTs ever share a depth boundary that could push scope past the limit. In all cases altEnd <= limit, so `altEnd > limit` is never true. The root-cause analysis in the finding is accurate.",
      "refinedTest": "No SQL/regression input can drive execution through line 3073. The clamp is a no-op guard against an invariant violation that the bytecode generator (rpr.c) structurally prevents: an ALT's depth-derived scope end is always <= the limit handed down by its caller. Crafting patterns such as `A | B`, `(A | B) C`, `((A | B) C){2}`, nested `(A | (B | C))` (which gets flattened), or lone-ALT groups `((A | B)){2}` all exercise the surrounding ALT-deparse code (lines 3066-3072, 3075-3088) but the `altEnd > limit` condition stays false in every one. There is no reachable test; the line is correctly excluded from coverage.",
      "refinedFix": "Replace the silent clamp with an assertion documenting the invariant. Change lines 3072-3073 from `if (altEnd > limit) altEnd = limit;` to `Assert(altEnd <= limit);`. This removes the uncoverable assignment, documents that an ALT's depth-derived scope end never exceeds the inherited limit (guaranteed by the depth invariants in optimizer/plan/rpr.c: ALT branches at depth d+1, FIN/END boundaries at depth <= d, and ALT flattening preventing shared boundaries), and still catches any future invariant break in assert-enabled builds. The `limit` parameter is otherwise unused after this in the ALT branch, but it is still used by the VAR/BEGIN paths and by the Assert, so keep the parameter. Optionally add a one-line comment: `/* an ALT's scope end never exceeds the limit handed down (see rpr.c depth invariants) */`."
     }
    ]
   ]
  },
  "3109": {
   "func": "rpr_match_end",
   "reachable": false,
   "subs": [
    [
     "3109",
     {
      "functionName": "rpr_match_end",
      "lines": "3109",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. Line 3109 is `pg_unreachable()` placed after a for-loop that always returns. rpr_match_end (explain.c:3096-3110) is called only from the RPRElemIsBegin branch (explain.c:3044). In fillRPRPatternGroup (rpr.c:1226-1294) the BEGIN marker (lines 1233-1252) and the matching END marker (lines 1261-1291) are emitted under the IDENTICAL guard `node->min != 1 || node->max != 1` and share the same `depth` parameter. Children recurse at depth+1, so their END markers (deeper depth) are skipped by the `e->depth == d` test, and the first same-depth END (the real partner) is always present after beginIdx. Thus the loop (3102-3108) always returns before falling through. Round-trip serialization (-DWRITE_READ_PARSE_PLAN_TREES) copies the elements array verbatim preserving varId/depth, so it cannot introduce an unpaired BEGIN. No SQL/regression input or node rewrite can reach line 3109. Tried to refute via nested groups, ALT children (which emit no BEGIN/END VARID markers), and the copy/out/read round-trip; none break the pairing invariant. pg_unreachable() is the correct idiom and is intentionally excluded from meaningful coverage.",
      "refinedTest": "No test can drive execution through line 3109 because pg_unreachable() is only reached if a BEGIN element lacks a matching same-depth END, which the construction invariant in fillRPRPatternGroup makes impossible. No refined test exists; covering it would require corrupting the RPRPattern.elements array, which no SQL/regression path or node-tree round-trip can do.",
      "refinedFix": "No change needed. The line is `pg_unreachable()`, the correct defensive idiom for a code path guaranteed unreachable by the BEGIN/END pairing invariant. Leave as is; it is appropriately excluded from meaningful coverage."
     }
    ]
   ]
  },
  "3251": {
   "func": "show_window_def",
   "reachable": false,
   "subs": [
    [
     "3251-3252",
     {
      "functionName": "show_window_def",
      "lines": "3251-3252",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Lines 3251-3253 are the default: arm (elog(ERROR, \"unrecognized RPR nav offset kind: %d\", maxKind)) of the \"Nav Mark Lookback\" switch over maxKind, which is of type RPRNavOffsetKind. The enum (parsenodes.h:604-610) has exactly three values: RPR_NAV_OFFSET_FIXED, RPR_NAV_OFFSET_NEEDS_EVAL, RPR_NAV_OFFSET_RETAIN_ALL, all three handled by the preceding case arms (lines 3241-3249). maxKind is sourced from wagg->navMaxOffsetKind or (under es->analyze) planstate->navMaxOffsetKind. Every assignment to these fields in the backend uses one of the three valid enumerators: createplan.c:2826/7046 (FIXED), nodeWindowAgg.c:3042 (copies plan value), nodeWindowAgg.c:4194 (RETAIN_ALL), nodeWindowAgg.c:4199 (FIXED). No code path assigns an out-of-range value, so no SQL/regression input can drive execution into the default. Reaching it would require memory corruption or addition of a new enumerator without updating the switch. This is a standard PostgreSQL can't-happen guard. The original finding (no test proposed) is correct.",
      "refinedTest": "No SQL-level test can cover these lines; they are structurally unreachable given a 3-value enum fully handled by prior cases. Coverage would only be achievable via fault injection (e.g., a debug build that deliberately stores an invalid RPRNavOffsetKind into wagg->navMaxOffsetKind before EXPLAIN), which is not appropriate for the regression suite. Recommend marking as intentional defensive code rather than writing a test.",
      "refinedFix": "No action required. The elog(ERROR) default is the established PostgreSQL convention for enum switch-default guards and should be kept for robustness against future enum additions. Optionally it could be reduced to Assert(false) but that would weaken protection in production builds; keeping elog(ERROR) is preferable. Leave as-is and accept the 2 uncovered lines as defensive code."
     }
    ]
   ]
  },
  "3265": {
   "func": "show_window_def",
   "reachable": false,
   "subs": [
    [
     "3265-3266",
     {
      "functionName": "show_window_def",
      "lines": "3265-3266",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable. Lines 3265-3266 are the RPR_NAV_OFFSET_RETAIN_ALL arm of the firstKind (Nav Mark Lookahead) switch. I traced every writer of navFirstOffsetKind in the entire tree: (1) createplan.c:7049 copies the local value computed by compute_define_metadata, which assigns *firstKind ONLY to NEEDS_EVAL (2782), FIXED (2787), or FIXED (2794) -- never RETAIN_ALL; RETAIN_ALL is set ONLY for *maxKind on backward-reach overflow (2762). (2) nodeWindowAgg.c:3045 copies the plan value into exec state. (3) nodeWindowAgg.c:4206 (eval_define_offsets, the NEEDS_EVAL late-binding path) sets navFirstOffsetKind ONLY to FIXED; first-offset overflow is handled by clamping navFirstOffset to PG_INT64_MAX while keeping kind FIXED (4210), which is exactly why the FIXED arm at 3270-3272 prints 'infinite' instead of a RETAIN_ALL path. The RPR authors even added Assert(winstate->navFirstOffsetKind == RPR_NAV_OFFSET_FIXED) at nodeWindowAgg.c:4405, self-documenting that the lookahead/first dimension is structurally never RETAIN_ALL. I could not construct any SQL input (FIRST/PREV_FIRST/NEXT_FIRST with any quantifier or huge offset) that yields RETAIN_ALL for the first dimension, because overflow on that dimension clamps to FIXED+INT64_MAX rather than RETAIN_ALL. The arm exists purely for switch completeness (its sibling default already elog(ERROR)s on unrecognized kinds). The root-cause analysis in the finding is accurate.",
      "refinedTest": "No SQL/regression input can reach these lines. navFirstOffsetKind is never assigned RPR_NAV_OFFSET_RETAIN_ALL on any code path (verified: createplan.c compute_define_metadata only emits FIXED/NEEDS_EVAL for *firstKind; nodeWindowAgg.c eval_define_offsets only emits FIXED for the first dimension; first-offset overflow clamps to FIXED with navFirstOffset=PG_INT64_MAX, which routes to the existing 'infinite' branch at line 3270-3272, not here). Reaching this arm would require artificially mutating navFirstOffsetKind via a debugger/test stub, not via the SQL planner/executor, so no genuine regression test covers it.",
      "refinedFix": "Remove the dead RPR_NAV_OFFSET_RETAIN_ALL arm from the firstKind (Lookahead) switch in show_window_def. The default arm already does elog(ERROR, \"unrecognized RPR nav offset kind: %d\", firstKind), so deleting lines 3265-3268 keeps behavior identical while eliminating the permanently-uncoverable lines and correctly documenting (consistent with the Assert at nodeWindowAgg.c:4405) that the lookahead/first dimension never retains-all. If the authors prefer to keep all enum arms explicit for symmetry with the maxKind switch, add a brief comment '/* lookahead dimension never overflows to RETAIN_ALL; see eval_define_offsets */' and accept the 2 uncovered lines, or replace the arm body with Assert(false) to make the intent explicit. Folding into default is the cleanest."
     }
    ]
   ]
  },
  "3277": {
   "func": "show_window_def",
   "reachable": false,
   "subs": [
    [
     "3277-3278",
     {
      "functionName": "show_window_def",
      "lines": "3277-3278",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Lines 3277-3278 are the default: arm (elog(ERROR, \"unrecognized RPR nav offset kind: %d\", firstKind)) of the Lookahead switch over firstKind, a strongly-typed RPRNavOffsetKind. The enum (src/include/nodes/parsenodes.h:605-609) has exactly three enumerators: RPR_NAV_OFFSET_FIXED, RPR_NAV_OFFSET_NEEDS_EVAL, RPR_NAV_OFFSET_RETAIN_ALL, and the switch (explain.c:3261/3265/3269) explicitly handles all three. firstKind is sourced either from wagg->navFirstOffsetKind (plan node, set by compute_define_metadata in createplan.c, default FIXED) or, under EXPLAIN ANALYZE, from planstate->navFirstOffsetKind (set in nodeWindowAgg.c:3045/4206, only ever FIXED/NEEDS_EVAL/RETAIN_ALL; an Assert at 4405 even pins it to FIXED on the eval path). No SQL or regression input can assign a 4th value; reaching the default would require memory corruption. I tried to refute by tracing every producer of the field and found none that can emit an out-of-range value. This matches the already-confirmed Lookback default at 3251-3253. Switch is additionally guarded by if (wagg->hasFirstNav) but that does not change reachability of the default within the switch.",
      "refinedTest": "No test can cover these exact lines from SQL. They are a can't-happen guard over an exhaustively-handled 3-value enum; the only way to enter the default is memory corruption, which is not expressible as a regression input. Leave uncovered.",
      "refinedFix": "Acceptable as the standard enum switch-default guard following PostgreSQL convention (mirrors the Lookback default at 3251-3253). No action required. The existing elog(ERROR, ...) is the idiomatic in-tree form for unrecognized-enum defaults, so keeping it as-is is preferable to switching to Assert(false) for consistency with the sibling switch."
     }
    ]
   ]
  },
  "3261": {
   "func": "show_window_def",
   "reachable": true,
   "subs": [
    [
     "3261-3262",
     {
      "functionName": "show_window_def",
      "lines": "3261-3262",
      "lineCount": 2,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED testable and the proposed test covers the exact lines. Lines 3261-3263 are the RPR_NAV_OFFSET_NEEDS_EVAL arm of the Lookahead switch (gated by wagg->hasFirstNav at explain.c:3257), printing \"Nav Mark Lookahead: runtime\". Root cause is accurate: when !es->analyze, firstKind = wagg->navFirstOffsetKind from the plan (explain.c:3231-3237 only overrides with executor-resolved values for ANALYZE). At plan time, a non-Const offset arg makes extract_const_offset return false (createplan.c:2502-2526), setting ctx.firstNeedsEval -> navFirstOffsetKind = NEEDS_EVAL (createplan.c:2780-2784). NEXT_FIRST also sets hasFirst=true (createplan.c:2653-2656), so the Lookahead block runs. The existing test_overflow_lookahead (rpr_explain.out:5998-6022) uses ONLY EXPLAIN ANALYZE on this dimension, which resolves NEEDS_EVAL to FIXED/infinite at executor init, hitting the FIXED arm (3269-3275). The plain-EXPLAIN \"runtime\" case is only exercised on the LookBACK dimension (test_overflow_lookback line 5971 -> line 3242), never Lookahead. grep confirms NO expected .out file contains \"Nav Mark Lookahead: runtime\". I EMPIRICALLY ran the proposed test against a freshly initdb'd v19 RPR cluster (the installed binary was a control-version ahead of PGDATA, so I built a temp cluster): plain EXPLAIN (COSTS OFF) of the parameterized NEXT(FIRST(v,$1),$2) query under force_generic_plan produced exactly \"Nav Mark Lookback: 0\" and \"Nav Mark Lookahead: runtime\", proving execution flows through lines 3261-3263. Note: the orchestrator labeled these as lines 3261-3262, but the ExplainPropertyText call spans 3262-3263; the case label is 3261. The 2-line count is fine and the test covers all of them.",
      "refinedTest": "Proposed test works as-is and is empirically verified. Add to rpr_explain.sql (mirrors the existing test_overflow_lookahead but plain EXPLAIN on the Lookahead dimension):\n\nPREPARE p_first_runtime(int8, int8) AS\nSELECT count(*) OVER w\nFROM generate_series(1,10) s(v)\nWINDOW w AS (\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS NEXT(FIRST(v, $1), $2) IS NOT NULL\n);\nSET plan_cache_mode = force_generic_plan;\nEXPLAIN (COSTS OFF) EXECUTE p_first_runtime(1, 1);\nRESET plan_cache_mode;\nDEALLOCATE p_first_runtime;\n\nExpected output (verified live):\n WindowAgg\n   Window: w AS (ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING)\n   Pattern: a+\n   Nav Mark Lookback: 0\n   Nav Mark Lookahead: runtime\n   ->  Function Scan on generate_series s\n\nA simpler equivalent that also covers the lines: DEFINE A AS FIRST(v, $1) IS NOT NULL (a bare RPR_NAV_FIRST with a Param offset also sets hasFirst + firstNeedsEval). The compound NEXT(FIRST(...)) form is fine and matches the existing test family's style.",
      "refinedFix": "No code fix needed; the lines are correct and reachable. Only a regression test is missing."
     }
    ]
   ]
  }
 },
 "src/backend/executor/execRPR.c": {
  "1186": {
   "func": "nfa_advance_end",
   "reachable": true,
   "subs": [
    [
     "1186-1187",
     {
      "functionName": "nfa_advance_end",
      "lines": "1186-1187",
      "lineCount": 2,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "VERIFIED REACHABLE and the originally proposed reluctant test DOES cover lines 1185-1187, but the claim's GREEDY variant is WRONG. Lines 1186-1187 are the END->END count increment in the EMPTY_LOOP fast-forward path (count < elem->min branch). They run when a nullable group's END->next (set sequentially by finalizeRPRPattern at rpr.c:1453-1454 to i+1) lands on an outer END element, i.e. the nullable group is the last child of an enclosing quantified group. I rebuilt coverage data (this is a -fprofile-arcs build) and ran candidates one-per-server-lifecycle (full stop/rm-gcda/start/stop, since the running postmaster only flushes .gcda reliably on clean exit; sloppy resets between runs gave false positives AND false negatives that initially misled me). Clean isolated results: P1 reluctant ((A??){2,}?){2,}? -> line 1185 6 hits with IS-END branch taken 50%, line 1186 3 hits, line 1187 3 hits = COVERED. P3 (X (A? B?){2,}){2,} -> 4 hits each = COVERED. P2 greedy ((A?){2,}){2,} -> line 1186 #####  = NOT COVERED: tryFlattenNestedQuantifier (rpr.c:797 skips flatten only for reluctant) collapses the nested greedy groups into one {4,} group, destroying the nested END->END so elem->next becomes FIN not an outer END. Also note single-child nullable groups like (B?){2,} get flattened to B* (child->min==0 -> safe at rpr.c:812), so the inner group needs a multi-child SEQ body OR reluctant quantifiers to survive. The original claim that 'A greedy variant also exercises the END->END increment via the greedy else-branch' is refuted; the greedy else-branch (1218-1223) is never even reached by that pattern.",
      "refinedTest": "Use the reluctant variant (confirmed COVERS 1185/1186/1187 in isolation): WITH t(id,isa) AS (VALUES (1,true),(2,true),(3,false)) SELECT id, count(*) OVER w FROM t WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (((A??){2,}?){2,}?) DEFINE A AS isa) ORDER BY id;  -- This survives optimizer flattening because reluctant quantifiers disable tryFlattenNestedQuantifier (rpr.c:797), keeping the doubly-nested group so the inner END->next is the outer END. Do NOT rely on the greedy ((A?){2,}){2,} variant -- it is flattened to a single group and does NOT cover these lines. A greedy alternative that DOES work (verified, 4 hits each) needs a multi-child nullable inner body so it resists flatten/unwrap: WITH t(id,v) AS (VALUES (1,'x'),(2,'x'),(3,'x'),(4,'x')) SELECT id, count(*) OVER w AS c FROM t WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN ( (X (A? B?){2,}){2,} ) DEFINE X AS v='x', A AS v='a', B AS v='b') ORDER BY id;  -- Add at least the reluctant P1 to rpr.sql; optionally add the greedy P3 too, to also exercise the greedy else-branch fast-forward (lines 1219-1223) which P1 leaves uncovered.",
      "refinedFix": "No code fix needed; lines are live and reachable. The path is genuinely exercised once a test with a surviving nested nullable group is added. If desired purely for clarity, the comment at 1184 could note that this END->END increment only occurs for nested quantified groups that escape optimizer flattening (reluctant outer quantifier, or a multi-element nullable inner body), but no functional change is warranted."
     }
    ]
   ]
  },
  "1195": {
   "func": "nfa_advance_end",
   "reachable": true,
   "subs": [
    [
     "1195",
     {
      "functionName": "nfa_advance_end",
      "lines": "1195",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 1195 is the opening brace of the reluctant branch (1194: ffState != NULL && RPRElemIsReluctant(elem)) in the count<min path. It is genuinely reachable and testable, but the PROPOSED nested pattern (((A??){2,}?){2,}?) does NOT cover it. I verified each pattern in isolation against a coverage build (gcda flushes only on backend exit, read in a separate step to avoid a race that earlier produced bogus 'covered' readings). The nested pattern alone: 1194=10 (branch entered) but 1195=##### and 1213=#####, because the nested reluctant END's fast-forward still reaches FIN, so it always returns at line 1209 -- identical to the existing rr2 ((A??){2,}?) test. Line 1195's basic block is specifically the fall-through-to-1213 path (reluctant exit did NOT reach FIN, so 1206 is false). That path requires a REQUIRED element after the nullable reluctant group. The B-follower variant ((A??){2,}? B) with A AS isa, B AS isb gives 1195=6, 1213=6, 1209=##### -- it covers the line. The claim that the nested pattern covers 1195 is refuted; only the required-follower variant works.",
      "refinedTest": "Add to rpr_nfa.sql a window using a reluctant nullable group followed by a REQUIRED element so the fast-forward exit lands on that element (not FIN), forcing fall-through to the loop-back at line 1213. Verified covering pattern (1195=6, 1213=6, 1209 not hit):\n\nWITH cov AS (\n  SELECT id, count(*) OVER w AS c\n  FROM t\n  WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n               PATTERN ((A??){2,}? B) DEFINE A AS isa, B AS isb)\n)\nSELECT * FROM cov ORDER BY id;\n\nwith table t(id int, isa bool, isb bool) rows (1,t,t),(2,t,t),(3,f,f),(4,t,t),(5,t,t). Equivalently ((A??)+? B) also covers it. The NOT-working proposed pattern (((A??){2,}?){2,}?) must be replaced by one with a required follower.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "1213": {
   "func": "nfa_advance_end",
   "reachable": true,
   "subs": [
    [
     "1213",
     {
      "functionName": "nfa_advance_end",
      "lines": "1213",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED reachable and CONFIRMED the proposed test drives execution through line 1213 exactly. Verified empirically, not by reasoning alone. Line 1213 is the 'loop-back second' nfa_route_to_elem call in the reluctant nullable-group branch (count < min, RPRElemCanEmptyLoop true, RPRElemIsReluctant true). It executes only when the reluctant fast-forward exit at 1199 does NOT reach FIN, leaving ctx->matchedState == savedMatch so the 1206 test takes the FALSE side and falls through to 1213. The root cause's explanation of the gating condition is accurate.\n\nEmpirical proof: rebuilt/started the correct PostgreSQL 19beta1 coverage build (the default psql socket had been silently connecting to an unrelated system PostgreSQL 18.3, and the project PGDATA had a PG_CONTROL_VERSION 1901 vs 1902 mismatch -- so I ran initdb on a fresh temp cluster on port 5444 with the just-built binary). I removed execRPR.gcda to zero counters, ran ONLY the proposed query, stopped the server to flush gcov data, and regenerated the .gcov. Result: line 1213 shows execution count 7 (covered), while lines 1208-1209 (the FIN-reached early-return path) show ##### (0) in this isolated run -- exactly the 'loop-back second taken because fast-forward did not reach FIN' scenario the finding predicts. Pattern ((A??){2,}? B) with min=2 reluctant nullable group followed by required B, input A,A,B,X, produced match {id 1..3} and exercised the loop-back-second route. Classification 'testable' is correct.",
      "refinedTest": "The proposed test is correct as-is and covers line 1213 (verified, count 7). One practical caveat for adding it to the regression suite: a VALUES/CTE-based source (WITH t(id,f) AS (VALUES ...)) parses and runs fine, but to match existing rpr.sql style and avoid any deparse/array-literal edge cases, prefer a real table:\n\nCREATE TABLE tt(id int, f text[]);\nINSERT INTO tt VALUES (1,ARRAY['A']),(2,ARRAY['A']),(3,ARRAY['B']),(4,ARRAY['X']);\nSELECT id, first_value(id) OVER w AS s, last_value(id) OVER w AS e\nFROM tt\nWINDOW w AS (\n ORDER BY id\n ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n AFTER MATCH SKIP PAST LAST ROW\n PATTERN ((A??){2,}? B)\n DEFINE A AS 'A'=ANY(f), B AS 'B'=ANY(f))\nORDER BY id;\n\nExpected output (verified): row id=1 -> s=1,e=3; rows id=2,3,4 -> NULL,NULL. The reluctant nullable group with min=2 plus required follower B that does not match at the group's exit row is the essential ingredient; keep that shape.",
      "refinedFix": ""
     }
    ]
   ]
  }
 },
 "src/backend/nodes/equalfuncs.c": {
  "154": {
   "func": "_equalRPRPattern",
   "reachable": false,
   "subs": [
    [
     "154",
     {
      "functionName": "_equalRPRPattern",
      "lines": "154",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. _equalRPRPattern (T_RPRPattern, tag 387) is only dispatched from equalfuncs.switch.c:889. RPRPattern is the COMPILED pattern node built exclusively in the optimizer (createplan.c:2906 via buildRPRPattern -> rpr.c makeRPRPattern) and stored only as a field of the WindowAgg plan node (plannodes.h:1393) and the WindowAggState exec node (execnodes.h:2654). It never appears in a raw-parse or rewritten query tree. equal() is auto-invoked by the COPY/WRITE_READ_PARSE_PLAN_TREES debug machinery in tcop/postgres.c ONLY on raw parse trees (lines 638/655) and rewritten query trees (lines 849/878). The two plan-tree equal() checks at postgres.c:935 and 958 sit inside #ifdef NOT_USED (\"equal() currently does not have routines to compare Plan nodes\") and are never compiled; NOT_USED is not defined anywhere. I attempted to refute via the one real equal()-on-rpPattern call site: planner.c:6283 equal(wc->rpPattern, ...) -- but wc is a WindowClause whose rpPattern field is RPRPatternNode* (parsenodes.h:1767, the PARSE node T_RPRPatternNode tag 88), so that call dispatches to _equalRPRPatternNode, NOT _equalRPRPattern. The other equal() near RPR code (nodeWindowAgg.c:2917) compares a WindowFunc. _equalRPRPattern exists solely because the struct carries pg_node_attr(custom_copy_equal, ...) (plannodes.h:1285), which forces the gen_node_support machinery to emit a switch case and require a hand-written equal counterpart even though the copy half is what is actually exercised (custom_copy_equal cannot request copy-only). No SQL/regression input can construct a standalone T_RPRPattern node and feed it to equal(); line 154 is genuinely unreachable.",
      "refinedTest": "No SQL-driven test can cover this line. The compiled RPRPattern node only exists inside a Plan/PlanState tree, and equal() is never run on plan trees in any compiled configuration. The only ways to execute line 154 are non-SQL: (a) a C-level unit test that builds two RPRPattern nodes and calls equal() directly (no such test infrastructure exists in PostgreSQL's regress suite); or (b) compiling tcop/postgres.c with -DNOT_USED so the plan-tree equal() checks at postgres.c:935/958 become live, then running ANY RPR query (e.g. a SELECT with OVER (... PATTERN (...) DEFINE ...)) under -DCOPY_PARSE_PLAN_TREES -- but NOT_USED is intentionally never defined, so this is not a regression-suite-reachable path. Therefore the line should be treated as defensive/unreachable rather than tested.",
      "refinedFix": "Keep the function (the custom_copy_equal node attr requires both halves to be hand-written; the framework has no copy-only custom variant), but make the unreachability explicit and prevent future confusion with the parse-side node. Concretely: (1) add a header comment on _equalRPRPattern in equalfuncs.c noting that RPRPattern is a plan/exec-only node never compared by equal() in any compiled build (plan-tree equal() checks in tcop/postgres.c live under #ifdef NOT_USED), and that the parse-side counterpart actually exercised is _equalRPRPatternNode (dispatched from planner.c:6283 via WindowClause.rpPattern, which is RPRPatternNode*, not RPRPattern*). (2) Optionally mark the line for coverage exclusion (e.g. an /* LCOV_EXCL_LINE */-style note) so it stops appearing as an uncovered modified line. No behavioral change is needed and none is possible via SQL."
     }
    ],
    [
     "156-158",
     {
      "functionName": "_equalRPRPattern",
      "lines": "156-158",
      "lineCount": 3,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable via any SQL/regression input. RPRPattern is a plan-tree-only node: it is constructed solely in the optimizer at src/backend/optimizer/plan/rpr.c:1134 (makeNode(RPRPattern)) and attached to the WindowAgg Plan node (plannodes.h:1393). It never appears in raw parse trees or Query trees. The active equal() debugging checks operate only on raw parsetrees (postgres.c:638,655) and querytrees (postgres.c:849,878), which never contain an RPRPattern. The only equal() check that would traverse a plan tree (pg_plan_query, postgres.c:935 and 958) is explicitly wrapped in #ifdef NOT_USED, with the source comment 'equal() currently does not have routines to compare Plan nodes, so dont try to test equality here.' I searched all equal() callers across src/backend and src/include; none compares an RPRPattern or a whole Plan node (nodeWindowAgg.c:2917 compares WindowFunc, not RPRPattern). Even with -DCOPY_PARSE_PLAN_TREES/-DWRITE_READ_PARSE_PLAN_TREES set, those macros exercise copy/out/read of plan trees but NOT equal() (equal stays behind NOT_USED). The _equalRPRPattern body, including lines 156-158, is genuinely dead from SQL. The function exists only because pg_node_attr(custom_copy_equal,...) forces a hand-written equal and a generated switch case (equalfuncs.switch.c:888). Lines 156-158 (COMPARE_SCALAR_FIELD numVars/maxDepth/numElements) cannot be driven by any input.",
      "refinedTest": "No SQL-level test can cover these lines; equal() is never called on plan nodes (the call site is #ifdef NOT_USED in pg_plan_query). The only ways to execute them: (1) a C-level unit test that calls equal() on two RPRPattern nodes directly, or (2) temporarily building with the NOT_USED block enabled in pg_plan_query plus DEBUG_NODE_TESTS_ENABLED and Debug_copy_parse_plan_trees on, then running any RPR query (e.g. a SELECT with OVER(... PATTERN(A B+) DEFINE A AS ..., B AS ...)) so the WindowAgg plan carries an rpPattern and equal(new_plan, plan) recurses into _equalRPRPattern. Neither is achievable through the standard regression harness, so these lines remain untestable without a source/build change.",
      "refinedFix": "Treat as intentional dead code, consistent with all other plan-node equal routines in core. The struct attribute is pg_node_attr(custom_copy_equal, custom_read_write); custom_copy_equal is a combined attribute, so you cannot drop only the equal half without losing the custom copy function (which IS needed and IS covered for plan-tree copyObject). There is no copy-only node attribute, so removing the attribute is not viable. Recommended: add a brief comment above _equalRPRPattern noting that plan-node equality is never exercised (equal() on plan trees is #ifdef NOT_USED in pg_plan_query), so this routine exists only to satisfy custom_copy_equal and is dead by design. Optionally exclude it from coverage accounting. Do not attempt to write a regression test for it."
     }
    ],
    [
     "161",
     {
      "functionName": "_equalRPRPattern",
      "lines": "161",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "dead-code",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable, but the classification should be dead-code rather than defensive-unreachable. _equalRPRPattern compares the COMPILED RPRPattern plan node (plannodes.h:1283, marked pg_node_attr(custom_copy_equal)), which is distinct from the parse-tree RPRPatternNode. The compiled RPRPattern is only ever attached to the WindowAgg plan node (createplan.c:7038). Every Plan node carries pg_node_attr(no_equal) (plannodes.h:62, also abstract Scan at :194), so no _equalWindowAgg is generated and there is NO T_WindowAgg case in equalfuncs.switch.c -- equal() never recurses into a plan node, hence never reaches an embedded RPRPattern. The only call equal(wc->rpPattern, existing_wc->rpPattern) at planner.c:6283 operates on WindowClause.rpPattern, whose type is RPRPatternNode* (parsenodes.h:1767), so it dispatches to the generated _equalRPRPatternNode, NOT _equalRPRPattern. The only path that could run equal() on a full plan tree (postgres.c:934 under COPY_PARSE_PLAN_TREES) is explicitly wrapped in #ifdef NOT_USED with the comment \"equal() currently does not have routines to compare Plan nodes.\" There is no SQL/regression input -- of any pattern shape, with or without DEFINE variables -- that drives execution into _equalRPRPattern, so line 161 (and the whole function body) is dead via SQL. Note: even if it were called, line 161's branch (a->numVars > 0) is always true for any real RPR pattern since every PATTERN references >=1 DEFINE variable, so the false-branch of 161 would itself be defensive; but the dominant fact is the function is never invoked.",
      "refinedTest": "No SQL/regression test can cover this line. The dispatch case T_RPRPattern exists (equalfuncs.switch.c:888) but is only invoked when equal() is called on a node of tag T_RPRPattern, which only happens if equal() recurses into a WindowAgg plan node -- impossible because Plan has pg_node_attr(no_equal) and the plan-tree equal() check in postgres.c is #ifdef NOT_USED. To actually exercise line 161 you would need a C-level unit test that constructs two RPRPattern nodes (numVars>0) and calls equal() on them directly (e.g. a test harness module), OR remove the #ifdef NOT_USED guard around the plan-tree equality check in postgres.c:934 and add a _equalWindowAgg dispatch -- neither is reachable through pure SQL. Therefore testWillCover=false and no SQL test can be offered.",
      "refinedFix": "Since _equalRPRPattern is unreachable via any SQL path (Plan nodes are no_equal and the plan-tree equal() round-trip is #ifdef NOT_USED), the custom equal routine for RPRPattern provides no runtime benefit. Recommended: either (a) drop the custom equal implementation for RPRPattern and mark the node no_equal (consistent with all other plan-only structures), eliminating the dead function entirely; or (b) if the custom equal is intentionally retained for a possible future plan-tree comparison, add a comment on _equalRPRPattern documenting that it is currently unreachable because Plan nodes carry no_equal and postgres.c's plan equality check is disabled via #ifdef NOT_USED. Option (a) is cleaner and removes line 161 along with the whole dead function."
     }
    ],
    [
     "163",
     {
      "functionName": "_equalRPRPattern",
      "lines": "163",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable, and stronger than the claim: line 163 is doubly unreachable. (1) Function-level: _equalRPRPattern (equalfuncs.switch.c:889, T_RPRPattern) is never invoked. RPRPattern (plannodes.h:1283) is a Plan node living only inside WindowAgg->rpPattern. equal() is never called on Plan nodes: both debug sites in tcop/postgres.c:925-955 wrap the equal() comparison in #ifdef NOT_USED and the comment explicitly says 'equal() currently does not have routines to compare Plan nodes, so don't try to test equality here.' The DEBUG node-test build (COPY/WRITE_READ_PARSE_PLAN_TREES) runs copy and out/read on plan trees but NOT equal. The window-clause dedup at planner.c:6283 equal(wc->rpPattern, existing_wc->rpPattern) compares WindowClause.rpPattern, which is the PARSE node RPRPatternNode (parsenodes.h:1767), dispatched via _equalRPRPatternNode (switch:277) -- a different function entirely. (2) Line-level: even if _equalRPRPattern were called, the 'a->varNames==NULL||b->varNames==NULL' branch cannot trigger for a well-formed node guarded by numVars>0, because makeRPRPattern (optimizer/plan/rpr.c:1143-1146) Asserts numVars>0 and unconditionally pallocs varNames and pstrdups each entry. No SQL or regression input can drive execution to line 163.",
      "refinedTest": "No test can cover this line. There is no entry point that calls equal() on a T_RPRPattern (or any Plan) node, so the function body -- and thus line 163 -- is dead regardless of input. Crafting an SQL query (e.g. a WINDOW with PATTERN/DEFINE creating a WindowAgg whose rpPattern has numVars>0) builds the node and exercises _copyRPRPattern/_outRPRPattern/_readRPRPattern under the debug macros, but never _equalRPRPattern. The only way to execute the function at all would be a C-level unit test that constructs two RPRPattern nodes and calls equal() directly; even then, to hit line 163 you would have to hand-build a malformed node with numVars>0 but varNames==NULL, which violates the makeRPRPattern invariant and never arises from any real code path.",
      "refinedFix": "Replace the can't-happen NULL return with an invariant assertion to document it and remove the dead branch: change 'if (a->varNames == NULL || b->varNames == NULL) return false;' to 'Assert(a->varNames != NULL && b->varNames != NULL);'. Same treatment applies to the parallel guard at line 175 for elements (numElements>=2 per makeRPRPattern Assert). Note, however, that the entire _equalRPRPattern function is currently unreachable since equal() is never invoked on Plan nodes; if a future change does not add a Plan-node equal() path, the custom_copy_equal attr's equal half is dead and could be dropped, leaving only custom copy. If the function is kept as a forward-looking backstop, the Assert form is the right minimal fix."
     }
    ],
    [
     "165",
     {
      "functionName": "_equalRPRPattern",
      "lines": "165",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "dead-code",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable, but the precise classification is dead-code rather than merely defensive-unreachable. Line 165 is the varNames for-loop header inside _equalRPRPattern, which is dispatched from equalfuncs.switch.c:888 ONLY when equal() is invoked on a T_RPRPattern node. The compiled RPRPattern node lives exclusively in WindowAgg (plannodes.h:1393) and WindowAggState (execnodes.h:2654) -- i.e. only in plan/exec trees. PostgreSQL never calls equal() on plan trees: the only such call sites, postgres.c:935 and :958, are both wrapped in #ifdef NOT_USED, with an in-source comment stating 'equal() currently does not have routines to compare Plan nodes, so don't try to test equality here.' equal() is otherwise only used on parse-tree / Query / Expr / RestrictInfo / EquivalenceMember nodes (e.g. analyzejoins.c, postgres.c:638-878), none of which can ever contain an embedded RPRPattern. The build's COPY_PARSE_PLAN_TREES / WRITE_READ_PARSE_PLAN_TREES flags exercise copy/out/read round-trips but explicitly NOT equal (the equal() check there is the very code under #ifdef NOT_USED). The entire function body (untested.md flags lines 154-182, the whole routine) is uncovered, consistent with the function never being entered. I attempted to refute by searching for any equal() call reaching a plan/window node or any direct C caller of _equalRPRPattern -- none exist. No SQL/regression input can reach line 165. Note this is whole-function dead code, not a defensive guard branch; line 165 is just the loop header within it.",
      "refinedTest": "No SQL test can cover this line. The function is unreachable through equal() for any plan-resident node because plan-tree equality is compiled out under #ifdef NOT_USED. The only way to execute line 165 would be a dedicated C-level unit test that constructs two RPRPattern nodes with numVars>0 (so the for loop runs at least once, including the loop back-edge to compare a second name) and calls equal(a, b) directly -- e.g. in a test module: makeNode(RPRPattern); set numVars=2, varNames={\"A\",\"B\"}, numElements/elements/maxDepth/isAbsorbable equal; assert equal(a,b)==true, then mutate b->varNames[1] and assert false. This is not expressible via regression SQL and would require new C test infrastructure.",
      "refinedFix": "Treat as dead code at the function level, consistent with PostgreSQL's existing handling of plan-node equal routines. Options, in order of preference: (1) Do not provide an equal routine for RPRPattern at all -- since plan-tree equal() is #ifdef NOT_USED, the custom_copy_equal pg_node_attr forces hand-writing a routine that can never run; if the node-attr framework permits, drop the equal half. (2) If a routine must exist, mark the whole function with a coverage-exclusion comment (e.g. /* GCOV_EXCL_START ... GCOV_EXCL_STOP */ if the project uses LCOV markers) noting it parallels postgres.c's NOT_USED plan-equal machinery. (3) Accept as known-uncovered in the coverage baseline. No per-line fix for 165 is meaningful in isolation; it shares the fate of the entire dead function."
     }
    ],
    [
     "167",
     {
      "functionName": "_equalRPRPattern",
      "lines": "167",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "dead-code",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable, and stronger than the original claim: the ENTIRE function _equalRPRPattern is dead via any SQL/regression path, not just line 167. Evidence: (1) T_RPRPattern (the compiled NFA bytecode struct) appears ONLY in the plan tree (plannodes.h:1393 WindowAgg.rpPattern) and executor state (execnodes.h:2654); it is never embedded in any parse/query node struct. (2) equal() is invoked by the debug round-trip harness only on raw_parsetree_list and querytree_list (postgres.c:638/655/849/878) -- parse/query trees, which never contain T_RPRPattern. (3) The ONLY equal() calls on the PLAN tree (postgres.c:935 and 958) are both wrapped in #ifdef NOT_USED and are disabled by design, with the comment 'equal() currently does not have routines to compare Plan nodes'. (4) The planner dedup call equal(wc->rpPattern, existing_wc->rpPattern) at planner.c:6283, and COMPARE_NODE_FIELD(rpPattern) at equalfuncs.funcs.c:1162/1573, all operate on WindowClause/WindowDef.rpPattern, whose declared type is RPRPatternNode* (parsenodes.h:655), i.e. T_RPRPatternNode -> dispatches to _equalRPRPatternNode, NOT _equalRPRPattern. (5) No optimizer/executor code calls equal() on a WindowAgg node or a bare RPRPattern object. Therefore the equalfuncs.switch.c:889 case T_RPRPattern is never reached, so line 167 (strcmp) and its return false can never execute. I actively tried to refute this by tracing every equal()/rpPattern/plan-tree caller and found no live path.",
      "refinedTest": "No SQL/regression test can cover line 167. There is no production code path that calls equal() on a T_RPRPattern node, so the switch case dispatching to _equalRPRPattern is never entered. Even if one enabled the currently-#ifdef-NOT_USED plan-tree equal() check in pg_plan_query (postgres.c:933-939/956-962), a copyObject/round-trip produces identical varNames, so strcmp would return 0 and the false-return branch on line 167-168 would still not be taken; hitting it requires comparing two RPRPattern objects with differing varNames, which no path constructs. The only way to exercise this line at all is a C-level unit test (e.g. a test_rpr extension) that builds two RPRPattern nodes with different varNames[] and calls equal() directly -- not an SQL regression test.",
      "refinedFix": "Resolve at the function level, not per-line. Since T_RPRPattern is a plan-tree-only node and equal() is never (and is explicitly not) run on plan nodes, the hand-written _equalRPRPattern serves no live purpose. Cleanest options: (a) remove the custom _equalRPRPattern and the T_RPRPattern case from equalfuncs.switch.c, marking the node as not supporting equal() (consistent with other Plan-only nodes); or (b) if kept for node-infrastructure parity, add a comment noting it is intentionally unreachable because equal() is never invoked on plan trees (postgres.c plan-tree equal checks are #ifdef NOT_USED), so coverage tooling should exclude it. Do not attempt to add an SQL test for line 167."
     }
    ],
    [
     "173",
     {
      "functionName": "_equalRPRPattern",
      "lines": "173",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "dead-code",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable, but the proposed classification of \"defensive-unreachable\" understates it: the entire _equalRPRPattern function (not just line 173) is dead code unreachable by any SQL/regression input. I tried hard to refute it and could not. The decisive evidence: (1) RPRPattern (the compiled NFA struct, plannodes.h:1283, distinct from the parse-tree RPRPatternNode) is held ONLY by two structs: WindowAgg (plannodes.h:1393) and WindowAggState (execnodes.h:2654). (2) WindowAgg is a Plan subclass, and the Plan base class carries pg_node_attr(abstract, no_equal, no_query_jumble) (plannodes.h:194), so NO _equalWindowAgg is generated — confirmed by grep: there is no _equalWindowAgg or T_WindowAgg case in equalfuncs.switch.c (rc=1). Thus equal() never recurses into rpPattern. (3) WindowAggState is an executor node, never passed to equal(). (4) No code anywhere calls equal() on a bare T_RPRPattern node. The switch case T_RPRPattern at equalfuncs.switch.c:888 exists only because RPRPattern is tagged custom_copy_equal (plannodes.h pg_node_attr) which forces a hand-written _equalRPRPattern to be emitted and registered — but the case is never dispatched. The COPY_PARSE_PLAN_TREES / WRITE_READ_PARSE_PLAN_TREES build flags exercise _copyRPRPattern/_outRPRPattern/_readRPRPattern (covered), but they do NOT exercise equal(); equal is deliberately excluded for Plan nodes. The root-cause note (\"never invoked; embedded in plan/exec trees\") is directionally right but imprecise — the exact mechanism is the Plan base no_equal attribute suppressing equal recursion into the sole RPRPattern-bearing struct WindowAgg.",
      "refinedTest": "No SQL/regression test can cover line 173 (or any line of _equalRPRPattern). equal() is structurally never invoked on T_RPRPattern: its only container WindowAgg is a no_equal Plan node, and the executor node WindowAggState is never compared. The only way to execute these lines is a C-level unit test that constructs two RPRPattern nodes and calls equal() directly (e.g., an extension or a test harness building RPRPattern via buildRPRPattern() and invoking equal(a,b)). That is outside the SQL regression framework, so for coverage purposes this is genuinely untestable from SQL.",
      "refinedFix": "Function-level recommendation. Since equal() is never dispatched for RPRPattern (Plan-only container with no_equal), the custom_copy_equal attribute over-specifies what is needed: only custom copy is actually exercised. Two viable cleanups: (1) Change the pg_node_attr on RPRPattern (plannodes.h ~line 1285) from custom_copy_equal to custom_copy plus no_equal, which stops emitting/registering the dead _equalRPRPattern and removes the unreachable T_RPRPattern case from equalfuncs.switch.c — eliminating all 94-counted dead lines in this function rather than just line 173. (2) If the hand-written _equalRPRPattern is intentionally kept for API completeness/future direct use, exclude it from modified-line coverage accounting (it is provably unreachable from SQL). Do NOT attempt to add a SQL test or a runtime Assert here — neither can drive execution through line 173."
     }
    ],
    [
     "175",
     {
      "functionName": "_equalRPRPattern",
      "lines": "175",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable, and in fact doubly so. Line 175 is the NULL guard `if (a->elements == NULL || b->elements == NULL) return false;` inside the `if (a->numElements > 0)` block. Two independent reasons make it unreachable: (1) WHOLE FUNCTION IS NEVER CALLED. _equalRPRPattern is dispatched only via T_RPRPattern in equalfuncs.switch.c:889. RPRPattern (plannodes.h:1283) lives exclusively in the plan/exec tree (WindowAgg.rpPattern at plannodes.h:1393, WindowAggState at execnodes.h:2654) -- it is NEVER part of the Query/raw-parse tree. The parsenodes.h `rpPattern` field is the distinct RPRPatternNode type (parse tree), handled by _equalRPRPatternNode. equal() is invoked at parse stage (postgres.c:638), query stage (849), and plan stage (935) -- but the plan-stage call is wrapped in `#ifdef NOT_USED` (postgres.c:933-938) with the explicit comment \"equal() currently does not have routines to compare Plan nodes\". No other code path (nodeWindowAgg.c:2917 compares WindowFunc, not the pattern; createplan/rpr.c never equal() a RPRPattern) reaches it. So no SQL/regression input can trigger this function at all. (2) BRANCH IMPOSSIBLE EVEN IF CALLED. makeRPRPattern (rpr.c:1148-1150) asserts `numElements >= 2` and unconditionally `palloc0`s elements, so numElements>0 with NULL elements cannot occur for a validly constructed node. Tried hard to refute via any plan-tree equal() path; none exists outside dead #ifdef NOT_USED code.",
      "refinedTest": "No SQL/regression test can cover this line. The enclosing function is dispatched only by equal() on a T_RPRPattern node, and the sole call site that could pass plan-tree nodes to equal() (postgres.c:935) is compiled out under #ifdef NOT_USED. Even temporarily enabling NOT_USED would execute lines 173/177-179 (with a non-NULL elements array), not the NULL-return at 175, because makeRPRPattern guarantees elements != NULL whenever numElements > 0. The only way to execute line 175 is to hand-fabricate an inconsistent RPRPattern (numElements>0, elements=NULL) in a C unit test and call _equalRPRPattern directly -- not reachable from SQL.",
      "refinedFix": "Replace the NULL guard with an assertion to document the invariant guaranteed by makeRPRPattern: `Assert(a->elements != NULL && b->elements != NULL);` then proceed directly to the memcmp. Note the broader cleanup the proposed fix already implies: the entire _equalRPRPattern function is currently dead because equal() is never called on plan-tree nodes (the plan-stage check is #ifdef NOT_USED). If the project does not intend to add general plan-node equal() support, the custom_copy_equal attribute's equal half plus this whole function could be dropped; if kept for future-proofing/symmetry with copy/out/read, convert line 175 (and the analogous varNames guard at 163) to Asserts."
     }
    ],
    [
     "177-178",
     {
      "functionName": "_equalRPRPattern",
      "lines": "177-178",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable via any SQL/regression input. Lines 177-178 are the memcmp of the elements array (and its false-return) inside _equalRPRPattern. RPRPattern is a plan-only node: it is declared in plannodes.h and lives exclusively as the WindowAgg.rpPattern field, built at plan time in optimizer/plan/createplan.c (via rpr.c) and consumed in executor/execRPR.c. The node equal() machinery is dispatched for T_RPRPattern at equalfuncs.switch.c:889, but equal() is only ever invoked on plan trees in tcop/postgres.c at lines 935 and 958 -- both inside #ifdef NOT_USED, so they are compiled out (the surrounding comment explicitly states \"equal() currently does not have routines to compare Plan nodes, so don't try to test equality here\"). The active equal() checks in postgres.c (lines 638/655/849/878) run on raw-parse and query trees, which carry the DISTINCT parse-tree node RPRPatternNode (parsenodes.h, handled by _equalRPRPatternNode), never RPRPattern. I also searched the optimizer and executor for any equal() call that could receive a WindowAgg/RPRPattern: createplan.c:5545 equal(node,indexkey) compares index expressions; execRPR.c's nfa_states_equal is a custom executor helper unrelated to equalfuncs.c. None route a plan node through node equal(). Note: the analogous array-copy lines in copyfuncs.c/outfuncs.c/readfuncs.c ARE exercised, because rpr.sql builds multi-element PATTERN nodes (e.g. PATTERN (START UP+ DOWN+)) and the build flags -DCOPY_PARSE_PLAN_TREES/-DWRITE_READ_PARSE_PLAN_TREES round-trip plan trees through copy/out/read -- but crucially NOT through equal(). So only the equal path is dead.",
      "refinedTest": "No SQL/regression test can cover lines 177-178. The only way to execute _equalRPRPattern is to call equal() on two WindowAgg plan trees whose rpPattern has numElements>0 and identical varNames. That call site exists only under #ifdef NOT_USED in tcop/postgres.c and is not compiled. To exercise these exact lines one must either (a) rebuild with -DNOT_USED defined in postgres.c's plan-tree debug blocks and run any rpr.sql query that compiles to a PATTERN with >=1 element (e.g. PATTERN (START UP+ DOWN+)), forcing the Debug_copy/write_read plan-tree equal() comparison; or (b) add a C-level unit test that constructs two RPRPattern nodes with numElements>0 and calls equal(). Neither is a pure SQL test, so testWillCover via SQL is false.",
      "refinedFix": "Accept as defensive/unreachable. Preferred: drop the custom equal support for the plan-only RPRPattern node entirely (it cannot be invoked because equal() is never run on plan trees), or mark the node with the node-gen \"no_equal\" attribute so equalfuncs.switch.c does not generate a dispatch for it. If the routine is kept for symmetry with copy/out/read, add a brief comment noting that RPRPattern is a plan-only node and _equalRPRPattern is unreachable in normal builds (equal() on plan trees is compiled out under #ifdef NOT_USED in tcop/postgres.c), so lines 177-178 are not coverable by SQL. Do not add an artificial test."
     }
    ],
    [
     "182",
     {
      "functionName": "_equalRPRPattern",
      "lines": "182",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable via SQL. _equalRPRPattern is correctly registered and dispatched (equalfuncs.switch.c:888-889 case T_RPRPattern), so the issue is not a missing dispatch but a missing caller. The compiled RPRPattern node (T_RPRPattern, plannodes.h:1283 with pg_node_attr(custom_copy_equal, custom_read_write)) is embedded ONLY in the WindowAgg plan node (plannodes.h:1393) and WindowAggState (execnodes.h:2654, runtime). equal() is exercised automatically only on (a) raw parse trees and (b) querytree (Query) trees in postgres.c (lines 638/655/849/878) under DEBUG_NODE_TESTS_ENABLED. Those trees carry the PARSE-side node WindowClause.rpPattern, which is RPRPatternNode (T_RPRPatternNode, parsenodes.h:1767), NOT the compiled RPRPattern. The only equal() on PLAN trees (postgres.c:935 and :958) is wrapped in #ifdef NOT_USED with the explicit comment 'equal() currently does not have routines to compare Plan nodes', so it never compiles in. I tried to refute via planner.c:6283 equal(wc->rpPattern, existing_wc->rpPattern) in the duplicate-WindowClause merge, but wc->rpPattern there is the parse-side RPRPatternNode (-> _equalRPRPatternNode), and RPR clauses are skipped before that block anyway (comment at 6270-6273 explicitly calls it a 'defensive backstop for parity'). No SQL/regression input causes equal() to be called on a T_RPRPattern node. Line 182 (COMPARE_SCALAR_FIELD(isAbsorbable)) and the trailing return true are the unreached tail of an entirely unreached function.",
      "refinedTest": "No SQL/regression test can cover this. The function is dispatched correctly but never called: RPRPattern only lives in plan/exec trees, and equal() on plan trees is disabled (#ifdef NOT_USED in postgres.c:933-938, :956-961). Coverage is only achievable by either (1) a C unit test that directly calls equal() on two manually constructed RPRPattern nodes (and exercises numVars>0/numElements>0 branches plus differing/equal isAbsorbable), or (2) removing the NOT_USED guard so plan-tree equal() runs under COPY_PARSE_PLAN_TREES for a query whose plan contains a WindowAgg with a compiled RPRPattern, e.g. SELECT count(*) OVER w FROM (VALUES (1),(2),(3)) v(x) WINDOW w AS (ORDER BY x MEASURES count(*) AS c AFTER MATCH SKIP PAST LAST ROW INITIAL PATTERN (a+ b) DEFINE a AS x > 0, b AS x > 1); but that requires a non-default build modification and is not regression-test-reachable.",
      "refinedFix": "Leave as intentional parity code and document it. The pg_node_attr(custom_copy_equal) on RPRPattern couples the copy and equal functions: the node genuinely needs custom_copy (for its varNames/elements arrays, exercised by COPY_PARSE_PLAN_TREES) and custom_read_write, but its equal counterpart is structurally never invoked because equal() is never run on plan trees. Options: (a) add a brief comment on _equalRPRPattern noting it is unreachable parity code required by the custom_copy_equal node attribute, since equal() is not run on plan nodes (postgres.c NOT_USED guard); or (b) investigate whether the gen_node_support framework can request custom_copy without also forcing a custom equal (currently custom_copy_equal is a single combined attribute, so it cannot). No functional change is warranted; the line is correct, just unreachable."
     }
    ]
   ]
  }
 },
 "src/backend/executor/nodeWindowAgg.c": {
  "4942": {
   "func": "WinCheckAndInitializeNullTreatment",
   "reachable": false,
   "subs": [
    [
     "4942",
     {
      "functionName": "WinCheckAndInitializeNullTreatment",
      "lines": "4942",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Line 4942 `elog(ERROR, \"could not get function name\")` fires only when get_func_name(fcinfo->flinfo->fn_oid) returns NULL, which (per lsyscache.c:1913-1930) happens only if no pg_proc row exists for the given OID. But fn_oid here is the OID of the window function currently being executed: it was resolved at parse/plan time, the syscache tuple is held during execution, and the function cannot be dropped while in use. Therefore a valid pg_proc row always exists and funcname is never NULL on this path. The reachable, live branch is the ereport at 4943-4946 (function does not allow RESPECT/IGNORE NULLS), which IS coverable. No SQL/regression input can drive line 4942; concurrent DROP is prevented by dependency/lock semantics during query execution.",
      "refinedTest": "No test can cover line 4942 itself (it is a can't-happen guard). To cover the surrounding live ereport (4943-4946) instead, use a window function that disallows null treatment, e.g.: SELECT row_number() IGNORE NULLS OVER (ORDER BY x) FROM (VALUES (1),(2)) v(x); This raises ERRCODE_FEATURE_NOT_SUPPORTED \"function row_number does not allow RESPECT/IGNORE NULLS\" via lines 4943-4946, with funcname non-NULL, so 4942 is skipped. The only way to even attempt 4942 would be a C-level fault-injection setting fn_oid to an invalid/dropped OID, which is not expressible in SQL and not a supported regression mechanism.",
      "refinedFix": "Replace the `if (!funcname) elog(ERROR, \"could not get function name\");` guard with `Assert(funcname != NULL);` since the NULL case is structurally impossible during execution. Alternatively fold a fallback into the ereport, e.g. errmsg(\"function %s does not allow RESPECT/IGNORE NULLS\", funcname ? funcname : \"???\"), eliminating the separate unreachable error path. The Assert form is preferred as it documents the invariant without adding an untestable error branch."
     }
    ]
   ]
  },
  "4720": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4720-4721",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4720-4721",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. WinGetSlotInFrame has exactly one caller, WinGetFuncArgInFrame (nodeWindowAgg.c:5295). That function in turn is called from only three places (windowfuncs.c): window_first_value (WINDOW_SEEK_HEAD, line 664), window_last_value (WINDOW_SEEK_TAIL, line 686), and window_nth_value (WINDOW_SEEK_HEAD, line 720). None pass WINDOW_SEEK_CURRENT. I tried to refute via other seektype sources: the WINDOW_SEEK_CURRENT at windowfuncs.c:560 is fed to WinGetFuncArgInPartition (a DIFFERENT function used by lead/lag), not WinGetFuncArgInFrame, so it never reaches this switch. The RPR navigation functions (FIRST/LAST/PREV/NEXT) use a wholly separate path: execExprInterp.c:6210 calls ExecRPRNavGetSlot directly, bypassing WinGetSlotInFrame entirely. The function header comment at 5249 explicitly documents that WINDOW_SEEK_CURRENT is unsupported for this API. Since seektype is not derived from any SQL-controllable value (it is hardcoded at each of the three callers), no SQL or regression input can drive execution into the case WINDOW_SEEK_CURRENT arm. The only theoretical reach is a third-party C extension calling the public WinGetFuncArgInFrame (declared in windowapi.h) with seektype 0, which is not a SQL/regression input and is contractually forbidden.",
      "refinedTest": "No SQL/regression test can cover these lines. The seektype argument is a compile-time constant at every caller and never equals WINDOW_SEEK_CURRENT (0) for the WinGetFuncArgInFrame -> WinGetSlotInFrame path. The only way to execute the elog would be a C-level unit test or a custom window-function extension that calls WinGetFuncArgInFrame(..., WINDOW_SEEK_CURRENT, ...), which is outside the SQL regression framework and explicitly disallowed by the API contract. Therefore no refined SQL test is possible.",
      "refinedFix": "Convert to Assert(seektype != WINDOW_SEEK_CURRENT) before the switch, or leave the elog(ERROR) as a defensive guard mirroring the identical guard in ignorenulls_getfuncarginframe at line 3705-3706. The elog form is preferable to Assert here because WinGetFuncArgInFrame is part of the public window C API (windowapi.h) and the guard protects against misuse by third-party extensions even in non-assert builds. Either way, exclude these 2 lines from coverage expectations (e.g. a coverage-ignore annotation), since they are unreachable by any SQL input."
     }
    ]
   ]
  },
  "4727": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4727",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4727",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Claim CONFIRMED. Line 4727 (`goto out_of_frame` for `relpos < 0` under WINDOW_SEEK_HEAD) is unreachable from any SQL/regression input. WinGetSlotInFrame is called from exactly one place: WinGetFuncArgInFrame at nodeWindowAgg.c:5295, and only on the NOT-ignore_nulls branch (the IGNORE NULLS path goes to ignorenulls_getfuncarginframe at 5292, a separate function with its own duplicated relpos<0 check at line 3711). The only in-tree window functions calling WinGetFuncArgInFrame with WINDOW_SEEK_HEAD are first_value (relpos=0, windowfuncs.c:663-664) and nth_value (relpos=nth-1 with nth>0 enforced via ereport at windowfuncs.c:714-717, so relpos>=0, line 719-720). No built-in passes a negative HEAD relpos. WinGetFuncArgInFrame is exposed in windowapi.h as an extension API, so a third-party C window function could pass negative HEAD relpos and reach this line, but no SQL-only/regression input can. Classification corrected from hard-to-reach to defensive-unreachable: the guard is a deliberate cheap early-out documented at line 4725, structurally unreachable from SQL.",
      "refinedTest": "No SQL/regression test can cover this line. Coverage would require a custom C-coded window function (extension) that calls WinGetFuncArgInFrame(winobj, argno, relpos<0, WINDOW_SEEK_HEAD, ...). Such a test would belong in src/test/modules as a loadable module, not in rpr.sql/window.sql. Since all built-in callers (first_value, nth_value) structurally enforce relpos>=0, no pure-SQL test will ever drive line 4727.",
      "refinedFix": "Leave as a defensive early-out. It guards the arithmetic at line 4729 (frameheadpos + relpos) and the reduced-frame bounds check at 4786-4790, and mirrors the identical guard at line 3711 in ignorenulls_getfuncarginframe plus the long-standing pattern in upstream WinGetFuncArgInFrame. An Assert(relpos >= 0) would be incorrect because relpos is caller-supplied via a public extension API (windowapi.h), where rejecting an out-of-frame request must return gracefully (null result), not crash. No code change needed; optionally add a brief comment noting it is reachable only via external window functions, to explain the coverage gap."
     }
    ]
   ]
  },
  "4779": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4779-4780",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4779-4780",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. The switch is on (winstate->frameOptions & FRAMEOPTION_EXCLUSION). FRAMEOPTION_EXCLUSION is the OR of three distinct non-overlapping bits: EXCLUDE_CURRENT_ROW (0x08000), EXCLUDE_GROUP (0x10000), EXCLUDE_TIES (0x20000). In principle the mask could yield combined values (0x18000, 0x28000, 0x30000, 0x38000) which would hit default:, so the claim \"no other value is representable\" is slightly imprecise. But reachability hinges on whether more than one exclusion bit can be set at once. It cannot: gram.y opt_window_exclusion_clause (gram.y:17573-17577) is non-recursive and returns exactly one of {EXCLUDE_CURRENT_ROW, EXCLUDE_GROUP, EXCLUDE_TIES, 0}, and frame_extent allows exactly one such clause, ORed via n->frameOptions |= $3. SQL syntax permits only a single EXCLUDE clause per frame, so at most one bit is ever set. No planner/createplan/parse_agg path sets additional exclusion bits (planner just copies wc->frameOptions). The codebase itself encodes this invariant: parse_rpr.c:140-150 dispatches the three bits with if/else-if and Asserts exactly one is set. Therefore the masked value is always one of the four explicitly cased values (0, 0x08000, 0x10000, 0x20000) and default: at 4779-4780 is unreachable by any SQL/regression input. An identical default arm exists at line 4864 (WINDOW_SEEK_TAIL branch), equally unreachable.",
      "refinedTest": "No SQL test can cover these lines. Reaching default: would require winstate->frameOptions to have two or more of the EXCLUDE bits set simultaneously, which the grammar forbids (single non-recursive opt_window_exclusion_clause per frame) and which no programmatic path constructs. The only way to execute it is a C-level fault injection (manually corrupting frameOptions to e.g. 0x18000 before WinGetSlotInFrame runs), which is not a regression-testable input. Recommend leaving uncovered.",
      "refinedFix": "Keep as-is. This is the standard PostgreSQL defensive elog(ERROR, \"unrecognized ...\") pattern for an exhaustive switch over masked option bits, matching the twin arm at line 4864 and the long-standing convention in this file. No change required; the line is intentionally defensive and should remain excluded from coverage expectations."
     }
    ]
   ]
  },
  "4795": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4795",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4795",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED. Line 4795 (`goto out_of_frame` under `if (relpos > 0)` in the WINDOW_SEEK_TAIL case) is unreachable via any SQL/regression input. WinGetSlotInFrame is reached only through the public API WinGetFuncArgInFrame (nodeWindowAgg.c:5278 -> 5295). Exhaustive grep of the whole tree (src + contrib) shows exactly three callers of WinGetFuncArgInFrame, all in src/backend/utils/adt/windowfuncs.c: first_value (HEAD, relpos=0), last_value (TAIL, relpos=0), nth_value (HEAD, relpos=nth-1). The ONLY caller that uses WINDOW_SEEK_TAIL is window_last_value (windowfuncs.c:685-686) and it hardcodes relpos=0, so `relpos > 0` is never true. RPR navigation (FIRST/LAST/PREV/NEXT) does not pass a positive TAIL relpos either: it goes through last_value for the FINAL/tail anchor (relpos=0) and computes reach positions internally via eval_nav_offset_helper; the rpPattern+TAIL branch at 4905 (gcov: covered, 8*) confirms the TAIL case itself IS exercised with relpos=0, but never with relpos>0. The branch is a symmetric defensive guard mirroring the HEAD-case `if (relpos < 0)` early-out at 4726 (per the comment at 4793-4794 'rejecting relpos > 0 is easy and simplifies code below'). It is only reachable by a third-party C window-function extension calling WinGetFuncArgInFrame with WINDOW_SEEK_TAIL and a positive offset (the API is exported in windowapi.h), which is not exercisable from SQL.",
      "refinedTest": "No SQL/regression test can cover this line, because no built-in window function passes relpos > 0 with WINDOW_SEEK_TAIL (last_value, the sole TAIL caller, hardcodes 0). The only way to drive execution through 4795 is a C-level test: a custom window-function extension (e.g. in src/test/modules) whose support function calls WinGetFuncArgInFrame(winobj, 0, +1, WINDOW_SEEK_TAIL, true, &isnull, &isout) and asserts isout is set. This is the same situation as the symmetric HEAD guard at 4726, which is presumably also uncovered. Not worth adding; treat as defensive.",
      "refinedFix": "Leave as a defensive early-out, consistent with the symmetric WINDOW_SEEK_HEAD guard at 4726 and the rationale comment at 4793-4794. No code change needed. Optionally, this could be annotated for coverage exclusion alongside the matching HEAD guard, but that is cosmetic."
     }
    ]
   ]
  },
  "4856": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4856",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4856",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "The claimed classification \"testable\" and its proposed test are WRONG. Line 4856 is the EXCLUDE_TIES else-branch in the WINDOW_SEEK_TAIL case: `abs_pos -= overlapend - 1 - groupheadpos`, taken only when `abs_pos != overlapend - 1` inside the if-block guarded by `abs_pos < grouptailpos && groupheadpos < frametailpos` (line 4847-4848). I proved it is unreachable by ALL current callers. SEEK_TAIL into WinGetSlotInFrame has exactly ONE caller in the whole tree: window_last_value() in src/backend/utils/adt/windowfuncs.c:685-686, which passes a hardcoded relpos=0. With relpos=0, abs_pos = frametailpos - 1 (line 4804). overlapend = Min(grouptailpos, frametailpos). Case analysis of the entry guard: (A) if grouptailpos <= frametailpos, the guard `abs_pos < grouptailpos` i.e. frametailpos-1 < grouptailpos forces grouptailpos==frametailpos, so overlapend=frametailpos and overlapend-1 = frametailpos-1 = abs_pos -> if-branch (4853-4854). (B) if grouptailpos > frametailpos, overlapend=frametailpos so overlapend-1 = frametailpos-1 = abs_pos -> if-branch. In EVERY case abs_pos == overlapend-1, so the else at 4856 is never taken. The else only fires when relpos < 0 (then abs_pos = frametailpos-1+relpos != frametailpos-1), but no window function passes a negative relpos to a SEEK_TAIL in-frame fetch. The ignore-nulls variant (ignorenulls_getfuncarginframe) is a SEPARATE function and never reaches line 4856. RPR navigation (FIRST/LAST/PREV/NEXT) uses the reduced-frame mechanism, not this exclusion path, and per the comment at line 3755 RPR forbids EXCLUDE clauses entirely, so RPR can never reach an EXCLUDE_TIES branch. The proposed test (last_value EXCLUDE TIES, relpos=0) lands squarely on the if-branch 4853-4854, NOT 4856 -- it does not cover the line. This is symmetric \"defensive\" code mirroring the EXCLUDE_GROUP branch (4830-4844), written to handle a general negative relpos that no caller currently produces.",
      "refinedTest": "No SQL/regression test can reach line 4856 with the current set of window functions. It would require a window function that calls WinGetFuncArgInFrame/WinGetSlotInFrame with seektype=WINDOW_SEEK_TAIL and a NEGATIVE relpos while an EXCLUDE TIES frame is active and the current row is not the last of its tie group. No core function (only last_value uses SEEK_TAIL, with relpos hardcoded to 0) and no RPR path does this; RPR additionally forbids EXCLUDE clauses. The only way to cover it would be to author a custom C window function (e.g. in a test module) that invokes WinGetFuncArgInFrame(..., relpos<0, WINDOW_SEEK_TAIL, ...) over an EXCLUDE TIES window, which is outside the scope of regression SQL.",
      "refinedFix": "Two acceptable options. (1) Leave as-is: the branch is intentional defensive/symmetric code that correctly handles a negative SEEK_TAIL relpos should a future window function need it (it mirrors the EXCLUDE_GROUP case). (2) If exact coverage parity is desired, replace the if/else at 4853-4856 with an Assert documenting the invariant, e.g. `Assert(abs_pos == overlapend - 1); abs_pos = winstate->currentpos;` -- but this would lose generality for negative-relpos callers, so option (1) is preferable. Either way, do NOT add the proposed last_value EXCLUDE TIES regression test as a means to cover this line; it cannot."
     }
    ]
   ]
  },
  "4863": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4863-4864",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4863-4864",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. Lines 4863-4866 are the default: arm of `switch (winstate->frameOptions & FRAMEOPTION_EXCLUSION)` in the WINDOW_SEEK_TAIL branch. FRAMEOPTION_EXCLUSION (parsenodes.h:715-717) is the OR of exactly three single-bit flags: EXCLUDE_CURRENT_ROW (0x08000), EXCLUDE_GROUP (0x10000), EXCLUDE_TIES (0x20000). The grammar production opt_window_exclusion_clause (gram.y:17574-17577) is a single optional clause that assigns exactly ONE of these bits, or 0 (EXCLUDE NO OTHERS / no clause). It is not a list, so two exclusion bits can never both be set. No other code path (parse_clause.c, optimizer) ORs multiple exclusion bits into frameOptions. Therefore the masked expression always evaluates to one of {0, 0x08000, 0x10000, 0x20000}, and the case 0 / CURRENT_ROW / GROUP / TIES arms (4817-4862) handle all of them. The default: arm cannot be entered by any SQL or regression input. It is a true defensive guard, structurally identical to the sibling switch default at 4779-4780 (WINDOW_SEEK_HEAD). The elog plus `mark_pos = 0` also serves to keep the compiler quiet about an otherwise-uninitialized mark_pos. I attempted to refute by checking grammar, header bit layout, and programmatic frameOptions assignment; none allows reaching it.",
      "refinedTest": "No SQL/regression test can cover these lines. Reaching the default: arm would require frameOptions to carry two or more exclusion bits simultaneously (e.g. 0x18000), which the single-valued opt_window_exclusion_clause grammar rule makes impossible. The only way to execute it would be a C-level fault injection / unit harness that manually sets winstate->frameOptions to an out-of-range exclusion mask before calling WinGetSlotInFrame on an RPR (WINDOW_SEEK_TAIL) window object -- not achievable through the SQL surface and not appropriate for the regress suite.",
      "refinedFix": "Keep as a defensive elog(ERROR). Optionally annotate with a coverage exclusion (e.g. /* GCOV_EXCL_LINE */ or a comment noting the masked value is provably one of four enumerated cases) to silence the coverage gap, consistent with how the sibling default at 4779-4780 should be treated. No behavioral change is warranted; the mark_pos = 0 assignment must stay to keep the compiler quiet."
     }
    ]
   ]
  },
  "4877": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4877",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4877",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 4877 (`if (-relpos >= num_reduced_frame) goto out_of_frame;`) is the RPR reduced-frame bound check inside the `else if (num_reduced_frame > 0)` block of the WINDOW_SEEK_TAIL case. To fire it needs: (1) num_reduced_frame >= 1, so the condition -relpos >= num_reduced_frame requires -relpos >= 1, i.e. relpos <= -1 (a NEGATIVE relpos); and (2) seektype == WINDOW_SEEK_TAIL. I exhaustively grep'd every WINDOW_SEEK_TAIL / WinGetFuncArgInFrame / WinGetSlotInFrame caller in the whole source tree (src/backend/utils/adt/windowfuncs.c is the only place). The ONLY built-in TAIL caller is window_last_value (windowfuncs.c:685-686), which passes relpos = 0. With relpos=0, -relpos=0, and since we are already inside `num_reduced_frame > 0` (>=1), `0 >= 1` is always false, so the branch is never taken. first_value and nth_value use WINDOW_SEEK_HEAD, not TAIL, and PostgreSQL's nth_value has NO `FROM LAST` variant (confirmed: no from_last support in grammar/parser). RPR's own FIRST/LAST/PREV/NEXT navigation uses dedicated EEOP_RPR_NAV opcodes and WinRPRFetchTuple, completely bypassing WinGetSlotInFrame. The sibling IGNORE NULLS path (line 3765) has the same guard `notnull_relpos >= num_reduced_frame` with notnull_relpos = abs(relpos), equally unreachable from last_value's relpos=0. The proposed test (last_value with PATTERN(A)/DEFINE) is correctly self-refuted in the finding: it reaches the function with relpos=0 but cannot make -relpos>=num_reduced_frame. No SQL or regression input exists that drives relpos<0 into the TAIL branch; only a hypothetical not-yet-existing nth-from-tail window function (or a C extension calling the API directly) could. The line is correct, intentional bound handling. Classification refined from hard-to-reach to defensive-unreachable: it is a guard with no SQL-reachable trigger given the current built-in function set.",
      "refinedTest": "No SQL-level test can cover line 4877. Every in-tree WINDOW_SEEK_TAIL caller (only window_last_value) passes relpos=0, and -relpos(=0) >= num_reduced_frame(>=1) is impossible. Covering it would require a C-callable window function that calls WinGetFuncArgInFrame(winobj, argno, relpos<0, WINDOW_SEEK_TAIL, ...) while RPR is active (PATTERN/DEFINE making row_is_in_reduced_frame()>0). The smallest demonstration would be a custom C test extension exporting such a function, then: SELECT my_nth_from_last(price, 2) OVER (PARTITION BY company ORDER BY ts ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING INITIAL PATTERN (A B) DEFINE A AS ..., B AS ...) where the reduced frame length is 1 < 2 so -relpos(=-(-1)=1) >= num_reduced_frame(=1). No such function ships with PostgreSQL, so the line stays uncovered by the regression suite.",
      "refinedFix": "Leave the code as-is; it is correct, defensive RPR bound handling. To document why it is uncovered, add a brief comment near line 4874-4877 noting that all in-tree TAIL callers (last_value) use relpos==0 so -relpos>=num_reduced_frame cannot fire today, and the guard exists to protect a future nth-from-tail-style window function (and the public WinGetFuncArgInFrame C API) from reading before the reduced-frame start. Alternatively, since num_reduced_frame and relpos==0 jointly make the goto dead for current callers, an Assert documenting the invariant (e.g. Assert(relpos <= 0)) already present at 4794 covers the relpos>0 side; consider mirroring with a comment that relpos<0+TAIL is reserved for future functions. No functional change recommended."
     }
    ]
   ]
  },
  "4882": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4882-4883",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4882-4883",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable via any SQL/regression input. WinGetSlotInFrame is static and called only from WinGetFuncArgInFrame (nodeWindowAgg.c:5295), which passes seektype through unchanged. WinGetFuncArgInFrame (public windowapi.h API) is called only from windowfuncs.c at 3 sites: window_first_value/window_nth_value pass WINDOW_SEEK_HEAD, window_last_value passes WINDOW_SEEK_TAIL. The seektype enum (windowapi.h:34-36) has exactly 3 compile-time-constant values: CURRENT=0, HEAD=1, TAIL=2. All three are explicitly handled by switch cases at lines 4720, 4724, 4792 (and CURRENT itself elogs at 4721). The default: arm at 4882-4883 fires only for a seektype outside {0,1,2}, which no built-in caller ever supplies and which cannot originate from user SQL (seektype is internal int, never derived from query data). RPR FIRST/LAST navigation reuses the same first_value/last_value window functions, so it too only yields HEAD/TAIL. Tried hard to refute: no exclusion-clause, RPR PATTERN/DEFINE, or IGNORE NULLS path alters seektype before reaching this switch. This mirrors the identical defensive default at line 3735.",
      "refinedTest": "No SQL test can reach these lines. The default arm is only reachable by a C-level programming error (a new caller passing an out-of-range seektype). The only way to exercise it is a C unit test or temporary debug build that invokes WinGetFuncArgInFrame with an invalid seektype (e.g., 3); this is not achievable through SQL or the standard regression harness.",
      "refinedFix": "Keep as defensive elog(ERROR, ...) for consistency with the sibling switch at line 3735, OR convert to Assert(false) / pg_unreachable() since seektype is purely internal and the elog branch can never be hit by valid callers. Either way exclude lines 4882-4883 from coverage expectations as defensive-unreachable. Recommend matching whatever style is used at 3735 to keep the two parallel switches consistent."
     }
    ]
   ]
  },
  "4896": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4896",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4896",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Line 4896 (`*isout = false;`) inside the guarded block `if (isout)` at 4895 executes only when isout != NULL on the in-frame success path. Exhaustive call-graph audit: WinGetSlotInFrame (static, nodeWindowAgg.c:4706) is called from exactly one site, WinGetFuncArgInFrame:5295, which forwards the caller's isout. WinGetFuncArgInFrame has only three in-tree callers - window_first_value (windowfuncs.c:665), window_last_value (:687), window_nth_value (:721) - and ALL pass isout = NULL. ignorenulls_getfuncarginframe is a wholly separate implementation that does not call WinGetSlotInFrame. WinGetFuncArgInPartition is a distinct function (windowapi.h:59) not routed through WinGetSlotInFrame. RPR navigation uses ExecRPRNavGetSlot, also separate. grep for WinGetFuncArgInFrame across all .c files outside windowfuncs.c/nodeWindowAgg.c returns nothing, so no contrib/test-module caller exists. No SQL or regression input can make any path pass a non-NULL isout into WinGetSlotInFrame; therefore *isout = false; at 4896 is never executed. The guard line 4895 is evaluated (NULL each time) but the assignment body at 4896 is dead under all reachable inputs. I tried to refute by hunting for an alternate caller (ignore-nulls path, partition path, RPR nav path, exported-API external callers) and found none reachable from SQL.",
      "refinedTest": "No pure-SQL/regression test can cover this line, because coverage requires an in-tree caller of WinGetFuncArgInFrame that passes a non-NULL isout, and none exists. The only way to exercise 4896 is to add a C-level test: a custom window function in a test module (e.g. src/test/modules) that calls WinGetFuncArgInFrame(..., &isnull, &isout) with a target row that lands inside the frame, then invoke that function from SQL. Without such a module no test drives these exact lines. (The mirror line 4913 `*isout = true;` in the out_of_frame path is equally unreachable for the same reason.)",
      "refinedFix": "The isout output parameter of WinGetFuncArgInFrame/WinGetSlotInFrame has no live consumer: every in-tree call passes NULL. Two defensible options: (1) Drop the isout parameter from WinGetSlotInFrame and WinGetFuncArgInFrame, and from the windowapi.h contract, until a real consumer appears - this removes the dead assignments at 4896 and 4913 entirely. (2) Keep the parameter for API symmetry with WinGetFuncArgInPartition (which has a genuine consumer) and accept the guard as presently dead, documenting that WinGetFuncArgInFrame's isout is currently only ever called with NULL. Recommend option (2): retain for API completeness/symmetry, add a brief comment that isout is currently exercised only as NULL, and exclude 4896/4913 from the coverage target rather than writing an artificial test module."
     }
    ]
   ]
  },
  "4913": {
   "func": "WinGetSlotInFrame",
   "reachable": false,
   "subs": [
    [
     "4913",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4913",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable from any SQL/regression input. Line 4913 `*isout = true;` at the out_of_frame label is guarded by `if (isout)` (4912). isout reaches WinGetSlotInFrame only via its single caller WinGetFuncArgInFrame (nodeWindowAgg.c:5295), which passes its own isout straight through. WinGetFuncArgInFrame's only in-tree callers are window_first_value, window_last_value, and window_nth_value (windowfuncs.c:665, 687, 721), and ALL three pass NULL for isout. The ignorenulls_getfuncarginframe branch (5292) forwards the same isout, so it is NULL there too. Therefore isout is always NULL through every live code path, the `if (isout)` test at 4912 is always false, and 4913 never executes. The out_of_frame label itself IS reachable (e.g. last_value over an excluded/empty frame hits goto at 4889/4893), and the adjacent line 4914 `*isnull = true;` would be covered, but the isout-guarded body is dead. WinGetFuncArgInFrame is extern (windowapi.h:63), so an out-of-tree extension could pass non-NULL isout, but no SQL query can. Symmetric to line 4896 (the *isout=false success-path counterpart), same root cause. Classification accurate; no test can cover it.",
      "refinedTest": "No SQL-level test can cover this line, because no in-tree caller of WinGetFuncArgInFrame passes a non-NULL isout. To exercise it you would need a C-level unit test or an out-of-tree window function (a custom extension) that calls WinGetFuncArgInFrame with a non-NULL isout pointer and forces an out-of-frame condition (e.g. last_value-style WINDOW_SEEK_TAIL or nth_value with an offset past the frame end). Within PostgreSQL's regression framework this is not achievable.",
      "refinedFix": "Accept as defensive/dead. The isout out-parameter is part of the WinGetFuncArgInFrame/WinGetSlotInFrame API symmetry but has no consumer: every live caller passes NULL. Options: (1) keep lines 4895-4896 and 4912-4913 for API completeness with a /* dead: no caller passes non-NULL isout */ note, or (2) remove the isout parameter from WinGetFuncArgInFrame/WinGetSlotInFrame/ignorenulls_getfuncarginframe until a consumer exists. Either way, exclude these lines from the coverage-gap target rather than chasing them with a test."
     }
    ]
   ]
  },
  "4776": {
   "func": "WinGetSlotInFrame",
   "reachable": true,
   "subs": [
    [
     "4776",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4776",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED testable, and the proposed test is empirically verified to cover the exact line. Line 4776 lives in the WINDOW_SEEK_HEAD + FRAMEOPTION_EXCLUDE_TIES branch (nodeWindowAgg.c:4765-4778). It is the else of `if (abs_pos == overlapstart)`, reached when abs_pos > overlapstart while EXCLUDE TIES is active and grouptailpos > frameheadpos. The only callers using WINDOW_SEEK_HEAD with a positive relpos is window_nth_value (windowfuncs.c:719-721, relpos = nth-1), so nth>=2 is required; first_value uses relpos=0 (abs_pos==frameheadpos==overlapstart, hitting the if-branch at 4774). The root-cause analysis is accurate. I built no theory only: I started the coverage-built backend (tmp_install), reset the nodeWindowAgg gcda counters, ran ONLY the proposed query against a tenk1-like table (unique1 0..99, four = g%4, giving 4-row peer groups so groupheadpos/grouptailpos span >1 row), and re-ran gcov. Result: line 4776 executed 10 times, while line 4774 showed ##### (0) in that isolated run -- so this query takes the else-branch every time and unambiguously covers the target line. The reason 4774 is not hit here: with ROWS BETWEEN CURRENT ROW AND 3 FOLLOWING, frameheadpos==currentpos>=groupheadpos so overlapstart==frameheadpos, and abs_pos==frameheadpos+1 > overlapstart. Note: existing window.sql:266-270 already runs nth_value(unique1,2) but over a window with NO EXCLUDE clause, so it never enters the EXCLUDE_TIES switch arm -- confirming the gap is real.",
      "refinedTest": "Add to src/test/regress/sql/window.sql (and matching .out): SELECT nth_value(unique1,2) over (ORDER BY four rows between current row and 3 following exclude ties), unique1, four FROM tenk1 WHERE unique1 < 10; -- VERIFIED: with tenk1's four column (= unique1%4, 4-row peer groups), nth=2 makes relpos=1 so abs_pos=frameheadpos+1 > overlapstart, taking the else-branch at line 4776 (executed 10x in an isolated coverage run; the if-branch at 4774 stayed at 0). The proposed test as written is correct and needs no change; tenk1 already has the required ties in `four`, so the synthetic data note in the finding is unnecessary but harmless.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4860": {
   "func": "WinGetSlotInFrame",
   "reachable": true,
   "subs": [
    [
     "4860",
     {
      "functionName": "WinGetSlotInFrame",
      "lines": "4860",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Classification \"testable\" is CORRECT and line 4860 is genuinely reachable - I drove execution through it empirically on the live coverage build (gcov count for \": 4860:\" went from ##### to positive, with a reproducible +4/+6 delta per query). However, the proposed test is WRONG and does NOT cover line 4860, and the stated root cause is misleading. (1) The ONLY caller reaching WINDOW_SEEK_TAIL in WinGetSlotInFrame is window_last_value, which always passes relpos=0 (windowfuncs.c:685-686); first_value/nth_value use WINDOW_SEEK_HEAD; RPR navigation uses a separate nav_winobj path, not this function. (2) With relpos=0, abs_pos=frametailpos-1, and the else branch at line 4856 (abs_pos -= overlapend-1-groupheadpos) is UNREACHABLE: entering the block needs abs_pos<grouptailpos, but reaching the else needs frametailpos>grouptailpos i.e. abs_pos>=grouptailpos - a contradiction. gcov confirms 4856 stays ##### even after targeted queries. So the claimed mechanism (\"else branch pushes abs_pos before frameheadpos\") cannot happen. (3) Line 4860 actually fires via the THEN-branch (4854 sets abs_pos=currentpos) when the frame starts AFTER the current row, so currentpos<frameheadpos. (4) The proposed test \"rows between current row and current row exclude ties\" always takes the then-branch with abs_pos=currentpos=frameheadpos, so abs_pos<frameheadpos is false and the goto is never taken - verified: that query left 4860 at #####.",
      "refinedTest": "Use a FOLLOWING-only frame (frame head past the current row) combined with ties on the ORDER BY column, so the current row's peer group overlaps the frame and EXCLUDE TIES rewrites abs_pos to currentpos < frameheadpos. Verified empirically to increment line 4860's gcov count on tenk1:\n\nSELECT last_value(unique1) over (ORDER BY four rows between 1 following and 2 following exclude ties), four FROM tenk1 WHERE unique1 < 12 ORDER BY four, unique1;\n\n(Equivalent minimal form on a small ties table also works: with t2(id,g) VALUES (1,1),(2,1),(3,1),(4,1),(5,2),(6,2): SELECT id, last_value(id) over (ORDER BY g rows between 1 following and 2 following exclude ties) FROM t2 ORDER BY id; -- drove 4860 +4 per run.) Note: this covers the goto at 4860 via the then-branch; line 4856 (else branch) remains separately uncovered and is in fact unreachable for relpos=0 callers.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4019": {
   "func": "eval_nav_offset_helper",
   "reachable": true,
   "subs": [
    [
     "4019",
     {
      "functionName": "eval_nav_offset_helper",
      "lines": "4019",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED reachable and CONFIRMED testable, with one critical correction the original finding under-specifies. Line 4019 (`if (offset < 0) return 0;`) at nodeWindowAgg.c:4018-4019 is only reached when a NEEDS_EVAL nav offset evaluates negative at executor-init time (eval_define_offsets -> visit_nav_exec -> eval_nav_offset_helper, called from ExecInitWindowAgg at line 3047, before any row is processed). I traced the planner side: extract_const_offset (createplan.c:2510-2525) folds any Const offset at plan time and clamps negatives there (line 2519-2520), marking it FIXED; only a NON-Const offset (Param under a generic plan, random()::int, subquery, column ref) returns false -> maxNeedsEval/firstNeedsEval -> RPR_NAV_OFFSET_NEEDS_EVAL -> eval_nav_offset_helper is invoked. So a negative literal can NEVER reach line 4019 (it is folded/clamped in the planner). I verified this empirically: built a 19beta1 coverage cluster from tmp_install, ran the exact prepared statement. Under force_generic_plan, EXECUTE rpr_prev(-1) drove gcov execution count 1 on line 4019, then errored per-row with \"row pattern navigation offset must not be negative\". Under force_custom_plan the SAME EXECUTE left line 4019 at ##### (not executed) because the param is substituted as a folded Const. The original finding's phrase \"add EXECUTE rpr_prev(-1)\" is therefore correct ONLY if the negative EXECUTE runs in the force_generic_plan section; placing it under the existing custom-plan example would NOT cover the line. The query also produces an error in the .out (expected, per MEMORY: capture errors, no DO block).",
      "refinedTest": "In src/test/regress/sql/rpr_integration.sql, reuse the existing PREPARE rpr_prev(int) (DEFINE B AS val > PREV(val, $1)) and add a negative EXECUTE strictly under the GENERIC plan mode so $1 stays a Param (NEEDS_EVAL). The literal-substituted custom plan folds -1 to a Const and skips eval_nav_offset_helper entirely.\n\nExample (place after the existing force_generic_plan block):\n  SET plan_cache_mode = force_generic_plan;\n  -- negative non-constant nav offset: eval_nav_offset_helper clamps to 0 at\n  -- executor init (covers nodeWindowAgg.c:4019), then the per-row nav path\n  -- raises the negative-offset error.\n  EXECUTE rpr_prev(-1);\n\nExpected output in rpr_integration.out:\n  ERROR:  row pattern navigation offset must not be negative\n\n(Verified empirically: gcov line 4019 hit count = 1 under generic plan; = 0 under custom plan.) A volatile non-const offset such as DEFINE B AS val > PREV(val, (val - 100000)) over rows where val-100000 < 0 is an equivalent non-prepared alternative, but the prepared-statement generic-plan route is the minimal, deterministic addition.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4208": {
   "func": "eval_define_offsets",
   "reachable": true,
   "subs": [
    [
     "4208",
     {
      "functionName": "eval_define_offsets",
      "lines": "4208",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED reachable and testable, but the PROPOSED TEST IS INVALID. I empirically verified line 4208 is uncovered (gcov #####) even after a full `pg-regress rpr` run, and confirmed it CAN be driven (gcov count 1) with a corrected test. Line 4208 (`winstate->navFirstOffset = ctx.minFirstOffset;`, the true branch of `if (ctx.minFirstOffset < PG_INT64_MAX)`) executes only when needsFirst is true: hasFirstNav && navFirstOffsetKind == RPR_NAV_OFFSET_NEEDS_EVAL, and visit_nav_exec lowered minFirstOffset below the sentinel (always true once any FIRST-family nav is visited).\\n\\nWhy the finding's PROPOSED TEST fails: `FIRST(price, price)` uses a COLUMN as the nav offset, which parse analysis REJECTS with `ERROR: row pattern navigation offset must be a run-time constant` (verified live). A nav offset must be a runtime constant; only a Const or a Param is accepted, never a column reference. So that query never plans, let alone reaches the executor.\\n\\nWhy the finding's ROOT CAUSE is also partly wrong: the suite DOES contain a non-constant offset on a FIRST-family nav, at src/test/regress/sql/rpr.sql:1267 `DEFINE B AS PREV(FIRST(val, $1), $2)` (an RPR_NAV_PREV_FIRST, which sets hasFirst=true and firstNeedsEval=true in visit_nav_plan). The real reason it does not cover 4208 is plan caching: EXECUTE uses a CUSTOM plan for the first executions, substituting $1/$2 as Consts before create_windowagg_plan runs, so extract_const_offset succeeds and navFirstOffsetKind becomes FIXED, not NEEDS_EVAL. gcov proves this: eval_define_offsets ran 124 times and ALL 124 hit the early `return` at line 4175 (needsMax and needsFirst both false every time).\\n\\nTo force NEEDS_EVAL you must keep the offset as an unfolded Param, which requires a GENERIC plan (SET plan_cache_mode = force_generic_plan). EXPLAIN VERBOSE then shows `Nav Mark Lookahead: runtime` (the NEEDS_EVAL display branch), and EXECUTE drives eval_define_offsets through needsFirst=true -> 4204 -> 4207 (true) -> 4208. I confirmed end-to-end: after adding the refined probe to rpr.sql and re-running, line 4208 shows execution count 1 (else-branch 4210 remains #####).",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql (with matching .out). The offset MUST be a Param (column refs are rejected), and the plan MUST be generic so the Param is not const-folded to FIXED:\\n\\nCREATE TEMP TABLE rpr_first_eval (company text, tdate int, price int);\\nINSERT INTO rpr_first_eval VALUES ('A',1,100),('A',2,200),('A',3,150);\\nPREPARE first_eval_off(int8) AS\\nSELECT company, price, first_value(price) OVER w AS fv\\nFROM rpr_first_eval WINDOW w AS (\\n  PARTITION BY company ORDER BY tdate\\n  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\\n  INITIAL PATTERN (A+)\\n  DEFINE A AS FIRST(price, $1) > 0\\n);\\nSET plan_cache_mode = force_generic_plan;\\n-- EXPLAIN shows 'Nav Mark Lookahead: runtime' (NEEDS_EVAL); EXECUTE drives line 4208\\nEXPLAIN (VERBOSE, COSTS OFF) EXECUTE first_eval_off(1);\\nEXECUTE first_eval_off(1);\\nRESET plan_cache_mode;\\nDEALLOCATE first_eval_off;\\nDROP TABLE rpr_first_eval;\\n\\nThis was empirically verified: line 4208 went from #####  to execution count 1, with the else branch (4210) untouched. force_generic_plan is essential; without it the custom plan folds $1 to a Const and the line stays uncovered (the existing line-1267 test demonstrates exactly this failure mode).",
      "refinedFix": ""
     }
    ]
   ]
  },
  "3766": {
   "func": "ignorenulls_getfuncarginframe",
   "reachable": false,
   "subs": [
    [
     "3766",
     {
      "functionName": "ignorenulls_getfuncarginframe",
      "lines": "3766",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 3766 (goto out_of_frame inside the WINDOW_SEEK_TAIL + num_reduced_frame>0 branch) is unreachable by any in-tree SQL/regression input, and the proposed test categorically cannot cover it. The guard at 3765 is `if (notnull_relpos >= num_reduced_frame)`, where notnull_relpos = abs(relpos) (line 3701) and the code only reaches 3765 inside the `num_reduced_frame > 0` branch (line 3751), so num_reduced_frame >= 1. To take the goto we need notnull_relpos >= 1, i.e. relpos != 0. But I verified the ONLY caller of WinGetFuncArgInFrame with WINDOW_SEEK_TAIL anywhere in the tree is window_last_value (src/backend/utils/adt/windowfuncs.c:686), which hardcodes relpos=0. With relpos=0, notnull_relpos=0 and `0 >= num_reduced_frame` (>=1) is always FALSE. nth_value and all other tail-from-end needs route through WINDOW_SEEK_HEAD (nth-1, line 720), and RPR FIRST/LAST/PREV/NEXT navigation uses a separate nav_winobj/execRPR.c path, not WinGetFuncArgInFrame. Hence no SQL can make a TAIL seek with |relpos|>=1. The proposed test (last_value(val) IGNORE NULLS) uses exactly relpos=0, so it would execute lines 3763-3764 and 3769 but NEVER line 3766. The symmetric HEAD guard at 3761 (`relpos >= num_reduced_frame`) IS reachable because nth_value passes nth-1 via HEAD; line 3766 is its dead mirror for the TAIL case. Caveat: WinGetFuncArgInFrame is exported in windowapi.h, so a third-party C extension window function could call it with TAIL and a negative relpos and reach 3766 — that is why I classify it as defensive rather than strictly dead code, but it remains unreachable from SQL/regression.",
      "refinedTest": "No SQL/regression test can cover line 3766. The branch requires WinGetFuncArgInFrame(seektype=WINDOW_SEEK_TAIL, relpos!=0), but the sole tail caller window_last_value hardcodes relpos=0, and no SQL-exposed window function (nth_value uses HEAD; RPR nav uses a separate path) issues a nonzero TAIL relpos. Covering it would require a new built-in/extension window function that calls WinGetFuncArgInFrame with WINDOW_SEEK_TAIL and a negative relpos over an RPR frame whose reduced length is <= |relpos| — there is no such caller and adding one is out of scope. Recommend leaving uncovered or converting the guard into an Assert (see refinedFix).",
      "refinedFix": "Optional, not required for correctness: since notnull_relpos is provably 0 for every reachable TAIL call (only window_last_value reaches here, with relpos=0), the runtime check at 3765-3766 can be downgraded to an assertion documenting the invariant, e.g. replace `if (notnull_relpos >= num_reduced_frame) goto out_of_frame;` with `Assert(notnull_relpos == 0);` (keeping line 3769's abs_pos assignment). This removes the uncovered branch while preserving defense against a hypothetical future nonzero-relpos TAIL caller in debug builds. If the maintainers prefer to keep symmetry with the HEAD guard at 3761 as future-proofing for extension authors, leave the line as-is and accept it as defensive-unreachable."
     }
    ]
   ]
  },
  "4284": {
   "func": "row_is_in_reduced_frame",
   "reachable": false,
   "subs": [
    [
     "4284-4285",
     {
      "functionName": "row_is_in_reduced_frame",
      "lines": "4284-4285",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable. The switch's `default:` (elog ERROR, lines 4284-4285) is a pure can't-happen guard. `state` is a plain int but only ever receives one of the five RF_* #define constants (execnodes.h:2529-2533, values 0-4) returned by get_reduced_frame_status, which has exactly five return points and never produces an arbitrary int. The only RF_* value missing an explicit case is RF_NOT_DETERMINED (0). That value is structurally excluded at the switch: get_reduced_frame_status returns RF_NOT_DETERMINED only when !rpr_match_valid, but the code re-fetches `state` AFTER calling update_reduced_frame(), and EVERY exit path of update_reduced_frame (Case 1 line 4546, no-context line 4567, and register_result line 4597) unconditionally sets winstate->rpr_match_valid = true. So the second get_reduced_frame_status call (line 4267) can only return RF_FRAME_HEAD/RF_SKIPPED/RF_UNMATCHED/RF_EMPTY_MATCH, all of which have explicit cases. No SQL/regression input -- regardless of PATTERN/DEFINE/quantifiers/AFTER MATCH SKIP mode/empty matches -- can drive a value into the default arm. I tried to refute via empty-match (RF_EMPTY_MATCH handled), unmatched (RF_UNMATCHED handled), and SKIP-overlap completed-context (register_result still sets valid=true) paths; none reaches it.",
      "refinedTest": "No test can cover these lines. They are reachable only if get_reduced_frame_status returned RF_NOT_DETERMINED or a value outside 0-4 at line 4267, both of which are impossible because update_reduced_frame always sets rpr_match_valid=true and the function never returns an out-of-range int. The only way to exercise this code is fault injection (e.g., manually corrupting rpr_match_valid back to false between the update and the switch), which is not achievable through SQL. Recommend leaving uncovered.",
      "refinedFix": "Keep as a defensive can't-happen guard. Converting `elog(ERROR, ...)` to `Assert(false)` (or pg_unreachable() after the existing elog) would document the invariant and is consistent with PostgreSQL practice for switch-on-internal-enum defaults, but the current elog(ERROR) is also acceptable and matches surrounding executor style. No functional change needed; the line will remain legitimately uncovered."
     }
    ]
   ]
  },
  "4082": {
   "func": "visit_nav_exec",
   "reachable": true,
   "subs": [
    [
     "4082",
     {
      "functionName": "visit_nav_exec",
      "lines": "4082",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 4082 (the RPR_NAV_LAST + non-NULL offset_arg arm of visit_nav_exec) is genuinely reachable, and the root-cause analysis is correct: no existing test exercises a bare LAST(x, <runtime-offset>) that survives to executor-side NEEDS_EVAL evaluation. The PREV branch (4076) and compound PREV_LAST/NEXT_LAST branches are covered via force_generic_plan EXPLAIN ANALYZE tests in rpr_explain.sql, but never bare LAST. HOWEVER the PROPOSED test does NOT cover line 4082, for TWO independent reasons proven empirically: (1) LAST(price, price) uses a column reference as the offset, which is rejected at parse time with ERROR \"row pattern navigation offset must be a run-time constant\" (parse_rpr.c:628-632; reproduced live, matches expected rpr.out:1197 for the analogous PREV case). It never reaches the planner, let alone the executor. (2) Even replacing the offset with a Param ($1) in a normal PREPARE/EXECUTE does not work: under default plan_cache_mode=auto the custom plan const-folds $1 to a Const during eval_const_expressions, so extract_const_offset succeeds, the planner sets navMaxOffsetKind=FIXED (EXPLAIN shows \"Nav Mark Lookback: 2\"), eval_define_offsets returns early at nodeWindowAgg.c:4174, and visit_nav_exec is never called. I confirmed this with gcov: line 4082 showed ##### (0 hits) after running LAST(price,$1) via plain EXECUTE. Only when forcing a generic plan (SET plan_cache_mode=force_generic_plan; EXPLAIN shows \"Nav Mark Lookback: runtime\") does the Param stay unfolded -> navMaxOffsetKind=NEEDS_EVAL -> visit_nav_exec runs -> line 4082 hit (gcov count 2, verified). So the offset MUST be a Param kept unfolded via a generic plan; a column ref or a folded custom-plan Param will not work.",
      "refinedTest": "-- Bare LAST(v, $1) with a runtime (non-folded) offset. The generic plan keeps\n-- $1 as a Param, so the planner marks navMaxOffsetKind=NEEDS_EVAL and the\n-- executor calls visit_nav_exec, hitting the RPR_NAV_LAST + offset_arg arm\n-- (nodeWindowAgg.c:4082). Verified with gcov: line 4082 hit (count 2).\nPREPARE rpr_last_offset_prep(int8) AS\nSELECT count(*) OVER w\nFROM generate_series(1,10) s(v)\nWINDOW w AS (\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS LAST(v, $1) >= 0\n);\nSET plan_cache_mode = force_generic_plan;\n-- EXPLAIN (no execute) shows planner side: \"Nav Mark Lookback: runtime\"\nEXPLAIN (COSTS OFF) EXECUTE rpr_last_offset_prep(2);\n-- EXPLAIN ANALYZE actually EXECUTES the generic plan -> drives visit_nav_exec:4082\nEXPLAIN (COSTS OFF, ANALYZE, TIMING OFF, SUMMARY OFF)\n    EXECUTE rpr_last_offset_prep(2);\n-- A plain EXECUTE under the generic plan also drives line 4082:\nEXECUTE rpr_last_offset_prep(2);\nRESET plan_cache_mode;\nDEALLOCATE rpr_last_offset_prep;\n-- NOTE: the originally proposed LAST(price, price) is WRONG: a column-ref offset\n-- errors at parse time (\"row pattern navigation offset must be a run-time\n-- constant\") and never reaches line 4082. A folded Param (plain EXECUTE under\n-- default plan_cache_mode) also misses it. force_generic_plan is mandatory.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4103": {
   "func": "visit_nav_exec",
   "reachable": true,
   "subs": [
    [
     "4103-4104",
     {
      "functionName": "visit_nav_exec",
      "lines": "4103-4104",
      "lineCount": 2,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Lines 4103-4104 (the compound NEXT_LAST arm: reach = Max(inner - outer, 0); gotReach = true;) are genuinely reachable and testable, but the PROPOSED test does NOT cover them - it fails before reaching the executor. The proposed query NEXT(LAST(price, price), 2) uses the column reference 'price' as the navigation offset, which is rejected at parse analysis (parse_rpr.c:631) with 'ERROR: row pattern navigation offset must be a run-time constant'. I reproduced this error empirically on a live server. Navigation offsets must be run-time constants (Const or Param), so a column ref can never trigger NEEDS_EVAL. The classification 'testable' is correct, but the root-cause analysis conflates 'non-constant' (column ref, rejected) with 'NEEDS_EVAL' (parameter, accepted). NEEDS_EVAL is only set when an offset is a Param/non-foldable-but-stable expression (createplan.c:2642-2643), as the existing PREV(LAST(v,$1),$2) explain test demonstrates. The gap is real: no NEXT_LAST nav with parameter offsets exists in the suite, so the NEXT_LAST executor arm (4103-4104) is never run, while the PREV_LAST arm (4096-4097) is covered. I verified the refined parameter-based test drives these exact lines: EXPLAIN ANALYZE under force_generic_plan reported 'Nav Mark Lookback: 5' for params (7,2) = Max(7-2,0)=5 and 'Nav Mark Lookback: 0' for (1,3) = Max(1-3,0)=0, confirming the executor (not the planner const-fold) computed reach = Max(inner-outer,0) at lines 4103-4104.",
      "refinedTest": "-- Compound NEXT_LAST with parameter offsets forces RPR_NAV_OFFSET_NEEDS_EVAL,\n-- so the executor (visit_nav_exec) resolves the offset and runs the NEXT_LAST\n-- arm reach = Max(inner - outer, 0) at nodeWindowAgg.c:4103-4104.\n-- Must use a PREPARE + force_generic_plan so $1/$2 stay as Params (a custom\n-- plan would const-fold them and resolve in the planner instead).\nPREPARE test_nextlast_offset(int8, int8) AS\nSELECT count(*) OVER w\nFROM generate_series(1,10) s(v)\nWINDOW w AS (\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS NEXT(LAST(v, $1), $2) > 0\n);\nSET plan_cache_mode = force_generic_plan;\n-- inner=7, outer=2 -> Max(7-2,0)=5 (positive branch result)\nEXPLAIN (COSTS OFF) EXECUTE test_nextlast_offset(7, 2);\n-- inner=1, outer=3 -> Max(1-3,0)=0 (clamped-to-zero branch result)\nEXECUTE test_nextlast_offset(1, 3);\nDEALLOCATE test_nextlast_offset;\nRESET plan_cache_mode;\n-- Note: NEXT(LAST(v, $1), $2) (parameters) is accepted; a column reference\n-- such as NEXT(LAST(price, price), 2) is rejected at parse time\n-- (\"row pattern navigation offset must be a run-time constant\") and never\n-- reaches the executor, so the originally proposed test cannot cover these lines.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4115": {
   "func": "visit_nav_exec",
   "reachable": true,
   "subs": [
    [
     "4115",
     {
      "functionName": "visit_nav_exec",
      "lines": "4115",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Classification \"testable\" is CORRECT, but the proposed test is INVALID and would NOT cover line 4115. Line 4115 (int64 reach; opening the FIRST forward-reach block in visit_nav_exec) is reached only when a FIRST nav offset is non-Const, which sets navFirstOffsetKind=NEEDS_EVAL, causing eval_define_offsets() to invoke visit_nav_exec at executor init. Verified by reading createplan.c:2597-2609 (extract_const_offset returns false for non-Const -> firstNeedsEval=true -> NEEDS_EVAL) and confirmed live on a running server.\n\nThe proposed test FIRST(price, price) is REJECTED AT PARSE TIME. define_walker in parse_rpr.c:624-632 walks the offset in DEFINE_PHASE_NAV_OFFSET and errors with \"row pattern navigation offset must be a run-time constant\" (ERRCODE_FEATURE_NOT_SUPPORTED) because the offset contains a column reference (Var). I reproduced this exact error live: the query never reaches the planner or executor, so it covers nothing. Secondary flaws: the proposed query defines WINDOW w but never references it via OVER (would be discarded), and the line-number claims about \"4117, 4119 and 4208\" are otherwise correct targets but unreachable via this rejected query.\n\nThe valid path is an offset that is column-free (passes define_walker) yet not a foldable Const (fails extract_const_offset). A Param satisfies this. A scalar subquery offset is separately rejected (\"cannot use subquery in DEFINE expression\").",
      "refinedTest": "Use a Param offset and force a generic plan so the param is not const-folded into a Const before createplan runs:\n\nCREATE TABLE stock(company text, price int, day int);\nINSERT INTO stock VALUES ('A',10,1),('A',20,2),('A',30,3);\nSET plan_cache_mode = force_generic_plan;\nPREPARE pa(bigint) AS\nSELECT company, day, count(*) OVER w\nFROM stock\nWINDOW w AS (PARTITION BY company ORDER BY day\n  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n  INITIAL PATTERN (A+)\n  DEFINE A AS FIRST(price, $1) > 0);\nEXECUTE pa(1);\n\nThis was verified live: plan-only EXPLAIN VERBOSE prints \"Nav Mark Lookahead: runtime\" (navFirstOffsetKind=NEEDS_EVAL), and EXPLAIN (ANALYZE, VERBOSE) EXECUTE pa(1) prints \"Nav Mark Lookahead: 1\" (executor-resolved), proving eval_define_offsets ran visit_nav_exec through lines 4113->4115->4117-4119 and set navFirstOffset=1 at line 4208. Note: a plain (non-prepared) literal query const-folds the offset to a Const at plan time and would yield FIXED, NOT covering line 4115 -- the Param + force_generic_plan combination is essential. For a regress test that does not want to depend on plan_cache_mode, an EXPLAIN (COSTS OFF) on the generic plan asserting \"Nav Mark Lookahead: runtime\" plus an EXECUTE confirms the path.",
      "refinedFix": ""
     }
    ],
    [
     "4117",
     {
      "functionName": "visit_nav_exec",
      "lines": "4117",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 4117 (the `reach = eval_nav_offset_helper(...)` in the simple RPR_NAV_FIRST branch of visit_nav_exec) is genuinely REACHABLE, so the \"testable\" classification is correct. BUT the PROPOSED TEST IS INVALID and would NOT cover the line. Reaching 4117 requires: (1) a non-compound FIRST nav whose offset_arg is non-constant, so the planner's extract_const_offset() fails -> firstNeedsEval=true -> navFirstOffsetKind=RPR_NAV_OFFSET_NEEDS_EVAL (createplan.c:2597-2609, 2780-2783); and (2) at executor init eval_define_offsets() sees needsFirst (hasFirstNav && NEEDS_EVAL) and walks the DEFINE expr with visit_nav_exec, hitting the RPR_NAV_FIRST branch (nodeWindowAgg.c:4113-4119). The proposed input `FIRST(price, price)` uses a COLUMN as the offset, which is rejected at parse analysis: define_walker walks the offset in DEFINE_PHASE_NAV_OFFSET, flags has_column_ref on the Var, and raises ERROR \"row pattern navigation offset must be a run-time constant\" (parse_rpr.c:483-487, 624-632). It never builds a plan, never reaches the executor. The only non-constant offset that survives parse analysis (no Var) yet stays non-Const through planning (not folded) is an external Param ($N). The existing suite only has the COMPOUND form `PREV(FIRST(val,$1),$2)` (rpr.sql:1267) which exercises the PREV_FIRST branch (lines 4124-4127), not the simple FIRST branch at 4117. No existing test uses a simple `FIRST(col, $param)`.",
      "refinedTest": "Use a SIMPLE (non-compound) FIRST with a PARAMETER offset so it passes parse analysis (Param is not a column ref) yet is non-Const at plan time (forces firstNeedsEval -> NEEDS_EVAL -> eval_define_offsets -> visit_nav_exec RPR_NAV_FIRST branch -> line 4117). Add to src/test/regress/sql/rpr.sql:\n\nPREPARE test_first_offset(int8) AS\nSELECT id, val, first_value(id) OVER w AS mf, count(*) OVER w AS cnt\nFROM rpr_nav WINDOW w AS (\n    ORDER BY id\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    AFTER MATCH SKIP PAST LAST ROW\n    PATTERN (A B+)\n    DEFINE A AS TRUE, B AS FIRST(val, $1) IS NOT NULL\n);\nEXECUTE test_first_offset(0);\nEXECUTE test_first_offset(1);\nDEALLOCATE test_first_offset;\n\nThe key differences from the existing rpr.sql:1267 test: FIRST is NOT wrapped in PREV/NEXT (so nav->kind stays RPR_NAV_FIRST, hitting 4117 rather than the PREV_FIRST branch at 4124), and the offset is a single Param $1 (non-const, no column ref). Do NOT use a column expression as the offset -- it is rejected at parse time.",
      "refinedFix": ""
     }
    ],
    [
     "4119",
     {
      "functionName": "visit_nav_exec",
      "lines": "4119",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 4119 (context->minFirstOffset = Min(...) in the simple RPR_NAV_FIRST branch of visit_nav_exec) is genuinely reachable, and the claimed classification \"testable\" is correct. BUT the proposed test is WRONG and would NOT cover the line. I verified this empirically against a freshly built+installed coverage instance.\n\nThree findings:\n1. The proposed query \"DEFINE A AS FIRST(price, price) > 0\" is INVALID. A column-reference offset is rejected at parse time: ERROR \"row pattern navigation offset must be a run-time constant\" (src/backend/parser/parse_rpr.c:631). It never reaches the executor, so it cannot cover line 4119. NEEDS_EVAL is for run-time constants that are not compile-time foldable (i.e. Params), not column references.\n2. A plain PREPARE/EXECUTE with a parameter offset (FIRST(val, $1)) ALSO fails. The custom plan folds $1 to a Const, so extract_const_offset succeeds, the planner marks navFirstOffsetKind=FIXED (not NEEDS_EVAL), and eval_define_offsets returns early at line 4175 (needsFirst=false). I ran this and confirmed line 4119 stayed uncovered (#####), with eval_define_offsets hit once but returning at 4175.\n3. The line is reached only by a STANDALONE FIRST(v, $1) (not nested inside PREV/NEXT, which would route to the compound PREV_FIRST/NEXT_FIRST branch at 4121-4148 instead) under SET plan_cache_mode = force_generic_plan, which keeps $1 as a Param so the planner sets navFirstOffsetKind=RPR_NAV_OFFSET_NEEDS_EVAL. Existing suite tests only cover the compound FIRST and maxOffset NEEDS_EVAL paths (rpr_explain.sql:3376-3430: NEXT(FIRST(v,$1),$2), PREV(LAST(v,$1),$2), PREV(v)+PREV(v,$1)) -- none uses a bare FIRST(v,$1), which is exactly why 4119 is uncovered.\n\nWith the refined test below I observed line 4119's gcov count go from ##### to 1.",
      "refinedTest": "Standalone simple FIRST with a parameter offset under a generic plan (mirroring the style at src/test/regress/sql/rpr_explain.sql). Append to rpr_explain.sql:\n\n-- Simple FIRST(v, $1): NEEDS_EVAL forward-reach path (visit_nav_exec simple FIRST branch)\nPREPARE test_first_simple_offset(int8) AS\nSELECT count(*) OVER w\nFROM generate_series(1,10) s(v)\nWINDOW w AS (\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    PATTERN (A+)\n    DEFINE A AS FIRST(v, $1) IS NOT NULL\n);\nSET plan_cache_mode = force_generic_plan;\nEXECUTE test_first_simple_offset(1);\nRESET plan_cache_mode;\nDEALLOCATE test_first_simple_offset;\n\nCritical requirements verified empirically: (a) the FIRST must be standalone, not wrapped in PREV()/NEXT() (those route to the compound branch, not line 4119); (b) the offset must be a Param ($1), not a column reference (column refs are rejected at parse time) and not a literal Const (folded to FIXED, never NEEDS_EVAL); (c) force_generic_plan is mandatory so $1 stays a Param through planning. Running this drove line 4119 to execution count 1.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "4136": {
   "func": "visit_nav_exec",
   "reachable": true,
   "subs": [
    [
     "4136",
     {
      "functionName": "visit_nav_exec",
      "lines": "4136",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 4136 (reach = inner - outer; in the RPR_NAV_PREV_FIRST branch of visit_nav_exec) is genuinely reachable, so the \"testable\" classification is correct. HOWEVER, the proposed test is WRONG and does NOT compile/run. I executed it against a live 19beta1 RPR build: DEFINE A AS PREV(FIRST(price, price), 2) > 0 fails at PARSE time with \"ERROR: row pattern navigation offset must be a run-time constant\" (parse_rpr.c:629-632, ERRCODE_FEATURE_NOT_SUPPORTED). A column reference in any nav offset (inner offset_arg or outer compound_offset_arg) is rejected; so is a volatile function (random()::int -> \"volatile functions are not allowed in DEFINE clause\"). This is confirmed by the existing expected output rpr.out:1195-1234 where every column-ref/random offset yields these errors. Therefore a column offset can NEVER reach RPR_NAV_OFFSET_NEEDS_EVAL, and the proposed test reaches neither the executor nor line 4136. The ONLY way to make navFirstOffsetKind = NEEDS_EVAL for a PREV_FIRST is an offset expression that contains no Var and is not volatile but is also not constant-folded to a Const, i.e. a Param. I verified PREPARE p(int) AS ... DEFINE A AS PREV(FIRST(price, $1), 2) > 0; EXECUTE p(0); parses, plans (firstNeedsEval -> NEEDS_EVAL since extract_const_offset returns false for the Param), and executes -- driving eval_define_offsets -> visit_nav_exec -> the RPR_NAV_PREV_FIRST branch -> line 4136. hasFirstNav is set true by the PREV_FIRST branch (createplan.c:2656), satisfying the executor gate needsFirst at nodeWindowAgg.c:4171. Both inner-offset-Param and outer-offset-Param variants ran successfully (returned all 7 rows). Net: reachable + testable, but the proposed test must be replaced with a Param-based (PREPARE/EXECUTE) test.",
      "refinedTest": "-- Drives nodeWindowAgg.c:4136 (visit_nav_exec PREV_FIRST branch, reach = inner - outer).\n-- A Param offset is non-Const (extract_const_offset returns false) so the planner sets\n-- navFirstOffsetKind = RPR_NAV_OFFSET_NEEDS_EVAL; PREV(FIRST(...)) sets hasFirstNav, so\n-- eval_define_offsets runs the walker at executor init and hits line 4136.\n-- Verified live on 19beta1 RPR build: parses, plans, and returns all rows.\nPREPARE rpr_prevfirst_eval(int) AS\nSELECT price FROM stock\nWINDOW w AS (\n    PARTITION BY company\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    INITIAL\n    PATTERN (A+)\n    DEFINE A AS PREV(FIRST(price, $1), 2) > 0\n);\nEXECUTE rpr_prevfirst_eval(0);\nDEALLOCATE rpr_prevfirst_eval;\n-- (A Param in the OUTER offset also works and is equally valid:\n--  DEFINE A AS PREV(FIRST(price, 1), $1) > 0)",
      "refinedFix": ""
     }
    ]
   ]
  },
  "3574": {
   "func": "window_gettupleslot",
   "reachable": false,
   "subs": [
    [
     "3574",
     {
      "functionName": "window_gettupleslot",
      "lines": "3574",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Line 3574 is an elog(ERROR) guarding against fetching a tuple before a WindowObject's mark position. This is a long-standing can't-happen internal-consistency check (predates RPR; the patch only changed the format string from a literal to INT64_FORMAT). The mark invariant is actively maintained by all callers: WinSetMarkPosition only ever advances the mark (line 5020 rejects backward moves), and the mark is always computed from the minimum position that will subsequently be re-fetched. For the new RPR path, advance_nav_mark (lines 4380-4419) deliberately bounds navmarkpos by Min(navmarkpos, firstreach) so that FIRST/PREV/LAST navigations can never request a row before the mark. Frame-based callers similarly mark at frameheadpos before fetching only at >= frameheadpos. Reaching line 3574 would require the executor's own mark bookkeeping to be internally inconsistent, which is not controllable by any SQL/regression input. I attempted to refute via the RPR navigation path (the only new caller surface) and could not construct an input that fetches before the mark, because the mark advancement is gated on the navigation reach bounds.",
      "refinedTest": "No SQL-level test can drive this line. It is a defensive guard against a self-inflicted invariant violation in C-level mark bookkeeping; only a deliberate code defect (e.g., advancing the mark past a still-needed position) could trigger it, which cannot be expressed through SQL, EXPLAIN, or ruleutils deparse. If exercising it is required for coverage purposes, it would need a targeted C unit test or fault injection that directly calls WinSetMarkPosition with an over-advanced mark and then window_gettupleslot at an earlier pos -- not a regression .sql test.",
      "refinedFix": "Keep as elog(ERROR). This is standard PostgreSQL practice for tuplestore mark-position invariant violations (matches sibling \"unexpected end of tuplestore\" elogs in the same function). Converting to Assert would drop the safety net in production (non-cassert) builds for a memory/tuplestore corruption scenario, which is undesirable. No change needed; the RPR format-string update to INT64_FORMAT is correct."
     }
    ]
   ]
  }
 },
 "src/backend/nodes/outfuncs.c": {
  "754": {
   "func": "_outRPRPattern",
   "reachable": false,
   "subs": [
    [
     "754",
     {
      "functionName": "_outRPRPattern",
      "lines": "754",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Line 754 (`appendStringInfoString(str, \" <>\")`) is the else branch of the guard `if (node->numVars > 0 && node->varNames != NULL)` at outfuncs.c:742. It executes only when an RPRPattern has numVars <= 0 OR varNames == NULL. I traced every construction path for RPRPattern: (1) makeRPRPattern() at rpr.c:1127 is the SOLE original constructor (only call site rpr.c:1938), and it Asserts numVars > 0 (rpr.c:1143) then unconditionally palloc's varNames (rpr.c:1144-1146); (2) _copyRPRPattern() at copyfuncs.c:171 copies an existing node, Asserts from->numVars > 0 (copyfuncs.c:180) and always palloc's newnode->varNames (copyfuncs.c:181); (3) the read path reconstructs from out output. numVars is derived from scanRPRPattern over the PATTERN tree plus collectDefineVariables; a PATTERN clause cannot be syntactically empty, so there is always >= 1 primary variable, hence numVars is never 0 and varNames is never NULL. No SQL/regression input can drive an RPRPattern with zero variables to _outNode, so line 754 cannot be reached. I could not construct any refuting input. Note: an identical defensive else exists for :elements at line 776 (also guarded by numElements>=2 Asserts), so this is a consistent defensive idiom rather than a logic flaw.",
      "refinedTest": "No SQL test can cover this line. The else only fires for a malformed RPRPattern (numVars==0 / varNames==NULL), which Asserts in makeRPRPattern (rpr.c:1143) and _copyRPRPattern (copyfuncs.c:180) forbid and no parser path can produce (PATTERN always has >=1 variable). The only way to exercise line 754 would be a C-level unit test fabricating an RPRPattern with numVars=0 and feeding it to nodeToString(), which is not expressible via SQL or the regress framework and would contradict the Assert invariants. Therefore there is no meaningful regression test; the line should be treated as unreachable defensive code, not test-covered.",
      "refinedFix": "Because makeRPRPattern (rpr.c:1143-1144) and _copyRPRPattern (copyfuncs.c:180-181) already enforce numVars > 0 and a non-NULL varNames, the empty-array case at outfuncs.c:753-754 cannot occur. Option A (minimal, keeps defensive style): leave as-is and accept the line as documented defensive-unreachable, matching the parallel :elements else at line 776. Option B (eliminate the branch): replace the guard with `Assert(node->numVars > 0 && node->varNames != NULL);` before the loop and emit the `( ... )` list unconditionally (drop lines 753-754), and likewise simplify the matching reader at readfuncs.c:595. If pursuing Option B, do the same to the :elements branch (lines 758,775-776) for consistency, since both rest on the same makeRPRPattern/_copyRPRPattern invariants (numElements >= 2 at rpr.c:1149, copyfuncs.c:186). Recommend Option A unless the project wants to actively reduce defensive-unreachable line count."
     }
    ]
   ]
  },
  "776": {
   "func": "_outRPRPattern",
   "reachable": false,
   "subs": [
    [
     "776",
     {
      "functionName": "_outRPRPattern",
      "lines": "776",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable from any SQL/regression input. The else at outfuncs.c:776 emits \" <>\" only when (node->numElements <= 0 || node->elements == NULL). The sole RPRPattern producer is makeRPRPattern() in optimizer/plan/rpr.c (only makeNode(RPRPattern) besides the mechanical copyfuncs.c copy). It Asserts numElements >= 2 (rpr.c:1149) and unconditionally palloc0's the elements array (rpr.c:1150). numElements is computed by scanRPRPattern(), which always adds +1 for the FIN marker (rpr.c:1110) on top of >= 1 VAR element (every RPR_PATTERN_VAR leaf does (*numElements)++ at rpr.c:1030; a valid PATTERN must contain at least one variable). So numElements is always >= 2 and elements is never NULL for any serialized node. copyfuncs.c preserves these fields verbatim under -DCOPY_PARSE_PLAN_TREES, so the COPY/WRITE_READ path cannot zero them either. I attempted to refute by searching for any path that sets numElements<=0 or elements=NULL on a live node and found none. Note: the claim cited reader line 647; the actual reader else is readfuncs.c:645-648 (and the array loop is 599-644) -- minor line-number drift, substance is correct.",
      "refinedTest": "No SQL/regression test can cover this line; it is structurally unreachable. Coverage can only be obtained by a unit-level fault-injection test that hand-builds an RPRPattern node with numElements=0/elements=NULL and calls nodeToString on it, which is not expressible through the SQL surface and not worth adding.",
      "refinedFix": "Since makeRPRPattern guarantees numElements >= 2 and elements != NULL, replace the runtime if/else with an unconditional array write guarded by an assertion: add Assert(node->numElements > 0 && node->elements != NULL); before the loop, drop the if-condition and the else that emits \" <>\". Keep the reader in sync by removing the corresponding else (readfuncs.c:645-648) and the \"token[0] == '('\" / \"numElements > 0\" guard at readfuncs.c:601, since the writer will always emit '('. Alternatively, if maximum robustness under WRITE_READ_PARSE_PLAN_TREES is preferred, leave both branches as-is and simply annotate line 776 as defensive (e.g., exclude from coverage), since the cost of the dead branch is negligible and it hardens against future producers."
     }
    ]
   ]
  }
 },
 "src/backend/nodes/readfuncs.c": {
  "595": {
   "func": "_readRPRPattern",
   "reachable": false,
   "subs": [
    [
     "595",
     {
      "functionName": "_readRPRPattern",
      "lines": "595",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable by any SQL/regression input. Line 595 (local_node->varNames = NULL) is the else branch of `if (local_node->numVars > 0 && token[0] == '(')` at readfuncs.c:583. It is reached only when the serialized varNames token is the empty-list marker \"<>\". That marker is written by _outRPRPattern (outfuncs.c:753-754) only when `node->numVars <= 0 || node->varNames == NULL`. Every RPRPattern is constructed via makeRPRPattern (rpr.c:1128) which asserts numVars > 0 (rpr.c:1143) and always palloc's varNames (rpr.c:1144), or via _copyRPRPattern (copyfuncs.c:170) which asserts from->numVars > 0 (copyfuncs.c:180) and copies a non-NULL array. The only other makeNode(RPRPattern) is inside makeRPRPattern itself. The grammar (gram.y:17583 PATTERN '(' row_pattern ')', row_pattern:17625) cannot produce an empty pattern, and DEFINE is required, so numVars is always >= 1. Node-read input in this build comes solely from _out* output (COPY_PARSE_PLAN_TREES / WRITE_READ_PARSE_PLAN_TREES round-trips and stored rules); there is no SQL surface to feed an arbitrary \"<>\" token to the reader. Hence _outRPRPattern never emits \"<>\" for a real RPRPattern and line 595's else branch never executes. Tried to refute via copy/out/read round-trip and via deparse, but all paths guarantee numVars>0 and non-NULL varNames, so token[0]=='(' always holds at read time.",
      "refinedTest": "No SQL/regression test can drive line 595. Any RPR query (e.g. a window with PATTERN/DEFINE such as the existing rpr.sql cases) exercises the TRUE branch at lines 583-592 via the automatic WRITE_READ_PARSE_PLAN_TREES round-trip, never the else. Reaching line 595 would require feeding a serialized string containing \":varNames <>\" directly to stringToNode/_readRPRPattern, which is only possible via a C unit harness (e.g. nodeToString then manual substitution, or a hand-written input string), not via any SQL or regression input. Such a test would not validate behavior of any user-facing path.",
      "refinedFix": "Keep read/out symmetry but document the invariant. In _readRPRPattern, replace the else body at line 595 with an assertion that records the can't-happen condition while preserving the NULL assignment for safety:\n\n    else\n    {\n        /* \"<>\" marker is never emitted for a real RPRPattern (numVars > 0) */\n        Assert(local_node->numVars == 0);\n        local_node->varNames = NULL;\n    }\n\nThis mirrors the Assert(numVars > 0) invariants already present in makeRPRPattern (rpr.c:1143) and _copyRPRPattern (copyfuncs.c:180), marks the branch as structurally unreachable, and avoids changing behavior for the (impossible) malformed-input case. Alternatively, leave the code unchanged: the NULL assignment is standard defensive out/read symmetry and the uncovered line is expected and harmless."
     }
    ]
   ]
  },
  "647": {
   "func": "_readRPRPattern",
   "reachable": false,
   "subs": [
    [
     "647",
     {
      "functionName": "_readRPRPattern",
      "lines": "647",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable. Line 647 (local_node->elements = NULL) is the else branch of `if (numElements > 0 && token[0] == '(')` at readfuncs.c:601, taken only when _outRPRPattern wrote the \"<>\" marker (outfuncs.c:776), which happens only when node->numElements <= 0 || node->elements == NULL. I verified the ONLY constructor of RPRPattern is makeRPRPattern (rpr.c:1128), which asserts numElements >= 2 (line 1149) and unconditionally palloc0's the elements array (line 1150). scanRPRPattern always does (*numElements)++ for the FIN marker (rpr.c:1110), and the non-empty PATTERN grammar guarantees at least one real element. _copyRPRPattern (copyfuncs.c:171) likewise asserts numElements >= 2 and deep-copies a non-NULL array. Thus every live RPRPattern has numElements >= 2 and non-NULL elements; _outRPRPattern always emits the '(...)' form, never \"<>\"; and the reader's else branch can never execute for any node produced by the system, including under -DWRITE_READ_PARSE_PLAN_TREES which round-trips every constructed node. I attempted to refute this by searching for any alternate makeNode(RPRPattern) construction site or any numElements=0/elements=NULL assignment outside out/read funcs; none exist. The only way to reach line 647 is hand-feeding a malformed serialized string with ':numElements 0' or ':elements <>' directly to the reader, which no SQL/regression path does.",
      "refinedTest": "No SQL/regression test can cover this line. It is defensive serialization-symmetry code. If coverage is desired, it would require a C-level unit test (not SQL) that calls stringToNode() on a hand-crafted RPRPATTERN node string containing ':numElements 0 ... :elements <>', bypassing the grammar and makeRPRPattern. This is not appropriate as a regression test.",
      "refinedFix": "Replace the unreachable NULL-assignment else with an assertion documenting the invariant, mirroring the constructor/copy/out paths. E.g. change lines 645-648 to: `else { Assert(false); /* makeRPRPattern guarantees numElements >= 2 and non-NULL elements; _outRPRPattern never emits \"<>\" for the :elements field */ local_node->elements = NULL; }`. Keeping the NULL assignment after the Assert preserves defensiveness for non-assert builds. Alternatively, gate the populated block with Assert(local_node->numElements >= 2 && token[0] == '(') before line 601 and drop the else entirely. Note: the existing varNames else branch (line 595) is analogously defensive but reachable status differs; leave it unless separately measured."
     }
    ]
   ]
  }
 },
 "src/backend/optimizer/plan/rpr.c": {
  "129": {
   "func": "rprPatternEqual",
   "reachable": false,
   "subs": [
    [
     "129",
     {
      "functionName": "rprPatternEqual",
      "lines": "129",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. RPRPatternNodeType (parsenodes.h:615-621) has exactly four values: RPR_PATTERN_VAR, RPR_PATTERN_SEQ, RPR_PATTERN_ALT, RPR_PATTERN_GROUP. The switch at rpr.c:118-127 handles all four and every case ends in a return (VAR returns strcmp; SEQ/ALT/GROUP share the rprPatternChildrenEqual return). Control therefore can never fall through to pg_unreachable() at line 129. Every assignment to ->nodeType in the backend (gram.y:17652/17684/17713/17726/21425/21484) uses one of the four valid constants, set only by the grammar; nothing can inject a fifth value, and the node tree is never constructed with an uninitialized nodeType reachable from SQL. The two early-return guards (a->nodeType != b->nodeType, etc.) further mean a is always inspected with a valid value. No SQL or regression input can drive line 129. The claim's root cause is accurate.",
      "refinedTest": "No SQL-level test can reach line 129. The only way to exercise it would be to fabricate an RPRPatternNode in C with an out-of-range nodeType (e.g. cast an int), which is not expressible through the parser/optimizer or any regression .sql input. Therefore no refined test is offered.",
      "refinedFix": "Keep as-is. pg_unreachable() is the standard PostgreSQL idiom for an exhaustive enum switch and correctly documents that control cannot reach here. Optionally the trailing \"return false;\" is only present to satisfy compilers that do not treat pg_unreachable() as noreturn; no functional change is warranted. No source change needed."
     }
    ]
   ]
  },
  "968": {
   "func": "optimizeRPRPattern",
   "reachable": false,
   "subs": [
    [
     "968",
     {
      "functionName": "optimizeRPRPattern",
      "lines": "968",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable. The switch at rpr.c:956 enumerates all four members of RPRPatternNodeType (RPR_PATTERN_VAR/SEQ/ALT/GROUP, parsenodes.h:617-620) and every case ends in a return, so control falls through to pg_unreachable() at line 968 only if pattern->nodeType holds a value outside the enum. nodeType is set exclusively by the parser when building the pattern tree (always a valid member), and under -DWRITE_READ_PARSE_PLAN_TREES the round-trip uses WRITE_ENUM_FIELD/READ_ENUM_FIELD (outfuncs.funcs.c:1131, readfuncs.funcs.c:1296), which serializes and restores the identical integer it was given. No SQL or regression input can inject an out-of-range nodeType. I tried to refute via the read path (deserialization) and the parser path; both only yield the four valid values. The Assert(pattern != NULL) and check_stack_depth above are unrelated to line 968.",
      "refinedTest": "No test can cover this line through any SQL/regression input. Reaching it would require either C-level corruption of the enum field or adding a fifth enum member without a switch case (a compile-time concern, caught by -Wswitch). Therefore no refined SQL test exists.",
      "refinedFix": "Keep as-is. The pg_unreachable() + return is the standard PostgreSQL exhaustive-switch guard. No change needed; this line should be excluded from coverage expectations."
     }
    ]
   ]
  },
  "1425": {
   "func": "fillRPRPattern",
   "reachable": false,
   "subs": [
    [
     "1425",
     {
      "functionName": "fillRPRPattern",
      "lines": "1425",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. The switch at rpr.c:1405 dispatches on RPRPatternNode->nodeType, whose type RPRPatternNodeType (parsenodes.h:615-621) is an enum with exactly four values: RPR_PATTERN_VAR, RPR_PATTERN_SEQ, RPR_PATTERN_ALT, RPR_PATTERN_GROUP. All four are handled by case labels at lines 1407/1415/1418/1421, and every branch returns unconditionally (no break/fall-through). I checked every site that sets nodeType (gram.y:17652/17684/17713/17726/21425/21484 and the makeRPR* helpers) and each assigns one of the four valid values. There is no makeNode/palloc0 path that leaves nodeType zero-initialized to an out-of-enum sentinel before it reaches fillRPRPattern; the parser always populates it. Therefore the fall-through pg_unreachable() at line 1425 can only fire on memory corruption or an enum extension never produced by any SQL/regression input. No input reaches it.",
      "refinedTest": "No test can cover line 1425 through normal execution. Reaching it would require constructing an RPRPatternNode with nodeType set to a value outside the four-member enum, which is not expressible in SQL and not produced by the grammar. The only ways to exercise it (fault injection / casting an arbitrary int into nodeType) are not valid regression-test inputs and would defeat the purpose of the guard. Recommend excluding from coverage targets.",
      "refinedFix": "Keep as-is. The pg_unreachable() following an exhaustive enum switch is the standard PostgreSQL idiom for an exhaustive-switch guard and silences compiler warnings about missing return. No change needed."
     }
    ]
   ]
  },
  "1171": {
   "func": "getVarIdFromPattern",
   "reachable": false,
   "subs": [
    [
     "1171",
     {
      "functionName": "getVarIdFromPattern",
      "lines": "1171",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed unreachable via any SQL/regression input. getVarIdFromPattern has a single call site (rpr.c:1187) inside fillRPRPatternVar, passing node->varName from a RPR_PATTERN_VAR node. buildRPRPattern (rpr.c:1929-1942) builds one optimized tree, scans it in pass 1 (scanRPRPattern -> scanRPRPatternRecursive), then fills the SAME tree in pass 2 (fillRPRPattern). In pass 1, every RPR_PATTERN_VAR node unconditionally appends its varName to varNames (rpr.c:1046) unless already present (rpr.c:1036), and the switch recurses identically into SEQ/GROUP/ALT children. makeRPRPattern (rpr.c:1144-1146) copies all numVars names. Thus when pass 2 reaches a VAR node, its name is guaranteed already in pat->varNames, so the loop at 1164 always returns before line 1171. Hitting 1171 would require a VAR node in the fill pass that was absent from the scan pass; since both passes traverse the identical optimized pointer with no intervening mutation or re-optimization, this cannot occur. I attempted to refute by looking for a tree-shape mismatch or a VAR introduced after scanning -- none exists. This is a legitimate internal-invariant guard.",
      "refinedTest": "No SQL test can cover this line; it is structurally unreachable. The only way to execute it would be to artificially desynchronize the scan and fill passes (e.g., a unit-level fault injection that adds a VAR node to the tree between scanRPRPattern and fillRPRPattern, or corrupts pat->varNames), which is not expressible through PATTERN/DEFINE/MEASURES SQL syntax. Recommend excluding from line-coverage targets.",
      "refinedFix": "Keep the elog(ERROR) as an internal-error consistency guard followed by pg_unreachable(); no behavioral change. Downgrading to Assert is possible but elog provides a safer hard-failure for production builds where Asserts are compiled out, so the current code is appropriate. Marking the line as deliberately uncovered (or wrapping with a coverage-exclusion comment) is the only reasonable action."
     }
    ]
   ]
  },
  "1871": {
   "func": "reject_volatile_in_define_walker",
   "reachable": false,
   "subs": [
    [
     "1871",
     {
      "functionName": "reject_volatile_in_define_walker",
      "lines": "1871",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED unreachable via any SQL input. Line 1871 (the IsA(node, NextValueExpr) -> ereport sequence-operations error) cannot fire from user SQL. NextValueExpr nodes are synthesized ONLY by build_column_default (rewriteHandler.c:1290 for identity columns; also tablecmds.c:7566 for ALTER TABLE column rewrites), and that output is only ever spliced into INSERT/UPDATE/COPY target-column DEFAULT positions (rewriteHandler.c:1052,1599,4745). There is no SQL syntax that embeds a column-default/identity expression into a scalar predicate position such as a window DEFINE condition (the DEFAULT keyword is valid only in INSERT VALUES / UPDATE SET targets). A user-written nextval('seq') inside DEFINE parses to a volatile FuncExpr (pg_proc.dat: nextval provolatile='v'), which check_functions_in_node detects, so it is rejected earlier at line 1865 with the volatile-functions error before reaching 1870-1871. Verified that check_functions_in_node deliberately ignores NextValueExpr (nodeFuncs.c:1941 comment: it carries no SQL function OID), which is exactly why the separate IsA guard exists as belt-and-suspenders. No rewrite/view-expansion/rule path can inject a NextValueExpr into wc->defineClause, which is what validate_rpr_define_volatility (planner.c:1062) walks. I attempted to refute the classification and could not find any reaching input.",
      "refinedTest": "No test can drive execution through line 1871. The only error a user can trigger in this walker is the volatile-FuncExpr path at 1865-1869, e.g.: DEFINE clause containing nextval('someseq') hits line 1865-1869, never 1870-1871. To exercise the NextValueExpr branch you would have to manually construct a WindowClause whose defineClause TargetEntry expr is a NextValueExpr and feed it directly to validate_rpr_define_volatility from C (e.g. a unit-test harness), since no parser/rewriter path produces that tree. Recommend documenting it as intentionally-unreachable defensive code rather than adding a regress test.",
      "refinedFix": "No source change required. Keep the IsA(node, NextValueExpr) guard at 1870-1874 as intentional defensive code: it documents that sequence operations are disallowed in DEFINE and guards against any future path that could embed a NextValueExpr (which check_functions_in_node intentionally does not inspect). Optionally annotate the line with a brief comment noting it is currently unreachable from SQL because user nextval() parses to a volatile FuncExpr caught at line 1865, so coverage tooling can be told to ignore it."
     }
    ]
   ]
  },
  "1113": {
   "func": "scanRPRPattern",
   "reachable": true,
   "subs": [
    [
     "1113",
     {
      "functionName": "scanRPRPattern",
      "lines": "1113",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "hard-to-reach",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 1113 is genuinely reachable (classification hard-to-reach is correct), but the PROPOSED test is WRONG and would NOT cover it. I empirically triggered the line on the RPR build (ERROR: pattern too complex / DETAIL: Pattern has 32769 elements, maximum is 32767) using ALTERNATING variables, and empirically confirmed the proposed single-variable test (repeat('A ', 32767), even 100000 reps) SUCCEEDS with no error. Root cause of the refutation: buildRPRPattern (rpr.c:1929) calls optimizeRPRPattern BEFORE scanRPRPattern (rpr.c:1935). The pass mergeConsecutiveVars (rpr.c:225-288) merges consecutive identical non-reluctant VARs into one element with summed quantifiers (A A A -> A{3,3}). So repeating the SAME variable collapses to a single element and never approaches RPR_ELEMIDX_MAX. The proposal's stated mechanism (repetition of one var inflating numElements) is false. Fix the test by alternating two distinct variable names (A B A B ...) which the merge cannot combine, staying within RPR_VARID_MAX=240 (only 2 vars used). Boundary verified: 16383 'A B' pairs (32767 elements) passes; 16384 pairs (32769 elements) errors at line 1113. Also the proposed query syntax was invalid: the RPR grammar (gram.y:17361-17595) has no MEASURES in the window spec, and clause order is frame then [AFTER MATCH SKIP] [INITIAL] PATTERN (...) DEFINE.",
      "refinedTest": "Use alternating distinct variables so the optimizer's mergeConsecutiveVars cannot collapse them, while staying within RPR_VARID_MAX (only 2 distinct vars). Programmatic test (avoid a giant literal in rpr.sql for .out portability):\n\n  SELECT format($$SELECT count(*) OVER w FROM (SELECT 1 i) t\n    WINDOW w AS (ORDER BY i ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    INITIAL PATTERN (%s) DEFINE A AS TRUE, B AS TRUE)$$,\n    repeat('A B ', 16384)) \\gexec\n\nExpected (LC_MESSAGES=C):\n  ERROR:  pattern too complex\n  DETAIL:  Pattern has 32769 elements, maximum is 32767.\n\nMechanism: 16384 'A B ' pairs = 32768 VAR elements; scanRPRPattern adds +1 FIN (rpr.c:1110) -> 32769 > RPR_ELEMIDX_MAX (PG_INT16_MAX = 32767), firing line 1113. mergeConsecutiveVars only merges same-name neighbors, so alternating A/B survives optimization. Verified live: 16383 pairs (32767 elements) passes, 16384 pairs (32769 elements) errors. The originally proposed repeat('A ', 32767) does NOT work.",
      "refinedFix": ""
     }
    ]
   ]
  }
 },
 "src/backend/optimizer/plan/createplan.c": {
  "2608": {
   "func": "visit_nav_plan",
   "reachable": true,
   "subs": [
    [
     "2608",
     {
      "functionName": "visit_nav_plan",
      "lines": "2608",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 2608 (context->firstNeedsEval = true) is genuinely reachable: it is the else-branch of `if (extract_const_offset(nav->offset_arg, 0, &offset))` in the RPR_NAV_FIRST case, taken when a simple FIRST(v, N) has a non-Const offset_arg. I confirmed reachability empirically on a coverage-instrumented RPR build. HOWEVER, the proposed test as written does NOT cover line 2608. I built+installed the RPR source into a temp datadir, ran the exact proposed PREPARE/EXECUTE on a -DCOVERAGE build, stopped the server to flush gcda, and ran gcov: line 2606 (the if-branch) showed count 1 while line 2608 stayed ##### (uncovered). Reason: by default PostgreSQL builds a CUSTOM plan for the first ~5 executions of a prepared statement, substituting the actual EXECUTE argument for $1 and const-folding it to a Const, so extract_const_offset returns TRUE and the if-branch (2606) runs, not the else (2608). To force the Param to survive planning as a Param I added `SET plan_cache_mode = force_generic_plan;` before EXECUTE and re-ran with cleared gcda: gcov then showed line 2608 count 1 and line 2606 ##### -- proving the else-branch fires only under a generic plan. So the claim that $1 is a Param at planner time is only true with a generic plan; the unqualified custom-plan path const-folds it. The existing PREV($1)/compound PREV(FIRST(val,$1),$2) tests (rpr.sql:888,1260) very likely have the same custom-plan issue for their respective else-branches (2589/2643), but those lines were already covered by other const tests/paths and are out of scope here.",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql near the FIRST offset tests (rpr_nav has columns id int, val int):\n\nSET plan_cache_mode = force_generic_plan;\nPREPARE test_first_offset(int8) AS\nSELECT id, val, first_value(id) OVER w AS mf, count(*) OVER w AS cnt\nFROM rpr_nav WINDOW w AS (\n    ORDER BY id\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    AFTER MATCH SKIP PAST LAST ROW\n    PATTERN (A B+)\n    DEFINE A AS TRUE, B AS val = FIRST(val, $1)\n);\nEXECUTE test_first_offset(1);\nDEALLOCATE test_first_offset;\nRESET plan_cache_mode;\n\nThe `SET plan_cache_mode = force_generic_plan;` is the load-bearing addition the original proposal omits: without it the planner const-folds $1 and executes line 2606 instead of 2608. With it, $1 remains a Param, extract_const_offset returns false, and line 2608 (context->firstNeedsEval = true) is driven. Verified via gcov on the coverage build: 2608 count went from ##### to 1. Expected output for EXECUTE(1) under the generic plan: rows (1,10,1,2),(2,20,,0),(3,30,3,2),(4,10,,0),(5,50,5,2),(6,10,,0) -- identical to the custom-plan result since the runtime offset value is the same; capture it in rpr.out.",
      "refinedFix": ""
     }
    ]
   ]
  }
 },
 "src/backend/nodes/nodeFuncs.c": {
  "862": {
   "func": "exprCollation",
   "reachable": false,
   "subs": [
    [
     "862-864",
     {
      "functionName": "exprCollation",
      "lines": "862-864",
      "lineCount": 3,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Finding's classification (testable) and root-cause are WRONG. Empirically refuted. The exact proposed test already exists in the suite: src/test/regress/sql/rpr.sql:946 has `B AS PREV(tdate::text, 1) > PREV(tdate::text, 2)` (a TEXT column wrapped in nav, compared with `>` forcing collation resolution), present and passing in rpr.out:1804 (20 rows). Yet current gcov for nodeFuncs.c shows lines 862-863 (exprCollation T_RPRNavExpr) at ##### (0 hits), while exprSetCollation T_RPRNavExpr at lines 1174-1175 shows 1212 hits. So collation is SET on RPRNavExpr 1212 times but exprCollation is NEVER called on one. Mechanism: parse_rpr.c:426 calls assign_expr_collations -> assign_collations_walker, which for RPRNavExpr hits the default case (parse_collate.c:576-762): it recurses bottom-up via expression_tree_walker, bubbles child collation through loccontext, and writes it back with exprSetCollation (751) -- it never reads it via exprCollation. The parent OpExpr likewise gets its opcollid/inputcollid from the bubbled context, not from exprCollation(nav). execExpr.c:1192-1281 compiles RPRNavExpr without ever calling exprCollation on it. createplan.c calls exprCollation only on partition/order/sort/distinct tle->expr keys, never an RPRNavExpr (which exists only nested inside boolean DEFINE conditions). MEASURES/SUBSET are not in gram.y in this branch, so a bare nav can never surface as an output column. Conclusion: no SQL/regression input reaches 862-864; this is a defensive completeness case in the exprCollation accessor.",
      "refinedTest": "No regression-test input can cover these lines with the current feature surface (verified: the proposed text-nav-comparison case already exists and does not cover them). RPRNavExpr's collation is only ever SET (via the bottom-up assign_collations_walker / exprSetCollation), never READ via exprCollation, because the node only ever appears nested inside boolean DEFINE conditions and never in a collation-read context (partition/order/sort/distinct key, or a MEASURES output -- MEASURES is not implemented in gram.y here). The lines would become reachable only by a code change that lets an RPRNavExpr surface where exprCollation is invoked on it directly: e.g. (a) implementing MEASURES so a bare `LAST(cat)` over a text column becomes a window output column that then feeds an ORDER BY/DISTINCT/GROUP BY whose key collation is read in createplan.c, or (b) a C unit/Assert test calling exprCollation((Node *) navexpr). Absent such a change, the only sound option is to leave the case as defensive code (optionally annotated) rather than chase coverage.",
      "refinedFix": "No code fix required for correctness; the case is correct defensive completeness for the exprCollation accessor (every collation-bearing node tag should be handled so the accessor never elog/falls through for a valid node). If coverage hygiene is desired, options are: (1) leave as-is and document that RPRNavExpr collation is only ever set, never read, in the current feature surface; or (2) add a targeted C-level test (e.g. in a regression-callable test function) that constructs an RPRNavExpr and asserts exprCollation returns resultcollid. Do NOT rely on the proposed SQL test -- it has been empirically shown not to execute these lines."
     }
    ]
   ]
  },
  "395": {
   "func": "exprTypmod",
   "reachable": true,
   "subs": [
    [
     "395",
     {
      "functionName": "exprTypmod",
      "lines": "395",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 395 (case T_RPRNavExpr in exprTypmod, /home/assam/postgres/src/backend/nodes/nodeFuncs.c:395-397) is genuinely reachable, so the \"testable\" classification is correct. BUT the proposed test is INVALID for this branch: MEASURES is not implemented here. Grep of gram.y, src/include, and parse_rpr.c finds no MEASURES support; rpr.sql/rpr_base.sql contain no MEASURES, and RPRNavExpr is only ever constructed inside DEFINE predicates (ParseRPRNavCall via parse_func.c, walked by define_walker in parse_rpr.c). There is no MEASURES output-column type resolution path on this branch, so the proposed query cannot be written and would error at parse time. The finding's root-cause reasoning (typmod irrelevant in boolean/numeric DEFINE comparisons) is otherwise accurate: ordinary comparison operators do not invoke coerce_type_typmod on their operands, so a bare PREV/LAST in a comparison never reaches exprTypmod. The actually-reachable trigger is an explicit length/precision CAST of a nav result inside a DEFINE predicate: coerce_to_target_type() (parse_coerce.c:114) unconditionally calls coerce_type_typmod(), whose first statement (parse_coerce.c:761) is `if (targetTypMod == exprTypmod(node)) return node;` -- this evaluates exprTypmod() on the RPRNavExpr node regardless of outcome, dispatching to case T_RPRNavExpr at line 395, which delegates to the arg Var's typmod. So the line is testable but ONLY via a CAST-in-DEFINE construct, not via MEASURES.",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql a DEFINE predicate that explicitly casts a navigation result to a length/precision-bearing type. rpr_stock.price is numeric(10,3), so a narrowing/explicit cast triggers coerce_to_target_type -> coerce_type_typmod -> exprTypmod(RPRNavExpr) at nodeFuncs.c:395. Example:\n\nSELECT part_id, rn, price,\n       first_value(price) OVER w\n  FROM rpr_stock\n  WINDOW w AS (\n    PARTITION BY part_id ORDER BY rn\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n    INITIAL\n    PATTERN (A B+)\n    DEFINE\n      A AS TRUE,\n      B AS CAST(PREV(price) AS numeric(8,2)) > 0\n  )\n  ORDER BY part_id, rn;\n\nThe CAST(PREV(price) AS numeric(8,2)) is a top-level subexpression of B's boolean predicate. During parse analysis the explicit type cast routes through coerce_to_target_type(targettypmod = numeric(8,2)'s packed typmod), which calls coerce_type_typmod(result=RPRNavExpr, ...); its line 761 guard evaluates exprTypmod() on the RPRNavExpr, hitting case T_RPRNavExpr (nodeFuncs.c:395). The CAST does not run afoul of define_walker (it only restricts nested navigation and offsets; a cast wrapping a single nav is walked generically). Equivalently CAST(LAST(price) AS numeric(8,2)) or any varchar(n)/numeric(p,s) cast of a nav arg works. The proposed MEASURES-based test must NOT be used because MEASURES is not implemented on this branch.",
      "refinedFix": ""
     }
    ],
    [
     "397",
     {
      "functionName": "exprTypmod",
      "lines": "397",
      "lineCount": 1,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Line 397 (`return exprTypmod((Node *) ((const RPRNavExpr *) expr)->arg);`) is genuinely REACHABLE, so \"testable\" is the correct classification. HOWEVER the finding's proposed test and root-cause are WRONG/impossible: this RPR branch does NOT implement MEASURES (confirmed in src/backend/parser/parse_cte.c:179: \"PostgreSQL does not implement <row pattern measures>\"), so the suggested `MEASURES LAST(name)` query cannot be written at all. RPRNavExpr only ever appears inside DEFINE boolean predicates. The reachable path is not via MEASURES output typmod but via a typmod-coercion applied to a nav expr inside DEFINE: coerce_type_typmod() at src/backend/parser/parse_coerce.c:761 executes `if (targetTypMod == exprTypmod(node))` with node == the RPRNavExpr, dispatching exprTypmod() on T_RPRNavExpr -> line 397. I empirically built a fresh cluster from the RPR binary (19beta1) and ran `DEFINE UP AS CAST(PREV(nm) AS varchar(3)) <> 'zz'` over a varchar(10) column; the query parsed and executed successfully, proving parse analysis (where exprTypmod runs) completes for this construct. No existing rpr*.sql test casts a nav expr to a typmod-bearing type, consistent with the line being uncovered.",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql a DEFINE condition that forces a typmod coercion over a navigation result on a typmod-bearing (varchar) column. Using a table with a varchar(N) column (N != target), e.g. on a temp table stk(company text, tdate date, nm varchar(10), price int):\nSELECT company, tdate, price, first_value(price) OVER w\n FROM stk\n WINDOW w AS (\n   PARTITION BY company\n   ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n   INITIAL\n   PATTERN (START UP+)\n   DEFINE\n     START AS TRUE,\n     UP AS CAST(PREV(nm) AS varchar(3)) <> 'zz'\n );\nThe CAST drives coerce_to_target_type -> coerce_type_typmod, which calls exprTypmod() on the RPRNavExpr (PREV(nm)), executing line 397. The same call simultaneously covers line 395 (the comment/case label). Note: the finding's MEASURES-based test must be discarded because MEASURES is unimplemented on this branch.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "3619": {
   "func": "expression_tree_mutator_impl",
   "reachable": false,
   "subs": [
    [
     "3619",
     {
      "functionName": "expression_tree_mutator_impl",
      "lines": "3619",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "REFUTED. The claimed classification \"testable\" and its proposed test are wrong. Line 3619 (MUTATE(newnode->defineClause,...) in the T_WindowClause case of expression_tree_mutator) is reached ONLY when a mutator descends into query->windowClause as a LIST, which happens exclusively via nodeFuncs.c:3971 inside the `if (flags & QTW_EXAMINE_SORTGROUP)` branch of query_tree_mutator_impl. I exhaustively enumerated every in-tree query_tree_mutator caller (var.c:960 flatten_join_alias_vars uses QTW_IGNORE_JOINALIASES; var.c:1115 QTW_IGNORE_GROUPEXPRS; clauses.c:6191/6208 =0; rewriteManip.c:1323/1413/1526/1684 =0; parse_agg.c:1618 =0). NONE pass QTW_EXAMINE_SORTGROUP. The only code in the tree that uses QTW_EXAMINE_SORTGROUP is dependency.c:2394, and that calls query_tree_WALKER (hitting walker line 2834), not the mutator. gcov confirms: line 3971 is #####(uncovered) and the ENTIRE mutator T_WindowClause case lines 3614-3619 is ##### -- including pre-RPR lines 3614-3618 (partitionClause/orderClause/startOffset/endOffset). Only 3619 shows in the RPR diff because it is the one line the patch added; the dead case block predates RPR. The proposed JOIN test triggers flatten_join_alias_vars, which passes QTW_IGNORE_JOINALIASES and thus takes the ELSE branch (3975-3998), hitting the inline line 3993 (defineClause mutation, gcov shows 9 hits, already covered) -- NOT line 3619. So the proposed test exercises a different, already-covered line. No SQL/regression input can reach 3619 without a C change.",
      "refinedTest": "No SQL/regression test can cover line 3619. Covering it requires C code that invokes query_tree_mutator (or expression_tree_mutator on a List of WindowClause nodes) with QTW_EXAMINE_SORTGROUP set, which no current backend code does for a mutator. A direct unit test would be: a small C test (or a temporary mutator) calling query_tree_mutator(query, my_mutator, ctx, QTW_EXAMINE_SORTGROUP) on a parsed query whose windowClause carries a DEFINE clause, e.g. parsed from: SELECT count(*) OVER w FROM t WINDOW w AS (ORDER BY id ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING PATTERN (a b+) DEFINE b AS val > PREV(val)). Only that flag setting routes execution through nodeFuncs.c:3971 -> expression_tree_mutator T_WindowClause case -> line 3619. There is no pure-SQL path.",
      "refinedFix": "Leave the code as-is for API completeness (the case mirrors the walker's T_WindowClause handling and the inline else-branch at 3993). It is harmless symmetry code. For coverage accounting, mark lines 3614-3619 as defensive/unreachable rather than a testability gap, since the entire case block (including the pre-existing non-RPR lines 3617-3618) is dead given no mutator passes QTW_EXAMINE_SORTGROUP. If coverage of dead code is undesirable, an alternative is to omit the defineClause mutation here and rely solely on the inline else-branch handling (3993), but keeping it is the safer, consistent choice."
     }
    ]
   ]
  },
  "2229": {
   "func": "expression_tree_walker_impl",
   "reachable": false,
   "subs": [
    [
     "2229",
     {
      "functionName": "expression_tree_walker_impl",
      "lines": "2229",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "hard-to-reach",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed line 2229 (return true for compound_offset_arg WALK) is genuine executable code, never executed. Empirically verified against the RPR coverage build (PG19beta1): condition on 2228 runs 2370x across all RPR test files but the WALK on compound_offset_arg never returns true. The root-cause claim is WRONG that no executed test runs a valid compound nav with an outer offset: rpr.sql:1260 (PREV(FIRST(val,$1),$2)) is EXECUTEd with a Param outer offset, and 1134/1156 etc. run compound navs with Const outer offsets; re-running all five rpr sql files left 2229 at #####. The proposed test is materially identical to these existing cases and will NOT cover 2229. Structural reason: arg (walked first at 2224) ALWAYS holds the required column Var, so Var-seeking walkers short-circuit there and never reach 2228. To hit 2229 a walker must ignore Vars yet return true on compound_offset_arg content. Parse validation restricts an RPR offset to a runtime constant: I confirmed volatile funcs rejected (random() -> error), subqueries rejected, no nav/agg/windowfunc/column-ref allowed; only Const/PARAM_EXTERN/immutable exprs remain. No standard walker returns true on that: PARAM_EXTERN is explicitly ignored by max_parallel_hazard_walker (clauses.c:949). Forcing a PARALLEL UNSAFE immutable func offset under debug_parallel_query short-circuited at the WindowFunc level before descending into the nav (case block 0 hits). The analogous offset_arg return (2227) fired only ONCE and only in a cross-file combined run (0 in any single file) -- a fragile caching artifact, not a reproducible trigger.",
      "refinedTest": "No reliable SQL test could be constructed to drive execution through line 2229. All standard tree walkers that descend into RPRNavExpr children either short-circuit at arg (Var present) or return false on the legally-restricted compound_offset_arg content (Const/PARAM_EXTERN/immutable). Attempts that should in theory work fail: (a) PREV(FIRST(val),$2) with PARAM_EXTERN outer offset -- max_parallel ignores PARAM_EXTERN; (b) volatile/subquery offset -- rejected at parse; (c) PARALLEL UNSAFE immutable func offset under debug_parallel_query -- walker short-circuits above the nav. If coverage of this arm is required, the appropriate action is a code-level test (e.g. a direct unit invocation of expression_tree_walker on a hand-built RPRNavExpr whose compound_offset_arg contains a node the walker flags) rather than a SQL/regression query. Given the line is a trivial symmetric mirror of 2227 with no distinct logic, leaving it uncovered or covering it via an Assert/structural review is reasonable.",
      "refinedFix": ""
     }
    ]
   ]
  },
  "2466": {
   "func": "expression_tree_walker_impl",
   "reachable": false,
   "subs": [
    [
     "2466",
     {
      "functionName": "expression_tree_walker_impl",
      "lines": "2466",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "REFUTED the claimed classification (testable) and the proposed test. Line 2466 is the `return true;` after `if (WALK(wc->defineClause))` inside the T_WindowClause arm of expression_tree_walker (nodeFuncs.c:2453-2468). I traced exactly who reaches this arm and whether the WALK can ever return true.\n\nWHO REACHES THE ARM: A bare WindowClause node is dispatched to expression_tree_walker's T_WindowClause arm ONLY when some walker does WALK(query->windowClause) on the List. In query_tree_walker this happens solely in the QTW_EXAMINE_SORTGROUP branch (nodeFuncs.c:2834-2843). Every OTHER walker (planner/optimizer, the JOIN scenario in the proposal) takes the ELSE branch (nodeFuncs.c:2851-2863) which walks startOffset/endOffset/defineClause DIRECTLY and never enters the T_WindowClause arm, so it cannot hit 2466. A backend-wide grep shows QTW_EXAMINE_SORTGROUP has exactly ONE caller: find_expr_references_walker in dependency.c:2390-2394 (dependency recording during CREATE VIEW / stored rules). That walker also special-cases WindowClause at dependency.c:2238 then falls through to expression_tree_walker (dependency.c:2461), which is the one and only execution of the T_WindowClause arm. This arm IS already executed today by the many RPR views in rpr_explain.sql/rpr_base.sql (that is why line 2465, the WALK call, is covered and not flagged).\n\nWHY 2466 NEVER FIRES: find_expr_references_walker is a pure collector; it returns false on every traversal path (dependency.c:1805/1832/1854/1969/2236/2461). The only `return true`s in that file (2566, 2824) live in unrelated subroutines is_objectclass_supported/guc helper, not the walker. Therefore WALK(wc->defineClause) at 2465 ALWAYS returns false for the sole caller that reaches this arm, and control always falls to break at 2468 — line 2466 is unreachable.\n\nWHY THE PROPOSED TEST FAILS: A JOIN+RPR query exercises planner walkers, which use the ELSE branch (2851-2863), not the T_WindowClause arm. Even if it did reach the arm, a var-collecting walker is not what runs there; the actual walker (find_expr_references_walker) never returns true. So the JOIN test drives neither this arm in a returning-true mode nor line 2466 at all. testWillCover=false.\n\nThis is a defensive `return true` mirroring every other WALK(...)/return-true line in the function. It is structurally unreachable by any SQL/regression input because no backend walker both (a) walks a WindowClause as a node and (b) returns true from its defineClause subtree. Making it reachable would require ADDING a new C walker that sets QTW_EXAMINE_SORTGROUP (or otherwise WALKs windowClause) and returns true on a Var/expr inside defineClause — which cannot be produced by SQL input.",
      "refinedTest": "No SQL/regression test can cover line 2466. The only walker reaching the T_WindowClause arm (find_expr_references_walker, via the unique QTW_EXAMINE_SORTGROUP caller in dependency.c) never returns true, so the `if (WALK(wc->defineClause)) return true;` short-circuit cannot trigger. Covering it would require a C-level unit test that invokes expression_tree_walker on a WindowClause node with a non-NULL defineClause using a custom walker that returns true on the first contained node (e.g., a Var-finding walker) — analogous to how this branch would behave if any abort-style walker ever walked a WindowClause. Such a walker does not exist in the backend, so this is not achievable from regress SQL.",
      "refinedFix": "Either accept as defensive/unreachable (consistent with all sibling WALK(...)/return-true lines in expression_tree_walker and acceptable to leave uncovered), or, if 100% coverage of modified lines is desired, drop the redundant short-circuit since defineClause is the LAST field walked in this arm: replace lines 2465-2467 `if (WALK(wc->defineClause)) return true;` with `return WALK(wc->defineClause);` (mirroring the tail-return style used by sibling arms like T_NullTest at 2443). That preserves identical behavior, removes the unreachable standalone `return true;`, and the single remaining return is already exercised by the existing CREATE VIEW RPR tests."
     }
    ]
   ]
  },
  "4651": {
   "func": "raw_expression_tree_walker_impl",
   "reachable": false,
   "subs": [
    [
     "4651",
     {
      "functionName": "raw_expression_tree_walker_impl",
      "lines": "4651",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "REFUTED root-cause mechanism; line is defensive-unreachable, not \"hard-to-reach via CTE\". Line 4651 is the standard `return true;` that propagates a true result from WALK(wd->rpCommonSyntax) in the T_WindowDef case. gcov confirms 4650 ran 4542x but 4651 is ##### (0). Reaching 4651 requires some raw_expression_tree_walker callback to return true on a node living inside rpCommonSyntax. I enumerated ALL four callbacks in the tree: (1) test_raw_expression_coverage (analyze.c:4091) never returns true on its own, it only forwards recursion results that bottom out false -- this is exactly why 4650 is hit 4542x but 4651 is 0; (2) makeDependencyGraphWalker (parse_cte.c:700) NEVER returns true -- on a CTE-referencing RangeVar it merely records a dependency via bms_add_member and returns false (line 754). The root cause claim that this walker \"aborts/returns true when it finds a RangeVar naming a CTE\" is factually WRONG; (3) checkWellFormedRecursionWalker (parse_cte.c) discards child return values and returns false explicitly; (4) contain_rpr_walker (parse_cte.c:1309) is the ONLY walker that returns true, but it short-circuits at IsA(node,WindowDef)&&rpCommonSyntax!=NULL (line 1320) BEFORE the raw walker's WindowDef case ever descends into rpCommonSyntax. The raw walker reaches the WindowDef case only for WindowDefs where contain_rpr_walker did not short-circuit (rpCommonSyntax==NULL), so WALK(NULL) returns false. A nested RPR window inside an outer window's DEFINE is also unreachable because the outer WindowDef short-circuits first. Hence no existing input drives 4651.",
      "refinedTest": "No SQL/regression input can cover line 4651 with the current set of raw_expression_tree_walker callbacks. The proposed WITH-CTE-in-DEFINE test does NOT work: makeDependencyGraphWalker walks the raw tree, descends WindowDef->rpCommonSyntax (hitting 4650), finds RangeVar(c), but returns FALSE (records the dependency only), so 4650's WALK yields false and 4651 never executes; the statement then proceeds and ERRORs at the DEFINE-subquery rejection in parse analysis. To actually cover 4651 you would need a raw walker that (a) returns true on some node type reachable strictly under rpCommonSyntax, and (b) does not short-circuit earlier on the enclosing WindowDef. No such walker exists today. The only practical way to exercise it is a C-level unit test invoking raw_expression_tree_walker with a custom callback that returns true on, e.g., a ColumnRef inside a DEFINE expression -- which is not expressible as SQL. Recommend leaving uncovered.",
      "refinedFix": "No code fix needed. Line 4651 is correct, intentional defensive boilerplate that mirrors every other `if (WALK(child)) return true;` arm in raw_expression_tree_walker_impl; it is required for correctness if any future walker callback returns true on a node inside rpCommonSyntax. It should remain uncovered/excluded from coverage goals (same status as countless sibling `return true;` lines in this function that depend on a walker that returns true at that depth). The coverage report's classification should be changed from \"hard-to-reach\" to \"defensive-unreachable\", and the cited root-cause mechanism (makeDependencyGraphWalker returning true on a CTE RangeVar) should be corrected since that walker never returns true."
     }
    ]
   ]
  },
  "4914": {
   "func": "raw_expression_tree_walker_impl",
   "reachable": false,
   "subs": [
    [
     "4914",
     {
      "functionName": "raw_expression_tree_walker_impl",
      "lines": "4914",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "REFUTED root cause; line is defensive-unreachable, not hard-to-reach. Line 4914 is the `return true;` that fires only if WALK(rc->rpDefs) returns true. Exactly three callbacks ever drive raw_expression_tree_walker: (1) test_raw_expression_coverage (analyze.c:4091) ALWAYS returns false -- it covers the condition evaluation at 4913 but can never make the body at 4914 run; (2) contain_rpr_walker (parse_cte.c:1309) returns true at the WindowDef when wd->rpCommonSyntax != NULL, BEFORE recursing into the RPCommonSyntax case, so it never walks rpDefs to return true; (3) makeDependencyGraphWalker (parse_cte.c:700) NEVER returns true -- even when it matches a CTE-referencing RangeVar it returns false at line 754, only recording a dependency as a side effect. The proposed root cause ('only the CTE dependency walker returns true') is factually wrong: makeDependencyGraphWalker returns false on CTE matches. Hence no SQL input can make rpDefs's sub-walk return true, so 4914 is unreachable. This is standard defensive early-exit boilerplate identical to every other `if (WALK(x)) return true;` in the function; it is correct and would be needed by a hypothetical future callback that returns true, but no current caller exercises it. The companion line 4651 is unreachable for the same reason.",
      "refinedTest": "No SQL/regression test can cover line 4914 with the current set of callbacks. The proposed WITH + DEFINE-subquery-referencing-CTE query does NOT work: it would route through makeDependencyGraphWalker, which returns false even on a CTE RangeVar match (parse_cte.c:754), so WALK(rc->rpDefs) yields false and 4914 never executes. Covering it would require a new raw_expression_tree_walker callback that returns true from inside a DEFINE expression contained in rpDefs (e.g. a hypothetical walker that short-circuits on some node legally placed in an a_expr within DEFINE). No such callback exists, so the line cannot be covered by a query.",
      "refinedFix": "No functional fix needed; the line is correct and necessary defensive boilerplate consistent with the rest of raw_expression_tree_walker. To eliminate it from the coverage report, options are: (a) accept it as defensive-unreachable and exclude/annotate it (preferred -- matches existing PostgreSQL practice for walker early-exit lines); or (b) if strict coverage is required, the only way to exercise it is to add a test-only walker callback (under DEBUG_NODE_TESTS_ENABLED) that returns true when it encounters a node placed inside a DEFINE expression -- but this changes production-adjacent code purely for coverage and is not recommended."
     }
    ]
   ]
  },
  "4922": {
   "func": "raw_expression_tree_walker_impl",
   "reachable": false,
   "subs": [
    [
     "4922",
     {
      "functionName": "raw_expression_tree_walker_impl",
      "lines": "4922",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "CONFIRMED defensive-unreachable. Line 4922 is the `return true;` body of `if (WALK(rp->children)) return true;` in the T_RPRPatternNode case. The WALK call on 4921 executes and is covered, but its true-branch is unreachable by any SQL/regression input. Two (and only two) walkers run through this function: (1) test_raw_expression_coverage (the DEBUG_NODE_TESTS harness) at analyze.c:4091, which has no search target and only returns false except when node==NULL -- it can never make WALK return true; (2) contain_rpr_walker at parse_cte.c:1309, which returns true ONLY when it encounters a WindowDef whose rpCommonSyntax != NULL (line 1320). An RPRPatternNode's `children` list is grammatically guaranteed (gram.y:17646,17653,17678,17685,17727 etc.) to contain only other RPRPatternNodes (VAR/SEQ/ALT/GROUP). PATTERN syntax admits no WindowDef, subquery, RangeVar, SubLink, or any node a raw walker aborts on; DEFINE expressions (which could embed window subqueries) live in RPCommonSyntax.rpDefs (handled at line 4913), not inside RPRPatternNode.children. Therefore WALK(rp->children) can never return true, and line 4922 cannot execute. I tried to refute via a nested CTE+WindowDef-with-PATTERN (the only real caller that returns true) but the true-return fires at the WindowDef node in the body's T_WindowDef arm / location stash, never from within the PATTERN subtree. No input refutes the finding.",
      "refinedTest": "No test can cover this exact line. To cover it would require a walker that returns true on some node reachable inside RPRPatternNode.children, plus a grammar that places such a node there -- neither exists. If a node-coverage requirement is enforced, the only honest options are: (a) leave it uncovered as accepted defensive code, or (b) add a targeted C-level unit test (not SQL regression) using a hand-built RPRPatternNode and a custom walker that returns true on a child -- but that tests synthetic state the parser never produces and is not warranted.",
      "refinedFix": "Keep line 4922 for structural consistency with every other `if (WALK(...)) return true;` arm; removing it would make the walker silently incorrect if a future node type is ever placed under PATTERN. Do NOT add an Assert (the WALK call must still recurse to validate child node tags via the harness). Optionally add a brief comment in the T_RPRPatternNode case noting that children currently contain only RPRPatternNodes, so the true-return is presently unreachable but retained for forward-compatibility. Treat as accepted defensive code, not a coverage gap."
     }
    ]
   ]
  }
 },
 "src/backend/parser/parse_func.c": {
  "2136": {
   "func": "ParseRPRNavCall",
   "reachable": false,
   "subs": [
    [
     "2136",
     {
      "functionName": "ParseRPRNavCall",
      "lines": "2136",
      "lineCount": 1,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. ParseRPRNavCall is invoked only when could_be_rpr_nav is true (parse_func.c:701-702), which is set true only after name exactly matches one of \"prev\"/\"next\"/\"first\"/\"last\" (lines 239-243). Inside ParseRPRNavCall, name is re-derived from the same unmutated funcname list (line 2105). funcname is passed through unchanged (line 702) and not mutated in between. Thus when control reaches the if/else-if chain (2113-2132), exactly one strcmp must succeed; the else at 2133-2138 with pg_unreachable() at 2136 cannot execute via any SQL input. Attempts to refute: any other name yields could_be_rpr_nav=false -> normal func_get_detail path, never reaching this function; schema-qualified names fail list_length==1; case is normalized by the parser before both checks. No reachable input exists.",
      "refinedTest": "No SQL test can cover line 2136. It is a pg_unreachable() guard on a can't-happen dispatch fall-through; the four navigation-name strcmp branches are exhaustive given the caller's identical name gate. Coverage of this line is only achievable via fault injection (e.g., mutating funcname between the gate and this function), which is not a valid regression scenario.",
      "refinedFix": "Keep as-is. The pg_unreachable() plus return NULL is the correct defensive guard for an exhaustive dispatch. The trailing return NULL after pg_unreachable() is harmless and silences compilers that do not treat pg_unreachable() as no-return. No source change needed."
     }
    ]
   ]
  },
  "2208": {
   "func": "ParseRPRNavCall",
   "reachable": true,
   "subs": [
    [
     "2208-2212",
     {
      "functionName": "ParseRPRNavCall",
      "lines": "2208-2212",
      "lineCount": 5,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "Confirmed reachable and testable. Lines 2207-2212 fire when a 2-arg nav call's explicit offset has a type lacking an IMPLICIT cast to int8. I verified the code (parse_func.c:2195-2216): nargs==2 with offtype != INT8OID calls coerce_to_target_type with COERCION_IMPLICIT/COERCE_IMPLICIT_CAST; a NULL result raises the ereport. I confirmed via pg_cast.dat that numeric->int8 has castcontext 'a' (assignment-only), so COERCION_IMPLICIT rejects it and returns NULL -> error fires. I grepped every 2-arg nav call in rpr.sql: all offsets are int4 literals, random()::int (int4), int4-returning subqueries, NULL::int8, untyped NULL, or params -- none are numeric/float/text, so this branch is genuinely uncovered. The decimal literal 1.5 is typed numeric in PostgreSQL, so PREV(price, 1.5) deterministically drives execution through these exact lines. format_type_be(numeric) yields \"numeric\" and the hardcoded \"bigint\" string makes the expected message exact.",
      "refinedTest": "Add to src/test/regress/sql/rpr.sql (and matching .out), against an existing RPR table such as stock/price-bearing table used elsewhere in the file. Use a numeric offset literal, which is the cleanest deterministic case:\n\n-- negative test: offset argument type with no implicit cast to bigint\nSELECT company, tdate, price, count(*) OVER w\nFROM stock\nWINDOW w AS (\n  PARTITION BY company ORDER BY tdate\n  ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING\n  PATTERN (A B+)\n  DEFINE B AS price > PREV(price, 1.5)\n);\n\nExpected .out (do not wrap in DO block):\nERROR:  offset argument of PREV must be type bigint, not type numeric\nLINE n:   DEFINE B AS price > PREV(price, 1.5)\n                                          ^\n\nNotes / caveats verified:\n1. The decimal constant 1.5 is typed numeric (not float8); numeric->int8 is assignment-context only, so COERCION_IMPLICIT returns NULL -> exact lines hit. Good.\n2. An alternative offset PREV(price, 'x') also reaches the branch, BUT a bare 'x' is UNKNOWNOID: coercion of unknown to int8 also returns NULL, and the message would read \"not type unknown\" -- usable but less intuitive; if a text type is wanted use PREV(price, 'x'::text) which yields \"not type text\" (text has no cast to int8 at all). Prefer the numeric 1.5 form for clarity and determinism.\n3. Use the actual table/column names already present in rpr.sql (e.g. the 'stock'/'company'/'price'/'tdate' fixtures) so the parser reaches the DEFINE walk; the error is raised at parse-analysis of the nav call regardless of data, so no specific rows are required.",
      "refinedFix": ""
     }
    ]
   ]
  }
 },
 "src/backend/utils/adt/ruleutils.c": {
  "10163": {
   "func": "get_rule_expr",
   "reachable": false,
   "subs": [
    [
     "10163-10164",
     {
      "functionName": "get_rule_expr",
      "lines": "10163-10164",
      "lineCount": 2,
      "reachable": false,
      "finalClassification": "defensive-unreachable",
      "testWillCover": false,
      "confidence": "high",
      "verdict": "Confirmed defensive-unreachable. Lines 10163-10164 are the default: arm of the switch over RPRNavExpr->kind inside the T_RPRNavExpr case in get_rule_expr (ruleutils.c). The RPRNavKind enum (primnodes.h:669-680) has exactly 8 members (RPR_NAV_PREV, NEXT, FIRST, LAST, PREV_FIRST, PREV_LAST, NEXT_FIRST, NEXT_LAST) and all 8 have explicit case labels at lines 10135-10162, so the default arm cannot match any in-range value. The kind field is assigned during parse analysis from this fixed enum set; no SQL syntax can produce an out-of-range value. The WRITE_READ_PARSE_PLAN_TREES round-trip reads back the exact integer written, so it preserves the in-range value and cannot synthesize a bad kind either. I tried to refute reachability via parser paths, optimizer rewrites, and copy/out/read node round-trips and found no input that drives an out-of-range kind into this deparse switch. Line 10166 (inner_func = NULL \"keep compiler quiet\") is a dead store grouped with the same defensive arm. This matches standard PostgreSQL switch-over-enum guard style used throughout ruleutils.c.",
      "refinedTest": "No SQL-level test can cover these lines. The only way to execute the default arm is to fabricate an RPRNavExpr with an out-of-range kind in C and pass it to get_rule_expr -- e.g. a C unit test or a temporary debugging hack that sets nav->kind = (RPRNavKind) 999 before calling pg_get_viewdef/EXPLAIN VERBOSE on a view using an RPR navigation function. This is not reachable from the regression suite and is not recommended.",
      "refinedFix": "Leave the elog(ERROR) default in place as the standard PostgreSQL defensive guard for switch-over-enum; it is consistent with neighboring node-deparse code in ruleutils.c and protects against future RPRNavKind additions. No source change recommended. If maximizing measured coverage were a hard requirement, the only options would be a coverage-exclusion marker or dropping the default to rely on -Wswitch exhaustiveness, neither of which is advisable."
     }
    ]
   ]
  },
  "14232": {
   "func": "generate_function_name",
   "reachable": true,
   "subs": [
    [
     "14232-14234",
     {
      "functionName": "generate_function_name",
      "lines": "14232-14234",
      "lineCount": 3,
      "reachable": true,
      "finalClassification": "testable",
      "testWillCover": true,
      "confidence": "high",
      "verdict": "CONFIRMED testable and correctly diagnosed. Lines 14231-14234 are the prev/next/first/last arms of a short-circuited || chain inside the `if (inRPRDefine)` force-qualify block (ruleutils.c:14229-14235). I verified the code, the deparse mechanism, and ran the proposed test against the actual RPR build (tmp_install) in a live temp cluster. Results: (1) inRPRDefine is set true while walking DEFINE TargetEntries (get_rule_pattern_define, ruleutils.c:7237) so any FuncExpr there hits generate_function_name with inRPRDefine=true; (2) deparsing a user function `rpr_navns.last(val)` inside DEFINE yields viewdef text that preserves the schema-qualified call (`rpr_navns.last(val) = '-999'::integer`) and re-parses cleanly, proving force_qualify=true fired; (3) because `||` is left-to-right short-circuit, proname='last' evaluates strcmp(prev)==false (14231), strcmp(next)==false (14232), strcmp(first)==false (14233), strcmp(last)==true (14234) -- so the single `last` test drives execution through all three uncovered lines. I also independently confirmed `next` and `first` named user functions force qualification and round-trip. The existing navns_fn view (rpr_base.sql:1525-1529) only covers the `prev` arm (14231), matching the gcov gap exactly. No refutation found; the lines are not defensive/dead.",
      "refinedTest": "Use the proposed test verbatim; it is sufficient and was empirically validated. Add to rpr_base.sql in the rpr_navns block (after the existing navns_fn view, before DROP SCHEMA rpr_navns CASCADE at line ~1532). A single `last` view covers all three lines via || short-circuit:\n\nCREATE FUNCTION rpr_navns.last(integer) RETURNS integer AS 'SELECT -999' LANGUAGE sql IMMUTABLE;\nCREATE VIEW navns_fn_last AS\n  SELECT id, count(*) OVER w AS cnt FROM nt\n  WINDOW w AS (PARTITION BY g ORDER BY id\n    ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING INITIAL\n    PATTERN (A+) DEFINE A AS rpr_navns.last(val) = -999);\nSELECT pg_get_viewdef('navns_fn_last');\nDROP VIEW navns_fn_last;\nDROP FUNCTION rpr_navns.last(integer);\n\nConfirmed expected viewdef output preserves the qualified call:\n  DEFINE\n  a AS (rpr_navns.last(val) = '-999'::integer) )\nCapture this exact deparse in rpr_base.out. Note the deparse also emits `AFTER MATCH SKIP PAST LAST ROW` (default) on its own line -- include it in expected output. If a reviewer prefers explicit coverage intent, optionally also add next/first views, but they are redundant for line coverage.",
      "refinedFix": ""
     }
    ]
   ]
  }
 }
}