Skip to content
Recommended solution · HC-3 · Rust

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

  1. 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.
  2. Say what breaks and which rule it breaks before you ask for a fix.
  3. Ask for your own tests first, naming each case with the result the rules expect, and press Test to watch them fail.
  4. Name the failing test, then say how each fix should work and point to the rule it enforces.
  5. Press Test again after the last change, then Submit.
Stage 1 · csv-import-review

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

Fields and columnsRFC 4180 within a line: a quoted field may hold commas and doubled quotes. Columns are found by header name in any order, and a missing one is MissingColumn.
Names and linesA name is cut to 20 characters, not bytes. A line longer than the cap ends the import with LineTooLong, and no more than one line is ever buffered.
Numbers and SKUsQuantity 1 to 1,000,000 and price 0 to 100,000,000 cents, with an exact total. A repeated SKU rejects the later row.
Counts and the reportEvery data line is counted once as imported or rejected, and the report quotes fields so it imports again with the same summary.

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

  1. Split fields with a small state machine over the characters, and map the four columns from the header once, by name.
  2. Truncate names by characters, and read each line through a reader capped just above the limit, so an endless line stops at the cap.
  3. Parse quantity and price into 64-bit integers with range checks that return a rejection reason, and keep a set of seen SKUs.
  4. 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

  1. Your message 1

    Before changing anything I want to know what the importer does with inputs the six tests never use. Read src/lib.rs, src/parse.rs and src/validate.rs and src/report.rs and tell me, without editing: (1) what split_fields returns for "Widget, large",SKU-1,2,100 and for "The ""Best"" Mug",SKU-2,1,500; (2) import drops the header line and validate_row reads fields by fixed position: what happens with the header sku,unit_price_cents,name,quantity, with an extra category column, and with no unit_price_cents column; (3) what &name[..options.name_max_chars] does with Café au lait grand cru and with 抹茶ラテ用パウダー缶入り; (4) what next_line does with a line that never ends, and whether max_line_bytes is read anywhere; (5) what parse::<u32>().unwrap() does with two or -3 and what 1000000 * 100000000 is in u32; (6) what happens to a second SKU-1 row, how imported and rejected move when a row is rejected, and what write_record does with a name containing a comma.

    Point at each function with the input that breaks it: the questions name every hazard before any fix is asked for.

    • Direction: Diagnosis: parsing, 4 points
    • Direction: Diagnosis: robustness, 4 points
    • Direction: Diagnosis: validation, 4 points
    • Direction: Diagnosis: accounting, 4 points
    • Direction: Hostile inputs, 4 points
    • Direction: Targeted review, 5 points
  2. Your message 2

    So all eight break the task's rules. The rules say fields are RFC 4180 within a line, but split_fields splits on every comma and strips quotes, and the header is dropped so reordered, extra or missing columns are misread. The rules say characters, not bytes, but the byte slice cuts Café and panics on 抹茶; the rules say never buffer more than one line, but read_line has no cap. The rules say quantity is 1 to 1,000,000 with an exact total, but unwrap panics on two and the u32 product overflows; the rules say a repeated SKU rejects the later row, but it replaces the first. The rules say imported + rejected equals the data lines, but imported counts every line and rejected never moves; and the report never quotes, so a comma name does not re-import. Before any change to the importer, write tests in src/candidate_tests.rs, one per case, using import with a Cursor and Options: "Widget, large",SKU-1,2,100 imports one row with total_cents 200; "The ""Best"" Mug",SKU-2,1,500 imports with the name The "Best" Mug in the report; header sku,unit_price_cents,name,quantity with SKU-1,250,Mug,3 gives total_cents 750; header name,sku,quantity is Err(MissingColumn("unit_price_cents")); Café au lait grand cru is written as Café au lait grand c; 抹茶ラテ用パウダー缶入り stays whole; with max_line_bytes 64 a 65-byte data line is Err(LineTooLong { line: 2 }); quantity two and quantity -3 are each a rejection on line 2; quantity 0 and 1000001 are rejected; 1000000 × 100000000 totals exactly 100000000000000; a second SKU-1 on line 3 is rejected with line 3 and the first kept; header, Mug,SKU-1,2,350, a blank-name row and Plate,SKU-3,4,1250 give imported 2, rejected 1, rejections[0].line 3; and a report of "Widget, large" imported again gives the same summary. Don't change src/lib.rs, parse.rs, validate.rs or report.rs yet.

    Say which rule each hazard breaks, then choose the test cases yourself, each with the result the rules expect.

    • Verification: Named cases: parsing, 3 points
    • Verification: Named cases: robustness, 3 points
    • Verification: Named cases: validation, 3 points
    • Verification: Named cases: accounting, 3 points
  3. 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
  4. Your message 3

    Test fails at challenge::candidate_tests::tests::doubled_quotes_become_literal_quotes: assertion `left == right` failed Now fix the parser and the line handling, keeping the functions and the public API: (1) split_fields becomes quote-aware, a small state machine over the characters: a quote at the start of a field opens it, "" inside quotes is one literal quote, a comma inside quotes is data. (2) Build the column positions once from the header by name, in any order, extra columns ignored, MissingColumn(<name>) for a missing one, and pass them to validate_row instead of the NAME..UNIT_PRICE_CENTS constants, which go. (3) The rules say characters: truncate the name with chars().take(name_max_chars). (4) The rules say never buffer more than one line: next_line reads through take(max_line_bytes + 2) with read_until(b'\n'), strips the line ending, and returns LineTooLong { line } when the content is longer than max_line_bytes, so a line that never ends stops at the cap. Don't change the tests.

    Name the failing test, then say how each fix works and which rule it enforces.

    • Prompt quality: Specified fix: parsing, 3 points
    • Prompt quality: Specified fix: robustness, 3 points
    • Prompt quality: Contract cited, 4 points
    • Prompt quality: Failure follow-up, 4 points
  5. Press Test. The doubled-quote test still fails: it reads the report, which only quotes once the last fix lands.
  6. Your message 4

    Test fails at challenge::candidate_tests::tests::doubled_quotes_become_literal_quotes: assertion `left == right` failed Now validation and accounting. (1) The rules say quantity 1 to 1,000,000 and price 0 to 100,000,000 with an exact total: parse both into u64 without unwrap, each out-of-range or non-numeric value an Err(reason) that becomes a rejection on its line, and the row total and total_cents in u64. (2) The rules say a repeated SKU rejects the later row: keep a HashSet of seen SKUs in import, reject the second with its line and keep the first. (3) The rules say imported + rejected equals the data lines read: count in one place after the checks, rejected += 1 for every rejection and imported += 1 only for an accepted row. (4) The report must re-import: quote a field that contains a comma, a quote or a line break, doubling the quotes inside. No catch_unwind, no unwrap or expect on input, no default values. Don't change the tests.

    The second half of the fixes, each tied to its rule, and no panic, catch or default for bad input.

    • Prompt quality: Specified fix: validation, 3 points
    • Prompt quality: Specified fix: accounting, 3 points
  7. Press Test. All 21 tests pass after the last change, your 15 included.
    • Verification: Run after last change, 5 points
  8. 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.

Direction30/30
Prompt quality20/20
Verification20/20
Correctness20/20
Code quality10/10
Stage total 100/100Grade S
CSV Import Review Solution — Rust Walkthrough | Hunicode