Skip to content
Recommended solution · HC-4 · Rust

Order Ledger Review

A review-and-harden task on a small Rust money ledger: an assistant generated it, with orders, discounts, refunds and a running total, and its six tests pass. Eight hazards hide in four families (money, validation, errors, accounting), and nothing fails until you try the orders and refunds the tests never use.

On this page

The codebase

The ledger records orders and refunds in integer cents: it prices each line, applies the order's discount, keeps a running total, and applies refunds against an order's balance.

The six visible tests use clean orders only, so they pass on the shipped code. Verification after Submit adds the 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.rsThe public types, the Ledger and its errors. The signatures are fixed.
src/money.rsPrice text into cents, a line's amount and the order's discount.
src/validate.rsThe limits on a line, an order and a refund.
src/ledger.rsStores orders and refund ids, applies refunds, keeps the running total.
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.
  • A rejected order or refund changes nothing, and no input panics.

How to work the review

  1. Read each module against the task's rules and ask what it does with the orders and refunds the tests never use: a discount that rounds, a huge line, a zero or negative value, a malformed price, a refund above the balance, a repeated id.
  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 · order-ledger-review

Review the generated ledger

What the ticket asks

An assistant generated an order ledger 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 orders.

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/money.rsPrice text into cents, a line's amount and the discount: check them against the rounding and exactness rules.
src/validate.rsOnly the upper limits are checked, and the discount not at all.
src/ledger.rsWhen the running total moves, what a refund is compared with, and whether a refund id is remembered.
src/lib.rsThe errors each rule names, and the signatures you must keep.

What the rules pin down

MoneyAll amounts are integer cents. A line's amount is exact, and the discount is rounded half-up once per order, not per line.
LimitsQuantity 1 to 1,000,000, a price of 0 to 1,000,000.00, a discount up to 10,000 basis points, and a refund of at most the order's balance.
ErrorsA price text is digits with an optional sign and two decimals, nothing else, and no input panics.
The running totalA rejected order or refund changes nothing, the total adds each order's total after its discount, and a refund id applies once.

Where the generated crate goes wrong

  • The discount is rounded per line in floating-point dollars, and a line's amount is multiplied in 32 bits with unchecked sums, so totals drift by a cent and large orders overflow.
  • Only the upper limits are checked and the discount is never checked, and a refund is compared with the order's total instead of its balance.
  • The price parse unwraps a floating-point parse, so a comma or a word panics and an exponent is accepted, and a refund changes the running total before its order is found.
  • An order changes the running total before it is validated and adds its subtotal, not its total, and refund ids are never stored, so the same refund applies twice.

The fix

  1. Round the discount once per order on the integer subtotal, half-up, and keep every amount in 64-bit integers with checked arithmetic.
  2. Parse price text by hand into cents and reject anything outside the format, without a panic.
  3. Check both limits on every value and compare a refund with the balance.
  4. Change the running total only once an order or a refund is accepted, add the total after the discount, and remember applied refund ids.
src/money.rsThe discount is rounded once per order, half-up, in integer cents, without leaving 64 bits.
-pub fn discount_cents(line_amounts: &[i64], discount_bps: u32) -> i64 {-    let rate = f64::from(discount_bps) / 10_000.0;-    line_amounts-        .iter()-        .map(|&cents| {-            let line_discount = cents as f64 / 100.0 * rate;-            (line_discount * 100.0).round() as i64-        })-        .sum()+pub fn discount_cents(subtotal_cents: i64, discount_bps: u32) -> Result<i64, LedgerError> {+    let bps = i64::from(discount_bps);+    let (blocks, remainder) = (subtotal_cents / 10_000, subtotal_cents % 10_000);+    blocks+        .checked_mul(bps)+        .and_then(|whole| whole.checked_add((remainder * bps + 5_000) / 10_000))+        .ok_or(LedgerError::Overflow) }
src/money.rsPrice text is parsed digit by digit into cents; anything else is an invalid price.
-    let value: f64 = text.trim().parse().unwrap();-    let cents = (value * 100.0).round();+    let (whole, fraction) = unsigned.split_once('.').unwrap_or((unsigned, "00"));+    let digits = |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());+    if !digits(whole) || fraction.len() != 2 || !digits(fraction) {+        return Err(malformed());+    }+    let mut cents: i64 = 0;+    for byte in whole.bytes().chain(fraction.bytes()) {+        cents = cents+            .checked_mul(10)+            .and_then(|cents| cents.checked_add(i64::from(byte - b'0')))+            .ok_or(LedgerError::Overflow)?;+    }
src/ledger.rsAn order is checked first and adds its total after the discount only once it is accepted.
-        let subtotal_cents: i64 = line_amounts.iter().sum();-        self.total_cents += subtotal_cents;-+        if self.orders.contains_key(&order.id) {+            return Err(LedgerError::DuplicateOrder(order.id));+        }         validate::order(&order)?;+        let discount_cents = money::discount_cents(subtotal_cents, order.discount_bps)?;+        let total_cents = subtotal_cents - discount_cents;+        let ledger_total = self.total_cents.checked_add(total_cents).ok_or(LedgerError::Overflow)?;+        self.orders.insert(order.id, summary.clone());+        self.total_cents = ledger_total;
src/ledger.rsA refund is checked against the balance and its id first; the total moves only when it is accepted.
+        if self.refund_ids.contains(&refund.id) {+            return Err(LedgerError::DuplicateRefund(refund.id));+        }         validate::refund_amount(refund.amount_cents)?;-        self.total_cents -= refund.amount_cents;-        if refund.amount_cents > summary.total_cents {+        let available_cents = summary.total_cents - summary.refunded_cents;+        if refund.amount_cents > available_cents {         summary.refunded_cents += refund.amount_cents;+        self.total_cents -= refund.amount_cents;+        self.refund_ids.insert(refund.id);

Tests that prove it

  • Three lines of 1.00 at 3,333 basis points, and the largest exact line.
  • A price with a comma, an exponent and a sign, through the ledger and through the price parse.
  • A zero and a negative quantity, a negative price, a discount over the limit, and a refund above the balance.
  • A rejected order and an unknown refund leaving the total alone, a discounted order adding its total, and the same refund id twice.

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 ledger does with orders and refunds the six tests never try. Read src/lib.rs, src/money.rs, src/validate.rs and src/ledger.rs and tell me, without editing: (1) how discount_cents rounds, and what three lines of 1.00 at discount_bps 3333 give; (2) what type quantity × price is computed in, and what happens with quantity 1000000 at 1000000.00, and whether the subtotal and running total are summed with checks; (3) what parse_amount does with "12,34", "abc" and "1e3"; (4) whether validate::line and validate::order reject quantity 0 or -3, a price of -1.00 and discount_bps 10001; (5) what refund does with 5.00 after 6.00 was refunded on a 10.00 order, with a refund for an order id that does not exist, and with the same refund id sent twice; (6) when add_order changes the running total and by how much, for a repeated order id and for an order with a discount.

    Point at each function with the order or refund that would break it, without asking for a change yet.

    • 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 the discount is rounded half-up once per order, but it is rounded per line in f64 dollars; the rules say a line's amount is exact, but it is multiplied as i32 and the sums are unchecked. The rules say parse_amount accepts D+(.DD)? and no input panics, but it unwraps an f64 parse, so 12,34 panics and 1e3 is accepted. The rules give quantity 1 to 1,000,000, price 0 to 1,000,000.00 and discount_bps up to 10,000, but only the upper limits are checked; and a refund must be at most the balance, but it is compared with the total. The rules say a rejected order or refund changes nothing, but refund subtracts before the order is found and add_order adds the subtotal before validation and the duplicate check, and adds the subtotal instead of the total; and refund ids are never stored, so the same refund applies twice. Before any change to the ledger, write tests in src/candidate_tests.rs, one per case, through Ledger: three lines of 1.00 at 3333 bps give discount 100 and total 200; one line of 1000000 at 1000000.00 gives subtotal 100000000000000; add_order with price "12,34" is InvalidPrice with that line's sku, and parse_amount("1e3") and parse_amount("12.3") are InvalidPrice while parse_amount("+5.00") is 500; quantity 0 and -3 are InvalidQuantity and the order is not recorded; a price of -1.00 is InvalidPrice; discount_bps 10001 is InvalidDiscount and 10000 gives total 0; after 6.00 refunded on 10.00, a 5.00 refund is RefundExceedsBalance with requested 500 and available 400; a refund for an unknown order leaves total_cents() unchanged; a repeated order id and a 501-line order after a 10.00 order leave total_cents() at 1000; 2 × 10.00 at 1000 bps plus an order of 5.00 gives total_cents() 2300; and refund R-1 of 3.00 twice against 10.00 is DuplicateRefund with refunded 300 and total_cents() 700. Don't change lib.rs, money.rs, validate.rs or ledger.rs yet.

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

    • Direction: Diagnosis: money, 4 points
    • Direction: Diagnosis: validation, 4 points
    • Direction: Diagnosis: errors, 4 points
    • Direction: Diagnosis: accounting, 4 points
    • Verification: Named cases: money, 3 points
    • Verification: Named cases: validation, 3 points
    • Verification: Named cases: errors, 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::discount_above_ten_thousand_bps_is_invalid: a discount above 100% is rejected: OrderSummary { id: "O-1", subtotal_cents: 100, discount_cents: 100, total_cents: 0, refunded_cents: 0 } Now fix the money and parsing. (1) The rules say round once per order: discount_cents takes the integer subtotal and rounds half-up, (subtotal × discount_bps + 5000) / 10000 with checked arithmetic, no f64. (2) The rules say amounts are exact: keep i64 throughout, line_amount uses checked_mul and the subtotal and running total use checked_add, each Overflow when it does not fit. (3) The rules say parse_amount accepts an optional + or -, digits and optionally a dot with exactly two digits, and nothing else: build the cents from the digits, no f64 and no unwrap, InvalidPrice otherwise, with the line's sku and the text as given on an order. Keep the functions and the public API. Don't change the tests.

    Name the failing test and its value, then say how the money and the parsing should work and which rule each change enforces.

    • Prompt quality: Specified fix: money, 3 points
    • Prompt quality: Contract cited, 4 points
    • Prompt quality: Failure follow-up, 4 points
  5. Press Test. The discount-limit test still fails: validation is the next request.
  6. Your message 4

    Test fails at challenge::candidate_tests::tests::discount_above_ten_thousand_bps_is_invalid: a discount above 100% is rejected: OrderSummary { id: "O-1", subtotal_cents: 100, discount_cents: 100, total_cents: 0, refunded_cents: 0 } Now validation and accounting. (1) The rules give the ranges: validate::line rejects quantity outside 1..=1000000 (InvalidQuantity) and a price outside 0..=1000000.00 (InvalidPrice); validate::order rejects discount_bps above 10000 (InvalidDiscount). (2) The rules say a refund is at most the balance: compare with total − refunded and answer RefundExceedsBalance with requested and available. (3) The rules say a rejected order or refund changes nothing: refund touches the running total only after the order is found and the refund accepted; add_order checks the duplicate id and validate::order first and then adds the order's total after discount, not the subtotal. (4) The rules say refund ids are unique: keep a set of applied refund ids, and the same id again is DuplicateRefund and changes nothing. No catch_unwind, no unwrap or expect on input, no default values. Don't change the tests.

    The rest 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: errors, 3 points
    • Prompt quality: Specified fix: accounting, 3 points
  7. Press Test. One test left: a price with a comma must be rejected with its line's SKU.
  8. Your message 5

    Test fails at challenge::candidate_tests::tests::price_with_a_comma_is_an_invalid_price: assertion `left == right` failed Please fix the code in src/ so it passes; do not change the test.

    A failing run gets its test named in the next request.

  9. Press Test. All 22 tests pass after the last change, your 16 included.
    • Verification: Run after last change, 5 points
  10. Submit. The stage closes. Scope, the 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
Order Ledger Review Solution — Rust Walkthrough | Hunicode