If a CSV export says “Completed” but records are missing, check what actually tells the worker to stop. An empty database result and an empty result from a formatting step can look identical by the time they reach the file writer. Only one of those tells you that the source has run out of rows.
We found this distinction while reading the code behind a batch export service. The worker fetched a page, sent it to a formatter, and passed the returned rows to a writer. A separate status handler treated an empty writer result as successful completion. Put those pieces together, and a formatter that returns no rows can end the whole export early.
That is a conditional failure path in the source we reviewed. We haven't established that it caused a new production incident. The six records below are synthetic; they let us show the behavior without using customer data.
Follow one batch before changing the SQL
There are three useful checkpoints: rows fetched from the database, rows returned by the formatter, and rows successfully written to the file. Keep those numbers separate.
In the service we reviewed, the important sequence looked like this. This is a shortened representation of the control flow, with application details removed:
$rows = fetchPage($offset, $limit);
$rows = formatRows($rows);
$offset += $limit;
if (appendBatchAndUpdateStatus($rows)) {
break;
}
The original database result gets overwritten. By the time the writer sees an empty array, it can't tell whether the database returned nothing or the formatter removed everything.
The formatting method also accepted an empty response field as an empty batch. A JSON response containing "format_list": "[]" was decoded into an empty array. The file writer then returned an empty array, and the surrounding status handler marked the job as finished. That completion branch didn't compare the number written with the expected total.
The code has another completion branch for reaching the expected count. So a wrong count is still worth investigating. But fixing the count alone won't fix this empty-batch path.
A middle page can stop the export
Imagine six source records, with a page size of two. The formatter returns nothing for the second page. Perhaps it's deliberately filtering those records; perhaps a response contract is wrong. For this example, we simply make it happen.
| Offset | Database returns | Formatter returns | Worker behavior |
|---|---|---|---|
| 0 | 1, 2 | 1, 2 | Writes two rows and continues |
| 2 | 3, 4 | Empty | Marks the job completed and stops |
| 4 | 5, 6 | Never called | These rows never reach the formatter |
The downloaded file contains records 1 and 2. If records 3 and 4 were intentionally excluded, you would still expect 5 and 6. Their absence is the clue: filtering one batch has also prevented later batches from being read.
We reproduced this sequence in a small PHP harness using the same empty-result completion rule. With filtering allowed but end-of-source checked before formatting, the harness continued to the third page and produced 1, 2, 5, and 6. That's a demonstration of the control-flow difference, not a deployment test of the full service.
Give the formatter an explicit contract
Before adding a guard, decide what the formatter is allowed to do.
For a formatter that only changes dates, labels, or column order, one input row should normally produce one output row. Returning fewer rows should be an error. Include the batch offset and counts in that error so someone can investigate it.
For a formatter that legitimately filters records, zero output rows can be valid. The worker must keep reading the source, and the formatter should report which source records it excluded and why. An unexplained empty array is a poor substitute for that information.
A formatter that expands one source record into several output rows needs a different contract again. Comparing input and output counts directly would reject valid data. Track source records processed separately from output rows produced.
Here's a design sketch for the simpler, one-input-to-one-output case. The helper functions are placeholders for your own query, formatter, and writer; this isn't a patch you can paste into an existing service unchanged.
$offset = 0;
$scanned = 0;
$written = 0;
while (true) {
$rawRows = fetchPage($offset, $limit);
if ($rawRows === []) {
break; // End of the source, before formatting.
}
$outputRows = formatRows($rawRows);
if (!is_array($outputRows)
|| count($outputRows) !== count($rawRows)) {
throw new RuntimeException(
"Formatter changed the row count at offset {$offset}"
);
}
// Must throw if the complete batch wasn't persisted.
writeRowsOrThrow($outputRows);
$scanned += count($rawRows);
$written += count($outputRows);
$offset += count($rawRows);
}
// Requires an exact expected count for the same fixed input.
if ($scanned !== $expected || $written !== $expected) {
throw new RuntimeException('Export reconciliation failed');
}
markCompleted();
This sketch assumes a fixed source with deterministic ordering. If rows are inserted or deleted while an OFFSET-based export runs, page boundaries can move. A saved input manifest or a suitable database snapshot can give the job a stable input; the right choice depends on how the service reads its data. A unique sort order alone doesn't freeze changing records.
Also check the write contract. Incrementing a counter after an upload call is only meaningful if that call confirms the complete write or throws on failure. For a stronger check, parse the final downloaded object and reconcile its record identifiers.
Log enough to find the first gap
For each batch, record its sequence number or offset, raw row count, formatted row count, acknowledged written count, and any deliberate exclusions. Record the terminal reason too: source exhausted, reconciliation failed, formatter rejected, or user cancelled.
For the synthetic failing batch, the useful trace is:
offset=2 raw_rows=2 formatted_rows=0
written_so_far=2 expected_source_rows=6
terminal_reason=empty_formatted_batch
That tells you where to look. A single “Completed” label doesn't.
Keep credentials and full customer payloads out of routine logs. Usually the batch counts, job identifier, and carefully scoped diagnostic identifiers are enough to start. If you need to inspect response data, use an access-controlled diagnostic path.
Count CSV records, then compare their identities
A quick line count can send you down the wrong path. A quoted CSV field may contain a newline, so physical lines and CSV records aren't interchangeable. Parse the file, exclude the header, and compare at the same level of detail as the export.
For example, an order-items export may have three rows for one order. Its key might be (order_id, line_id), rather than order_id. Comparing the number of orders on screen with the number of item rows in the file won't establish a defect.
For a manageable file with a unique row_id column, save the following as check_export.py. It compares a trusted expected manifest with the downloaded CSV. Both files need a row_id header. Use a manifest captured for the same filters, permissions, row definition, and point in time as the job; another broken export isn't an independent reference.
import csv
import sys
from collections import Counter
def keys(path):
counts = Counter()
with open(path, encoding="utf-8-sig", newline="") as handle:
reader = csv.DictReader(handle, strict=True)
if not reader.fieldnames or "row_id" not in reader.fieldnames:
raise ValueError(f"{path}: missing row_id header")
if len(set(reader.fieldnames)) != len(reader.fieldnames):
raise ValueError(f"{path}: duplicate column names")
for number, row in enumerate(reader, 1):
if None in row or any(value is None for value in row.values()):
raise ValueError(f"{path}: malformed record {number}")
key = row["row_id"]
if not key.strip():
raise ValueError(f"{path}: empty row_id at record {number}")
counts[key] += 1
return counts
if len(sys.argv) != 3:
raise SystemExit("Usage: python check_export.py expected.csv export.csv")
expected, actual = map(keys, sys.argv[1:])
if any(count != 1 for count in expected.values()):
raise ValueError("Expected manifest must have unique row_id values")
missing = expected - actual
extra = actual - expected
print("Expected records:", sum(expected.values()))
print("Actual records:", sum(actual.values()))
print("Missing occurrences:", sum(missing.values()))
print("Unexpected or repeated occurrences:", sum(extra.values()))
raise SystemExit(1 if missing or extra else 0)
The script keeps identifiers as strings, preserving leading zeros. It also compares occurrences, so an extra copy of one row can't hide a missing row merely because the totals match. It checks identifiers and CSV structure, not the correctness of every field value. It holds the keys in memory; for very large exports, use a disk-backed comparison or database reconciliation instead.
Python's CSV documentation explains the parser and why CSV files should be opened with newline="". Its Counter documentation describes the counting and subtraction operations used here.
What we'd check before shipping a fix
Start with an ordinary multi-page export. Then make the first page and a middle page produce no formatted rows. Under a strict one-to-one contract, those cases should fail visibly. Under an intentional filtering contract, later source pages should still be processed, and the excluded records should be accounted for.
Include a final partial page, an empty source, and a formatter response with a missing or invalid field. Test a writer failure too. A success label should require the agreed reconciliation to pass; reaching the end of a loop is only one part of that.
Finally, compare the downloaded file with the fixed input manifest. Equal counts are useful, but matching identifiers catches the more awkward case where one missing record and one duplicate cancel each other out.
If your investigation instead shows that the expected total is already wrong before the first batch runs, see why a MySQL count query can return 1 instead of the real total. For a count query that fails after joins or grouping change, see investigating an unqualified GROUP BY column in a SQL export.
For this particular failure path, the first change is small and concrete: keep the raw batch until you've decided whether the source is exhausted. An empty formatter response then becomes something you can validate, rather than an accidental instruction to stop.
