CSV Import Review
A review-and-harden task on a small Rust crate: an assistant generated a CSV product importer and six tests, and the tests pass. Eight hazards hide in four families (parsing, robustness, validation, accounting), and nothing fails until you try the inputs the tests never use.
On this page
The codebase
The crate imports a product export: it reads a header and data lines from any BufRead, validates every row against the task's rules, writes the accepted rows to a report and returns a summary of what was imported and rejected.
The six visible tests use clean input only, so they pass on the shipped code. Verification after Submit adds 23 hidden tests, one file per family.
The assistant explains the code and Rust on request and makes the changes you direct, but it does not audit the crate for you and volunteers no defect.
Where things live
src/lib.rsimport: the reading loop, the counters and the duplicate check. The public types and the signature of import are fixed.src/parse.rsThe line reader, the header and the field splitter.src/validate.rsChecks one row against the rules and normalises it.src/report.rsWrites the accepted rows back as CSV.src/candidate_tests.rsYour tests. Test runs them after the visible tests in tests/, which are read-only.Rules that shape every fix
- Fix the crate in place: no rewrite, no new crate, the public API and the supplied tests unchanged.
- Rust standard library only.
- Bad input becomes a rejection with its line and a reason, never a panic.
How to work the review
- Read each module against the task's rules and ask what it does with inputs the tests never use: quoted fields, reordered columns, accented names, a line that never ends, bad numbers, a repeated SKU, a bad row among good ones.
- Say what breaks and which rule it breaks before you ask for a fix.
- Ask for your own tests first, naming each case with the result the rules expect, and press Test to watch them fail.
- Name the failing test, then say how each fix should work and point to the rule it enforces.
- Press Test again after the last change, then Submit.
Review the generated importer
What the ticket asks
An assistant generated a CSV product importer from the task's rules and wrote six tests for it, and they pass. Review the crate before it ships: fix, in src/, whatever does not meet the rules or would misbehave on real exports.
Keep the public API and the supplied tests as they are. The assistant explains code and makes the changes you direct, but it will not find the defects for you.
Where to look
src/parse.rsThe field splitter and the line reader: check them against the quoting rule and the one-line buffering rule.src/lib.rsimport drops the header line, counts every line before validation and replaces a repeated SKU. Read the loop against the counting rule.src/validate.rsReads fields by fixed position, cuts the name with a byte slice and unwraps the quantity.src/report.rsJoins fields with commas and never quotes: a report with a comma in a name does not import again.What the rules pin down
MissingColumn.LineTooLong, and no more than one line is ever buffered.Where the generated crate goes wrong
- The splitter splits on every comma and strips quotes, and the header is dropped while fields are read by position, so quoted names and reordered, extra or missing columns are misread.
- The name is cut with a byte slice, which cuts accented text short and panics on Japanese text, and the line reader has no cap, so a line that never ends grows without bound.
- The quantity is unwrapped and multiplied in 32 bits, so a word or a negative number panics and a large order overflows, and a repeated SKU silently replaces the first row.
- The imported counter moves before validation and the rejected one never moves, and the report never quotes, so a comma in a name breaks the round trip.
The fix
- Split fields with a small state machine over the characters, and map the four columns from the header once, by name.
- Truncate names by characters, and read each line through a reader capped just above the limit, so an endless line stops at the cap.
- Parse quantity and price into 64-bit integers with range checks that return a rejection reason, and keep a set of seen SKUs.
- Count each line once after its checks, and quote report fields that contain a comma, a quote or a line break.
src/parse.rsA quote-aware splitter: a quote opens a field, a doubled quote inside it is one quote, a comma inside it is data.-pub fn split_fields(line: &str) -> Vec<String> {- line.split(',')- .map(|field| field.trim().trim_matches('"').to_string())- .collect()+pub fn split_fields(line: &str) -> Vec<String> {+ let mut fields = vec![String::new()];+ let mut quoted = false;+ let mut chars = line.chars().peekable();+ while let Some(c) = chars.next() {+ let field = fields.last_mut().expect("there is always a current field");+ match c {+ '"' if quoted && chars.peek() == Some(&'"') => {+ field.push('"');+ chars.next();+ }+ '"' if quoted => quoted = false,+ '"' if field.is_empty() => quoted = true,+ ',' if !quoted => fields.push(String::new()),+ c => field.push(c),+ }+ }+ fields }src/parse.rsThe line reader reads at most the cap plus its line ending, then refuses a longer line.- let mut line = String::new();- if self.input.read_line(&mut line)? == 0 {+ let limit = (self.max_line_bytes as u64).saturating_add(2);+ let mut line = Vec::new();+ if (&mut self.input).take(limit).read_until(b'\n', &mut line)? == 0 { return Ok(None); }+ if line.len() > self.max_line_bytes {+ return Err(ImportError::LineTooLong { line: self.line_number });+ }src/validate.rsNames are cut by characters; numbers are parsed into 64-bit integers and range-checked into rejection reasons.- let name = if name.len() > options.name_max_chars {- &name[..options.name_max_chars]- } else {- name- };+ let name: String = name.chars().take(options.name_max_chars).collect();- let quantity = fields[QUANTITY].trim().parse::<u32>().unwrap();+ let quantity = parse_in_range("quantity", &fields[columns.quantity], 1, MAX_QUANTITY)?;+ let unit_price_cents = parse_in_range("unit_price_cents", &fields[columns.unit_price_cents], 0, MAX_UNIT_PRICE_CENTS)?;src/report.rsReport fields are quoted as RFC 4180 requires, so the report imports again unchanged. fn write_record(&mut self, fields: &[&str]) -> io::Result<()> {- writeln!(self.out, "{}", fields.join(","))+ let quoted: Vec<String> = fields.iter().map(|field| quote_field(field)).collect();+ writeln!(self.out, "{}", quoted.join(",")) }+fn quote_field(field: &str) -> String {+ if field.contains([',', '"', '\r', '\n']) {+ format!("\"{}\"", field.replace('"', "\"\""))+ } else {+ field.to_string()+ }+}Tests that prove it
- A quoted name with a comma, a name with doubled quotes, reordered columns and a missing column.
- An accented name cut at 20 characters, a Japanese name kept whole, and a line over the cap ending the import on its line number.
- A word, a negative, zero and an out-of-range quantity each rejected on their line, the largest exact total, and a repeated SKU rejected with the first kept.
- One bad row among good ones counted once, and a report with a comma in a name imported again to the same summary.
The conversation
Only your side is shown: the assistant reads, writes and runs between your messages. Each chip is a rubric item the step earns.
DirectionPrompt qualityVerificationCorrectnessCode quality
- Press Test. Your own tests run after the six visible ones, and the first of them fails on the shipped code.
- Verification: Checks own, 3 points
- Press Test. The doubled-quote test still fails: it reads the report, which only quotes once the last fix lands.
- Press Test. All 21 tests pass after the last change, your 15 included.
- Verification: Run after last change, 5 points
- Submit. The stage closes. Scope, the 23 hidden tests and code quality are judged on the final code.
- Direction: Scope, 5 points
- Correctness: Hidden tests, 20 points
- Code quality: Code quality, 10 points
Where the stage lands
Measured when this conversation was played on the platform. A+ needs 92, S needs 95.