Skip to content

feat(api): add a document content hash with ETag, If-Match and no-op writes - #751

Merged
pikann merged 6 commits into
Paca-AI:masterfrom
msammu07:feat/doc-content-hash
Nov 14, 2026
Merged

pikann merged 6 commits into
Paca-AI:masterfrom
msammu07:feat/doc-content-hash

Conversation

@msammu07

@msammu07 msammu07 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Summary

First part of #747 (docs pull / push / content check for coding agents). It gives every document a content hash and uses it for conditional requests, so an identical write costs nothing and a stale write is refused instead of silently winning.

  • Content hash. content_hash is the sha256 of a document's content with each block's own id removed and keys sorted. The same blocks give the same hash whatever ids the writer generated. Only a block's own id is ignored (the same rule as cleanBlocks in the web app); every other field counts.
  • Reads. GET /docs/{docId} returns content_hash in the body and an ETag of the form "<content hash>-<meta tag>", where the meta tag fingerprints every other field of the response (title, folder, position, timestamps). If-None-Match with the current ETag gets 304 with no body, so a rename or a move is never hidden behind a 304. Responses carry Cache-Control: private, no-cache.
  • Writes. PATCH /docs/{docId} accepts If-Match with a content hash or a whole ETag (or *). It is a precondition on content only: a rename or a move since the caller read the document does not fail it. A mismatch gets 412 (VERSION_CONFLICT) with the stored version's content_hash, updated_at and updated_by in the error details. The check runs under the row lock.
  • No-op writes. A write whose content, title, folder and position all match what is stored writes nothing: no UPDATE, no snapshot, no updated_at change, no activity, no realtime event, no mention notifications.
  • Snapshots. Each snapshot records the hash of the version it holds, and GET /docs/{docId}/snapshots?content_hash=<hex> returns that version, so a client can fetch the version it last saw.

Why

Until now "content changed" was decided by comparing raw JSON strings, which never matched: the MCP Markdown parser gives blocks new ids on every write, the web editor strips ids before saving, and JSONB re-serializes what it stores. Every identical push created a snapshot, bumped updated_at, recorded a doc.updated activity and made the live-editing hub merge every block again. Two agents writing the same doc silently overwrote each other.

What does not change

  • The web editor sends no If-Match, so its saves behave as before, except that a save of unchanged content is now skipped.
  • Tasks and sprints keep their numeric row version (ifMatchVersion). Documents use the content hash instead, for the reason given in migration 000083: a row version would bump on every autosave, rename and move.
  • Live editing: the checks run against the stored copy. A write that passes still goes through the existing block merge in services/realtime.

Migration

000087_add_documents_content_hash.sql adds a nullable content_hash to documents and doc_snapshots, plus an index on doc_snapshots (document_id, content_hash). Existing rows stay NULL: the hash is computed in memory when one is needed and stored on the row's next write. The next PR adds a backfill.

Testing

  • golangci-lint run: 0 issues.
  • Unit tests: normalizer, service (no-op, title-only change, If-Match match / mismatch / *, check under the lock, row without a stored hash), handlers (ETag, 304, 400 on a malformed If-Match, 412 with details, snapshot filter, no activity on a no-op).
  • API e2e: TestDocs_IdenticalPushIsNoOp, TestDocs_TwoWritersSecondGets412; the full test/e2e suite and the real-migrations test pass.
  • Browser e2e (apps/e2e, Chromium, tests/docs and tests/realtime, run on macOS against a stack built from this branch): 207 passed, 6 skipped, 1 failed. The failure is docs.spec.ts "User can edit their own comment": the test presses Control+a, which does not select all on macOS. With only that key changed to ControlOrMeta+a the test passes on the same build. This PR does not touch comment code, and the test file is left unchanged here.

Closes two of the acceptance criteria in #747: "pushing identical content creates no snapshot and leaves updated_at unchanged" and "two agents read the same doc and both write with If-Match: the second gets 412".

Remaining PRs for #747

# PR Contents
1 this PR Content hash, ETag, If-None-Match / If-Match, no-op writes
2 Change feed A per-project change sequence on documents; GET /docs/changes?since=<cursor>; POST /docs/batch-get; hash backfill
3 By path PUT and GET /docs/by-path; source metadata and a lock for managed copies; a change note, client label and task reference on writes; MCP doc tools resolve a path in one request
4 Web UI Managed copies are marked, read-only when locked, and can be unlocked
5 CLI npx @paca-ai/paca-mcp pull and push
6 MCP partial tools read_doc outline / section / line range, grep_docs, edit_doc
7 Search A plain-text column with a trigram index, so a phrase crossing bold or italic is found
8 Editable mirror Edit a pulled file and push it back; conflicts merged locally with a three-way merge

PRs 2 and 3 are independent of each other and both build on this one.

Design decisions for the feature

Happy to change any of these; they are listed so they can be challenged early.

  1. The hash is computed on the server, in Go. It works for every writer (web, MCP, CLI) with no client changes. The alternative, each client sending canonical JSON, would need every writer to agree on a byte format.
  2. If-Match compares the content hash, not a row version. It answers "has the body changed since I read it". Renames and moves cause no false conflicts, and a revert to the same text reads as unchanged. The ETag starts with that hash and adds a tag over the rest of the response, so If-None-Match only gets a 304 when nothing in the response changed.
  3. The change feed will return the folder tree rather than a path per document. A folder rename changes the path of every document under it without touching those documents. This differs from the wording in [Feature] Docs: efficient pull/push/content-check for coding agents (change feed, ETags, upsert by path, partial reads) #747 ("folder path").
  4. Access loss will be detected with a visibility fingerprint. Visibility can change through a role edit, a folder move or a document move, so no single event covers it. The feed cursor carries a hash of the document ids the caller could see; if that set looks different on the next call, the server sends the full list (metadata only) and the client removes what is gone.
  5. Retention. Deleted documents are soft-deleted and not purged, so tombstones do not expire. The server may answer any cursor with a full reset, and clients must handle that. Removing a mirrored file cannot revoke copies an agent already made; the CLI docs will say so.
  6. A locked managed copy rejects content edits that carry no source (the web editor, MCP write_doc). A push from the same repository passes.
  7. Intent is captured at write time. Writes can carry a change note, an opaque client label and a task reference, kept in the document's activity and returned with a 412. There is no live messaging between agent sessions; questions go through document comments.
  8. History stays as full snapshots. They gain a hash (this PR) so a version can be fetched by it. Diffs are computed when viewed, as today.
  9. The local mirror is the fork. An agent pulls, edits the file and pushes; a conflict is merged locally. No server-side forks or branches.
  10. edit_doc works on top-level blocks. A change inside a nested list rewrites that list block; every other block is sent back exactly as stored.
  11. Server search stays literal. Regex runs in the MCP process over candidate documents.
  12. Out of scope: change notifications for agents (SSE, webhook, MCP subscription) and a snapshot restore endpoint.

Type of Change

  • Other (API feature)

Checklist

  • The change is focused and scoped.
  • Related documentation is updated. (docs/api has no list of document endpoints, so there was nothing to update; the handler and migration comments describe the behaviour.)
  • New structure or direction is explained clearly.
  • I avoided unnecessary detail or premature abstraction.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — one design consequence worth a look.

Reviewed changes

The full PR (4 commits, 23 files) was read end to end and the affected Go packages build and test clean locally.

  • Content hash — canonical sha256 of BlockNote content with block-level ids stripped (recursively through children), sorted keys, exact number literals; props.* / inline ids still count, and nil/empty/null all hash as [].
  • Storage — migration 000087 adds nullable content_hash to documents and doc_snapshots plus a lookup index; existing rows stay NULL and are hashed in memory until their next write.
  • Conditional writes — PATCH /docs/{docId} honours If-Match (single hash or *), compared inside the row-locked decide; a mismatch returns 412 VERSION_CONFLICT carrying the stored hash, updated_at and updated_by.
  • No-op writes — identical content, title, folder and position skip the UPDATE, snapshot, updated_at bump, activity, realtime event and mention notifications, with DocChange now driving both the snapshot decision and the activity fields.
  • Conditional reads — GET returns the hash as ETag and content_hash, answers If-None-Match with a bodyless 304, and sets Cache-Control: private, no-cache.
  • Snapshots — each snapshot records its version's hash and GET .../snapshots?content_hash= filters on it.
  • Tests — new unit, handler, PG-gated repository and e2e coverage for the no-op and two-writer cases, plus the If-Match/If-None-Match parsing table.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

The ETag was the content hash alone, but the response also carries the
title, folder, position and timestamps. A client revalidating with
If-None-Match after a rename or a move got 304 and kept a stale title.

The ETag is now "<content hash>-<meta tag>", where the meta tag is a
fingerprint of every other field of the document response. If-None-Match
compares the whole ETag. If-Match still compares content only and accepts
either a content hash or a whole ETag, so a rename causes no conflict.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

The incremental commit 6a952bd4 addresses the prior review's ETag-scope concern: the response ETag is now "<content hash>-<meta tag>", If-None-Match compares the whole tag, and renames/moves now return a 200 with a new ETag. If-Match remains content-only by design and is documented in UpdateDocument; the tests cover both behaviors.

I reviewed the new commit and its six changed files. go build ./... and the affected Go packages (internal/transport/http/..., internal/domain/doc, internal/service/doc, internal/repository/postgres) pass. The prior review thread is resolved.

No further changes requested.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

A write returned the in-memory document, whose updated_at came from
time.Now() with nanoseconds, while the row and every later read have
microseconds. On Linux the two differed: an identical second push
appeared to move updated_at, and the ETag a write returned was not the
ETag of the next read, so If-None-Match with it got 200.

Document timestamps are now truncated to microseconds when set, and the
ETag's meta tag normalizes timestamps to UTC microseconds, so the same
instant always gives the same tag.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

The incremental commit since the prior pullfrog review, which aligns document write responses and ETags with the row Postgres stores.

  • Write-response timestamps — CreateDocument and the locked UpdateDocument now set timestamps through storedNow() (time.Now().Truncate(time.Microsecond)). The repository returns the in-memory document on a real write (result = current), so without this the response carried nanoseconds that the row never holds.
  • ETag stability — docMetaTag projects created_at/updated_at to UTC microseconds before hashing, so the same instant tags identically whether it came from a fresh time.Now() or a row scanned in another zone or precision.
  • Coverage — TestDocumentWrites_TimestampsAtStoredPrecision and TestDocETag_SameInstantSameTag pin both halves of the round trip.

I verified the load-bearing assumption against pgx v5.9.2 source: TimestamptzCodec encodes microseconds by integer division in binary format and UTC().Truncate(time.Microsecond) in text format, so storedNow() truncation matches what Postgres stores rather than rounding. go test ./internal/service/doc/ ./internal/transport/http/handler/ passes. The prior review's thread remains resolved.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

@pikann pikann left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thank you for the contribution! 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature] Docs: efficient pull/push/content-check for coding agents (change feed, ETags, upsert by path, partial reads)

2 participants