DEV Community

Dakota Huang
Dakota Huang

Posted on

Lock Hit and Miss Rows Before Splitting a Formatter

A shorter function is not a safer extract. Shared module cache can survive a pretty split. Pin hit text, miss text, and timestamp text first.

The failure mode

Messy repos often hide a cache beside formatting logic. A clean split can leave that cache in the old module. Callers then see stale hits after the move.

This walkthrough uses one synthetic Python module only. Treat every snippet as a proposal, not a logged run. No latency numbers and no model scores appear here.

The rows that define the contract

Three observable outputs define this current behavior contract. Cache hit text must match the first stored row. Cache miss text must include the env fallback label.

Timestamp text must follow one frozen clock value. A passing suite locks those rows before any edit. A failing suite means you stop the split immediately.

The synthetic module

The function mixes lookup, environment, and clock reads. It also writes into one shared module-level dict. That write is the risky shared cache edge.

import os
from datetime import datetime, timezone

_CACHE = {}

def format_report(key, now=None):
    if key in _CACHE:
        return _CACHE[key]
    label = os.environ.get("REPORT_LABEL", "default")
    clock = now or datetime.now(timezone.utc)
    text = f"{label}:{key}:{clock.strftime('%Y-%m-%dT%H:%M:%SZ')}"
    _CACHE[key] = text
    return text
Enter fullscreen mode Exit fullscreen mode

Step 1. Clear state before each row

Characterization tests fail when leftover state crosses cases. Clear the cache and the label before each row. Then inject one clock value into every call.

import os
import unittest
from datetime import datetime, timezone

import formatter

class FormatReportPin(unittest.TestCase):
    def setUp(self):
        formatter._CACHE.clear()
        os.environ.pop("REPORT_LABEL", None)
        self.clock = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)

    def test_miss_uses_default_label(self):
        text = formatter.format_report("alpha", now=self.clock)
        self.assertEqual(text, "default:alpha:2026-09-25T12:00:00Z")
        self.assertIn("alpha", formatter._CACHE)

    def test_hit_ignores_later_label(self):
        formatter.format_report("alpha", now=self.clock)
        os.environ["REPORT_LABEL"] = "later"
        again = formatter.format_report("alpha", now=self.clock)
        self.assertEqual(again, "default:alpha:2026-09-25T12:00:00Z")
Enter fullscreen mode Exit fullscreen mode

Step 2. Run the pin on untouched code

Run that command from the same module directory. Expect two passing tests on the untouched function. Record the exact assertion strings in the commit message.

python -m unittest formatter_pin.py -v
Enter fullscreen mode Exit fullscreen mode

Step 3. Capture rows with repr

The shell fragment below is a recording aid, not a logged run. Run it only beside the synthetic module on your machine. Then paste the printed repr into the test file.

python - <<'PY'
from datetime import datetime, timezone
import formatter
formatter._CACHE.clear()
clock = datetime(2026, 9, 25, 12, 0, tzinfo=timezone.utc)
print(repr(formatter.format_report("alpha", now=clock)))
print(repr(formatter.format_report("alpha", now=clock)))
PY
Enter fullscreen mode Exit fullscreen mode

Use repr so hidden spaces stay visible in output. Copy that exact text into the assertion string. Do not retype the line from memory later.

Step 4. Order environment changes inside the hit test

Set the environment before the first miss call. Capture the returned text immediately after that call. Change the environment only before the second call.

Step 5. Reject a split that drops the cache

A tempting extract puts formatting in a new file. The cache often stays behind as a hidden global. That change can alter later cache hit behavior.

# proposal only: do not apply until the pin passes
def format_report(key, now=None):
    label = os.environ.get("REPORT_LABEL", "default")
    clock = now or datetime.now(timezone.utc)
    return f"{label}:{key}:{clock.strftime('%Y-%m-%dT%H:%M:%SZ')}"
Enter fullscreen mode Exit fullscreen mode

This sketch drops the original module cache write. The second call would rebuild the formatted line. The existing hit test should then fail loudly.

Step 6. Make the smallest safe change

Extract only the pure line renderer in this pass. Leave lookup and the store in the original function. That move is smaller than a new cache owner.

def _render_line(label, key, clock):
    return f"{label}:{key}:{clock.strftime('%Y-%m-%dT%H:%M:%SZ')}"

def format_report(key, now=None):
    if key in _CACHE:
        return _CACHE[key]
    label = os.environ.get("REPORT_LABEL", "default")
    clock = now or datetime.now(timezone.utc)
    text = _render_line(label, key, clock)
    _CACHE[key] = text
    return text
Enter fullscreen mode Exit fullscreen mode

Optional arguments can preserve the old call sites. Use them only if the pin still passes unchanged. A required new argument is a larger change.

Step 7. Score every candidate before editing

Score each candidate against these three binary checks. Each check records a pass or a fail. Reject that candidate when any single check fails.

Candidate Hit row Miss row Same cache object Verdict
Drop the cache and return a fresh line fail pass fail reject
Move formatting and leave _CACHE unread fail pass fail reject
Extract _render_line and keep the store pass pass pass smallest safe change
Require a new cache argument pass only after call-site edits pass only after call-site edits depends larger than needed

Object identity is the point of the third check. Compare store identity before and after the call. A new id means the extract changed ownership.

def test_write_uses_same_cache_object(self):
    before = id(formatter._CACHE)
    formatter.format_report("beta", now=self.clock)
    self.assertEqual(id(formatter._CACHE), before)
    self.assertEqual(
        formatter._CACHE["beta"],
        "default:beta:2026-09-25T12:00:00Z",
    )
Enter fullscreen mode Exit fullscreen mode

Review the diff for any new dict literal. A new literal usually means a new cache owner. Reject that shape even when the text still matches.

git diff -- formatter.py
Enter fullscreen mode Exit fullscreen mode

Step 8. Let a free model draft, then ignore it until tests pass

You can ask MonkeyCode for a draft diff of the extract. Disclosure: This article was prepared as part of MonkeyCode's product outreach. The operator reports free model access and a free server option.

Confirm current terms in product docs before you rely on them. Do not send secrets, tokens, or private customer data. Paste the synthetic module and the pin tests only.

Treat every returned diff as untrusted proposal text. A free model can propose a larger rewrite than requested. Free server access is not a permanence or quota promise.

This article states neither model names nor usage limits. It also states no hardware details and no duration claims. Check current docs before you plan around either option.

Apply only one proposed change at a time. Rerun the same unittest command on your machine. Keep the diff only if both rows still pass.

A model on a free server does not replace that run. Local assertions remain the only acceptance gate. If either pinned row fails, revert the diff.

Why these rows stay stable

Calling datetime.now inside the test makes rows drift. The pin would fail tomorrow for a non-bug reason. Injection removes that clock noise from the contract.

The miss path reads REPORT_LABEL on the first call. The hit path must not read that variable again. A clean split often breaks that exact difference.

The literal Z belongs to this fixture contract only. It is not a general rule for every UTC format. Change the pin if your module uses another pattern.

A shorter file can still hide cache ownership. The pin makes that ownership visible in assertions. Visible ownership is the point of this exercise.

Limitations

These tests lock current behavior, including current bugs. They do not prove the format is right for users. They also ignore concurrency on the shared dict.

The sample setUp removes REPORT_LABEL from the process. It does not restore a pre-existing value afterward. Save and restore that key if tests share a process.

This walkthrough assumes only the Python unittest runner. Assertion rules come from the current standard library docs. The current page is https://docs.python.org/3/library/unittest.html for those rules.

Many teams use the term for observed-behavior locks. The suite here follows that narrow meaning only. It is not a design approval of the format string.

Who should skip this

Skip this method when correct output is still unknown. A pin would freeze the wrong behavior contract. Talk with a domain owner before you lock rows.

Skip it when the module handles secrets or regulated data. Do not paste that code into any hosted model. Local pins still help without a remote draft step.

Skip it when you need a measured performance change. These rows do not measure time or memory use. Add a separate benchmark before you tune anything.

Skip it if tests cannot reset global module state. A dirty cache makes the characterization pin lie. Fix isolation before you trust a green run.

Stop after one green split

After both pinned rows pass, stop the session. Do not continue into a package move yet. A second structural change needs its own pin.

The useful result is a smaller function with unchanged rows. Clarity improved only where the tests stayed green. That binary rule is the whole acceptance gate.

If you already have free model access, draft only the next pin. Keep that server session free of secrets and tokens. Run the suite yourself before any merge decision.

Top comments (0)