Repository navigation
feat(api): add a document change feed and batch read - #753
Conversation
There was a problem hiding this comment.
ℹ️ 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-projectdoc_sync_statecounter,documents.seq/created_seq, and the two triggers that number every document and folder write; existing rows are numbered per project, oldest first. - Feed —
Changesservice over a read-onlyREPEATABLE READsnapshot:GET /projects/{projectId}/docs/changesreturns metadata entries, or the full visible list as a reset when the cursor's document-id fingerprint no longer matches. - Batch read —
FindDocumentsByIDsandPOST /projects/{projectId}/docs/batch-get, capped at 100 ids, IAM-scoped, project-bound, returned in request order without duplicates. - Hash backfill —
DocHashBackfillworker plusBackfillContentHashes, suppressingseq/updated_atthrough the transaction-localpaca.skip_doc_seqsetting. - Writes — document and folder create/delete now run in a transaction that takes the counter first; a repeated
DeleteDocumentkeeps 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.mdand 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.deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏
pikann
left a comment
There was a problem hiding this comment.
LGTM! Thank you for the contribution! 🚀
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.

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.
doc_sync_state). A trigger numbers every insert and update of a document (documents.seq;created_seqkeeps the number of the insert). Folder writes bumpfolders_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.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.foldersis the whole folder tree when a folder changed, otherwisenull.reset: truewith 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.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.content_hashon 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 changingseqorupdated_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:readand are narrowed to the documents the caller may read, like the document list. The contract is indocs/api/doc-change-feed.md.How the feed stays correct
REPEATABLE READsnapshot, sequence first.TestDocSeq_ConcurrentWritesAndFolderDeleteDoNotDeadlock).Trade-offs, listed so they can be challenged
doc_sync_statehas no foreign key toprojects: the triggers run inside the cascade of a hard project delete.Other changes
DeleteDocumentno longer movesdeleted_aton a repeated delete, and document and folder creates and deletes now run in a transaction (for the counter lock).Migration
000088_add_doc_change_seq.sql(up only, idempotent):doc_sync_state,documents.seqandcreated_seqwith an index on(project_id, seq), numbers existing rows per project oldest first, and adds the two triggers.Testing
golangci-lint run: 0 issues.-raceand the full API e2e suite, run in a Linux container (golang:1.26) with CI's commands: pass.apps/e2e, Chromium,tests/docsandtests/realtime, on macOS against a stack built from this branch before the rebase onto currentmaster): 206 passed, 6 skipped, 1 failed, 1 passed on retry.docs.spec.ts"User can edit their own comment" pressesControl+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).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 unmodifiedmasterand 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
Checklist
docs/api/doc-change-feed.md, linked fromdocs/api/README.md).