# Flip-N-Write: count the flag as well as the payload

An exact, synthetic binary-cell example. This is not a PCM benchmark or a reproduction of a paper's speedup.

## Mechanism and assumptions

Flip-N-Write combines selective writes with normal/complemented representations and an inversion bit. The full MICRO 2011 paper describes the mechanism and evaluates it as a baseline: [Hay et al., sections 2-3](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/MICRO44-final.pdf). Its reference 1 credits [Cho and Lee, MICRO 2009](https://doi.org/10.1145/1669112.1669157). The latter full text was unavailable for this review; no original experimental claims are reproduced here.

The example assumes an even number n of binary data cells, one fixed binary flag cell, and selective cell updates. It excludes ECC, write atomicity, flag protection, wear leveling, unequal SET/RESET costs and physical cell variation.

## Independent derivation

Decode the old physical word using its existing inversion flag. Let d be its Hamming distance from the new logical word. Keeping the flag changes d data cells. Toggling it changes n-d data cells and one flag cell, for n-d+1 updates. Choose the smaller total.

For even n, d <= n/2 selects d. Otherwise d >= n/2+1, so n-d+1 <= n/2. Thus total updates, **including the flag**, never exceed n/2. A comparison that ignores the old flag can produce the wrong distance.

## Concentration counterexample

Start with eight physical zero bits and flag zero. Write 255, then 0, alternating for 16 writes.

| Accounting | Plain differential writes | Encoded writes |
| --- | ---: | ---: |
| Payload updates | 128 | 0 |
| Flag updates | Not present | 16 |
| Total updates | 128 | 16 |
| Maximum updates to one cell | 16 | 16 |

Aggregate updates fall eightfold, but the busiest cell receives the same number of transitions. This constructed sequence demonstrates why aggregate bit counts alone do not establish lifetime. It predicts neither actual PCM wear nor a universal weakness of a physical implementation.

## Reproduce

With Node.js, in the directory containing these four files:

```sh
node model.mjs --check
node --test model.test.mjs
```

[model.mjs](./model.mjs), [model.test.mjs](./model.test.mjs), [results.json](./results.json).

The exhaustive calculation covers every physical word, both old flag states and every new logical word at widths 2, 4, 6 and 8: 139,808 transitions. Tests also check an independent two-candidate cost oracle, 32-bit handling, invalid inputs, decoding and the per-cell sequence. These are deterministic counts, not samples from hardware.

[Glossary definition](https://hesela.dev/terms/flip-n-write/).
