DEV Community

Dakota Wu
Dakota Wu

Posted on

Cap the First Extract at One Stable Seam

A billing repository kept refund pricing and audit writes inside one function that had grown past six hundred lines. Two cleanup pulls had already renamed helpers, and each of those pulls shifted partial-refund rounding by one cent. The happy-path tests stayed green because they asserted only the returned total and ignored collaborator sequence. This worked example shows how to pin that sequence before anyone accepts the smallest extract from the function.

The failure mode is an unrecorded seam

Cleanliness is a weak acceptance signal when one function hides several collaborators behind ordinary local calls. A rename can look safer than a behavior change, yet the call sequence can still move underneath the new names. Reviewers then trust the tidier shape and miss a pricing defect that appears only on partial refunds. The characterization step should record collaborator order before the team discusses names, comments, or file splits.

An invocation-order oracle is narrower than a golden snapshot that freezes the entire refund response payload. It answers one question, which is which collaborator ran, and in what sequence, for a single fixture. It does not prove amounts, taxes, or database writes, so those checks remain in separate tests. The narrowness is intentional, because a wide oracle often tempts a large rewrite inside the same change.

Build a seam inventory before touching code

Start by listing seams the function already crosses, using only collaborator names that exist in the current module. You should postpone any proposed replacement architecture while this inventory of existing seams is still incomplete. The inventory should name each collaborator, the input that matters, and whether call order is part of the contract. If the order looks accidental, mark that row unstable and refuse to assert it in the first test.

Seam Collaborator Order stable? Safe to extract now?
Price partial refund pricing.quote Yes, before audit Yes, behind current call
Write audit row audit.append Yes, after quote No, leave in place
Load tax table tax.lookup No, cache dependent No, characterize later
Notify ledger ledger.emit Unknown No, needs a separate trace

How to read the inventory

The table is a decision aid for this example, not a measurement taken from production traffic. Fill the stable column from a test run that you execute, rather than from a model guess. If a row remains unknown, that seam stays outside the first diff and waits for its own trace. The first extract may include only the single row that the inventory marks safe to move.

An unexecuted order recorder

The Python below is a proposal for a characterization test, and this article has not executed it. Adapt the import paths to the module you actually own before you treat the assertion as evidence. Keep the recorder inside the test tree so that production code does not gain a tracing dependency. The sample still calls the real pricing function, so use it only when that call is safe without live credentials.

class OrderRecorder:
    def __init__(self):
        self.calls = []

    def wrap(self, name, fn):
        def inner(*args, **kwargs):
            self.calls.append(name)
            return fn(*args, **kwargs)
        return inner


def test_partial_refund_call_order(monkeypatch):
    recorder = OrderRecorder()
    import refunds.quote as quote

    monkeypatch.setattr(
        quote.pricing,
        "quote",
        recorder.wrap("pricing.quote", quote.pricing.quote),
    )
    monkeypatch.setattr(
        quote.audit,
        "append",
        recorder.wrap("audit.append", lambda *args, **kwargs: None),
    )

    quote.price_refund(order_id="o-19", amount_cents=2500, partial=True)

    assert recorder.calls == ["pricing.quote", "audit.append"]
Enter fullscreen mode Exit fullscreen mode

Commands that gate the extract

Run that characterization file by itself before you open any production diff in the refund module. A focused pytest command keeps unrelated suite failures from diluting the order oracle you just added. If the assertion fails, change the expected order only after you confirm that current behavior is worth preserving.

python -m pytest tests/characterization/test_refund_call_order.py -q
git diff --numstat -- src/refunds/quote.py tests/characterization/test_refund_call_order.py
Enter fullscreen mode Exit fullscreen mode

Spend a diff budget, then stop

The smallest safe change is a budget you set in advance, not a mood you judge after the rewrite. After the order test is green on the unchanged function, allow one extract and then stop. The numbered budget below is a proposal for this example, and you should tighten it when your review bar is stricter.

  1. Touch only the pricing.quote call site and the new wrapper that preserves its current arguments exactly.
  2. Keep the audit.append call in the original function so the recorded order cannot drift during the extract.
  3. Reject the diff when git diff --numstat shows more than forty changed production lines in the refund module.
  4. Reject the diff when any characterization assertion was edited in the same commit as the production extract.
  5. Re-run the order test and the existing amount tests before you ask another person to review the change.

A forty-line cap is an example threshold for this walkthrough, not a universal law for every repository. The point is to decide that cap before you see an attractive rewrite that expands the task. If the extract cannot fit inside the cap, stop and add another characterization row instead of widening the change.

Use a remote scratch session only for the scaffold

MonkeyCode's free model access and free server option can hold scratch work for this scaffold when those options are still offered. Disclosure: This article was prepared as part of MonkeyCode's product outreach.

This draft does not name a model, a token quota, a hardware shape, or a duration, because those details were not verified here. Treat the remote session as a place to draft the recorder and the inventory, then copy the test back for a run you control. Paste the function signature and the collaborator names, and do not paste production credentials or customer payment rows. Ask for a failing characterization test first, and do not ask the session to perform the extract in that same prompt.

When the draft returns, run the commands above yourself and discard any production edit that the session added without review. A free server helps only when it cannot reach your real databases, because a characterization run must not write shared audit rows. Check the current product terms before you rely on availability, because a free option can change after this article is published. Do not treat a model-written assertion as the oracle until a human has compared it with the function that is running today.

If that session cannot run pytest, it is not a substitute for the command step, and you should finish the proof elsewhere. The hosted draft is optional scaffolding, and the acceptance evidence remains the local or CI command output. Remove any generated file that imports unreviewed helpers or widens the diff beyond the single safe seam. A session that offers a full rewrite has left the workflow, even if the prose around that rewrite sounds careful.

Who should skip this workflow

Skip the order oracle when collaborators run concurrently and the sequence is not an actual contract. An assertion on accidental order will fail under load and will train the team to weaken the characterization suite. Skip the method when you cannot execute the legacy function safely, because a recorder that never runs is only fiction. Skip a free remote session when the module handles secrets, payment keys, or personal data you are not allowed to upload.

The same characterization file still works on an offline machine that never contacts a hosted coding session. Also skip the extract when you do not have a reviewer who can reject a diff that exceeds the written budget. Teams that need a multi-seam redesign should schedule that work as a separate effort with its own oracles. This workflow is a poor fit for a release-night patch, because the inventory itself takes a deliberate pass.

Review notes that keep the change small

Write the review comment as a checklist that points at the inventory row, the order assertion, and the numstat result. Ask the author to attach command output rather than describing the refactor with adjectives about clarity. If the expected call list and the observed call list differ, the review stops even when the helper looks cleaner. That rule is what separates a characterization-led extract from a cleanliness pass that happens to include tests.

  • Quote the inventory row that marks the seam safe, including the collaborator name and the stability judgment.
  • Quote the expected call list and the observed call list from the characterization run, not a paraphrase of the diff.
  • Paste the numstat line count for production files and stop the review if that count exceeds the written budget.

What this does not prove

A green order test does not prove correct cents, tax calculations, or idempotent audit writes under retries. Keep those oracles in separate tests, and do not fold them into the first commit that moves a collaborator. The inventory table does not rank architectural quality, and it should not be cited as a performance or cost result. It also does not authorize a second extract, a rename sweep, or a comment rewrite in the same review.

If your team already keeps characterization tests beside messy modules, compare today's free-model and free-server terms with the limits above. Open a remote session only when those terms still match this narrow scaffold job, and keep acceptance on the test run you execute.

Top comments (0)