Skip to content

feat(api): add a document change feed and batch read - #753

Merged
pikann merged 3 commits into
Paca-AI:masterfrom
msammu07:feat/doc-change-feed
Nov 14, 2026
Merged

pikann merged 3 commits into
Paca-AI:masterfrom
msammu07:feat/doc-change-feed

Conversation

@msammu07

Copy link
Copy Markdown
Contributor

Summary

Second part of #747 (docs pull / push / content check for coding agents), on top of #751. It lets a client that mirrors a project's documents ask "what changed since my last pull" instead of listing and downloading everything.

  • Change sequence. Each project gets a counter (doc_sync_state). A trigger numbers every insert and update of a document (documents.seq; created_seq keeps the number of the insert). Folder writes bump folders_seq. A write that changes nothing (feat(api): add a document content hash with ETag, If-Match and no-op writes #751) and the hash backfill are not numbered.
  • Change feed. GET /projects/{projectId}/docs/changes?since=<cursor> returns {cursor, reset, docs[], folders}: metadata only (id, folder_id, title, content_hash, updated_at, deleted). A deleted document is a bare tombstone. folders is the whole folder tree when a folder changed, otherwise null.
  • Reset rule. Without a cursor, with an unusable one, or when the set of documents the caller may read changed without those documents being written (a role edit, a document or folder moved under a denied folder), the reply is reset: true with the full list; the client drops what is not in it. The cursor carries a fingerprint of the document ids the caller could see, which is how the server notices.
  • Batch read. POST /projects/{projectId}/docs/batch-get {ids} returns up to 100 documents with their bodies, in the order asked. An id the caller cannot read, or that is deleted or unknown, is left out without saying which.
  • Hash backfill. A worker fills content_hash on rows written before feat(api): add a document content hash with ETag, If-Match and no-op writes #751, once per process start, in batches, without changing seq or updated_at. Until a row is reached, the feed computes its hash on the fly, so every live entry carries its real hash.

Both endpoints need docs:read and are narrowed to the documents the caller may read, like the document list. The contract is in docs/api/doc-change-feed.md.

How the feed stays correct

  • A reader must never store a cursor of 43 while change 42 is still uncommitted. Every write takes the project's counter row and holds it until commit, so numbers become visible in order. The feed reads everything from one REPEATABLE READ snapshot, sequence first.
  • The repository takes the counter row at the start of each transaction that writes documents or folders, before any other row. The triggers alone take it after the row they fire for, which deadlocks a document save against a folder delete (reproduced by TestDocSeq_ConcurrentWritesAndFolderDeleteDoNotDeadlock).
  • A tombstone is sent only for a document that existed at the cursor and that the caller may see. A document created and deleted out of the caller's sight is in no reply, also after its folder is deleted.

Trade-offs, listed so they can be challenged

  1. Document and folder writes are serialized per project for the length of one write transaction (a few milliseconds), saves that turn out to change nothing included. Writes in different projects and all reads are not affected. Two alternatives if this is a concern: skip the counter for a save that changes nothing (small change), or number changes from a plain sequence and have the feed track transactions still open at pull time (no write lock, harder cursor logic, clients may see a document twice).
  2. The feed is not paginated. An entry is about 200 bytes; a reset on a large project sends the full list.
  3. Every pull evaluates the caller's document scope over the project's documents (once when up to date, twice otherwise).
  4. A folder write that changes nothing still resends the folder tree.
  5. The cursor is not signed. It grants nothing: every reply is filtered by what the caller may read now. A cursor ahead of the project's sequence is answered with a reset.
  6. Small residual disclosure: a document the caller once held, then moved into a denied folder, deleted there, and whose folder is then deleted, comes back as a bare tombstone (an id the caller already had, plus the deletion time) instead of a reset.
  7. doc_sync_state has no foreign key to projects: the triggers run inside the cascade of a hard project delete.

Other changes

  • DeleteDocument no longer moves deleted_at on a repeated delete, and document and folder creates and deletes now run in a transaction (for the counter lock).
  • The API e2e environment now applies document list scoping like production; before, document lists were unscoped there.

Migration

000088_add_doc_change_seq.sql (up only, idempotent): doc_sync_state, documents.seq and created_seq with an index on (project_id, seq), numbers existing rows per project oldest first, and adds the two triggers.

Testing

  • golangci-lint run: 0 issues.
  • Unit tests with -race and the full API e2e suite, run in a Linux container (golang:1.26) with CI's commands: pass.
  • New API e2e tests: feed with no cursor, up to date, edit / move / delete, folder rename, access loss (document moved, folder moved, policy edit, access restored), bad cursor, deleted documents not leaked, a write during a request lands in the next pull, a row without a stored hash, batch read scoped and capped, sequence on insert / update / soft delete / folder delete, no-op write, migration numbering of existing rows, concurrent writes against a folder delete, backfill.
  • Browser e2e (apps/e2e, Chromium, tests/docs and tests/realtime, on macOS against a stack built from this branch before the rebase onto current master): 206 passed, 6 skipped, 1 failed, 1 passed on retry.
    • Failed: docs.spec.ts "User can edit their own comment" presses Control+a, which does not select all on macOS (same as reported in feat(api): add a document content hash with ETag, If-Match and no-op writes #751).
    • Passed on retry: docs.spec.ts "Rename a document from the sidebar". The test reads the API right after the sidebar shows the new title, before the save has landed. Without retries it fails 10 of 38 runs on unmodified master and 17 of 38 on this branch; that sample does not show whether this branch makes it more likely.

Relation to the by-path PR

The by-path PR for #747 is raised at the same time and does not depend on this one. Both touch document_repository.go, so whichever merges second needs a rebase, and in it the by-path write must take the counter row (lockDocSeq) before the folder advisory lock. I will do that rebase.

Type of Change

  • Other (API feature)

Checklist

  • The change is focused and scoped.
  • Related documentation is updated (docs/api/doc-change-feed.md, linked from docs/api/README.md).
  • 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 — the cursor, the reset rule and the counter-first lock order hold up under scrutiny. One design question and one performance suggestion below.

Reviewed changes

  • Change sequence — migration 000088: a per-project doc_sync_state counter, documents.seq/created_seq, and the two triggers that number every document and folder write; existing rows are numbered per project, oldest first.
  • Feed — Changes service over a read-only REPEATABLE READ snapshot: GET /projects/{projectId}/docs/changes returns metadata entries, or the full visible list as a reset when the cursor's document-id fingerprint no longer matches.
  • Batch read — FindDocumentsByIDs and POST /projects/{projectId}/docs/batch-get, capped at 100 ids, IAM-scoped, project-bound, returned in request order without duplicates.
  • Hash backfill — DocHashBackfill worker plus BackfillContentHashes, suppressing seq/updated_at through the transaction-local paca.skip_doc_seq setting.
  • Writes — document and folder create/delete now run in a transaction that takes the counter first; a repeated DeleteDocument keeps the original deletion time.
  • Tests & docs — unit, repository, handler and e2e coverage for the feed, batch read, numbering, concurrency and backfill, plus docs/api/doc-change-feed.md and its README link.

ℹ️ Plugin SQL can invert the counter-first lock order

The deadlock fix rests on every writer taking doc_sync_state before it touches a document or folder row, but the plugin host executes plugin-supplied DML on the API's own connection pool and alwaysBlockedWriteTables does not list documents or doc_folders. A plugin UPDATE documents … therefore locks the document row and only then takes the counter inside documents_bump_seq, which is exactly the inversion that deadlocks against UpdateDocumentAtomic. Writing shared tables from plugins is a documented capability, so this is worth a deliberate decision even though no vendored plugin does it today.

Technical details
# Plugin DML bypasses the lock order the change feed relies on

## Affected sites
- `services/api/internal/platform/plugin/runtime.go` — `paca.db_exec` / `paca.db_query` run plugin SQL against the API pool (`internal/bootstrap/app.go` passes `DB: sqlDB`); `alwaysBlockedWriteTables` and `coreSensitiveFields` cover neither `documents` nor `doc_folders`.
- `services/api/migrations/000088_add_doc_change_seq.sql:32-37` — states the invariant: "the counter row is taken before any document or folder row".
- `docs/plugins/backend-plugin-system.md:36` — documents writes against "plugin-owned tables or allowed shared tables".

## Required outcome
- Decide deliberately whether plugin SQL may write these two tables. If it may, record that the counter-first invariant does not cover plugin DML: a single-statement plugin UPDATE/DELETE on `documents` or `doc_folders` can deadlock with a concurrent save or folder operation (one side gets a 500), and a plugin hard DELETE of a document is unnumbered (the next pull's fingerprint comparison still forces a reset).
- If it may not, reject those tables before execution rather than relying on the trigger.

## Suggested approach (optional)
- Add `documents` and `doc_folders` to `alwaysBlockedWriteTables`, or leave the surface unchanged and note the limitation beside the trigger comments in `000088` so future plugin authors are not surprised.

## Open questions for the human (optional)
- Is any plugin in the marketplace writing to `documents` today? That decides whether this is a latent or a live risk.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | 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! 🚀

@pikann
pikann merged commit 1a98043 into Paca-AI:master Nov 14, 2026
6 checks passed
msammu07 added a commit to msammu07/paca that referenced this pull request Nov 14, 2026
The change feed (Paca-AI#753) makes every document and folder write take the
project's change counter before any other lock. The by-path write now
takes it before the folder advisory lock, and document and folder
creates take it around the shared insert helpers. The deadlock test
pushes by path against a folder delete.
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