A CSV upload can look ordinary while asking an application to make several hidden decisions. Does a leading space belong to a column name? Does an empty final field mean an empty note or a missing column? Should a quantity written as 01 be accepted? What happens when the last record repeats a product already seen near the beginning? Successful parsing alone cannot answer these questions.
DeepSeek can help you examine those decisions before they become accidental behavior. Give it an explicit import contract, ask for small counterexamples, and turn useful suggestions into independently executed tests. Keep the final acceptance decision in deterministic code. This tutorial develops that workflow around a deliberately small inventory import with three columns: sku, quantity, and note.
The boundary here is the incoming file itself: bytes, text decoding, CSV records, and application rules. No records are repaired, no database is updated, and no spreadsheet is produced. If your next step involves changing accepted values, the separate DeepSeek data-cleaning workflow explains how to make those transformations reviewable. Establishing what you received comes first.
1. Define the import contract before writing a parser
Assume a small internal tool receives a complete byte string through parse_import(data: bytes). The maximum input is 65,536 bytes, including any initial byte-order mark. Its supported encoding is UTF-8, with one optional initial UTF-8 signature handled by UTF-8-SIG decoding. Invalid encoding and NUL characters are rejected. The file uses comma-separated fields and double quotes, with doubled quotes inside quoted fields.
The first parsed record must contain exactly sku,quantity,note, in that order and lowercase. Duplicate names, additional columns, missing columns, and whitespace-modified names fail validation. There must be between one and 500 data records, each containing exactly three fields. A blank record is an error. An empty note is allowed; an absent third field is not.
A SKU starts with an ASCII uppercase letter and contains at most 16 characters in total. Remaining characters may be uppercase ASCII letters, ASCII digits, or hyphens. A quantity is an ASCII integer from zero through 9999, written without signs, spaces, separators, or leading zeros except for zero itself. Notes may contain up to 200 Unicode code points, including embedded newlines. Their text is preserved without trimming or normalization.
Every SKU must be unique within the file. Only after the entire input passes does the function return immutable rows. These are product decisions for this example, rather than universal CSV requirements. A supplier with different identifiers needs a reviewed contract change. Write that change down and add examples before relaxing a validator. The requirements-analysis guide provides a useful way to connect each decision to acceptance evidence.
2. Ask DeepSeek to challenge the rules, not guess them
A broad request such as “validate this CSV” leaves too much unstated. The model could assume that headers are case-insensitive, empty lines should be skipped, or a plausible numeric conversion is sufficient. Those choices may sound helpful while changing the import’s meaning. Start with the written contract and distinguish required behavior from possible future conveniences.
Ask for examples on both sides of each boundary. A useful review pairs a valid 16-character SKU with an invalid 17-character SKU, or a 200-code-point note with a 201-code-point note. The rejected example should identify the precise rule it violates. Requesting only “edge cases” tends to produce an unstructured list that is harder to translate into reliable tests.
Use synthetic identifiers and notes. The model does not need an actual customer export to reason about quoting, row width, or duplicate keys. A tiny invented file is usually easier to inspect than hundreds of real records. If a production failure must be investigated, minimize and anonymize the reproducer locally before deciding whether any external sharing is appropriate.
The following prompt is an original, unexecuted template. It represents a review task you can adapt; it is not a recorded DeepSeek response or evidence that a model found a defect.
Review this CSV import contract as a skeptical test designer.
[Paste the complete contract and validator here.]
For each proposed case, provide:
1. The exact contract clause under review.
2. A minimal synthetic input, with CR, LF and BOM shown explicitly.
3. Expected acceptance or rejection and the reason.
4. Any ambiguity that requires a product decision.
Cover accepted examples as well as rejected ones. Do not repair inputs,
change the contract, execute code, or claim tests passed. Keep parser
behavior separate from schema rules and downstream storage concerns.
3. Bound the bytes, then decode without guessing
The size check belongs before text decoding. The interface receives bytes, so the limit is measured on that exact input rather than on decoded characters or a re-encoded approximation. A note containing multibyte characters can consume more storage than its visible length suggests. The byte ceiling and the note-length ceiling answer different questions and both need boundary tests.
A caller reading a regular buffered file can request at most the limit plus one byte to distinguish a file at the limit from one that exceeds it. Reading the entire file and checking afterward misses the opportunity to bound that read. Arbitrary streams require additional care because a short read does not necessarily mean end-of-file. The article’s core function receives an already constructed byte string; it cannot retroactively protect an upload server or an earlier unbounded read.
UTF-8-SIG decoding recognizes an initial UTF-8 signature and otherwise handles UTF-8 text. Strict decoding makes invalid byte sequences an error. Avoid replacing undecodable bytes, ignoring them, or falling back automatically to a different encoding. Each would produce a new interpretation of the submitted file. When an export uses an unsupported encoding, the appropriate next step is an explicit re-export or separately reviewed conversion.
Only the initial signature receives that special treatment. An interior U+FEFF remains content: in a header or SKU it fails the corresponding exact-value rule, while in a note it remains part of the text and its length. A second initial signature leaves a residual character before the first header name and therefore fails the header check. The contract separately rejects NUL anywhere, rather than hoping a later consumer will handle it consistently.
This policy makes an encoding error actionable without inventing a corrected value. Preserve the original file for an authorized diagnostic workflow if appropriate, tell the submitter which encoding is required, and ask for a replacement. Keep retention and access decisions separate from validation. A support log can record the failure category without copying the contents of a potentially private note.
4. Parse the chosen dialect and describe it honestly
The processing order is intentional: bound the input, decode it, reject prohibited NUL content, parse records, check structure, validate field values, and return only after successful completion. Reordering these steps can hide useful evidence. For example, converting values before checking record width might give a numeric error when the more important problem is an unexpected column.

The lab supplies decoded text to StringIO with newline='', then uses csv.reader with a comma delimiter, double-quote quoting, doubled embedded quotes, skipinitialspace=False, and strict=True. It does not guess the delimiter or infer a header. Semicolon-separated input is unsupported under this contract even if a spreadsheet happens to open it convincingly.
The word “strict” needs a narrow explanation. It enables the selected CPython parser’s error behavior. It does not turn that parser into an RFC 4180 certification tool. In particular, the chosen parser accepts an unescaped quote inside an otherwise unquoted field. It also accepts LF-only and CR-only record endings. The lab treats those behaviors as part of its declared dialect.
RFC 4180 is an informational description of a common CSV format; its described quoting and CRLF rules are useful context. An application can deliberately support a different, documented dialect. If your integration requires exact adherence to a particular external specification, design and test that requirement explicitly. Do not promise it merely because a parser option has a reassuring name.
Preserve embedded newlines through parsing. Splitting the text into lines first, replacing all carriage returns, or splitting records on commas loses the context supplied by quoting. A note with a comma is still one field when correctly quoted. A note spanning two physical lines can still belong to one logical data record. Those cases deserve accepted tests, because a validator that rejects legitimate records also violates its contract.
5. Validate headers and row width before mapping values
Treat the header as an ordered record that must pass inspection before you create any name-to-value mapping. First check for repeated names, then require the exact expected sequence. A header containing two quantity names is especially dangerous if a dictionary silently keeps only one value. Detect the ambiguity while both original columns are still visible.
Exact comparison also makes small differences observable. Quantity, quantity , and quantity are different from the required name. Automatically stripping or lowercasing them would expand the accepted format. That may be a reasonable product feature later, but it should have a named rule, explicit examples, and a considered effect on duplicate detection.
CSV quoting is syntax rather than part of a parsed header’s value. A quoted header cell containing exactly sku is acceptable. This is a useful positive test because strict application validation does not require a single textual spelling of every valid file. The contract constrains the parsed values where stated and the input bytes where stated; keep those levels distinct.
Check every data record’s width before unpacking fields. A1,2, contains a legitimate empty third field. A1,2 lacks that field, while A1,2,, has an extra one. Counting commas cannot distinguish these reliably once quoted commas are allowed. Validate the parser’s resulting field sequence instead.
A plain reader is convenient here because the application wants to inspect structure explicitly. Python’s DictReader accommodates extra or missing fields rather than enforcing this schema for you. That behavior can serve other workflows, but this importer must reject structural mismatches. Blank records are rejected as well; silently skipping them would create another undocumented exception that changes record numbering.
6. Separate textual grammar from value conversion
Use a full-field SKU match against [A-Z][A-Z0-9-]{0,15}. That states the allowed alphabet and total length together. A search for a matching substring would be insufficient: a field could contain a valid-looking identifier surrounded by disallowed text. Test a one-character SKU, a maximum-length SKU, lowercase letters, an underscore, an empty string, and a visually similar non-ASCII letter.
Quantity validation needs two stages: verify the accepted text, then convert it to an integer. The grammar (?:0|[1-9][0-9]{0,3}) expresses this example’s whole domain. Calling int first would admit spellings the contract excludes, such as a plus sign, surrounding spaces, some Unicode digits, or underscores. The numerical result alone cannot tell you how the input was written.
ASCII digit classes are deliberate. A shorthand such as \d has broader Unicode behavior in ordinary Python string patterns. If an integration identifies a quantity as an ASCII decimal token, spell that requirement with [0-9]. Conversely, if a future application wants localized input, it needs a clear conversion policy and tests for that policy rather than an accidental side effect of a regular expression.
The note has a different role. It is free text, so this contract preserves spaces, punctuation, and embedded newlines, subject to the shared NUL prohibition and a 200-code-point limit. Empty quoted and unquoted notes become the same empty string. Quoted commas and doubled quotes become their intended text values. None of those cases authorizes trimming, title-casing, or normalizing the content.
A code-point limit is easy to test but is not a count of visible symbols. Combining characters and multi-code-point emoji can make that difference noticeable. Explain the unit in a user-facing error instead of saying only “200 characters” when precision matters. The Unicode-handling guide explores normalization choices; this import intentionally leaves them to a separate, explicit operation.
7. Distinguish logical records from physical lines
Diagnostics should help a person locate the failing input without claiming more precision than the parser supplies. Use a stable error code for software and a short explanation for people. Where available, include the logical record number and the physical line reached while parsing it. Here the header is logical record one, so the first data record is logical record two. Keep that convention consistent across returned rows, exceptions, and the interface displaying them.
In the example, imagine the header occupies physical line one and the first data record starts on line two. Its quoted note contains a newline, so the same record finishes on line three. The following data record begins on line four. Reporting only “row three” is ambiguous: the person might look at the wrong spreadsheet row or the wrong line in a text editor.

The reader’s line_num reports source-line progress, which can differ from the number of returned records. Capture that information after successful parsing for structural or value errors. For a CSV syntax error, the current line indicates how far the parser got; it is not a guaranteed exact offending byte position. Encoding failures occur earlier and may have no meaningful parsed-record location.
Avoid making the complete parser exception string part of your application’s public contract. Wording can vary with interpreter behavior, and raw values may be unsuitable for logs. A stable category such as a header, width, quantity, or syntax failure lets callers decide what to display. Detailed diagnostics can remain available in a controlled development context without becoming a compatibility dependency.
The lab reports the first detected failure according to its validation order. A file containing both an invalid quantity and a duplicate SKU can therefore report the quantity problem first. Document that behavior rather than promising a complete error inventory. Fixing one issue may reveal another on the next attempt, and users should understand why a second submission can fail differently.
If your product needs a downloadable report containing many errors at once, treat that as additional design work. Decide which failures allow safe continuation and how a syntax error affects later record boundaries. Set limits on report size and avoid echoing unrestricted input into messages. The small fail-fast function here gives you a clear baseline from which to make those choices deliberately.
8. Keep accepted rows private until the whole file passes
Duplicate detection requires file-wide state. Track every accepted SKU in a private set while collecting candidate rows. A repeated SKU fails even if its quantity and note match the earlier record. The importer neither overwrites the earlier value nor merges quantities. Repetition is a contract violation, and making it visible is more predictable than selecting a winner.
The most revealing test places a duplicate near the end after several valid rows. If the function yields rows as it reads them, a caller might already have acted on the early records before the duplicate is discovered. Collecting privately and returning only after end-of-file avoids that exposure at this boundary. It also makes an unterminated final quoted note reject the whole import.
Return an immutable collection of immutable row values. That gives downstream code a stable validated snapshot rather than a mutable list it can accidentally alter in place. Immutability does not make the data safe for every future use, but it preserves the result of this validation step and makes tests easier to reason about.
This is an all-or-nothing function result, not a database transaction. A later caller still needs its own storage transaction, uniqueness checks against existing records, authorization, and failure handling. In-file uniqueness says nothing about conflicts with a live inventory database. Keeping those responsibilities separate prevents a small parser from being described as a complete import system.
9. Read and run the standard-library lab
The implementation below makes the acceptance boundary visible in one place. Read its constants alongside the contract before trying the fixtures. Notice where decoding finishes, where parser errors are translated, and where the final collection becomes available. An error path should never return the candidate rows accumulated so far, even when every earlier record was valid.
"""Bounded CSV validation example. No database, network, or file writes."""
from __future__ import annotations
import csv
import hashlib
import io
import re
from dataclasses import dataclass
MAX_BYTES = 65_536
MAX_ROWS = 500
MAX_NOTE_CHARS = 200
HEADERS = ("sku", "quantity", "note")
SKU = re.compile(r"[A-Z][A-Z0-9-]{0,15}")
QUANTITY = re.compile(r"(?:0|[1-9][0-9]{0,3})")
class ImportRejected(ValueError):
"""A stable error code, with location when the parser supplies one."""
def __init__(self, code: str, record: int | None = None,
end_line: int | None = None):
self.code = code
self.record = record
self.end_line = end_line
where = "" if record is None else f" at record {record}, end line {end_line}"
super().__init__(code + where)
@dataclass(frozen=True)
class StockRow:
sku: str
quantity: int
note: str
record: int
end_line: int
@dataclass(frozen=True)
class ValidatedImport:
sha256: str
rows: tuple[StockRow, ...]
def parse_import(data: bytes) -> ValidatedImport:
"""Validate a complete supplied byte string or raise ImportRejected.
Accepts the selected CPython csv dialect, not full RFC 4180 conformance.
The caller must separately bound upload reads before constructing data.
"""
if type(data) is not bytes:
raise TypeError("data must be bytes")
if len(data) > MAX_BYTES:
raise ImportRejected("file_too_large")
try:
text = data.decode("utf-8-sig", errors="strict")
except UnicodeDecodeError as exc:
raise ImportRejected("invalid_utf8") from exc
if "\x00" in text:
raise ImportRejected("nul_character")
rows: list[StockRow] = []
seen: set[str] = set()
with io.StringIO(text, newline="") as source:
reader = csv.reader(source, delimiter=",", quotechar='"',
doublequote=True, skipinitialspace=False,
strict=True)
record = 1
try:
header = next(reader, None)
if header is None:
raise ImportRejected("missing_header")
if len(set(header)) != len(header):
raise ImportRejected("duplicate_header", 1, reader.line_num)
if tuple(header) != HEADERS:
raise ImportRejected("unexpected_header", 1, reader.line_num)
record = 2
for fields in reader:
line = reader.line_num
if len(rows) >= MAX_ROWS:
raise ImportRejected("too_many_rows", record, line)
if len(fields) != len(HEADERS):
raise ImportRejected("row_width", record, line)
sku, quantity, note = fields
if SKU.fullmatch(sku) is None:
raise ImportRejected("invalid_sku", record, line)
if QUANTITY.fullmatch(quantity) is None:
raise ImportRejected("invalid_quantity", record, line)
if len(note) > MAX_NOTE_CHARS:
raise ImportRejected("note_too_long", record, line)
if sku in seen:
raise ImportRejected("duplicate_sku", record, line)
seen.add(sku)
rows.append(StockRow(sku, int(quantity), note, record, line))
record += 1
except csv.Error as exc:
raise ImportRejected("csv_syntax", record, reader.line_num) from exc
if not rows:
raise ImportRejected("no_data_rows")
return ValidatedImport(hashlib.sha256(data).hexdigest(), tuple(rows))
The returned ValidatedImport contains a SHA-256 receipt and a tuple of StockRow values. Each row carries its SKU, integer quantity, preserved note, logical record number, and physical end line. Callers can use that provenance when showing a preview. If validation raises ImportRejected, its code and optional location describe the failure without exposing a partially accepted result.
The core implementation leaves csv.field_size_limit untouched. Changing a shared parser limit for one import and restoring it afterward can still affect other readers during the change. The byte ceiling bounds the supplied file, and the application separately checks its fields. An unusually low ambient parser limit can still reject an input; that is a configuration issue to surface, not a reason to modify shared state inside this function.
Keep expectations about memory precise. A 65,536-byte input ceiling does not imply a 65,536-byte process-memory ceiling. Decoded text, parser allocations, Python objects, and the final rows also consume memory. An upload endpoint additionally needs its own request limits and operational protections. The lab makes a small deterministic boundary testable without claiming to cover those surrounding systems.
The demonstration should show both acceptance and failure without writing to a destination. Its receipt can include a hash of the exact supplied bytes, making two differently encoded submissions distinguishable even if their parsed rows match. That fingerprint supports repeatable diagnostics; it does not authenticate the sender, establish authorization, or prove that the contents are trustworthy.
Download the complete CSV import validation lab (ZIP). It includes the validator, demonstration, author tests, independent tests and checksum manifest. Save the files in one directory, then run python3 -m unittest discover -v and python3 demo.py. The supplied examples were checked on Linux with CPython 3.12.14 and 3.13.5; no other operating-system runtime is claimed.
from csv_import_lab import ImportRejected, parse_import
sample = ('sku,quantity,note\r\n'
'P-1,2,"first line\r\nsecond line"\r\n'
'Q-2,0,"shelf, west"\r\n').encode("utf-8")
result = parse_import(sample)
for row in result.rows:
print(row.sku, row.quantity, repr(row.note), row.record, row.end_line)
print("Accepted:", len(result.rows), "data records")
try:
parse_import(sample + b"P-1,5,duplicate\r\n")
except ImportRejected as error:
print("Rejected:", error.code, error.record, error.end_line)
10. Work through four practical import cases
Case A: A valid note contains punctuation and a newline
Start with the exact header and a single record whose note contains a comma, a doubled quote, and an embedded newline. Predict the resulting note before running the lab. Check that the comma does not add a field, the doubled quote becomes one quote, and the newline stays in the note. Then inspect the diagnostic line counter separately from the accepted row count.
sku,quantity,note
A1,2,"Shelf A, bin ""blue""
Handle carefully"
Repeat the case with an empty note and with a note consisting only of spaces. Both are allowed within the length limit, but they produce different values. This small comparison guards against an eager cleanup step that turns all apparently blank text into the same value. The test should compare the complete resulting strings rather than merely checking that parsing succeeds.
Case B: An export changes the header
Imagine a supplier reorders columns to quantity,sku,note. The file is readable CSV, yet it violates the agreed structure. Reject it before interpreting any quantities or identifiers. Next try sku,quantity,quantity to expose the duplicate-header rule. These cases help a team decide whether to update the supplier export or deliberately introduce a new supported schema version.
Case C: A file contains damaged UTF-8
Construct the failing fixture as bytes so the test does not accidentally repair it while saving a text file. Include an incomplete multibyte sequence after otherwise plausible content. Expect an encoding failure before any result is available. Compare that with a valid UTF-8 file containing an optional initial signature. They exercise different outcomes and should not be collapsed into one generic “encoding issue” test.
Case D: The final record invalidates the file
Create two distinct valid SKUs, then add a final record repeating the first. Expect the entire call to fail and no return value to be assigned. Repeat with malformed quoting at the end instead of a duplicate. These examples target different layers while protecting the same public promise: callers receive a complete accepted import or an error.
For each case, keep three artifacts together: the exact fixture bytes, the predicted outcome, and the actual test result. If the result differs, investigate the contract and implementation before changing either. A passing test whose expected value was copied uncritically from a model is weak evidence. Reviewers should be able to explain the outcome directly from the published rules.
For a user-facing preview, show how many data records passed and which contract version was applied, if your application versions its format. Avoid an “import complete” message at this stage when storage has not happened. A later commit step may still fail because of permissions, existing inventory conflicts, or concurrent updates. Accurate status wording prevents people from mistaking validation for a completed operational change.
11. Build a test matrix that covers both sides
Organize tests by the decision they establish: input size, decoding, parser behavior, header shape, record width, field grammar, file-wide uniqueness, and return behavior. Include accepted cases in every relevant group. A function that rejects every input would pass a rejection-only suite. Positive examples are necessary evidence that legitimate imports remain usable.
Exercise the exact limits and their nearest neighbors. For this contract, that includes zero, one, 500, and 501 data records; 16- and 17-character SKUs; quantities zero, 9999, and an excluded spelling or value; and notes of 200 and 201 code points. Test exactly 65,536 bytes and one byte more with fixtures whose construction makes the intended boundary obvious.
Some limits interact. A file with 500 long notes may exceed the byte cap before the row limit becomes the deciding rule. Keep boundary fixtures otherwise valid and small enough to isolate their target. For the byte-limit case, calculate the full encoded length including the header, delimiters, line endings, and any signature. Record that length in the test instead of estimating from visible text.
Exercise LF, CRLF, and CR record endings, optional final termination, quoted headers, commas inside notes, and multiline notes. Add the intentionally accepted unescaped quote in an unquoted note to document the selected parser behavior. Then distinguish that from malformed text after a closing quoted field. These cases make the dialect a tested choice rather than a vague claim of universal strictness.
As an exercise, ask a colleague to add a harmless-looking strip() before quantity validation and predict which test should fail. Try a version that silently ignores blank records, or stores results in a dictionary keyed by SKU without checking repetition first. Do these experiments in a disposable copy. Their purpose is to check whether the suite detects changed behavior, not to introduce those changes into the validator.
Another useful exercise compares two files with identical parsed rows but different accepted line endings. Their row values can agree while their byte receipts differ. Explain which comparison answers a support question about resubmitting the exact same file and which answers a question about equivalent inventory values. This distinction keeps the receipt from becoming an accidental business-level duplicate detector.
The accompanying execution report records 64 unique test methods for the supplied lab across the documented Linux CPython 3.12 and 3.13 normal and optimized runs. Use that report for the exact evidence; test counts alone are not coverage guarantees. Running under optimization is useful because input validation must not depend on assertions that can be removed. No DeepSeek model or API benchmark is implied by these local Python checks.
12. Review DeepSeek suggestions as proposals
Once the deterministic tests exist, a second model review can be more focused. Supply the contract, implementation, and a concise inventory of covered decisions. Ask which specific promise lacks evidence and what smallest input would expose the gap. You can use the synthetic test-data guide to keep fixtures purposeful and separate their origin from their validation status.
Require the suggestion to name a clause rather than just call an input “bad CSV.” A proposal to reject every quote inside an unquoted note conflicts with this article’s explicitly selected parser behavior. That could motivate a future specification discussion, but it is not automatically a bug in the current implementation. Distinguishing a defect from a proposed policy change prevents reviews from drifting.
This second original prompt is also unexecuted. It is designed to produce reviewable hypotheses, with no implied claim about a particular DeepSeek model’s accuracy or execution capabilities.
Review the validator and tests against this exact contract.
Do not broaden or tighten the accepted dialect without labeling it
as a proposed contract change.
Return at most five findings. For each, state:
- Contract clause and suspected implementation path.
- Minimal synthetic fixture with exact bytes where encoding matters.
- Expected outcome, including whether location information is available.
- A focused test that would confirm or disprove the concern.
Separate defects, missing tests, and proposed policy changes.
State uncertainty. Do not claim that suggested tests were executed.
If you later automate review through DeepSeek’s Chat Completions API, its JSON Output guide specifies response_format={"type":"json_object"}, an explicit instruction containing “json,” and an example of the desired format. Allocate enough output tokens, and handle empty, truncated, or structurally invalid reports as review failures. Validate the report’s fields before using them. Valid JSON does not establish that a finding is correct or decide whether a CSV import passes. This optional integration was not executed for the article; the supplied lab makes no API calls.
Inspect suggested tests before running them, particularly if the model includes setup commands or extra dependencies. This lab needs only the standard library. A CSV fixture should not require executing a downloaded script, contacting a service, or reading unrelated local files. Keep the review environment small enough that a surprising suggestion is easy to notice.
When a useful case fails, fix the narrow cause and rerun the full suite. When it passes, retain it if it documents an important boundary without needless duplication. When the expected result is wrong, record the correction in the review rather than bending the validator to satisfy an authoritative-sounding explanation. The lasting deliverable is executable evidence tied to the contract.
13. Know what acceptance does not establish
An accepted note can begin with a spreadsheet formula marker. This validator treats the note as text and does not export it. CSV quoting, a typed quantity, and successful import validation do not establish safety when the value later reaches spreadsheet software. A spreadsheet-export feature needs its own consumer-specific handling and tests at that separate boundary.
Likewise, preserved note text still requires appropriate treatment in HTML pages, logs, database operations, and other destinations. A field being acceptable business data does not remove the rules of the system that later consumes it. Avoid attaching a universal “sanitized” label to returned rows; describe which checks actually passed and keep destination-specific handling explicit.
Before adding this boundary to a real product, decide who can submit files, how request size is bounded, where errors are displayed, and whether rejected content is retained. Confirm how accepted imports interact with existing inventory and concurrent updates. Those decisions belong to the surrounding application and cannot be inferred from the three-column fixture format.
When requirements change, resist adding automatic retries through progressively looser interpretations. Trying another encoding, dropping an extra column, or ignoring a duplicate after the first rejection creates a second undocumented contract. Prefer an explicit new format version or a separate conversion step that produces a reviewable replacement file. That lets the submitter see which interpretation will actually be used.
A useful release review asks whether each acceptance rule has an example, each rejection rule has a focused test, and each reported limitation is still accurate. Revisit the contract when a supplier changes its export or the supported runtime changes. Keep the exact fixtures under version control so the team can compare behavior rather than relying on remembered screenshots or a model’s explanation.
The repeatable workflow is straightforward: state the rules, use DeepSeek to challenge them, implement deterministic checks, and verify the outcomes locally. At the end, you should be able to explain why each file was accepted or rejected without appealing to model confidence. That is the practical foundation for a CSV import people can debug and maintain.
Sources & References
- Python 3.13 CSV documentation: reader configuration, dictionary-reader behavior, physical-line counters, and parser limits.
- Python UTF-8-SIG codec documentation: optional initial signature handling and decoding policy.
- Python StringIO documentation: in-memory text streams and newline handling.
- Python regular-expression documentation: whole-field matching and Unicode character classes.
- Python integer-conversion documentation: accepted textual forms for integer conversion.
- RFC 4180: informational description of a common CSV format.
- CPython 3.13.5 CSV parser source: implementation context for the dialect behavior discussed here.
- DeepSeek JSON Output guide: optional structured-review configuration and output caveats.

[…] source is tabular rather than object-based, the same separation of concerns appears in our guide to CSV import validation with DeepSeek. The framing details differ, so do not transfer CSV assumptions about quoted multiline fields into […]