Most indexing pipelines treat a file as one item: read it, split it, embed the chunks, write the rows. That works while files are small. It stops working when one file holds thousands of independent records, because the file then sets the unit of memory, of commit and of retry for all of them.
This post uses USPTO patent files as the example. It shows where to put the unit of work in CocoIndex v1, and measures what the choice changes on a real run against Postgres.
What one unit of work per file costs
The USPTO issues patents every Tuesday and publishes the full text of each week’s grants as one zipped XML file. The file is a concatenation of XML documents, one per patent, so a standard XML parser cannot read it whole; you split it into documents first. The USPTO issued about 324,000 utility patents in 2024, roughly 6,000 a week, so one weekly file holds thousands of patents.
Each patent fans out into chunks, and each chunk into an embedding. If the whole file is one unit of work, four things follow:
- Memory. Every chunk and vector of the file is held until the file is done.
- Latency. No row from the file reaches the index until the last patent finishes.
- Restarts. A worker restart loses all the work on the file. If one file takes 24 hours and the worker restarts every 8 hours, a run that starts over each time never finishes.
- Edits. A change to one patent re-runs the whole file.
The fix is to establish a smaller unit of work after the fan-out: one per patent, not one per file.
The processing component is the unit of sync and recovery
In CocoIndex v1 that unit has a name: the processing component. A component runs the logic for one item and declares the rows (target states) that item produces. When the component finishes, CocoIndex compares those rows with the ones the same component declared last run, and writes the difference as a unit. Nothing is written before a component finishes. If a crash interrupts the write itself, the next run converges the target to the right rows.
A component marked memo=True is skipped on the next run when its input and code have not changed, and the rows it declared are kept. A component also has a stable path, such as one ending in process_patent/"12000150". When an item disappears, CocoIndex deletes the rows owned by its path.
The CocoIndex docs state the size trade-off in How big should a processing component be?: coarse components sync more rows together as a unit, but you see updates only after the larger component finishes. Fine components sync each item’s rows as soon as it is processed and isolate failures to that item, but rows owned by different components do not sync together.
For a large file, the size of the component decides four things: how much is held in memory, when rows become visible, what a restart loses and what an edit re-runs.
One component per patent
<?xml ...?><us-patent-grant>
<?xml ...?><us-patent-grant>
<?xml ...?><us-patent-grant>
⋮one XML document per patent, back to backThe file is still the source item, so one process_file component per file reads and parses it. Instead of chunking every patent itself, it calls coco.mount_each with one (doc_number, patent) pair per patent. Each pair becomes a process_patent component that chunks and embeds one patent and declares its rows.
import os
import pathlib
import xml.etree.ElementTree as ET
from dataclasses import dataclass
from typing import Annotated, AsyncIterator
import asyncpg
from numpy.typing import NDArray
import cocoindex as coco
from cocoindex.connectors import localfs, postgres
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from cocoindex.ops.text import RecursiveSplitter
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
PG_DB = coco.ContextKey[asyncpg.Pool]("pg_db")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
async with asyncpg.create_pool(os.environ["POSTGRES_URL"]) as pool:
builder.provide(PG_DB, pool)
builder.provide(EMBEDDER, SentenceTransformerEmbedder("sentence-transformers/all-MiniLM-L6-v2"))
yield
@dataclass
class Patent:
doc_number: str
title: str
text: str
@dataclass
class PatentChunk:
doc_number: str
chunk_start: int
text: str
embedding: Annotated[NDArray, EMBEDDER]
splitter = RecursiveSplitter()
def parse_patents(xml_text: str) -> list[Patent]:
# A weekly file is many XML documents back to back: split, then parse each.
patents = []
for doc in xml_text.split("<?xml ")[1:]:
root = ET.fromstring(doc[doc.index("<us-patent-grant"):])
patents.append(Patent(
doc_number=root.findtext(".//publication-reference//doc-number"),
title=root.findtext(".//invention-title"),
text=" ".join("".join(p.itertext()) for p in root.iter("p")),
))
return patents
@coco.fn
async def embed_chunk(chunk: Chunk, doc_number: str, table: postgres.TableTarget[PatentChunk]) -> None:
table.declare_row(row=PatentChunk(
doc_number=doc_number,
chunk_start=chunk.start.char_offset,
text=chunk.text,
embedding=await coco.use_context(EMBEDDER).embed(chunk.text),
))
@coco.fn(memo=True)
async def process_patent(patent: Patent, table: postgres.TableTarget[PatentChunk]) -> None:
chunks = splitter.split(patent.text, chunk_size=1000, chunk_overlap=100)
await coco.map(embed_chunk, chunks, patent.doc_number, table)
@coco.fn(memo=True)
async def process_file(file: FileLike, table: postgres.TableTarget[PatentChunk]) -> None:
patents = parse_patents(await file.read_text())
# One component per patent, keyed by its document number.
await coco.mount_each(process_patent, [(p.doc_number, p) for p in patents], table)
@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
table = await postgres.mount_table_target(
PG_DB,
table_name="patent_chunks",
table_schema=await postgres.TableSchema.from_class(
PatentChunk, primary_key=["doc_number", "chunk_start"]
),
)
files = localfs.walk_dir(
sourcedir, path_matcher=PatternFilePathMatcher(included_patterns=["*.xml"])
)
await coco.mount_each(process_file, files.items(), table)
app = coco.App(
coco.AppConfig(name="PatentIndex"),
app_main,
sourcedir=pathlib.Path("./uspto"),
)
Save it as main.py, set POSTGRES_URL and COCOINDEX_DB, and run cocoindex update main. Four lines matter here:
coco.mount_each(process_patent, [(p.doc_number, p) ...])makes the patent the unit of sync and recovery. The document number is the key, so each patent keeps the same component path across runs.@coco.fn(memo=True)onprocess_patentskips every patent whose text did not change.coco.map(embed_chunk, chunks, ...)runs the chunks of one patent concurrently inside the patent’s component. Chunks do not become components of their own.chunk_size=1000is your choice:RecursiveSplittersplits to the size you pass.
SentenceTransformerEmbedder.embed is memoized itself, so an unchanged chunk inside a re-run patent costs no model call.
To make the whole file one component instead, replace the mount_each line with a loop that calls coco.map(embed_chunk, ...) for every patent inside process_file. To make each chunk a component, have process_patent call mount_each over its chunks.
What the boundary changes, measured
To measure the three choices, _data-src/measure.py runs the pipeline above on cocoindex 1.1.1 and Postgres 17, with the default concurrency limit. The input is one synthetic file in the USPTO format with 300 patents, which split into 2,187 chunks. The embedder is a memoized stand-in that waits 10 ms per call with 4 calls at a time, like a rate-limited embedding service, and logs each call; the embed counts below come from that log. Each choice runs in three scenarios: a clean run; a run killed with SIGKILL after half of the embed calls, followed by a second run; and a run after one paragraph of patent 12000150 changed.
Where the component boundary sits
Measured: cocoindex 1.1.1, Postgres, one file of 300 patentsPer patent: each component writes its rows when it finishes. At the halfway point Postgres already had 1,086 rows.
- Components
- 3011 file + 300 patents
- Rows held before write
- 74peak, declared but not yet in Postgres
- Rows in Postgres at halfway
- 1,086sampled at 1,099 of 2,187 embed calls
- Embed calls
- 2,187one per chunk
Rows in Postgres as the embed calls finish
Gray dashes: rows written the moment each embed returns.
The 300 patents in the file
- about 149 patents in Postgres at halfway (from the row count)
- 151 still to come
| Whole file | Per patent | Per chunk | |
|---|---|---|---|
| Components | 1 | 301 | 2,488 |
| Rows held before write (peak) | 2,187 | 74 | 105 |
| Rows in Postgres at halfway | 0 | 1,086 | 1,072 |
| Kill at half: rows already in Postgres | 0 | 1,082 | 1,103 |
| Kill at half: embed calls repeated | 1,098 | 28 | 24 |
| Edit one patent: patents whose code ran | 300 | 1 | 1 |
| Edit one patent: embed calls | 1 | 1 | 3 |
Whole file. The one component holds all 2,187 rows until the end, and Postgres shows no rows until the last embed call returns. The kill lost all the work on the file. The second run made all 2,187 embed calls again, because the memo entries of a component that did not finish are not saved. After the edit, the memo on the embedder held the model calls to one, but the file component still parsed and split all 300 patents and declared all 2,187 rows again.
Per patent. Rows reach Postgres as each patent finishes, so the index fills while the run goes on. The kill cost 28 embed calls. Most were the patents in progress at that moment; the rest belonged to a few patents whose rows had reached Postgres but whose finish CocoIndex had not yet recorded, so they ran again and converged to the same rows. The second run skipped the 146 patents recorded as finished. After the edit, the file component parsed the file again, but of the 300 patent components only the one for 12000150 ran.
Per chunk. The run tracks eight times as many components as per patent, for little gain in this pipeline: the restart cost was about the same, and the edit made more embed calls. The chunks are keyed by character offset, so the inserted text moved the keys of the chunks after it, and those became new components with no memo entries of their own. Per-chunk components are more likely to pay off when the work on one chunk is itself long.
The restart numbers, the peak rows held and the halfway counts depend on timing, so they move between runs; the table shows one recorded run. Across three recorded runs, the peak rows held ranged from 74 to 146 per patent and from 59 to 117 per chunk. The edit counts and the whole-file zeros were the same in every run.
Bound how much runs at once
A component boundary bounds what one component holds. How many components run at the same time is a separate limit: by default CocoIndex runs up to 1024 components at once per app. Set max_inflight_components in AppConfig to lower that limit:
app = coco.App(
coco.AppConfig(name="PatentIndex", max_inflight_components=8),
app_main,
sourcedir=pathlib.Path("./uspto"),
)
A mount_each call then waits while no slot is free, so the file component cannot run ahead of the patents. In the three recorded per-patent runs with a limit of 8, the peak rows held before write ranged from 25 to 46, against 74 to 146 with the default. The limit caps concurrency; memory follows from how much each running component holds. Flow control covers the limit and how a parent lends its slot to its children.
The boundary does not change one cost: process_file reads the whole file and holds the parsed patents while it mounts them. The per-patent components bound the derived data (chunks and vectors); the input text is still held whole.
When records depend on each other
Per-record components work when the records are independent, as patents in a weekly file are. When records depend on each other, the right unit of work is the result of combining them:
- a join between two sources: one component per joined entity;
- grouping or clustering: one component per group, keyed by the group ID;
- an aggregate across records: one component per aggregate.
The rule is the same as for a large file. Establish the component after the fan-in or fan-out, at the level where the unit is independent and its key is stable.
Choosing the component size
- Make one component per independent record, keyed by an ID the source gives you (a document number, a primary key), not by a position in the file.
- Keep the work inside a record, such as its chunks, in that record’s component with
coco.map. - Mark components
memo=Trueso a restart and an edit skip what did not change. - Set
max_inflight_componentswhen each component holds a sizeable amount of data or calls a rate-limited service.
For the full model, read The processing component and Concurrency control in the CocoIndex docs. The source is on GitHub.
Frequently asked questions
Why is a large file a problem for an indexing pipeline?
A file connector yields one item per file. If one unit of work handles the whole file, every chunk and vector is held until the file is done, no row reaches the index before the end, a worker restart loses all the work, and a change to one record re-runs the whole file. A USPTO weekly grant file is an example: it holds thousands of patents.
What is a processing component in CocoIndex?
A processing component runs the logic for one item and declares the rows that item produces. When it finishes, CocoIndex writes the difference from the last run as a unit, and nothing is written for a component that has not finished. A component marked memo=True is skipped when its input and code have not changed. The component is the unit of sync and recovery.
See The processing component is the unit of sync and recovery.
How do I process one patent at a time from a large USPTO XML file?
Keep one component per file that reads and parses it, then call coco.mount_each with one (doc_number, patent) pair per patent. Each patent becomes its own memoized component that chunks and embeds its text with coco.map and declares its rows with declare_row. The document number keeps each patent's component path stable across runs.
What does component size change in a measured run?
On cocoindex 1.1.1 and Postgres, with one file of 300 patents (2,187 chunks): with one component for the whole file, Postgres had 0 rows at the halfway point, a kill at half lost all the work, and the second run made all 2,187 embed calls again. With one component per patent, rows landed as patents finished, the kill cost 28 embed calls, and an edit to one patent re-ran only that patent's component.
Should each chunk be its own processing component?
Usually not. In the measured run, per-chunk components tracked eight times as many components as per-patent ones, with about the same restart cost. Chunks keyed by character offset also change keys when text is inserted before them, so the edit to one patent ran 3 chunk components and made 3 embed calls, against 1 embed call per patent. Run the chunks of one record inside its component with coco.map.
How do I bound how many components hold data at once?
Set max_inflight_components in AppConfig. The default is 1024. With a lower limit, a mount_each call waits while no slot is free, so the parent cannot run ahead of its children. The limit caps concurrency; memory follows from how much each running component holds. In three measured per-patent runs, a limit of 8 kept the peak rows held before write between 25 and 46, against 74 to 146 with the default.
What if records depend on each other, as in a join or grouping?
Then the unit of work is the result of combining them: one component per joined entity, per group or per aggregate, keyed by a stable ID. Establish the component after the fan-in or fan-out, at the level where the unit is independent.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.
