Resuming a warehouse export after a truncated JSON text
An RFC 7464 example quarantines an incomplete frame and resumes at the next independent valid record.
Archive retrospective · Topic year 2015
In this article
A partly written record at shift end
A warehouse terminal appends stock-check records throughout the shift. Power fails after it starts writing one record, and an independent reading arrives after recovery. The reporting team wants an evidence trail showing both usable records and gaps. RFC 7464, published in February 2015, describes a sequence of UTF-8 JSON texts with a byte delimiter at the front and an ASCII line feed at the end of each encoded text. The next record separator provides a recovery point. Compare that with a single JSON array whose incomplete element can make it impossible to decode the entire document as one value. The example uses warehouse checks as separate observations and keeps the incomplete observation visible in the result.
Frame the bytes before decoding the text
A JSON text can span multiple lines when the producer indents the fields. Line splitting would break our complete object into fragments, while splitting at the record separator preserves the indentation inside it. A control character that belongs inside a JSON string appears as an escape in the encoded text, so the escaped notation is separate from a delimiter byte on the wire. The A record contains the UTF-8 letter Ç. Preserving that character in the output is a small but concrete check on the path from producer to decoder. A reader receiving arbitrary chunks must preserve a character that straddles two read calls. Collecting a whole frame before decoding avoids treating the first half of that character as invalid text.
A bare number can hide a truncation
An incomplete object will normally fail to parse. The bytes for 42 might instead be accepted as a complete number, even if the producer intended to write 420. The line feed required by the encoder helps a reader detect this ambiguity for scalars without a closing delimiter. This export requires a final LF for top-level numbers, booleans and null. Its Python check covers booleans because bool is a subclass of int, and handles null explicitly. The local reader also rejects non-JSON constants such as NaN and checks whether floating-point conversion ended outside its finite range. This last check is a reader policy. Decide independently what numeric precision the warehouse contract requires, especially for counts and identifiers that cross implementation boundaries.
The four observations from a local run
The Windows run used Python 3.12. The first frame produced A with its original Ç. The second contained only the start of an object and went into quarantine. The third produced B, demonstrating that the reader could resume at the next separator. The fourth contained 42 without its final line feed and was quarantined. The assertion checks the complete sequence of those results so a skipped or reordered report would fail the run. A 2015 production implementation was outside the experiment. This is a current runtime checking byte-level behavior derived from the 2015 specification. The implementation uses a small in-memory capture. For large exports an incremental byte reader should discard or quarantine the oversized frame while continuing to look for another separator.
import json
from math import isfinite
RS, LF = b"\x1e", b"\x0a"
def encode(value):
text = json.dumps(value, ensure_ascii=False, allow_nan=False, indent=2)
return RS + text.encode("utf-8") + LF
def invalid_constant(value):
raise ValueError(value)
def inspect_small_capture(data):
preamble, *frames = data.split(RS)
if preamble:
raise ValueError("bytes before first record separator")
for position, frame in enumerate(frames, 1):
if not frame:
continue
try:
item = json.loads(frame.decode("utf-8"), parse_constant=invalid_constant)
if (item is None or isinstance(item, (int, float))) and not frame.endswith(LF):
raise ValueError("missing final LF for scalar in this export")
if isinstance(item, float) and not isfinite(item):
raise ValueError("numeric range exceeds this reader")
yield position, "accepted", item
except (ValueError, RecursionError):
yield position, "quarantined", None
capture = (encode({"id": "A", "bin": "Ç"}) + RS + b'{"id":' +
encode({"id": "B", "bin": "D"}) + RS + b"42")
result = list(inspect_small_capture(capture))
assert result == [(1, "accepted", {"id": "A", "bin": "Ç"}),
(2, "quarantined", None),
(3, "accepted", {"id": "B", "bin": "D"}),
(4, "quarantined", None)]
for position, status, value in result:
print(position, status, value)
Choose which records may affect counts
An accepted JSON text still needs application validation. For example, two transfers involving the same bin may each be syntactically valid and depend on order. Applying the second when the first is missing might leave the stock report internally inconsistent. An independent count reading can have a different policy. Give an import quarantine an identity based on its source file and byte range so the producer can recover the original observation. Keep the business event identifier separately. Frame positions can change when someone reconstructs the export, whereas a retried movement should not add to stock a second time. The demonstration prints frame ordinals for diagnosis and leaves business reconciliation to the consuming system.
Write a test fixture for the handoff
The producer and consumer should share fixtures for literal separator bytes, escaped characters inside strings, invalid UTF-8, truncated scalars and incomplete final records. Agree on a maximum frame size and on how to report an oversized record without losing later observations. An HTTP endpoint can declare application/json-seq so a client selects the right reader. Monitor quarantined frames alongside the retrieved movement count, since a technically readable file can still carry operational gaps. In the demonstrated capture success includes two explicit quarantine results as well as the two accepted records. The person investigating a missing stock check can see exactly which intervals require attention.
Reader discussion
How would you measure this development's real-world impact?
No comments yet. Be the first to contribute.
Write a comment