An agent and a person edit the same task description. Both save by replacing the whole text. If the server just writes whatever body it receives (last-write-wins), the later save overwrites the earlier one and you get a lost update.
def save_lww(proposed: str) -> str:
# whatever was on the server is gone
return proposed
Take this note:
deadline: Friday
owner: A
From the same base, the agent changes deadline to Monday and the person changes owner to B. Whichever order the saves arrive in, one change is lost. The two edits are on different lines, so they never actually conflicted.
Optimistic locking pushes the merge onto the caller
The next option is optimistic concurrency control. The writer sends the version it read, and if the body has changed since then, the server rejects the save and returns the current body and a diff. That prevents lost updates, but merging becomes the caller’s job.
In an editor, the UI can ask the user to merge. For an agent that writes out a full replacement after a long run, reading the conflict, folding it in, and saving again is one more round trip, and another write can land during it.
So the requirements were narrowed to three: keep independent edits from both sides, resolve conflicts mechanically without a model call, and finish in one transaction.
A 3-way merge of base, proposed, and current
A merge needs three versions: the body the writer read (base), the body it wants to save (proposed), and the body on the server now (current). As in Git’s 3-way merge, take two diffs against base and apply every hunk that does not collide. Unlike Git, a colliding pair is not turned into conflict markers; it is resolved by taking the current side.
The unit is the line, including its line ending. In notes and task descriptions, most concurrent edits land on different lines. difflib.SequenceMatcher diffs base against each version and yields insert/delete/replace opcodes. autojunk=False turns off the heuristic that ignores frequent elements in sequences of 200 or more items, so Markdown with many blank or repeated lines does not get needlessly large diffs.
from dataclasses import dataclass
from difflib import SequenceMatcher
@dataclass(frozen=True)
class Edit:
start: int
end: int
replacement: tuple[str, ...]
def edits(base: list[str], text: list[str]) -> list[Edit]:
return [
Edit(i, j, tuple(text[x:y]))
for tag, i, j, x, y in SequenceMatcher(None, base, text, autojunk=False).get_opcodes()
if tag != "equal"
]
Two hunks conflict when their ranges on base intersect. An insertion (an empty range) also conflicts when it only touches the edge of the other range. Where a boundary insertion should go is ambiguous, so current wins.
def overlap(a: Edit, b: Edit) -> bool:
if a.start == a.end:
return b.start <= a.start <= b.end
if b.start == b.end:
return a.start <= b.start <= a.end
return max(a.start, b.start) < min(a.end, b.end)
def merge_text(base: str, proposed: str, current: str) -> str:
if current == base:
return proposed
if proposed == base or proposed == current:
return current
lines = base.splitlines(keepends=True)
current_edits = edits(lines, current.splitlines(keepends=True))
proposed_edits = edits(lines, proposed.splitlines(keepends=True))
accepted = current_edits + [
e for e in proposed_edits if not any(overlap(e, o) for o in current_edits)
]
for e in sorted(accepted, key=lambda e: (e.start, e.end), reverse=True):
lines[e.start : e.end] = e.replacement
return "".join(lines)
On a conflict, the proposed hunk is dropped and the current hunk is kept. The server never synthesizes a combined sentence. Hunks are applied from the end, so applying one does not shift the indexes of the ones before it.
On the note above:
base = "deadline: Friday\nowner: A\n"
proposed = "deadline: Monday\nowner: A\n" # agent
current = "deadline: Friday\nowner: B\n" # person
assert merge_text(base, proposed, current) == "deadline: Monday\nowner: B\n"
Last-write-wins would store proposed as is and drop owner: B. In the 3-way merge, the two hunks touch different lines of base, so both survive.
The merge is not idempotent, though. If you merge the same proposed again with the merged result as current, the diff alignment can shift where identical lines repeat, such as blank lines, and a deletion or insertion can be applied twice. If a retried save can arrive twice, reject the second one with an idempotency key.
The base comes from an immutable snapshot on the server
A 3-way merge does not work without base. Without it, you cannot tell whether a difference between current and proposed is someone else’s edit or a part the writer never saw. A version number that only bumps when a new history row is added cannot stand in for base either: an in-place overwrite of the same version leaves no row with the old body.
So store an immutable snapshot every time the body changes, keyed by a digest of the body. Readers get a token of the form version:digest and send it back when saving. The server locks the row with SELECT ... FOR UPDATE, loads the snapshot by digest, merges, and writes in the same transaction.
SELECT description FROM tasks
WHERE id = %s AND workspace_id = %s
FOR UPDATE;
-- then read snapshot by digest, merge_text(...), write
FOR UPDATE serializes writes to the same row, so each merge sees the most recently committed current. The application role can only append snapshots; only a trigger adds rows, when the body changes. If the snapshot is missing, the save is rejected instead of guessing a base.
Why a 3-way merge rather than OT or a CRDT
OT or a CRDT requires writers to send operations or CRDT updates instead of the whole text. These writers save by full replacement, so both the clients and the save API would have to change. A 3-way merge keeps the API and the text column as they are and only changes the server.
The cost is that it does not merge within a line. If both sides edit the same line, current stays and the proposed change is lost. If writers keep rewriting the same paragraph, conflicts pile up and that paragraph behaves almost like last-write-wins. Changes to unrelated lines are still never overwritten.
Last-write-wins is a single assignment, but it loses updates. Optimistic locking prevents that by pushing the merge onto every caller. A line-level 3-way merge on the server, with an immutable base snapshot and a row lock, keeps independent changes from both sides without an extra round trip.