bool_or Taints Sessions In A Running Window

bool_or over a running window taints every later request in a session once a failure appears, and bool_and confirms the whole session stayed clean.

SqlResilience

Code

snippet
-- 会话健康面板:一旦出现错误,同一会话此后的每一行都标记为"已污染"
CREATE TABLE requests (
    id         integer PRIMARY KEY,
    session_id integer NOT NULL,
    failed     boolean NOT NULL
);
INSERT INTO requests VALUES
    (1, 100, false),
    (2, 100, false),
    (3, 100, true),
    (4, 100, false),
    (5, 200, false),
    (6, 200, false);

SELECT
    id,
    session_id,
    failed,
    -- 运行窗口:从会话开头到当前行为止有没有失败过
    bool_or(failed) OVER (PARTITION BY session_id ORDER BY id
                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_tainted,
    -- 全分区聚合:整个会话是否零失败
    bool_and(NOT failed) OVER (PARTITION BY session_id) AS session_clean
FROM requests
ORDER BY session_id, id;

How it works

SELECT / INSERT / CREATE statements share the script, touching requests.

Mechanically, the statements are built from: a window function (OVER (…)) calculating values across rows while every row stays visible; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Using it

Point it at the requests table.

Key statements worth quoting

SELECT
    id,
    session_id,
    failed,
    bool_or(failed) OVER (PARTITION BY session_id ORDER BY id
                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS session_tainted,
    bool_and(NOT failed) OVER (PARTITION BY session_id) AS session_clean
FROM requests
ORDER BY session_id, id;
INSERT INTO requests VALUES
    (1, 100, false),
    (2, 100, false),
    (3, 100, true),
    (4, 100, false),
    (5, 200, false),
    (6, 200, false);
CREATE TABLE requests (
    id         integer PRIMARY KEY,
    session_id integer NOT NULL,
    failed     boolean NOT NULL
);

Interactive Tools for This Topic

FAQ

What are the relations in play here?
`requests`.