Memo diffs
MERGE and EXACT patches (Python 0.20.0)
Read an original RTC snapshot, prepare a patch against its exact source, and
keep that snapshot while submitting the patch. MERGE is the default and sends
no If-Match header. The server validates the original source, compiles edits
against its original RTC identities, and uses ordinary CRDT synchronization.
Concurrent edits are handled by the existing CRDT behavior, without fuzzy
rebasing onto the newest text.
For a separate request that must refuse any intervening revision, select EXACT:
EXACT is per request, never a permanent document mode. if_match=revision is an
explicit compatibility spelling for EXACT. It can supply the original baseline
when base_revision is absent; when both are supplied they must match.
format="inline-dff" is the default; format="diff" accepts the line format.
The Python client transports the patch without applying DMP or fetching a newer
baseline. The API must retain the original native identity snapshot; an old
content hash alone is not an RTC baseline.
NoteSnapshot is immutable and carries note, content, hash, revision.
A v2 PatchReceipt is a separate immutable value carrying note, mode,
base_revision, hash, and revision. Its to_dict() uses the same JSON fields
as CLI/API receipts: note, mode, baseRevision, hash, revision.
hash describes content; revision identifies an RTC state. The receipt is not
a string and does not pretend that these two references are interchangeable.
Snapshot reads do not alter the legacy Note/Doc cache.
Missing or expired original baselines, mismatched patch source, and failed EXACT
checks are explicit errors. No HTTP patch request is automatically retried.
Preserve the draft and original snapshot on any error. For an ambiguous lost
acknowledgment, inspect the current state and reconcile before resubmitting;
separate HTTP requests do not share an idempotency receipt. Unknown baselines
raise NoteNotFound; EXACT conflicts raise NoteChanged; source mismatches
raise PatchFailed; unavailable RTC responses raise NoteBusy.
Python 0.20.0 provides this contract with the matching Memos v2 API. Use
legacy=True for the earlier ETag patch interface. Package and deployed
acceptance receipts are tracked in workspace #706.
Concurrent edit walkthrough
Use a private test Memo containing exactly Hello world.. Run the first part,
then prepend Human: in the browser and wait for that edit to sync. Keep the
original immutable snapshot and patch unchanged.
The SDK itself prints nothing: values are returned, failures are exceptions.
The example prints only when requested. Receipt hash and revision describe
one coherent observation after acknowledgment, not a guarantee that all peers
are synchronized or that the state remains current forever. Original native
identity preservation and zero patch writes after EXACT rejection are checked
by the paired API/RTC acceptance fixture. The SDK does not fall back from EXACT
to MERGE or overwrite the saved snapshot after a failure.
Successful EXACT and the next MERGE request
Continue from the merged fixture, taking a new snapshot for this separate edit.
If a writer intervenes again, EXACT raises NoteChanged; retain this snapshot
and draft and inspect the memo before deciding on another request.
Recorded Python fixture values
The following values were replayed through the candidate SDK from an isolated API + RTC + Mongo fixture. Authentication, catalog, and S3 projections were mocked. This is test evidence, not a released-package or production transcript.
receipt.to_dict() has the same field names as CLI/API JSON:
EXACT raised NoteChanged with this message, after HTTP 412 and zero patch
journal writes. The SDK emitted no stdout or stderr:
The fixture's missing-baseline response was HTTP 404 with
error="revision_not_found", message="Original RTC baseline is not retained".
Malformed inline input was HTTP 422 with error="patch_failed",
message="Expected inline header and one record". The SDK raises NoteNotFound
and PatchFailed respectively; it does not turn either response into a MERGE
retry against newer source.
Recorded successful EXACT return value
A separate run of the same isolated API/RTC/Mongo fixture produced this receipt, replayed through the candidate SDK. The SDK emitted no stdout or stderr; these are returned attributes, not a published-package or production transcript.
exact_receipt.to_dict():
The next empty patch omitted exact=True, returned mode == "merge", and kept
the same hash and revision. Its to_dict() was:
Legacy ETag compatibility
read() still returns the editable Doc; Doc.save(), whole-body writes, and
section writes retain their previous ETag behavior. For old unified-diff callers,
select patch(..., legacy=True) explicitly. That path continues to return
PatchResult(str) with .etag and .size_bytes, and retains the previous cached
ETag precondition. A legacy content ETag must not be passed as a v2 RTC baseline.
Legacy comparisons against your last read or edit
The legacy note.read() body read returns doc.etag, a quoted SHA-256 hash of the complete text.
Keep it as a revision reference, including across processes:
The server retains note-scoped content snapshots for body/section reads and API
writes. Identical content has the same hash; a ref identifies text, not an RTC
operation or author. Partial body reads return the hash of the complete body.
Diff inspection does not advance the handle's cached revision or write
precondition. Use read()/refresh() when you want to adopt the latest state.
GET /namespaces/:slug/notes/:noteId/diff?since=<etag> returns diff, from,
to, and etag (the current ref). context accepts 0–100 lines, default 3.
The endpoint enforces current memo read permissions. Unknown or unavailable
snapshots return 404, never an empty-baseline diff. Old ETags issued before
snapshot retention was deployed may be unavailable. Retention requires the
matching server deployment; the SDK does not infer historical bytes.
Inspect and patch a local draft
Read a memo once, inspect edits, apply unified diffs locally, and save against that snapshot's revision:
since="last_edit" compares the current draft with its contents immediately
before its latest content-changing operation, including element edits, patches,
and revert(). Before any edit it returns an empty string. No-op edits and
successful saves preserve this comparison; a new read() creates a new draft.
It does not retrieve other collaborators' history or persisted server revisions.
doc.patch(diff) accepts a single-file unified diff, including diffs from
doc.diff(), diff -u, and git. Hunk positions and context must match exactly;
there is no fuzzy relocation. Invalid patches raise EditError and leave both
the draft and last-edit comparison unchanged. Empty diffs do nothing. Diffs
preserve Unicode, CRLF, and missing final newlines. context=0 is supported;
the default for diff() is three context lines.
To apply a patch directly to the remote memo, use the existing API:
The CLI equivalent is:
Remote writes reject stale revisions. A local patch is committed only when
doc.save() succeeds; a rejected save retains the draft for inspection.
Original-revision append (Python 0.26.0 release candidate)
This candidate changes note.append(text) from a cached whole-body PUT returning
an ETag string to a native original-revision insertion returning PatchReceipt.
Requires Python 0.26.0; publication acceptance is tracked separately. Read exact
source once, retain it, and append:
Without at, append reads one fresh hash-verified snapshot. With at, it validates
Memo identity, source hash and the original opaque revision before any network
request; it never substitutes current source. The insertion uses Unicode code
point positions and escapes inline framing and delimiter punctuation (+,
-) in the canonical form the CLI and server use, preserving CRLF and LF bytes.
An existing nonempty body lacking a final LF receives one LF before the addition,
including when the addition is empty. A completely unchanged MERGE returns an
observational receipt without PATCH or a new commit; it does not claim current
revision verification. exact=True submits even an unchanged patch so the server
checks the saved baseline. No request is automatically replayed.
Retained read_snapshot(at=revision) verifies the returned revision and source
hash even if another edit has since arrived. if_match=revision instead checks
current source; combining the two is rejected. A successful patch updates the
legacy cached ETag only in its content-hash domain, never to an RTC revision.
Unknown write outcomes preserve caches and drafts: keep the original baseline
and draft, inspect retained/current source, and reconcile before resubmitting.
For previous cached-text/LF/ETag PUT behavior and string return values, choose
note.append(text, legacy=True). Existing force=True also selects that legacy
path. Combining either with at or exact is rejected before HTTP. Doc.save(),
whole-body writes and section APIs retain their existing behavior.
Native body drafts (Python 0.27.0 release candidate)
Python 0.27.0 changes note.write(text) from whole-body PUT to disjoint
Unicode-codepoint patches against original RTC source. at=original_snapshot
pins identity and source without GET; without it one verified snapshot is read
before planning. Unchanged gaps remain untouched, and alignment work/trace/source
limits fail before PATCH instead of replacing a coarse region. No automatic
replay occurs. Explicit legacy=True, existing force=True, or legacy
if_match=etag retain the ETag PUT/string contract; modern at/exact cannot
be mixed with those compatibility options.
note.read() creates a modern editable Doc retaining its original immutable
snapshot. Edits remain local. doc.save() submits against that same snapshot,
returns PatchReceipt, and reads the acknowledged retained revision to adopt
its coherent merged content as the next draft/original. A different write through
the Memo handle does not move this draft's baseline. exact=True checks even
unchanged drafts; unchanged MERGE returns an observational receipt without a new
commit or a current-revision claim. note.read(at=revision) opens retained source.
If post-ACK readback fails, the raised NoteError.receipt contains the known
acknowledgment; draft and original source stay available. Further save calls are
refused until the caller reconciles: inspect note.read_snapshot(at=receipt.revision)
and current source, then explicitly open a new draft and reapply intended edits.
This failure is not a rollback and must not be blindly resubmitted. Ambiguous
PATCH failures retain drafts and snapshots without adopting a newer baseline.
For legacy editable drafts, choose note.read(legacy=True) or the legacy ETag
verification if_match=etag; their save behavior and SaveResult are retained.
doc.save(legacy=True) / force=True explicitly choose legacy body behavior.
Publication acceptance remains separate. Partial reads, section writes and section
selector mapping remain legacy and are a separate pending migration; their
ranges must not be guessed into original native snapshot coordinates.
Full source reads and remote inspection (Python 0.28.0 release candidate)
Default note.refresh() and note.text read full source through verified Memos
v2 snapshots. Cached ETags stay in the quoted content-hash domain; RTC revisions
stay on immutable snapshots. note.read() also populates that verified cache,
while existing Docs retain their own original snapshot even after another refresh.
read_snapshot() itself still leaves caches unchanged. Explicit
refresh(legacy=True) and get_text(legacy=True) preserve older body-read behavior.
Legacy append and legacy editable reads select that path explicitly on cache miss.
No v2 failure silently falls back to a legacy read.
note.diff(since=content_hash) uses the shipped v2 body inspection endpoint and
continues returning a diff string. It checks Memo, base hash, format and revision,
then reads the retained acknowledged revision to verify its source hash. Inspection
updates no cache or draft baseline. since is a content hash (raw, quoted ETag or
sha256-prefixed), never an RTC revision or a native patch baseRevision. Omitting
since uses this handle's last full read/edit content-hash ETag. The returned string
is inspection material; retaining only its hash does not establish a writable
original identity snapshot.
The v2 endpoint has fixed diff formatting and no context-selection parameter.
Explicit nondefault context selects the retained compatibility /diff endpoint
before transport, preserving existing calls; legacy=True also selects it. This
is option-based compatibility, never a fallback after a failed v2 response. V2
context selection remains an unresolved Namespace-owned endpoint capability. There is no existing Python DiffResult value; no new
protocol or parser is introduced. Sections and partial reads still await their
retained range/discovery contracts and remain an explicit separate migration.
Publication acceptance for Python 0.28.0 remains separate.
The Memos API facade (Python 0.34.0)
dl.notes implements the Python tabs of the Memos API
design pages. Stable IDs are primary, every operation takes keyword arguments,
and the facade is an adapter over the retained-baseline contract above: edits
compile to one inline-dff record against the original revision and go
through the same validated PATCH. dl.note(), read_snapshot() and the
released note.append() separator behavior are unchanged.
Reading
read() returns exact source. read(view="mapped") returns a MappedRead:
the same exact content, its absolute code-point chars, the observed
elements (address, chars, lines, section) and the reading view in
text — generated <!-- … --> hints that are never source. It is the snapshot
the CLI's --view html reads (view=html&contentFormat=literal-markdown),
validated the same way. Exactly one of lines=(a, b) (1-based, inclusive;
past-the-end is refused), section="s1" or address="s1.p2" scopes a read;
the last two need the mapped view. at= reads a retained revision and
verifies it. outline(at=) lists headings with addresses; find(text=, case_sensitive=False, at=) searches exact source and returns absolute ranges;
diff(since=revision, format="diff") returns base/result revisions and hashes
with the patch.
A FocusedRead/scoped MappedRead carries the whole memo's hash and
revision but complete=False; it baselines a targeted edit inside its span
and is refused (SnapshotRequired) as a whole-body baseline. A complete
mapped read is accepted wherever a snapshot is.
Editing
replace/insert/remove take exactly one selector or placement (lines,
address; before, after, cursor) and default to mode="merge"; an
address must have been observed at at's revision (a MappedRead resolves it
without a request). write and patch require mode; patch requires
format. Replacement text is verbatim: no newline, indentation or marker is
added, and input containing <!-- notes-reading-view is refused.
Receipts, outcomes and command identity
A successful write returns PatchReceipt {memo, mode, base_revision, hash, revision, outcome, command_id, replayed}; outcome is accepted or
no-write. Every error carries .outcome: invalid-usage (refused before
any request: RevisionExpected, SnapshotRequired, InvalidLineRange,
SelectionError, ReadingViewRefused), no-write (NoteChanged,
PatchFailed, NoteReadOnly, NoteNotFound, CommandIntentMismatchError),
unknown (UncertainOutcomeError, WriteOutcomeUnknown,
NoteCreatedWithoutSource) or operational (NoteBusy,
CommandInProgressError, CommandStatusInvalid,
CommandIdentityUnsupportedError).
command_id is the documented answer to a lost-response append. Pass one
([A-Za-z0-9._:-]{8,128}) to append/replace/insert/remove/write/
patch; it is sent as commandId and the receipt must echo it. A transport
failure after the request was handed over raises UncertainOutcomeError
carrying the id: resend the same call with the same id (the server returns the
stored receipt rather than appending twice) or call
note.command_status(command_id=...). It stays opt-in until the recording
server is deployed; without one nothing new is sent.
Resources and collaboration
note.rename(name=), note.versions.list() / .read(version_id=),
note.files.move(file=, to_folder=, name=), note.presence() and
note.visit(intent=, address=|cursor=, at=) mirror the CLI's requests.
dl.notes.create(text=...) creates the memo, then writes the initial source
through the retained-baseline contract; if that second step fails,
NoteCreatedWithoutSource carries the created id so no second memo is made.
Not in this release (listed by tests/test_notes_docs_contract.py):
note.watch(...) and note.move(...); the other collections' move facades.
Source: Python SDK guide.