Bound the PostgreSQL dump skip to tab-indented continuations

This commit is contained in:
gadgethd committed 2026-11-20 04:59:12 +00:00
1 parent 939bf25eae
commit 369303e38f
2 files changed
+73 -11

No files matched your search

+20 -11
View File
@@ -24,14 +24,21 @@ ERROR_FIELD = re.compile(r'''\b(?:error|err)=(?:"([^"]*)"|'([^']*)'|(\S+))''', r
# bind values across continuation lines that have no record prefix; their text
# is data, not a new failure. The severity record itself (ERROR/FATAL/PANIC)
# remains the failure evidence.
# PG_RECORD assumes the deployed log_line_prefix '%m [%p] ' (fractional-second
# timestamp, pid, severity directly before the colon). A different prefix would
# fall back to the ordinary message scan rather than misclassify records.
PG_RECORD = re.compile(r'^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+ \S+ \[\d+\] ([A-Z]+\d*):')
PG_DUMP_SEVERITIES = frozenset({'STATEMENT', 'QUERY', 'DETAIL', 'HINT', 'CONTEXT', 'LOCATION'})
def log_body(line: str) -> str:
"""The line without the docker --timestamps prefix, when present."""
return line.split(' ', 1)[1] if re.match(r'^\d{4}-\d\d-\d\dT', line) else line
def pg_record_severity(line: str) -> str | None:
"""Severity of a PostgreSQL log record, or None for any other line."""
body = line.split(' ', 1)[1] if re.match(r'^\d{4}-\d\d-\d\dT', line) else line
match = PG_RECORD.match(body)
match = PG_RECORD.match(log_body(line))
return match.group(1) if match else None
@@ -57,7 +64,7 @@ def failed_value(value) -> bool:
def failure_line(line: str) -> bool:
# Docker prepends its timestamp. Parse structured fields before scanning
# messages so false/null counters do not hide quoted failure messages.
body = line.split(' ', 1)[1] if re.match(r'^\d{4}-\d\d-\d\dT', line) else line
body = log_body(line)
try:
return failed_value(json.loads(body))
except (ValueError, TypeError):
@@ -78,19 +85,21 @@ def inspect_log(path: Path) -> dict:
checksum = hashlib.sha256()
failures = 0
examples = []
in_pg_dump = False
with path.open('rb') as source:
for number, line in enumerate(source, 1):
checksum.update(line)
text = line.decode('utf8', errors='replace')
severity = pg_record_severity(text)
if severity is not None:
# A new record ends any previous multiline dump. Dump records
# echo SQL/bind data; only their owning severity record counts.
in_pg_dump = severity in PG_DUMP_SEVERITIES
if in_pg_dump:
continue
elif in_pg_dump:
if severity in PG_DUMP_SEVERITIES:
# Dump records echo SQL/bind data; only their owning severity
# record counts.
continue
if severity is None and log_body(text).startswith('\t'):
# PostgreSQL continuation lines are tab-indented. Skip them
# wherever they appear: inside a dump, and when the capture
# window opened mid-dump (leading orphaned continuations).
# Any other line ends the echo and is scanned normally, so a
# non-PostgreSQL failure right after a dump stays visible.
continue
if failure_line(text):
failures += 1
@@ -96,6 +96,59 @@ class RuntimeErrors(unittest.TestCase):
log.write_text(record('LOG', 'background worker failed to start') + '\n')
self.assertEqual(inspect_log(log)['failure_lines'], 1)
def test_dump_boundaries_keep_neighbouring_failures_visible(self):
def record(severity, message, gap=' '):
return ('2026-11-19T09:06:39.785605000Z 2026-11-19 09:06:39.771 UTC [835438] '
f'{severity}:{gap}{message}')
dump = [record('STATEMENT', "SELECT status FROM jobs WHERE status = 'failed'"),
"\t AND last_error IS NOT NULL -- exception panic failure"]
with tempfile.TemporaryDirectory() as directory:
log = Path(directory) / 'sample-db.log'
# A non-PostgreSQL failure right after a dump is NOT swallowed.
log.write_text('\n'.join(dump + ['[link-worker] job failed: database offline']) + '\n')
result = inspect_log(log)
self.assertEqual(result['failure_lines'], 1)
self.assertEqual(result['example_line_numbers'], [3])
# Structured application failures after a dump stay visible too.
log.write_text('\n'.join(dump + ['{"level":"error","msg":"commit failed"}']) + '\n')
self.assertEqual(inspect_log(log)['failure_lines'], 1)
# A window opened mid-dump: orphaned tab continuations are echo
# data even without their owning record; the later FATAL counts.
log.write_text('\n'.join(["\t WHERE status = 'failed' -- panic exception",
record('FATAL', 'connection to client lost')]) + '\n')
result = inspect_log(log)
self.assertEqual(result['failure_lines'], 1)
self.assertEqual(result['example_line_numbers'], [2])
# A tab-indented continuation that looks like a record is still
# echo data, not a new failure.
log.write_text('\n'.join([record('ERROR', 'permission denied for table packets')] + dump
+ ["\tERROR: fake failure inside echoed SQL"]) + '\n')
result = inspect_log(log)
self.assertEqual(result['failure_lines'], 1)
self.assertEqual(result['example_line_numbers'], [1])
# Single-space severity gaps and records without the docker prefix
# keep the same classification.
log.write_text(record('FATAL', 'connection to client lost', gap=' ') + '\n')
self.assertEqual(inspect_log(log)['failure_lines'], 1)
bare = '2026-11-19 09:06:39.771 UTC [835438] '
log.write_text(bare + 'STATEMENT: SELECT 1\n' + bare + 'FATAL: connection to client lost\n')
result = inspect_log(log)
self.assertEqual(result['failure_lines'], 1)
self.assertEqual(result['example_line_numbers'], [2])
# HINT/CONTEXT/LOCATION echoes are data; WARNING messages keep the
# ordinary scan (pre-existing behavior).
log.write_text('\n'.join([
record('ERROR', 'duplicate key value violates unique constraint'),
record('HINT', 'failed insert may be retried'),
record('CONTEXT', 'SQL statement "SELECT failed"'),
record('LOCATION', 'exec_stmt, pl_exec.c:1'),
]) + '\n')
result = inspect_log(log)
self.assertEqual(result['failure_lines'], 1)
self.assertEqual(result['example_line_numbers'], [1])
log.write_text(record('WARNING', 'background worker failed to start') + '\n')
self.assertEqual(inspect_log(log)['failure_lines'], 1)
def test_saved_soak_lost_client_input_counts_only_the_six_fatal_records(self):
saved = Path(__file__).parent / 'fixtures' / 'runtime-logs' / 'soak-spam-lost-clients.log.txt'
result = inspect_log(saved)