Read-After-Write Wrapper¶
Category: Gate Pattern
Overview¶
The read-after-write wrapper is the runtime form of a gate: it writes, reads back, compares, and reports the difference. Where the other gates run in a test suite, this one runs in production, catching what tests cannot be present for. It converts an entire class of silent data loss into a message, once, at the wrapper, rather than being remembered at each call site.
The distinguishing detail is that a refused write and a discarded write are separate outcomes. One is visible and one is not, and collapsing them into "it did not work" throws away the only information that says which.
Concepts¶
Refused¶
The write was rejected and the caller was told. The system reported an error, nothing changed, and the failure is already visible. The response is to handle the error.
Discarded¶
The write was accepted, reported success, and stored nothing. The read-back does not match what was sent. This is the failure the wrapper exists to find, because nothing else reports it.
Landed¶
The write was accepted and the read-back matches. The wrapper adds one read per write to establish this, which is the cost of the pattern.
Usage Guidelines¶
Use when:
- A remote system is known to accept writes it does not store
- A silently lost write causes damage that is discovered much later
- The same write is issued from several call sites, each of which would otherwise need its own confirmation
Avoid when:
- The store is transactional and reports failures accurately
- The extra read is prohibitively expensive relative to the write
- The store is eventually consistent, so an immediate read-back is not evidence of anything
Implementation¶
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Protocol
class WriteOutcome(Enum):
"""Distinguishes a visible refusal from an invisible discard."""
LANDED = "landed"
REFUSED = "refused"
DISCARDED = "discarded"
@dataclass(frozen=True)
class WriteResult:
"""The outcome of a write, with the fields that did not survive it."""
outcome: WriteOutcome
message: str
discarded: dict[str, Any] = field(default_factory=dict)
@property
def ok(self) -> bool:
"""Whether the write landed."""
return self.outcome is WriteOutcome.LANDED
class Store(Protocol):
"""The minimum a store must offer for the wrapper to confirm a write."""
def apply(self, key: str, changes: dict[str, Any]) -> None: ...
def read(self, key: str) -> dict[str, Any]: ...
def apply_and_confirm(store: Store, key: str, changes: dict[str, Any]) -> WriteResult:
"""Apply changes, read them back, and report what did not survive."""
try:
store.apply(key, changes)
except Exception as error: # the refusal is the information, not a surprise
return WriteResult(
outcome=WriteOutcome.REFUSED,
message=f"{key} refused the write: {error}",
)
stored = store.read(key)
discarded = {
name: value for name, value in changes.items() if stored.get(name) != value
}
if discarded:
return WriteResult(
outcome=WriteOutcome.DISCARDED,
message=(
f"{key} accepted the write and stored none of {sorted(discarded)}. "
f"The write reported success; the record did not change."
),
discarded=discarded,
)
return WriteResult(outcome=WriteOutcome.LANDED, message=f"{key} accepted the write")
Usage¶
result = apply_and_confirm(store, "assays/17", {"data_files": ["a", "b"]})
if result.ok:
return "assays/17"
report_warning(result.message)
return None
Keeping the outcomes distinct lets callers respond differently: a refusal is retried or surfaced as an error, while a discard is a defect in the remote system that needs reporting and a workaround.
Trade-offs¶
Benefits:
- Detects silently discarded writes, which no return code reports
- Handles the confirmation once rather than at every call site
- Names the specific fields that did not survive, not just that something failed
Drawbacks:
- Doubles the request count for every write
- Unreliable against eventually consistent stores, where an immediate read proves nothing
- Comparison needs care where the store normalises values, causing false discards
Real-World Examples¶
- Confirming relationship writes against APIs that accept and ignore them
- Verifying object storage uploads by reading back size and checksum
- Post-write validation in migration tools that must not lose records
Related Patterns¶
- Live Contract Gate is the test-suite form of the same check
- Proxy wraps access to an object in the same structural way
- Decorator adds the confirmation behaviour around an existing write
API Reference¶
design_patterns.gates.read_after_write
¶
Read-After-Write Wrapper: confirm at runtime that a write landed.
Where the other gates run in a test suite, this one runs in production, catching what tests cannot be present for. It writes, reads back, compares, and reports the difference, converting an entire class of silent data loss into a message once at the wrapper rather than being remembered at each call site.
A refused write and a discarded write are kept as separate outcomes. One is visible and one is not, and collapsing them into "it did not work" throws away the only information that says which.
InMemoryStore
¶
A store that can demonstrate each of the three outcomes.
Example
Source code in src/design_patterns/gates/read_after_write.py
__init__(records, ignored_fields=None, refuses=False)
¶
Configure how the store treats writes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
dict[str, dict[str, Any]]
|
Initial contents, mapping key to stored field values. |
required |
ignored_fields
|
set[str] | None
|
Fields the store accepts and silently drops, which is the behaviour the wrapper exists to detect. |
None
|
refuses
|
bool
|
Whether the store rejects every write with an error. |
False
|
Source code in src/design_patterns/gates/read_after_write.py
apply(key, changes)
¶
Write field values, dropping the ignored ones without complaint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Identifier of the record. |
required |
changes
|
dict[str, Any]
|
Field values to write. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the store is configured to refuse writes. |
Source code in src/design_patterns/gates/read_after_write.py
read(key)
¶
Read a record back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Identifier of the record. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The stored field values, empty for an unknown key. |
Source code in src/design_patterns/gates/read_after_write.py
Store
¶
Bases: Protocol
The minimum a store must offer for a write to be confirmed.
Source code in src/design_patterns/gates/read_after_write.py
apply(key, changes)
¶
Write field values to a record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Identifier of the record. |
required |
changes
|
dict[str, Any]
|
Field values to write. |
required |
read(key)
¶
Read a record back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Identifier of the record. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: The stored field values. |
WriteOutcome
¶
Bases: Enum
Distinguishes a visible refusal from an invisible discard.
Attributes:
| Name | Type | Description |
|---|---|---|
LANDED |
The store accepted the write and the read-back matches. |
|
REFUSED |
The store rejected the write and said so. |
|
DISCARDED |
The store reported success and stored nothing. |
Source code in src/design_patterns/gates/read_after_write.py
WriteResult
dataclass
¶
The outcome of a write, with the fields that did not survive it.
Attributes:
| Name | Type | Description |
|---|---|---|
outcome |
WriteOutcome
|
Which of the three outcomes occurred. |
message |
str
|
Text describing the outcome, suitable for a warning. |
discarded |
dict[str, Any]
|
Fields that were sent but are absent from the read-back, mapped to the values that were sent. |
Source code in src/design_patterns/gates/read_after_write.py
ok
property
¶
Whether the write landed.
apply_and_confirm(store, key, changes)
¶
Apply changes, read them back, and report what did not survive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
store
|
Store
|
The store to write to and read from. |
required |
key
|
str
|
Identifier of the record. |
required |
changes
|
dict[str, Any]
|
Field values to write. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
WriteResult |
WriteResult
|
LANDED when the read-back matches, REFUSED when the store reported an error, and DISCARDED when the store reported success but the values are absent. |