BigQuery UDF Logs Are Not a Quarantine Table
BigQuery’s Python UDF logging can help diagnose bad rows, but a diagnostic log does not automatically become a replayable quarantine table. If it retains only the first 200 characters and no other store preserves the complete input, reconstruction may be impossible. A missing stable row reference also obstructs correlation. Separate the paths: logs locate problems; controlled source storage retains the evidence needed to repair and replay them.
Contents
阅读中文版. This analysis starts from Google Cloud’s October 20, 2026 introduction to Python UDF logging. Vendor-described capabilities are distinguished from the engineering recommendations below. The example ran only in local Python; no BigQuery resources were created, cloud queries executed, or log-delivery latency measured.
The update improves observability
The capability introduced in the official post lets Python UDFs use standard logging to send diagnostics to Cloud Logging without a custom external connector. Its example enables debug output for the session and logs parsing failures or missing required fields. It catches anticipated input errors and returns None, represented as NULL in SQL, before filtering invalid results. This design can prevent those expected bad inputs from failing the whole query; it does not eliminate every possible execution error.
There are three distinct actions: validate an input, return a query value, and emit a diagnostic. Logging is not an exception handler. Adding a logging call without handling the anticipated parse failure cannot guarantee query success. Conversely, successful query execution does not prove that every source row reached the clean output. Filtered NULL results still need an explicit disposition.
The announcement also demonstrates alerting and querying logs through Log Analytics. Searchable diagnostics are useful, but searchability and recoverability have different requirements. This article does not assume that log-entry counts equal bad-row counts, and does not establish any account-specific price, quota, or alert-delivery time. Those conditions need verification in the intended deployment.
A 200-character prefix is not a replay record
The blog’s sample writes raw_payload[:200] into some diagnostics, while its recovery discussion refers to preserved raw payloads. Those are not equivalent for long inputs. A valid JSON object can end after character 200. Cutting its prefix can remove a closing quote and brace, leaving invalid JSON. Even a prefix that still parses cannot reveal fields discarded from the suffix.
In this example, [:200] selects Python string character positions, not a 200-byte limit. Truncation can control log volume, but it is not compression. Compression requires a reversible encoding; slicing discards information. Adding a brace cannot tell you which fields originally followed it. Our local check builds a valid object with a padding field longer than 250 characters. The full object parses while its 200-character prefix fails. That is an information-loss counterexample, not a claim that the platform truncates every emitted log.
Correlation matters too. Some sample diagnostics contain an error type, a missing field, and a payload prefix. Two different inputs can share that prefix. A recovery design should use a stable ingestion reference to connect a diagnostic to a complete input. It need not duplicate the input in the log, particularly when the original contains credentials or personal information unrelated to the diagnosis.
Filtering NULL must not hide a row’s disposition
Take three inputs: one valid event, one malformed JSON string, and one object without an event field. A query that retains only non-NULL validated values produces one clean row. A successful query describes execution status, not successful ingestion of all three inputs. A traceable pipeline should account separately for accepted, quarantined, and explicitly rejected records.
The recommended design retains controlled source data and a stable reference before validation, then routes on the classification result. Logs carry the reference and error code. A real implementation must also define its commit boundary: if the clean write succeeds but the quarantine write fails, how is the discrepancy detected and repaired? The in-memory lists below provide no cross-system transaction and cannot prove atomic storage.
Quarantine is not a reason to retain unrestricted copies of sensitive data indefinitely. Select the minimum required fields, appropriate access controls, and a retention policy. When a reference can retrieve an existing controlled source record, a second copy may be unnecessary.
A local check with metadata-only diagnostics
Our teaching contract requires event to be a nonempty string. A JSON array or JSON null is not an object; successful parsing alone does not establish the required structure. A present field whose value is zero also fails the string contract. The error categories are defined for this example and are not BigQuery platform error codes.
The program uses standard logging with StringIO to capture local output. Quarantine retains full inputs; each diagnostic contains only row_ref and error_code. References such as r1 are synthetic identifiers, not a recommendation to log account names or email addresses. Duplicate references are rejected, but earlier local side effects are not rolled back. The route function is therefore not a transaction implementation.
import json
import logging
from io import StringIO
stream = StringIO()
logger = logging.getLogger('row_check_demo')
logger.handlers.clear()
logger.addHandler(logging.StreamHandler(stream))
logger.setLevel(logging.INFO)
logger.propagate = False
def classify(raw):
if not isinstance(raw, str) or not raw.strip():
return 'EMPTY_INPUT', None
try:
value = json.loads(raw)
except json.JSONDecodeError:
return 'INVALID_JSON', None
if not isinstance(value, dict):
return 'NOT_OBJECT', None
if value.get('event') is None:
return 'MISSING_EVENT', None
if not isinstance(value['event'], str) or not value['event']:
return 'INVALID_EVENT', None
return 'OK', value
def route(rows):
clean, quarantine = [], []
seen = set()
for ref, raw in rows:
if ref in seen:
raise ValueError('duplicate row reference')
seen.add(ref)
code, value = classify(raw)
if code == 'OK':
clean.append((ref, value))
else:
# Local in-memory illustration, not a durable cloud write.
quarantine.append((ref, raw, code))
logger.error(json.dumps({'row_ref': ref, 'error_code': code}))
return clean, quarantine
checks = 0
def check(ok):
global checks
assert ok
checks += 1
long_raw = json.dumps({'pad': 'x'*250, 'event': 'view'})
check(len(long_raw) > 200)
try:
json.loads(long_raw[:200])
except json.JSONDecodeError:
check(True)
else:
raise AssertionError('expected an incomplete prefix')
check(classify(long_raw)[0] == 'OK')
for raw, expected in [('', 'EMPTY_INPUT'), (None, 'EMPTY_INPUT'),
('{', 'INVALID_JSON'), ('[]', 'NOT_OBJECT'),
('null', 'NOT_OBJECT'), ('{}', 'MISSING_EVENT'),
('{"event":null}', 'MISSING_EVENT'),
('{"event":0}', 'INVALID_EVENT'),
('{"event":""}', 'INVALID_EVENT')]:
check(classify(raw)[0] == expected)
rows = [('r1', '{"event":"view"}'), ('r2', '{'), ('r3', '{}')]
clean, bad = route(rows)
check(len(clean) == 1 and len(bad) == 2)
check([r[0] for r in clean + bad] == ['r1','r2','r3'])
check(bad[0][1] == '{' and bad[1][1] == '{}')
records = [json.loads(s) for s in stream.getvalue().splitlines()]
check(records == [{'row_ref':'r2','error_code':'INVALID_JSON'},
{'row_ref':'r3','error_code':'MISSING_EVENT'}])
check(all(set(r) == {'row_ref','error_code'} for r in records))
try:
route([('same', '{}'), ('same', '{}')])
except ValueError:
check(True)
else:
raise AssertionError('duplicate accepted')
import sys
print(checks, 'checks passed; Python', sys.version.split()[0])
print('local routing: clean=1, quarantine=2; diagnostic fields only')
The program ran on Python 3.15.0 and passed 18 assertions covering truncation, input shape and field types, three-row routing, retained raw inputs, the diagnostic-field allowlist, and duplicate-reference rejection. It does not simulate BigQuery invocation counts, Cloud Logging transport, concurrency, or process crashes. Those deployment behaviors require separate evidence. Nothing here establishes zero loss, guaranteed immediate delivery, or end-to-end exactly-once execution.
Replay needs evidence for a repair
Missing fields and malformed JSON need different repair paths. A parsing failure generally requires consulting the producer or complete source. A missing required value raises the question of whether a trusted source can supply it. Filling in default_user makes a field nonempty but does not recover a real identity. Likewise, the event field in this example cannot safely be replaced with view for every missing value without a business decision.
A replay record should bind the original reference, transformation version, repair evidence, and destination-write status. Reprocessing the same input must have a defined outcome: overwrite, reject, deduplicate, or create a version. Repeating INSERT does not itself create idempotency. The distinction connects to retry and idempotency; two diagnostics also do not establish that the destination received two writes.
If diagnostics are sampled to reduce volume, the sampled entries are not a complete error ledger. Retries can also produce several diagnostics for one bad row, making an undeduplicated log count larger than the row count. An error rate needs a numerator and denominator covering the same population, rather than sampled error logs divided by every input. Quarantine records and operational diagnostics serve different purposes, which is why their accounting should be designed independently.
Verify observability and recoverability separately
Start with fixed, nonsensitive examples: a valid object, empty input, malformed JSON, an array, a missing field, an incorrect field type, and identical contents with different references. Verify that classification results correlate with retained complete source records. Then separately test log visibility, duplicate-processing policy, and failed destination writes in the actual cloud environment. The 18 local assertions do not complete those cloud checks.
The value of this logging capability is a shorter path from a failure symptom to the relevant input. A recoverable pipeline additionally needs complete source evidence, explicit classifications, and repair and write rules. A useful diagnostic identifies the problem without copying unrelated content.
Source: the Google Cloud post dated October 20, 2026. This is not presented as a feature first released on the intended article date. The article was backfilled on October 25, retaining the intended October 22, 2026, 11:30 Beijing article date.
Support
If the explanations or examples helped you solve a problem or save time, you’re welcome to support this site with a voluntary tip.
Click a QR code to enlarge. More options: support page。


