Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
feat(google_docs)!: read_doc_edits, a typed list of the blocks people changed (#2867)
Jiangzhou31652c95bfba
diff --git a/dev/google_docs_real_account_check.py b/dev/google_docs_real_account_check.pyindex 9c67e123..043a7582 100644--- a/dev/google_docs_real_account_check.py+++ b/dev/google_docs_real_account_check.py@@ -6,19 +6,22 @@ Run it once you have signed in with ``cocoindex auth sign-in google-docs``uv run python dev/google_docs_real_account_check.pyIt writes one doc in your My Drive and, at the end, moves it to the trash. On-the way it asks you, in the browser, to comment on one section and edit-another; then it changes a third section and checks:+the way it asks you, in the browser, to comment on one section, edit another+and suggest an edit to a third; then it changes a fourth section and checks:1. the doc it created reads back as exactly what was declared (nothing leftto write), which is what makes "a person's edit" detectable at all;2. a rerun with unchanged content makes no request to Google;-3. ``read_doc`` hands back your edit of Gamma, and a memoized reader runs- again for it but not for the target's own writes;+3. ``read_doc_edits`` hands back your edit of Gamma, not your pending+ suggestion in Delta, and a memoized reader runs again for the edit but not+ for the target's own writes;4. a change to one section rewrites that section only: the commented sectionkeeps its text, and the comment is still there, quoting the same text;5. the section you edited keeps your text, and the run warns about it;-6. declaring what ``read_doc`` returned takes your edit in, without rewriting it;-7. dropping the declaration moves the doc to the trash (not deleted for good).+6. declaring what ``read_doc_edits`` returned takes your edit in, without+ rewriting it, and leaves Delta, with its suggestion, as it is;+7. once you accept the suggestion, it is an edit like any other;+8. dropping the declaration moves the doc to the trash (not deleted for good).It also reports whether stamping the doc's Drive appProperties leaves itsDocs revision where the write left it, which keeps a reader's validation to@@ -60,6 +63,10 @@ Comment on this sentence in Beta.## GammaEdit a word in this Gamma sentence.++## Delta++Suggest a word for this Delta sentence."""V2 = V1.replace("version one.", "version two.").replace(@@ -85,12 +92,14 @@ class _Counting:return getattr(self._inner, name)-_watch_runs: list[google_docs.DocRead | None] = []+_watch_runs: list[google_docs.DocEdits | None] = []@coco.fn(memo=True)-async def _watch(name: str, declared: str) -> None:- _watch_runs.append(await google_docs.read_doc(GDOCS, name, declared))+async def _watch(name: str, last_declared: str) -> None:+ _watch_runs.append(+ await google_docs.read_doc_edits(GDOCS, name, last_declared=last_declared)+ )def _pause(prompt: str) -> None:@@ -163,12 +172,16 @@ def main() -> int:watcher.update_blocking()return len(_watch_runs) - before- def read_back(declared: str) -> google_docs.DocRead | None:- out: list[google_docs.DocRead | None] = []+ def read_back(last_declared: str) -> google_docs.DocEdits | None:+ out: list[google_docs.DocEdits | None] = []@coco.fnasync def read_main() -> None:- out.append(await google_docs.read_doc(GDOCS, name, declared))+ out.append(+ await google_docs.read_doc_edits(+ GDOCS, name, last_declared=last_declared+ )+ )coco.App(coco.AppConfig(name="GoogleDocsRealAccountRead", environment=env),@@ -206,7 +219,9 @@ def main() -> int:_pause(f"In the doc, add a comment on the sentence {COMMENTED!r} (section "- "Beta), and change one word in the Gamma sentence. Leave Alpha alone."+ "Beta), and change one word in the Gamma sentence. Then switch to "+ "Suggesting mode and suggest adding a word to the Delta sentence; "+ "leave the suggestion pending. Leave Alpha alone.")before = _docs.read_document(google.get(doc_id))beta_id = blocks[2].block_id@@ -224,15 +239,23 @@ def main() -> int:return 1gamma = ("CocoIndex real-account check", "Gamma")+ delta = ("CocoIndex real-account check", "Delta")check("your edit runs the reader again", watch() == 1)seen = _watch_runs[-1]check(- "read_doc names Gamma as edited, and nothing as deleted",- seen is not None and seen.edited == (gamma,) and seen.deleted == (),+ "read_doc_edits names Gamma as edited, not Delta's pending "+ "suggestion, and nothing as deleted",+ seen is not None+ and [(e.heading_path, e.current is None) for e in seen.edits]+ == [(gamma, False)],)if seen is not None:- print(" read back:", [ln for ln in seen.content.splitlines() if ln][-1])- check("read_doc gives the doc's link", seen.url == _target.doc_url(doc_id))+ for edit in seen.edits:+ print(" read back:", edit.current)+ check(+ "read_doc_edits gives the doc's link",+ seen.url == _target.doc_url(doc_id),+ )content["content"] = V2app.update_blocking()@@ -291,7 +314,7 @@ def main() -> int:app.update_blocking()adopted = _docs.read_document(google.get(doc_id))check(- "declaring what read_doc returned takes your edit in, unchanged",+ "declaring what read_doc_edits returned takes your edit in, unchanged",taken is not Noneand not any("Gamma" in w for w in warnings)and adopted.content(adopted.ranges[blocks[3].block_id]) == gamma_before@@ -299,6 +322,26 @@ def main() -> int:== _markdown.fingerprint(gamma_before),)check("taking your edit in does not run the reader again", watch() == 0)+ delta_id = blocks[4].block_id+ check(+ "Delta, with your pending suggestion, was left as it is",+ any("Delta" in w for w in warnings)+ and _docs.classify(+ adopted,+ adopted.ranges[delta_id],+ _markdown.fingerprint(blocks[4].paragraphs),+ settled=True,+ )+ != "kept",+ )++ _pause("Now accept the suggestion in Delta.")+ check("the accepted suggestion runs the reader again", watch() == 1)+ seen = _watch_runs[-1]+ check(+ "read_doc_edits names Delta as edited once accepted",+ seen is not None and delta in [e.heading_path for e in seen.edits],+ )content["content"] = Noneapp.update_blocking()diff --git a/docs/src/content/docs/connectors/google_docs.mdx b/docs/src/content/docs/connectors/google_docs.mdxindex 1b915847..e341cc49 100644--- a/docs/src/content/docs/connectors/google_docs.mdx+++ b/docs/src/content/docs/connectors/google_docs.mdx@@ -145,28 +145,37 @@ When the declaration goes away (the code no longer declares the doc, or the appIf a person moves the doc to the trash while it is still declared, the next change creates a new doc with the full content.-### Reading back a person's edits+### Reading back what people changed```python-async def read_doc(- account: ContextKey[UserAccount], name: str, declared: str-) -> DocRead | None+async def read_doc_edits(+ account: ContextKey[UserAccount], name: str, *, last_declared: str+) -> DocEdits | None@dataclass(frozen=True)-class DocRead:+class DocEdits:url: str+ edits: tuple[BlockEdit, ...]content: str- edited: tuple[tuple[str, ...], ...]- deleted: tuple[tuple[str, ...], ...]++@dataclass(frozen=True)+class BlockEdit:+ heading_path: tuple[str, ...]+ declared: str+ current: str | None```-`read_doc` reads back the doc that `declare_doc(account, name, ...)` keeps, and returns `None` when there is none (not created yet, or in the trash). `declared` is the Markdown the doc was last declared with: the content of the run that last wrote it.+`read_doc_edits` returns what people changed in the doc that `declare_doc(account, name, ...)` keeps, since the target last wrote it, and `None` when there is no such doc (not created yet, or in the trash). It writes nothing.+`last_declared` is the Markdown the doc was last declared with: the content of the run that last wrote it. Your code keeps it, for example in `coco.use_state`. The changes are reported against it:++- `edits` lists the [blocks](#how-a-change-is-written) people changed, in the order of `last_declared`. Each has its `heading_path` as declared (`("Brief", "Risks")` for the block under `## Risks` under `# Brief`, `()` for the text before the first heading), its `declared` text, and its `current` text in the doc, in [Markdown](#markdown), or `None` when people deleted it.+- `content` is `last_declared` with those changes applied: each changed block's text replaced by its `current` text, each deleted one left out, the rest exactly as declared. Declaring `content` takes the changes in: those blocks are the target's again, and their text is not rewritten, so comments on them stay.- `url` is the doc's link.-- `content` is `declared`, with each block a person edited in the doc replaced by the person's text, in Markdown, and each block a person deleted left out. The rest is `declared` exactly, so `content == declared` when no one changed a block. Declaring `content` takes the person's edits in: those blocks are the target's again, and their text is not rewritten.-- `edited` and `deleted` are the heading paths of those blocks, as declared, in order: `("Brief", "Risks")` for the block under `## Risks` under `# Brief`, and `()` for the text before the first heading.-It tells a person's edit from the target's own writes the same way the target does, by the [named ranges](#how-a-change-is-written).+A change is told from the target's own writes the way the target tells it, by the [named ranges](#how-a-change-is-written), and the same things are not counted: whitespace, text between blocks, comments, and formatting other than the [Markdown](#markdown) subset's. A pending suggestion counts once someone accepts it (the target leaves a block that holds one as it is, as it does an edit).++A deleted block leaves no trace in the doc: it is a block of `last_declared` that the doc no longer has. The target records in the doc which content it was last written from, and when `last_declared` is not that content (it is newer, or a write failed), no deletion is reported, since a block the doc lacks may never have been written, and a warning names the blocks it lacks. Other edits are reported either way.```python@coco.fn@@ -174,14 +183,16 @@ async def app_main() -> None:report = await write_report() # Markdownlast = coco.use_state("brief", initial_value=None) # what the doc was declared withif last.value is not None:- doc = await google_docs.read_doc(GDOCS, "Weekly brief", last.value)- if doc is not None and doc.content != last.value:- print(f"People edited {doc.edited} and deleted {doc.deleted} in {doc.url}")+ doc = await google_docs.read_doc_edits(GDOCS, "Weekly brief", last_declared=last.value)+ if doc is not None and doc.edits:+ for edit in doc.edits:+ print(edit.heading_path, "deleted" if edit.current is None else "edited")+ report = keep_people_edits(report, doc) # your own policygoogle_docs.declare_doc(GDOCS, "Weekly brief", report)last.value = report```-A read is a data dependency of the function that made it, as a read of a file is. A memoized function that called `read_doc` runs again when a person edits or deletes a block of the doc, or the doc goes to the trash or is replaced, and is reused otherwise. The target's own writes do not make it run again: after each write the target stamps the doc with the revision it wrote, so that the next run can tell its write from a person's. Neither does a comment. Checking the record costs one Drive and one Docs request per run, and one more read of the doc when the doc's revision moved for another reason than the target's write. In a [preview](../programming_guide/app#previewing-an-update), `read_doc` reads the doc too.+A read is a data dependency of the function that made it, as a read of a file is. A memoized function that called `read_doc_edits` runs again when people edit or delete a block of the doc, or the doc goes to the trash or is replaced, and is reused otherwise. The target's own writes do not make it run again: after each write the target stamps the doc with the revision it wrote, so that the next run can tell its write from a person's. Neither does a comment or a pending suggestion. Checking the record costs one Drive and one Docs request per run, and one more read of the doc when the doc's revision moved for another reason than the target's write. In a [preview](../programming_guide/app#previewing-an-update), `read_doc_edits` reads the doc too.A person's text comes back in the [Markdown](#markdown) below, which parses back to what the doc holds. What the subset cannot spell (a style other than a heading, such as Title; a list item two levels deeper than the one above it) reads back otherwise, and the block stays the person's after `content` is declared.diff --git a/python/cocoindex/connectors/google_docs/_docs.py b/python/cocoindex/connectors/google_docs/_docs.pyindex 4a01a35e..42cdbde5 100644--- a/python/cocoindex/connectors/google_docs/_docs.py+++ b/python/cocoindex/connectors/google_docs/_docs.py@@ -18,6 +18,11 @@ and plans requests that touch only what changed:computes, so nothing depends on how Docs grows a range at its boundary;- a block a person edited is left as it is and reported.+A pending suggestion (an insertion made in suggestion mode, not yet accepted)+is part of the text the writer sees, so a block that holds one is left as it+is, as an edit would be. A reader of what people changed leaves it out+(``DocState.settled``): it is no one's change until someone accepts it.+Positions are UTF-16 code units, as the Docs API counts them."""@@ -80,6 +85,7 @@ class _Element:end: inttext: strstyle: Run # the style of ``text``; its own ``text`` is unused+ suggested: bool = False # a pending suggested insertion@dataclass(frozen=True)@@ -92,12 +98,13 @@ class DocParagraph:bullet: int | Noneelements: tuple[_Element, ...]- def clipped(self, start: int, end: int) -> Paragraph:- """The part of this paragraph inside ``[start, end)``, its newline left out."""+ def clipped(self, start: int, end: int, *, settled: bool = False) -> Paragraph:+ """The part of this paragraph inside ``[start, end)``, its newline left+ out; ``settled`` leaves out pending suggested insertions too."""runs: list[Run] = []for element in self.elements:lo, hi = max(element.start, start), min(element.end, end)- if lo >= hi:+ if lo >= hi or (settled and element.suggested):continuetext = _u16slice(element.text, lo - element.start, hi - element.start)style = element.style@@ -159,10 +166,19 @@ class DocState:return founddef content(self, rng: OurRange) -> list[Paragraph]:+ """The block's text as the writer sees it, pending suggestions included."""return [p.clipped(rng.start, rng.end) for p in self.overlapping(rng.start, rng.end)]+ def settled(self, rng: OurRange) -> list[Paragraph]:+ """The block's text with pending suggested insertions left out: what+ people changed, as a reader sees it."""+ return [+ p.clipped(rng.start, rng.end, settled=True)+ for p in self.overlapping(rng.start, rng.end)+ ]+def whole(self, rng: OurRange) -> bool:"""Whether ``rng`` spans whole paragraphs, none of them the body's lastone, and shares none with another block's range."""@@ -208,9 +224,14 @@ def _paragraph(element: Mapping[str, Any]) -> DocParagraph:if text_run is not None:text = str(text_run.get("content", ""))style = _text_style(text_run.get("textStyle") or {})+ suggested = bool(text_run.get("suggestedInsertionIds"))else:text, style = OBJECT * (p_end - p_start), Run("")- elements.append(_Element(p_start, p_end, text, style))+ suggested = any(+ isinstance(value, Mapping) and value.get("suggestedInsertionIds")+ for value in part.values()+ )+ elements.append(_Element(p_start, p_end, text, style, suggested))paragraph_style = paragraph.get("paragraphStyle") or {}bullet = paragraph.get("bullet")return DocParagraph(@@ -263,16 +284,17 @@ def read_document(document: Mapping[str, Any]) -> DocState:def classify(- state: DocState, rng: OurRange, declared_fp: str+ state: DocState, rng: OurRange, declared_fp: str, *, settled: bool = False) -> Literal["same", "update", "kept"]:"""What the block in ``rng`` is, against the declared version ``declared_fp``.``same``: the doc has the declared version (written by the target, ortyped by a person). ``update``: it has what the target last wrote, and thedeclaration changed. ``kept``: a person changed it since the target wrote- it, to something other than the declared version.+ it, to something other than the declared version. ``settled`` compares+ the block's text without its pending suggestions, as a reader does."""- current = fingerprint(state.content(rng))+ current = fingerprint(state.settled(rng) if settled else state.content(rng))whole = state.whole(rng)if whole and current == declared_fp:return "same"@@ -284,10 +306,10 @@ def classify(def observe(state: DocState) -> str:"""A digest of what a person can change in the target's blocks: which arethere, and the text of each one edited since the target wrote it. Neither a- comment nor text outside every block changes it."""+ comment, a pending suggestion nor text outside every block changes it."""seen = []for block_id, rng in sorted(state.ranges.items()):- current = fingerprint(state.content(rng))+ current = fingerprint(state.settled(rng))edited = not state.whole(rng) or current != rng.writtenseen.append([block_id, current if edited else ""])payload = json.dumps(seen, separators=(",", ":"))diff --git a/python/cocoindex/connectors/google_docs/_reader.py b/python/cocoindex/connectors/google_docs/_reader.pyindex 2d7bd6be..d755e716 100644--- a/python/cocoindex/connectors/google_docs/_reader.py+++ b/python/cocoindex/connectors/google_docs/_reader.py@@ -1,26 +1,38 @@-"""Reading back a doc the target keeps: what a person changed in it.--``read_doc`` takes the Markdown the doc was last declared with and returns it-with each block a person edited in the doc replaced by the person's text (as-Markdown, ``_markdown.render``) and each block a person deleted left out. A-block is the person's when its text no longer matches the fingerprint its-named range records (``_docs.classify``), the same test the target's writes-use, so the reader and the writer never disagree about what a person did.+"""Reading back a doc the target keeps: what people changed in it.++``read_doc_edits`` takes the Markdown the doc was last declared with and+returns the blocks people changed in the doc since, each with its declared text+and its text now (as Markdown, ``_markdown.render``), and that Markdown with+those changes applied. A block is a person's when its text no longer matches+the fingerprint its named range records (``_docs.classify``), the test the+target's writes use too, so the reader and the writer agree about what people+did. Two differences, both on the reader's side:++- A pending suggestion is no change until someone accepts it: the reader+ compares a block's text without it (``DocState.settled``). The writer counts+ it, so it leaves such a block as it is.+- A deleted block leaves no trace in the doc, so a deletion is a block of+ ``last_declared`` that the doc no longer has. That holds only when+ ``last_declared`` is what the doc was last written from, which the doc's+ appProperties record (``_target.declared_fingerprint``). When it is not,+ no deletion is reported, and a warning says so.A read is recorded as a data dependency of the caller (``coco.use_data_dep``),keyed by the sign-in's token file and the doc's tag. Its state is the doc, the-revision read and a digest of what a person can change in the blocks+revision read and a digest of what people can change in the blocks(``_docs.observe``). Validating it asks Docs for the doc's revision; anunchanged one is valid at that, and so is the one the target's own writeproduced when the doc's stamp says that write was planned on the revisionread (``_target.Stamp``). Otherwise the doc is read: it is still valid when-its blocks are as they were read (a comment moved the revision), or as the-target's write left them. Anything else re-runs the caller, which reads again.+its blocks are as they were read (a comment or a suggestion moved the+revision), or as the target's write left them. Anything else re-runs the+caller, which reads again."""from __future__ import annotationsimport asyncio+import loggingimport osfrom dataclasses import dataclassfrom typing import NamedTuple@@ -32,27 +44,48 @@ from cocoindex.connectors.google_drive._oauth import SignInErrorfrom . import _docs, _markdown, _targetfrom ._auth import UserAccount+_logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+class BlockEdit:+ """One block people changed in a doc ``declare_doc`` keeps (experimental).++ A block is a heading and its paragraphs up to the next heading, or the+ paragraphs before the first heading.++ Attributes:+ heading_path: The headings that lead to the block, outermost first, as+ declared; ``()`` for the text before the first heading. A heading+ a person renamed shows in ``current``.+ declared: The block as last declared, its heading line included.+ current: The block as it is in the doc now, in Markdown; ``None`` when+ people deleted it.+ """++ heading_path: tuple[str, ...]+ declared: str+ current: str | None+@dataclass(frozen=True)-class DocRead:- """A doc ``declare_doc`` keeps, as read back with ``read_doc`` (experimental).+class DocEdits:+ """What people changed in a doc ``declare_doc`` keeps, from ``read_doc_edits`` (experimental).Attributes:url: The doc's link.- content: The Markdown it was declared with, with each block a person- edited in the doc replaced by the person's text in Markdown, and- each block a person deleted left out. The rest is the declared- text exactly, so ``content == declared`` when no one changed a- block. Declaring ``content`` makes the doc the target's again.- edited: The heading paths of the blocks a person edited, in order, as- declared (``()`` for the text before the first heading).- deleted: The heading paths of the blocks a person deleted, in order.+ edits: The blocks people changed since the doc was last written, in+ the order of ``last_declared``; empty when no one changed one.+ content: ``last_declared`` with ``edits`` applied: each changed block's+ text replaced by its ``current`` text, each deleted one left out.+ The rest is ``last_declared`` exactly. Declaring ``content`` takes+ the edits in: those blocks are the target's again, and their text+ is not rewritten."""url: str+ edits: tuple[BlockEdit, ...]content: str- edited: tuple[tuple[str, ...], ...]- deleted: tuple[tuple[str, ...], ...]# What a read saw, as its record keeps it: the doc, the revision read and@@ -61,43 +94,64 @@ _Seen = tuple[str, str, str] | Noneclass _Read(NamedTuple):- doc: DocRead | None+ doc: DocEdits | Noneseen: _Seen-def read_back(state: _docs.DocState, declared: str, url: str) -> DocRead:- """``declared`` with the blocks a person edited or deleted in ``state`` as they are there."""+def read_back(+ state: _docs.DocState, last_declared: str, url: str, *, deletions: bool+) -> DocEdits:+ """``last_declared`` with the blocks people changed in ``state`` as they are+ there. ``deletions``: whether ``last_declared`` is what the doc was last+ written from, so that a block missing from the doc was deleted."""out: list[str] = []cursor = 0- edited: list[tuple[str, ...]] = []- deleted: list[tuple[str, ...]] = []- for span in _markdown.block_spans(declared):+ edits: list[BlockEdit] = []+ for span in _markdown.block_spans(last_declared):block = span.blockrng = state.ranges.get(block.block_id)+ if rng is None and not deletions:+ continueif rng is not None:- status = _docs.classify(state, rng, _markdown.fingerprint(block.paragraphs))- if status != "kept":+ declared_fp = _markdown.fingerprint(block.paragraphs)+ if _docs.classify(state, rng, declared_fp, settled=True) != "kept":continue- out.append(declared[cursor : span.start])- text = declared[span.start : span.end]- trailing = text[len(text.rstrip()) :]+ out.append(last_declared[cursor : span.start])+ text = last_declared[span.start : span.end]+ declared = text.rstrip()if rng is None:- deleted.append(block.path)+ edits.append(BlockEdit(block.path, declared, None))else:- edited.append(block.path)- out.append(_markdown.render(state.content(rng)) + trailing)+ current = _markdown.render(state.settled(rng))+ edits.append(BlockEdit(block.path, declared, current))+ out.append(current + text[len(declared) :])cursor = span.end- out.append(declared[cursor:])- return DocRead(url, "".join(out), tuple(edited), tuple(deleted))+ out.append(last_declared[cursor:])+ return DocEdits(url, tuple(edits), "".join(out))-def _read(account: UserAccount, tag: str, declared: str) -> _Read:+def _read(account: UserAccount, tag: str, last_declared: str) -> _Read:google = _target._Google(account)found = google.find(tag)if found is None:return _Read(None, None)state = _docs.read_document(google.get(found.doc_id))- doc = read_back(state, declared, _target.doc_url(found.doc_id))+ url = _target.doc_url(found.doc_id)+ written_from = found.declared == _target.declared_fingerprint(last_declared)+ doc = read_back(state, last_declared, url, deletions=written_from)+ if not written_from:+ missing = [+ span.block.label+ for span in _markdown.block_spans(last_declared)+ if span.block.block_id not in state.ranges+ ]+ if missing:+ _logger.warning(+ "Google Doc %s was not last written from the Markdown given as "+ "last_declared, so blocks it lacks are not reported as deleted: %s",+ url,+ "; ".join(repr(label) for label in missing),+ )return _Read(doc, (found.doc_id, state.revision_id, _docs.observe(state)))@@ -146,36 +200,41 @@ _DOC_READ = coco.DataDep("cocoindex.google_docs.read", validate=_validate_read)@coco.fn-async def read_doc(- account: ContextKey[UserAccount], name: str, declared: str-) -> DocRead | None:- """Read back the Google Doc ``declare_doc(account, name, ...)`` keeps (experimental).+async def read_doc_edits(+ account: ContextKey[UserAccount], name: str, *, last_declared: str+) -> DocEdits | None:+ """What people changed in the Google Doc ``declare_doc(account, name, ...)`` keeps (experimental).++ ``last_declared`` is the Markdown the doc was last declared with: the+ content of the run that last wrote it, which the caller keeps (for example+ in ``coco.use_state``). The blocks people changed are reported against it,+ and its text is kept for every block no one changed. When it is not what+ the doc was last written from, no deletion is reported (the doc has no+ trace of a deleted block, only of the ones it has) and a warning says so.+ ``None`` when there is no such doc (not created yet, or in the trash).- ``declared`` is the Markdown the doc was last declared with, the content of- the run that last wrote it: the blocks a person deleted are those it has- and the doc no longer does, and the text of each block no one changed is- taken from it. ``None`` when there is no such doc (not created yet, or in- the trash).+ A pending suggestion counts once someone accepts it.The read is a data dependency of the caller: a person's edit or deletionof a block, or the doc going to the trash or being replaced, makes a- memoized caller run again, and the target's own writes and a comment do- not. Each run validates it with one Drive and one Docs request, and reads- the doc when its revision moved for another reason than the target's write.+ memoized caller run again; the target's own writes, a comment and a+ suggestion do not. Each run validates it with one Drive and one Docs+ request, and reads the doc when its revision moved for another reason than+ the target's write.Args:account: The ``ContextKey`` the run provides the signed-in``UserAccount`` under, as given to ``declare_doc``.name: The doc's name, as given to ``declare_doc``.- declared: The Markdown the doc was last declared with.+ last_declared: The Markdown the doc was last declared with."""user = coco.use_context(account)tag = _target.tag_of(account.key, name)- read = await asyncio.to_thread(_read, user, tag, declared)+ read = await asyncio.to_thread(_read, user, tag, last_declared)coco.use_data_dep(_DOC_READ, key=(os.path.abspath(user.token_path), tag), state=read.seen)return read.doc-__all__ = ["DocRead", "read_doc"]+__all__ = ["BlockEdit", "DocEdits", "read_doc_edits"]diff --git a/python/cocoindex/connectors/google_docs/_target.py b/python/cocoindex/connectors/google_docs/_target.pyindex 9196bf75..a62c9af1 100644--- a/python/cocoindex/connectors/google_docs/_target.py+++ b/python/cocoindex/connectors/google_docs/_target.py@@ -12,8 +12,11 @@ trash.After each write the target stamps the doc (another ``appProperties`` entry)with the revision it planned on, the revision its write produced, and a digest-of the blocks as it left them, so that ``read_doc``'s record can tell the-target's own write from a person's edit without a second read.+of the blocks as it left them, so that ``read_doc_edits``'s record can tell the+target's own write from a person's edit without a second read. Each change of+the declaration also records the fingerprint of its content (a third entry),+so a reader can tell whether the text it was given is the one the doc was+last written from."""from __future__ import annotations@@ -63,6 +66,8 @@ _DOC_MIME = "application/vnd.google-apps.document"_TAG_PROPERTY = "cocoindexDoc"# The Drive appProperties key of the stamp a write leaves (see the module docstring)._STAMP_PROPERTY = "cocoindexWrite"+# The Drive appProperties key of the fingerprint of the content last declared.+_DECLARED_PROPERTY = "cocoindexDeclared"# A stamp's base for a doc the target created in that write.NEW = "new"# Raised when what a declaration writes changes, so every doc is planned again.@@ -119,12 +124,18 @@ class _DocAction:key: _DocKeyblocks: tuple[_markdown.Block, ...] | None # None: trash the docwritten_blocks: frozenset[str] | None+ declared: str = "" # ``declared_fingerprint`` of the content; "" to trashdef _content_fingerprint(content: str) -> bytes:return fingerprint_str(f"{_FORMAT_VERSION}\n{content}")+def declared_fingerprint(content: str) -> str:+ """The fingerprint of declared content, as the doc's appProperties keep it."""+ return _content_fingerprint(content).hex()++class _DocHandler(coco.TargetHandler[str, _DocRecord, None]):def reconcile(self,@@ -155,7 +166,7 @@ class _DocHandler(coco.TargetHandler[str, _DocRecord, None]):if len(prev_possible_records) == 1 and not prev_may_be_missing:written = frozenset(next(iter(prev_possible_records)).block_ids)return coco.TargetReconcileOutput(- action=_DocAction(doc_key, blocks, written),+ action=_DocAction(doc_key, blocks, written, content_fp.hex()),sink=_sink,tracking_record=_DocRecord(content_fingerprint=content_fp,@@ -224,6 +235,8 @@ class Stamp(NamedTuple):class Found(NamedTuple):doc_id: strstamp: Stamp | None+ # ``declared_fingerprint`` of the content the doc was last written from.+ declared: str | Noneclass _Google:@@ -257,7 +270,12 @@ class _Google:return Nonenewest = files[-1]properties = newest.get("appProperties") or {}- return Found(str(newest["id"]), Stamp.decode(properties.get(_STAMP_PROPERTY)))+ declared = properties.get(_DECLARED_PROPERTY)+ return Found(+ str(newest["id"]),+ Stamp.decode(properties.get(_STAMP_PROPERTY)),+ str(declared) if declared else None,+ )def create(self, name: str, tag: str) -> str:body = {@@ -281,12 +299,15 @@ class _Google:if exc.resp.status != 404:raise- def stamp(self, doc_id: str, stamp: Stamp) -> None:+ def stamp(self, doc_id: str, stamp: Stamp | None, declared: str) -> None:+ """Record the target's last write (``stamp``, when it wrote) and the+ fingerprint of the content it was declared with."""+ properties = {_DECLARED_PROPERTY: declared}+ if stamp is not None:+ properties[_STAMP_PROPERTY] = stamp.encode()_execute(self._drive.files().update(- fileId=doc_id,- body={"appProperties": {_STAMP_PROPERTY: stamp.encode()}},- fields="id",+ fileId=doc_id, body={"appProperties": properties}, fields="id"))@@ -369,7 +390,12 @@ def _apply_action(account: UserAccount, action: _DocAction) -> None:f"read it to write, {_WRITE_ATTEMPTS} times; run again once it is quiet.")if written is not None or created:- _stamp(google, doc_id, NEW if created else short(state.revision_id), written)+ base = NEW if created else short(state.revision_id)+ _stamp(google, doc_id, base, written, action.declared)+ elif found is not None and found.declared != action.declared:+ # Nothing to write (the doc already reads as declared), but the+ # declaration changed: a reader compares its text with this one.+ google.stamp(doc_id, None, action.declared)if plan.person_edits:_logger.warning("Google Doc %r (%s) keeps a person's edits; CocoIndex left these blocks "@@ -380,9 +406,12 @@ def _apply_action(account: UserAccount, action: _DocAction) -> None:)-def _stamp(google: _Google, doc_id: str, base: str, written: _Written | None) -> None:+def _stamp(+ google: _Google, doc_id: str, base: str, written: _Written | None, declared: str+) -> None:"""Record that the doc's latest revision is the target's own write, planned- on ``base``: read it again, and stamp it only if no one edited it since."""+ on ``base``, of the content ``declared`` fingerprints: read it again, and+ vouch for it only if no one edited it since."""state = _docs.read_document(google.get(doc_id))after = written.after if written is not None else Noneif after is None or after == state.revision_id:@@ -390,7 +419,7 @@ def _stamp(google: _Google, doc_id: str, base: str, written: _Written | None) ->after = state.revision_idelse:observed = "" # someone edited after the write; no stamp vouches for it- google.stamp(doc_id, Stamp(base, short(after), observed))+ google.stamp(doc_id, Stamp(base, short(after), observed), declared)def _describe(edit: _docs.PersonEdit) -> str:diff --git a/python/tests/connectors/test_google_docs_target.py b/python/tests/connectors/test_google_docs_target.pyindex 98a7ebb1..8f2a2096 100644--- a/python/tests/connectors/test_google_docs_target.py+++ b/python/tests/connectors/test_google_docs_target.py@@ -9,7 +9,9 @@ ranges grow when text is inserted at either of their boundaries, the leasthelpful reading of Docs' behavior, so the target must not depend on it.A *comment* in the fake is anchored to the code units of a quoted text, as a-Docs comment is: it survives only if those units were never deleted.+Docs comment is: it survives only if those units were never deleted. A+*suggestion* is text inserted in suggestion mode: it is in the body, marked+with ``suggestedInsertionIds`` as Docs reports it to an editor, until accepted."""from __future__ import annotations@@ -37,7 +39,13 @@ try:import httpxfrom cocoindex.connectors import google_docs, google_drive- from cocoindex.connectors.google_docs import _auth, _docs, _markdown, _target+ from cocoindex.connectors.google_docs import (+ _auth,+ _docs,+ _markdown,+ _reader,+ _target,+ )from cocoindex.connectors.google_drive import _oauthHAS_GOOGLE = True@@ -67,6 +75,7 @@ class _Unit:ch: strstyle: dict[str, Any]para: dict[str, Any] | None = None+ suggested: bool = False # a pending suggested insertionclass BadRequest(Exception):@@ -264,19 +273,22 @@ class FakeDoc:i = 0while i < len(units):j = i- while j + 1 < len(units) and units[j + 1].style == units[i].style:+ while (+ j + 1 < len(units)+ and units[j + 1].style == units[i].style+ and units[j + 1].suggested == units[i].suggested+ ):j += 1text = "".join(u.ch for u in units[i : j + 1])text = text.encode("utf-16-le", "surrogatepass").decode("utf-16-le")+ text_run: dict[str, Any] = {+ "content": text,+ "textStyle": copy.deepcopy(units[i].style),+ }+ if units[i].suggested:+ text_run["suggestedInsertionIds"] = ["suggest.1"]elements.append(- {- "startIndex": s + i,- "endIndex": s + j + 1,- "textRun": {- "content": text,- "textStyle": copy.deepcopy(units[i].style),- },- }+ {"startIndex": s + i, "endIndex": s + j + 1, "textRun": text_run})i = j + 1para = units[-1].para@@ -347,6 +359,19 @@ class FakeDoc:self.delete(index, index + len(_code_units(old)))self.revision += 1+ def person_suggest(self, after: str, text: str) -> None:+ """Insert ``text`` after ``after`` in suggestion mode."""+ index = self.find(after) + len(_code_units(after))+ self.insert(index, text)+ for unit in self.units[index - 1 : index - 1 + len(_code_units(text))]:+ unit.suggested = True+ self.revision += 1++ def accept_suggestions(self) -> None:+ for unit in self.units:+ unit.suggested = False+ self.revision += 1+def person_delete_paragraph(self, text: str) -> None:index = self.find(text)span = next((s, e) for s, e in self.spans() if s <= index < e)@@ -677,8 +702,15 @@ def test_the_first_run_creates_the_doc_with_a_named_range_per_block((file,) = google.files.values()assert file["name"] == "Weekly brief"assert file["mimeType"] == "application/vnd.google-apps.document"- # The tag the doc is found by, and the stamp of the target's last write.- assert set(file["appProperties"]) == {"cocoindexDoc", "cocoindexWrite"}+ # The tag the doc is found by, the stamp of the target's last write, and+ # the fingerprint of the content it was written from; each within the 124+ # bytes Drive allows a property's key and value.+ assert set(file["appProperties"]) == {+ "cocoindexDoc",+ "cocoindexWrite",+ "cocoindexDeclared",+ }+ assert all(len(k) + len(v) <= 124 for k, v in file["appProperties"].items())doc = google.only_doc()assert doc.lines() == [("NORMAL_TEXT", None, "Kept current from the sources."),@@ -1321,13 +1353,15 @@ def test_random_successive_versions_leave_exactly_the_declared_doc(# --- reading back a person's edits ---------------------------------------------------def _read(setup: Setup, declared: str) -> google_docs.DocRead | None:- """``read_doc`` run in a component of its own app, as a flow would."""- out: dict[str, google_docs.DocRead | None] = {}+def _read(setup: Setup, last_declared: str) -> google_docs.DocEdits | None:+ """``read_doc_edits`` run in a component of its own app, as a flow would."""+ out: dict[str, google_docs.DocEdits | None] = {}@coco.fnasync def main() -> None:- out["read"] = await google_docs.read_doc(GDOCS, "Weekly brief", declared)+ out["read"] = await google_docs.read_doc_edits(+ GDOCS, "Weekly brief", last_declared=last_declared+ )setup.google.calls.clear()coco.App(@@ -1345,7 +1379,7 @@ def _person_deletes_block(doc: FakeDoc, block: _markdown.Block) -> None:doc.revision += 1-def test_read_doc_hands_back_a_persons_edits_in_the_declared_markdown(+def test_read_doc_edits_hands_back_a_persons_edits_against_the_declared_markdown(setup: Setup,) -> None:setup.run(setup.app("read_back_doc"), BRIEF)@@ -1354,11 +1388,10 @@ def test_read_doc_hands_back_a_persons_edits_in_the_declared_markdown(# Nothing changed by a person: the declared text exactly, and two reads.read = _read(setup, BRIEF)- assert read == google_docs.DocRead(+ assert read == google_docs.DocEdits(url=f"https://docs.google.com/document/d/{doc_id}/edit",+ edits=(),content=BRIEF,- edited=(),- deleted=(),)assert [m for m, _ in setup.google.calls] == ["GET", "GET"] # find, readassert setup.google.writes() == []@@ -1373,8 +1406,18 @@ def test_read_doc_hands_back_a_persons_edits_in_the_declared_markdown(read = _read(setup, BRIEF)assert read is not None- assert read.edited == (("Brief", "Risks"),)- assert read.deleted == (("Brief", "Sources"),)+ assert read.edits == (+ google_docs.BlockEdit(+ heading_path=("Brief", "Risks"),+ declared="## Risks\n\nGoogle may change *named range* behavior.",+ current="## Risks\n\nGoogle could change _named range_ behavior.",+ ),+ google_docs.BlockEdit(+ heading_path=("Brief", "Sources"),+ declared="## Sources\n\nhttps://example.com/a and https://example.com/b.",+ current=None,+ ),+ )assert read.content == BRIEF.replace("## Risks\n\nGoogle may change *named range* behavior.\n\n","## Risks\n\nGoogle could change _named range_ behavior.\n\n",@@ -1397,14 +1440,15 @@ def test_declaring_the_content_read_back_makes_the_blocks_the_targets_again(doc.person_replace("Google may change", "Google could change")on_edit = doc.comment("could change")read = _read(setup, BRIEF)- assert read is not None and read.edited == (("Brief", "Risks"),)+ assert read is not None+ assert [e.heading_path for e in read.edits] == [("Brief", "Risks")]with caplog.at_level(logging.WARNING, logger=_target.__name__):setup.run(app, read.content)assert not _warnings(caplog) # nothing kept from the flow any moreassert doc.comment_survives(on_edit) # the person's text is not rewritten- assert _read(setup, read.content) == google_docs.DocRead(- read.url, read.content, (), ()+ assert _read(setup, read.content) == google_docs.DocEdits(+ read.url, (), read.content)# The block is the flow's again: its next change is written.setup.run(app, read.content.replace("could change", "will change"))@@ -1425,7 +1469,8 @@ def test_a_heading_a_person_renamed_is_taken_in_without_a_second_copy(on_c1 = doc.comment("c1")doc.person_replace("Plan", "The plan") # renames the blocks under it tooread = _read(setup, markdown)- assert read is not None and read.edited == (("Plan",),)+ assert read is not None+ assert read.edits == (google_docs.BlockEdit(("Plan",), "## Plan", "## The plan"),)assert read.content == markdown.replace("## Plan", "## The plan")setup.run(app, read.content)@@ -1444,12 +1489,95 @@ def test_a_heading_a_person_renamed_is_taken_in_without_a_second_copy(assert _docs.plan_write(state, _blocks(read.content), None).requests == []+def test_deletions_are_reported_only_against_what_was_written(+ setup: Setup, caplog: pytest.LogCaptureFixture+) -> None:+ """A deleted block leaves no trace in the doc: against Markdown the doc+ was not written from, a block it lacks may never have been there."""+ setup.run(setup.app("base_check"), BRIEF)+ doc = setup.google.only_doc()+ _person_deletes_block(doc, _blocks(BRIEF)[4]) # Sources+ doc.person_replace("Google may change", "Google could change")++ # The next version, never written: its new block is not "deleted".+ newer = BRIEF + "\n## Next steps\n\nWrite the docs.\n"+ with caplog.at_level(logging.WARNING, logger=_reader.__name__):+ read = _read(setup, newer)+ assert read is not None+ assert [(e.heading_path, e.current is None) for e in read.edits] == [+ (("Brief", "Risks"), False)+ ]+ assert "## Sources" in read.content and "## Next steps" in read.content+ (record,) = [r for r in caplog.records if r.name == _reader.__name__]+ assert "'Brief > Sources'" in record.getMessage()+ assert "'Brief > Next steps'" in record.getMessage()++ # Against what was written, the deletion is reported, with no warning.+ caplog.clear()+ with caplog.at_level(logging.WARNING, logger=_reader.__name__):+ read = _read(setup, BRIEF)+ assert read is not None+ assert [(e.heading_path, e.current is None) for e in read.edits] == [+ (("Brief", "Risks"), False),+ (("Brief", "Sources"), True),+ ]+ assert not caplog.records+++def test_a_respelled_declaration_is_what_the_doc_was_written_from(+ setup: Setup,+) -> None:+ """Markdown spelled otherwise writes nothing, and still becomes the text+ deletions are reported against."""+ app = setup.app("respelled")+ setup.run(app, BRIEF)+ respelled = BRIEF.replace("*named range*", "_named range_")+ setup.run(app, respelled)+ assert [m for m, _ in setup.google.writes()] == ["PATCH"] # the fingerprint only+ _person_deletes_block(setup.google.only_doc(), _blocks(BRIEF)[4])+ read = _read(setup, respelled)+ assert read is not None+ assert [(e.heading_path, e.current) for e in read.edits] == [+ (("Brief", "Sources"), None)+ ]+++def test_a_pending_suggestion_is_no_edit_until_accepted(+ setup: Setup, caplog: pytest.LogCaptureFixture+) -> None:+ app = setup.app("suggest")+ setup.run(app, BRIEF)+ doc = setup.google.only_doc()+ doc.person_suggest("Google may change", " eventually")+ read = _read(setup, BRIEF)+ assert read is not None and read.edits == () and read.content == BRIEF++ # The writer leaves the block as it is, suggestion and all.+ with caplog.at_level(logging.WARNING, logger=_target.__name__):+ setup.run(app, BRIEF.replace("behavior.", "behavior, soon."))+ assert "Google may change eventually named range behavior." in [+ t for _, _, t in doc.lines()+ ]+ assert "'Brief > Risks' (edited" in caplog.text++ doc.accept_suggestions()+ read = _read(setup, BRIEF.replace("behavior.", "behavior, soon."))+ assert read is not None+ (edit,) = read.edits+ assert (+ edit.current+ == "## Risks\n\nGoogle may change eventually _named range_ behavior."+ )++_watch_runs: list[str | None] = []@coco.fn(memo=True)-async def _watch(declared: str) -> None:- read = await google_docs.read_doc(GDOCS, "Weekly brief", declared)+async def _watch(last_declared: str) -> None:+ read = await google_docs.read_doc_edits(+ GDOCS, "Weekly brief", last_declared=last_declared+ )_watch_runs.append(None if read is None else read.content)@@ -1481,12 +1609,16 @@ def test_a_read_reruns_its_reader_on_a_persons_edit_only(setup: Setup) -> None:doc.comment("Google may")doc.revision += 1 # a comment may move the revisionassert run() == 0+ doc.person_suggest("Ship the", " shiny") # a pending suggestion: no change yet+ assert run() == 0+ doc.accept_suggestions() # ... until someone accepts it+ assert run() == 1 and "Ship the shiny new" in str(_watch_runs[-1])doc.person_replace("Google may change", "Google could change")assert run() == 1 and "Google could change" in str(_watch_runs[-1])assert run() == 0- # The flow takes the person's text in: the target's write, planned on the+ # The flow takes the people's text in: the target's write, planned on the# revision the reader read, makes the blocks the target's again.- edited = BRIEF.replace("Ship the", "Ship the new").replace(+ edited = BRIEF.replace("Ship the", "Ship the shiny new").replace("Google may change *named range*", "Google could change _named range_")assert run(edited) == 0