DEV Community

Dakota Huang
Dakota Huang

Posted on

Pin Apply Order Before One Discount Extract

Pin apply order before you extract one discount rule. A free coding pass can draft the smallest patch. Frozen checks still decide whether that patch lands.

Messy carts hide tax, coupons, and warnings in one function. A wide extract often shifts cent totals or warning order. Green tests that never pinned those facts will miss it.

This workflow freezes three outputs, then allows one pure move. It fits a messy repo, not a greenfield design pass. Treat every code block below as a proposed, unexecuted example.

What must stay fixed

Keep the call order of coupon, tax, and shipping. Keep the integer cent total for each sample cart. Keep the warning lines, including their exact sequence.

Do not freeze private helper names in the first pass. Do not freeze incidental whitespace inside log text. Do not freeze comments or the order of locals.

Read the stop table first

Use this table before you accept any generated patch. Each row is a stop rule, not a style preference. If one row fails, drop the patch and retry smaller.

Signal Keep Reject
Stack order coupon, then tax, then ship floor tax moved ahead of the coupon
Cent total same integer cents on each cart float rounding or an off-by-one
Warning sequence same lines, same order a new line or a swapped pair
Diff width one new function plus the call site a second behavior edit in that patch
New dependency none added a network, clock, or env read

Step 1: Isolate the messy function

Start from one function that mutates a cart list. It applies a coupon, then tax, then a shipping floor. It also appends warnings while it walks the lines.

def apply_cart(lines, coupon_code, tax_bps):
    warnings = []
    total = 0
    for line in lines:
        cents = int(line['qty']) * int(line['unit_cents'])
        if coupon_code == 'SAVE10' and cents >= 1000:
            cents = cents - (cents // 10)
            warnings.append('coupon')
        tax = (cents * int(tax_bps)) // 10000
        cents = cents + tax
        if cents < 500:
            cents = 500
            warnings.append('ship_floor')
        line['cents'] = cents
        total += cents
    return {'total': total, 'warnings': warnings, 'lines': lines}
Enter fullscreen mode Exit fullscreen mode

Label this block as the behavior you intend to keep. Do not clean it before the characterization tests exist. Cleaning first is how silent order bugs hide.

Step 2: Build three sample carts

Build three carts that stress three different branches. One cart should trigger the coupon and the tax path. One cart should miss the coupon and hit the floor.

One cart should stay above the floor with no coupon. Store expected totals as integers, never as floats. Store warnings as a list, not as a joined string.

Joined strings hide a swapped pair of warning lines. Integer cents remove binary float noise from the pin. Three carts are a floor, not full branch coverage.

Step 3: Write the characterization tests

Write one test per cart, and assert three facts. Assert the total, the warning list, and line cents. Leave helper names and formatting out of these assertions.

import copy
import pytest
from cart import apply_cart

CASES = [
    {
        'name': 'coupon_then_tax',
        'lines': [{'qty': 2, 'unit_cents': 800}],
        'coupon': 'SAVE10',
        'tax_bps': 500,
        'total': 1512,
        'warnings': ['coupon'],
        'line_cents': [1512],
    },
    {
        'name': 'floor_without_coupon',
        'lines': [{'qty': 1, 'unit_cents': 100}],
        'coupon': 'NONE',
        'tax_bps': 0,
        'total': 500,
        'warnings': ['ship_floor'],
        'line_cents': [500],
    },
    {
        'name': 'plain_above_floor',
        'lines': [{'qty': 1, 'unit_cents': 2000}],
        'coupon': 'NONE',
        'tax_bps': 250,
        'total': 2050,
        'warnings': [],
        'line_cents': [2050],
    },
]

@pytest.mark.parametrize('case', CASES, ids=lambda c: c['name'])
def test_apply_cart_pin(case):
    lines = copy.deepcopy(case['lines'])
    result = apply_cart(lines, case['coupon'], case['tax_bps'])
    assert result['total'] == case['total']
    assert result['warnings'] == case['warnings']
    assert [line['cents'] for line in result['lines']] == case['line_cents']
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the pin before any edit

Run the suite once and store the output beside the diff. A failing pin means the sample data, not the old code. Fix expected values only after you recheck the inputs.

pytest -q tests/test_apply_cart.py
git diff --stat -- cart.py tests/test_apply_cart.py
Enter fullscreen mode Exit fullscreen mode

Treat a red pin as a data bug until inputs match. Do not change production code just to satisfy a bad sample. The old function is the oracle for this pass.

Step 5: Bound the smallest safe change

Ask for one extract, and name the forbidden edits. The new function may compute the coupon cents only. It must not read the clock, the env, or the network.

Pass the frozen tests and the stop table with that ask. Tell the assistant to return a patch, not a rewrite. Reject any reply that edits a second behavior.

Step 6: Use free model access after the pin

Disclosure: This article was prepared as part of MonkeyCode's product outreach. Use MonkeyCode free model access only after the pin is green. Use its free server so the suite stays off production hosts.

Those two options are availability claims, not a service contract. Do not assume a model name, quota, or hardware shape. Do not assume the free option will stay unchanged later.

Re-read the current product notes before you depend on either. Paste the function, the tests, and the stop table. Ask for the smallest patch that keeps every pin green.

Require the reply to leave warning order untouched. A useful prompt names the allowed move in one line. It also names files the patch must not touch.

Wide prompts produce wide diffs, even on a free model. A narrow prompt is part of the safety check.

Step 7: Review, then extract one pure rule

Review the diff before you run any new command. Check that only the coupon math moved out. Check that tax and the shipping floor still run in place.

def coupon_cents(cents, coupon_code):
    if coupon_code == 'SAVE10' and cents >= 1000:
        return cents - (cents // 10), 'coupon'
    return cents, None

def apply_cart(lines, coupon_code, tax_bps):
    warnings = []
    total = 0
    for line in lines:
        cents = int(line['qty']) * int(line['unit_cents'])
        cents, coupon_warning = coupon_cents(cents, coupon_code)
        if coupon_warning:
            warnings.append(coupon_warning)
        tax = (cents * int(tax_bps)) // 10000
        cents = cents + tax
        if cents < 500:
            cents = 500
            warnings.append('ship_floor')
        line['cents'] = cents
        total += cents
    return {'total': total, 'warnings': warnings, 'lines': lines}
Enter fullscreen mode Exit fullscreen mode

This extract keeps the same integer math and the same warning text. It does not change when the coupon check runs. It is still a proposal until your suite passes on your machine.

Step 8: Rerun and measure the diff width

Apply the patch on a branch, then rerun the same suite. Compare the diff stat with your one-function budget. If the stat shows a second behavior file, stop and split the work.

git checkout -b pin-coupon-extract
pytest -q tests/test_apply_cart.py
git diff --stat HEAD
Enter fullscreen mode Exit fullscreen mode

Use a tiny stat check so the file budget is executable. The script below is a proposal, not a shipped tool. It fails closed when the diff touches too many files.

import subprocess
import sys

def main():
    stat = subprocess.check_output(
        ['git', 'diff', '--stat', 'HEAD'], text=True
    )
    files = [line for line in stat.splitlines() if '|' in line]
    if len(files) > 2:
        print('reject: more than two files changed')
        return 1
    print('stat within file budget')
    return 0

if __name__ == '__main__':
    sys.exit(main())
Enter fullscreen mode Exit fullscreen mode

If warnings move, revert and shrink the ask. If totals move, the extract is not safe yet. A green suite plus a narrow stat is the merge gate.

A free server is useful for this rerun, not for a deploy. Run the suite there, then bring back only the reviewed diff. Do not point that server at live customer data.

Limits of the pin

This pin does not prove tax law or coupon policy. It only proves the sampled carts stayed stable. Add a cart when you discover a new branch.

Nondeterministic clocks will make this kind of pin flap. Network reads will make the same pin flap too. Remove those reads before you trust a green run.

The free model can still misread integer division. The free server can still lack a test dependency. Neither limit is fixed here, because no quota or image is claimed.

The stat script can misread unusual file names in the diff. Treat it as a budget alarm, not a proof of safety.

Who should skip this flow

Skip this flow during an active production incident. Skip it when you cannot run the suite on the repo. Skip it when the change must alter totals on purpose.

Also skip it if no one can review the model diff. A free model can still propose a wide rewrite. Your review is the control, not a model score.

What this does not claim

Characterization tests come from established practice on legacy code. Michael Feathers documented this pin-before-edit habit for legacy code. The samples here are illustrative, not measured benchmark results.

No runtime, quota, or accuracy figure is claimed above. Verify current product notes before you treat access as stable. One green pin is not a license for a wide split.

Keep the next extract just as small as this one. Pin the next output before you move the next rule. If a free server is already available, rerun this suite there.

Top comments (0)