CocoIndex is an incremental engine for long-horizon agents. It continuously transforms data from any source (codebase, meeting notes) and builds the context for agents deployed in production.
CocoIndex V1 is now live. It is a redesign of how you write incremental data pipelines, built from a year of watching what people wanted to do with CocoIndex.
CocoIndex V1 is built for AI engineers and agent builders: people building context, RAG, memory, knowledge graphs that live agents depend on. For that audience the most important design choice is a small one: you write the pipeline in Python, with the data types you already use, so code that Claude or Cursor already writes works here.
The headline change: V1 has no DSL. Your whole pipeline is now regular async Python, growing organically as functions call each other. The engine still does what CocoIndex has always done (managed targets, incremental processing, change tracking in Rust), but it now sits behind a Python-native API instead of a DSL with its own type system and rules.
The mental model is unchanged: you declare what the target should look like as a function of the source, and the engine figures out the transitions. CocoIndex calls this state-driven programming, the same shape as React, spreadsheets, or SQL materialized views.
Why CocoIndex: the incremental engine for long-horizon agents
[Agents] use tools that were designed for human-speed interaction … In this world where you have an agent that is operating 50 times faster than a human …
At GTC 2026, Jeff Dean, in conversation with Bill Dally, described a bottleneck that affects every piece of infrastructure around AI. He compared it to Amdahl’s law: no matter how fast the model gets, end-to-end throughput is capped by the slowest thing in the loop, and for an agent that is often a tool built for people, such as a compiler’s startup time.
Jeff Dean also stressed low-latency inference for agents that work on their own for hours or even days, doing many things and correcting themselves along the way.
Data infrastructure is one of those tools, and it matters beyond inference. An agent reasoning over a codebase, a conversation graph, a document corpus, or a stream of events needs that data fresh, organized, and cheap to query throughout the run, not only on the first call, because:
- Agents write code. The artifacts they produce become source data for the next reasoning step.
- Agents make decisions and record them. Traces, plans, audit logs: written by agents, read by other agents.
- Agents update data while they run. A long-horizon agent isn’t a one-shot query; it’s a process that edits its own context as it proceeds.
- Source data arrives faster, too. Codebases, logs, Slack, PRs, tickets, sensor feeds: all updating in the background, all expected to be visible to whatever the agent is doing next.
The default pattern for indexing that data (“batch-rebuild overnight”) was built for humans who check a dashboard every morning. For agents running 50 times faster, that cadence is the bottleneck. What agents need is an engine that treats derived data as a function of source data and keeps it in sync incrementally: only what changed gets re-embedded, re-upserted, or re-published, without a full rebuild or a wait for the next batch window.
That has always been CocoIndex’s job. V1 keeps the same incremental, state-driven guarantees and makes them cover the pipeline shapes agents produce (entity resolution, clustering, multi-phase reduction, per-tenant topologies, conditional targets), beyond “chunk → embed → upsert.”
The patterns in the examples gallery are ones a long-horizon agent can run itself, with outputs that become fresh source data for the next agent and no refresh job to maintain by hand.
What is an incremental engine, and why it’s hard to build for production
@coco.fn def f(src): chunks = split(src) target.row(embed(chunks))
persistent data pipeline · control plane · eight subsystems
- Live cachingReuse what has not changed; only the Δ runs.
- Pipeline catalogEvery flow is registered and can be reused.
- Version trackingCode, schema and data, versioned end to end.
- Continuously learningAdapts as your data and code evolve.
- LineageEvery target row traces back to a source.
- Task schedulingTasks run in parallel.
- Metrics collectionReports throughput, freshness and cost.
- Failure managementRetries, back-off, dead letters.
An incremental engine does one job: keep derived data in sync with source data without redoing work that’s already been done. The source data is changing and the processing code is dynamic.
To do it right, you need:
- Reliable change detection across heterogeneous sources (filesystems, databases, queues, APIs).
- Content fingerprints stable enough to diff but cheap enough to compute every run.
- Persistent state that records what the last run produced so this run can compare against it.
- Memoization keyed on both data and code fingerprints so that editing a helper function invalidates only the callers that depended on it.
- Managed target lifecycles (schema evolution, orphan cleanup when a source disappears, idempotent upserts).
- Transactional behavior when you’re writing to multiple targets at once.
- Recovery logic for every partial failure in between.
Building this in-house is a large engineering project, and the maintenance continues as sources, targets, and schemas evolve. CocoIndex ships all of this in the engine, so the code you write is the pipeline itself, not the scaffolding around it.
everything else you would build and keep running
Notion published the engineering work behind its in-house incremental pipeline for vector search, which serves live agents and runs simpler transformations than the ones above (no clustering, for example).
The V1 mental model: declare states, not steps
Target = F(Source)
The mental model is the same as in V0; the execution model changed.
CocoIndex has always been a state-driven framework. You don’t write code that says “compute this delta and apply it”; you describe what the target should look like as a function of the source, and the engine works out the transitions. If you’ve used React, spreadsheets, or SQL materialized views, you already know the shape of this:
- React: declare UI as a function of state → React re-renders what changed.
- Spreadsheets: declare formulas → cells recompute when inputs change.
- CocoIndex: declare target states as a function of source → engine syncs what changed.
What’s new in V1 is how you express that declaration. The whole pipeline is now plain async Python, without FlowBuilder, DataScope, or a two-phase “define, then run” lifecycle. Functions call other functions, and loops and if statements are ordinary Python. Behind the scenes, CocoIndex tracks every target state you declare and every memoized intermediate value, so the next run only does what changed.
V1 is deliberately not intrusive. You can start with a single @coco.fn on a plain Python function and opt into more of the engine as the pipeline grows:
- Flip on
memo=Truewhen re-running starts to cost real time. - Add
declare_*targets when you want the engine to own the output lifecycle. - Move to live mode when you want the pipeline to keep watching for changes.
That model rests on a small vocabulary:
- An App is the top-level entity you run.
- Inside it, each processing component groups one item’s work with its target states and runs independently.
- Incremental processing means only what changed gets reapplied to the target.
- Function memoization skips any function whose input and code haven’t changed since the last run.
What that means in practice is code you don’t have to write: a bookkeeping table tracking which file was last processed, insert / update / delete branches, “did I already embed this chunk?” checks, migration scripts when your schema changes. The engine owns the target state, diffs against the previous run, and only does what changed. V0 already did this; V1 lets you write it as plain Python.
A complete V1 app (a PDF-to-Markdown converter) is short enough to read at a glance:
import pathlib
import cocoindex as coco
from cocoindex.connectors import localfs
from cocoindex.resources.file import PatternFilePathMatcher
from docling.document_converter import DocumentConverter
_converter = DocumentConverter()
@coco.fn(memo=True)
def process_file(file: localfs.File, outdir: pathlib.Path) -> None:
markdown = _converter.convert(file.file_path.resolve()).document.export_to_markdown()
outname = file.file_path.path.stem + ".md"
localfs.declare_file(outdir / outname, markdown, create_parent_dirs=True)
@coco.fn
async def app_main(sourcedir: pathlib.Path, outdir: pathlib.Path) -> None:
files = localfs.walk_dir(
sourcedir, path_matcher=PatternFilePathMatcher(included_patterns=["**/*.pdf"]),
)
await coco.mount_each(process_file, files.items(), outdir)
app = coco.App("PdfToMarkdown", app_main,
sourcedir=pathlib.Path("./pdf_files"),
outdir=pathlib.Path("./out"))
app.update_blocking()
Three things to notice:
process_fileis just a function: you can set a breakpoint in it, call it directly, or run it under pytest. The@coco.fn(memo=True)decorator hooks it into the engine’s change-detection and memoization, but doesn’t change its calling convention.localfs.declare_file(...)is a declaration, not a write. It tells CocoIndex “the target state for this path is this content.” If the target state hasn’t changed since the last run, nothing happens on disk. If the source file disappears, the declaration disappears too, and CocoIndex deletes the corresponding output file automatically.coco.mount_each(...)mounts one processing component per file. Each component is its own unit of incremental change detection: when one file’s content changes, only that component re-runs.
Why V1: the V0 ceiling
V0 worked (developers shipped real pipelines in production), but four constraints kept coming back, all consequences of the DSL-first design:
- Two worlds, one program.
FlowBuilder/DataScope/DataSlicefor topology, regular Python for leaves. The DSL world couldn’tifits way into a different shape, couldn’t pass values into normal Python and back. Clustering, entity resolution, reduction across items, conditional sources: every one of them hit the seam. - A separate type system. Like a database, the engine had its own types distinct from Python’s, so every Python type you wanted to use needed a bi-directional conversion wired in.
dataclassandNDArraywere covered; a PILImageor a pyarrow array was not: if no conversion existed, you couldn’t hand it to a function, and what did cross the boundary got marshaled on the way in and out. - Postgres as a hard dependency. The engine used Postgres for its own bookkeeping, so
pip install cocoindex && python script.pywasn’t a real path: you stood up a database first, even for a tiny local pipeline. - Static topology.
add_source()and.export()were declared before execution, so multi-tenancy, config-driven topologies, and runtime target selection all required scaffolding around CocoIndex rather than being expressible in it.
Four shifts that change what you can build
FlowBuilder.build() → frozen graphV1 await coco.mount(fn) adds a node while it runs + nodeNative Python typesno bindingsV0 dataclassNDArraydicttupleV1 PIL.ImagepyarrowtorchanythingEmbedded LMDBno database serverV0 Postgres server for bookkeeping: process, migrations, portsV1 One local directory, cocoindex.db, no serverDynamic I/Oper tenant, per config rowV0 Sources declared up front: add_source() at startupV1 for cfg in tenants: await mount(…) new row → new mount1. No more DSL: the flow grows during execution
In V0, the flow had to be fully described before any data moved through it. FlowBuilder returned a frozen graph; the engine then interpreted that graph at execution time. In V1, the flow is built as your code executes. app_main runs as the root processing component. Every await coco.mount(...) it does adds a child component. Every declare_* call records a target state. The component tree is built by running your code, not by parsing a graph beforehand.
V1 supports these pipeline shapes:
-
Reduction patterns: “for each project, look at all its files, then aggregate.” The multi-codebase summarization example does exactly this:
@coco.fn(memo=True) async def process_project(project_name, files, output_dir): file_infos = await coco.map(extract_file_info, files) # fan out project_info = await aggregate_project_info(project_name, file_infos) # reduce markdown = generate_markdown(project_name, project_info, file_infos) localfs.declare_file(output_dir / f"{project_name}.md", markdown) -
Multi-phase pipelines with cross-item logic: entity resolution across sessions, clustering, deduplication. The conversation-to-knowledge example uses three phases (per-session extraction, cross-session entity resolution, knowledge-base assembly) all expressed as function calls in a single
app_main. -
Conditional topology:
if config.enable_kafka: await kafka.mount_kafka_topic_target(...). This needs neither a flag pattern nor a separate flow definition.
The engine calls your functions directly instead of interpreting a graph, so the debugging tools you already use work.
2. Native Python types instead of a separate type system
V1 doesn’t have a separate type system: it uses Python’s directly. The types V0 supported through bindings (dataclass, Pydantic, NDArray, dict, list, tuple) still work with nothing to wire up, and types V0 couldn’t express (a PIL Image, a pyarrow array, an arbitrary class from a library you just pulled in) can be passed as function arguments the same way:
from PIL.Image import Image
@coco.fn(memo=True)
async def caption_image(img: Image) -> str:
return await vlm.describe(img)
That Image is just PIL.Image: no wrapper, no conversion. Pass the function a pyarrow Table, a torch.Tensor, or any class from a library you happen to have imported; the signature is whatever you’d write in plain Python.
Targets, function arguments, return types, memoization keys: everything is described in the type hints you’d write anyway. For memoized return values that persist between runs, the same type hint drives serialization; we wrote a long post on how the type-guided serializer works underneath.
3. Embedded LMDB instead of a Postgres dependency
V0’s “Postgres for engine bookkeeping” requirement is gone. V1 stores its internal state in LMDB, an embedded key-value store that lives in a local directory (COCOINDEX_DB). There’s no server process to run, schema to migrate, or port to expose.
pip install cocoindex
# where CocoIndex keeps its LMDB state
export COCOINDEX_DB=./cocoindex.db
cocoindex update main.py
That is the setup (the examples ship COCOINDEX_DB in their .env). The LMDB store holds the target-state ledger, the memoization cache, and the component-path tree across runs. The memory map starts at 4 GiB, and since 1.0.15 CocoIndex enlarges it automatically when a write needs more space, so map_size is a starting point, not a cap. On a 64-bit system the map is reserved virtual address space, not physical memory.
Postgres is still a first-class target (with pgvector support); it’s just no longer required for the engine to function.
4. Dynamic sources and targets
In V0, sources and targets were declared in the flow definition, before execution. In V1, they’re created during execution, by regular function calls, and the component-path tree tracks their identity across runs. So you can:
- Mount a target conditionally based on a config row, an environment variable, or a feature flag.
- Create different targets per item: e.g., one Postgres schema per tenant, one Kafka topic per category, one LanceDB table per dataset.
- Build the topology from a database: query the list of active tenants at startup and mount one component per tenant, each with its own set of targets. When a tenant disappears from the list, CocoIndex automatically cleans up their target states (because the path is no longer mounted).
The conversation-to-knowledge example does this for entity types: it iterates over a list of entity configurations and mounts one SurrealDB target per type, all from a dict comprehension in app_main.
entity_tables = {
cfg.name: await surrealdb.mount_table_target(SURREAL_DB, cfg.name, entity_schema)
for cfg in ENTITY_TYPES
}
Add a new entity type to ENTITY_TYPES, restart, and a new table appears, managed by CocoIndex from then on. Remove a type, and CocoIndex drops its table, without a migration script and without leaving orphaned data.
The larger difference from V0 shows when that list isn’t a constant (a changing file, a database row, a live tenant registry): V0 could already generate topology from static inputs at flow-creation time, but couldn’t react when those inputs changed.
What we kept from V0
V1 exists to make what V0 already did well available to more pipelines. Those guarantees are unchanged, and they now apply across a much wider set of pipeline shapes.
Fully managed targets
You declare what your target should look like; CocoIndex makes sure it’s in that state, on any change, whether to source data or to your code. This is the lifecycle, top to bottom:
| Layer | Upsert (first or changed declaration) | Delete (no longer declared) |
|---|---|---|
| Container: schema (tables · directories · other containers) | Create or alter | Drop |
| Leaf: data (rows · files · embeddings · other leaves) | Insert or update | Delete |
The target is fully owned by CocoIndex: if you stop declaring something, it goes away. You write neither migrations nor “did I already write this row?” checks, and no orphaned data is left behind. This is the same contract whether the target is a Postgres table, a LanceDB table, a Neo4j node label, or a directory of files on disk. (A Kafka topic gets a tombstone for each key you stop declaring.)
Incremental processing, two levels deep
Incremental processing is still the core of the engine, and V1 exposes it through two concepts:
- Components own target states. When a component finishes, CocoIndex diffs its declared target states against the last run and applies only the changes (create / alter / drop for containers, insert / update / delete for contents), including recursive cleanup of sub-paths no longer mounted. When a memoized component’s inputs and code haven’t changed, the whole component is skipped.
@coco.fnfunctions participate in change detection. Every decorated function’s code is fingerprinted, and that fingerprint propagates up the call chain. Addmemo=Trueand the return value is also cached, keyed on the function’s arguments plus its code fingerprint and any change-tracked context it reads, so the body is skipped when none of them has changed.
Edit a @coco.fn helper and only the components and memoized callers that depend on it are invalidated.
Rust-powered engine
The change-detection, fingerprinting, target-state diffing, and persistence are all written in Rust on top of Tokio. That has not changed: Python is the user-facing API, and the hot paths still run in Rust, as they did in V0.
An end-to-end text-embedding pipeline
Here’s a complete text-embedding pipeline that walks markdown files, chunks them, embeds the chunks with a SentenceTransformer model, and writes everything (with a vector index) to Postgres. It’s the text_embedding example trimmed down: every line of pipeline logic is below.
import pathlib
from dataclasses import dataclass
from typing import AsyncIterator, Annotated
import asyncpg
from numpy.typing import NDArray
import cocoindex as coco
from cocoindex.connectors import localfs, postgres
from cocoindex.ops.text import RecursiveSplitter
from cocoindex.ops.sentence_transformers import SentenceTransformerEmbedder
from cocoindex.resources.chunk import Chunk
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
from cocoindex.resources.id import IdGenerator
PG_DB = coco.ContextKey[asyncpg.Pool]("text_embedding_db")
EMBEDDER = coco.ContextKey[SentenceTransformerEmbedder]("embedder", detect_change=True)
_splitter = RecursiveSplitter()
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
async with asyncpg.create_pool("postgres://...") as pool:
builder.provide(PG_DB, pool)
builder.provide(EMBEDDER, SentenceTransformerEmbedder("sentence-transformers/all-MiniLM-L6-v2"))
yield
@dataclass
class DocEmbedding:
id: int
filename: str
chunk_start: int
chunk_end: int
text: str
embedding: Annotated[NDArray, EMBEDDER]
@coco.fn
async def process_chunk(chunk, filename, id_gen, table):
table.declare_row(row=DocEmbedding(
id=await id_gen.next_id(chunk.text),
filename=str(filename),
chunk_start=chunk.start.char_offset,
chunk_end=chunk.end.char_offset,
text=chunk.text,
embedding=await coco.use_context(EMBEDDER).embed(chunk.text),
))
@coco.fn(memo=True)
async def process_file(file: FileLike, table) -> None:
text = await file.read_text()
chunks = _splitter.split(text, chunk_size=2000, chunk_overlap=500, language="markdown")
id_gen = IdGenerator()
await coco.map(process_chunk, chunks, file.file_path.path, id_gen, table)
@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
table = await postgres.mount_table_target(
PG_DB, table_name="doc_embeddings",
table_schema=await postgres.TableSchema.from_class(DocEmbedding, primary_key=["id"]),
)
table.declare_vector_index(column="embedding")
files = localfs.walk_dir(
sourcedir, recursive=True,
path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),
)
await coco.mount_each(process_file, files.items(), table)
app = coco.App(coco.AppConfig(name="TextEmbedding"), app_main,
sourcedir=pathlib.Path("./markdown_files"))
Several things you would expect in a pipeline are not in the code, because the engine handles them:
| Not in the code | What handles it |
|---|---|
| A flow definition phase | app_main runs and the topology emerges. |
| Custom column types | embedding: Annotated[NDArray, EMBEDDER] is the schema; from_class reads it. |
| Insert / update / delete branches | declare_row(...) describes the desired state; the engine diffs. |
| A “did this chunk already get embedded?” check | Memoization. |
| A bookkeeping table for which file was last processed | LMDB keeps the previous run’s fingerprints. |
A manual migration when you change DocEmbedding | Schema evolution is part of the managed-target contract. |
The same code handles every kind of change. Pick one below to see what the next cocoindex update does: which per-file components run, which memoized calls hit, and which rows change in Postgres.
What runs on the next cocoindex update
Illustrative: 3 files, 6 rows. Names, ids and offsets are made up; what runs, hits and writes follows the engine’s rules.ChangeAdd pricing.md (about 2,300 characters) to markdown_files/.
- Files processed
- 1 of 4
- Embeddings computed
- 2 · 0 from memo
- Postgres writes
- 2 inserts
Processing components
app_mainrunsroot, runs on every update: lists 4 filesintro.mdskippedmemo hit, body skippedinstall.mdskippedmemo hit, body skippedfaq.mdskippedmemo hit, body skippedpricing.mdnewnew path, mounted and run
Memoized calls
process_file(intro.md)hitsame path, mtime and contentprocess_file(install.md)hitsame path, mtime and contentprocess_file(faq.md)hitsame path, mtime and contentprocess_file(pricing.md)missno entry yetembed(pricing.md #1)missnew textembed(pricing.md #2)missnew text
Postgres doc_embeddings
id 1–6 3 files 6 rowsno writeid 7 pricing.md 0–1700insertid 8 pricing.md 1200–2300insert
WhyA new path mounts a new component. The other three files keep their path, mtime and content, so their memos hit and nothing inside them runs.
ChangeAdd one sentence (60 characters) to a paragraph in the middle of install.md.
- Files processed
- 1 of 3
- Embeddings computed
- 1 · 2 from memo
- Postgres writes
- 1 insert, 1 update, 1 delete
Processing components
app_mainrunsroot, runs on every update: lists the filesintro.mdskippedmemo hit, body skippedinstall.mdrunscontent changed, re-splitfaq.mdskippedmemo hit, body skipped
Memoized calls
process_file(intro.md)hitsame path, mtime and contentprocess_file(install.md)misscontent fingerprint changedembed(install.md #1)hitsame textembed(install.md #2)misstext changedembed(install.md #3)hitsame text, movedprocess_file(faq.md)hitsame path, mtime and content
Postgres doc_embeddings
id 1 intro.md 0–850no writeid 2 install.md 0–1950no writeid 3 install.md 1450–3300deleteold text of #2id 7 install.md 1450–3360insertnew text of #2id 4 install.md 2860–4160updatewas 2800–4100; offsets moved by 60id 5–6 faq.md 2 rowsno write
WhyThe file’s content fingerprint changed, so its component runs again and re-splits. embed is memoized on the model and the chunk text, so only the changed chunk is embedded. The row id comes from next_id(chunk.text): the changed chunk gets a new id, its old row is deleted, and the chunk that only moved keeps its id and is updated.
ChangeDelete faq.md.
- Files processed
- 0 of 2
- Embeddings computed
- none called
- Postgres writes
- 2 deletes
Processing components
app_mainrunsroot, runs on every update: lists 2 filesintro.mdskippedmemo hit, body skippedinstall.mdskippedmemo hit, body skippedfaq.mdremovedno longer mounted
Memoized calls
process_file(intro.md)hitsame path, mtime and contentprocess_file(install.md)hitsame path, mtime and content
Postgres doc_embeddings
id 1–4 2 files 4 rowsno writeid 5 faq.md 0–1900deleteid 6 faq.md 1400–2400delete
Whyfaq.md is no longer listed, so its component is not mounted and its rows are no longer declared. The engine deletes them. No function runs for the deleted file.
ChangeChange the splitter call in process_file.
- chunk_size=2000, chunk_overlap=500
+ chunk_size=1000, chunk_overlap=500- Files processed
- 3 of 3
- Embeddings computed
- 11 · 1 from memo
- Postgres writes
- 11 inserts, 5 deletes
Processing components
app_mainrunsroot, runs on every update: lists the filesintro.mdrunslogic changedinstall.mdrunslogic changedfaq.mdrunslogic changed
Memoized calls
process_file(intro.md)missits source changedembed(intro.md #1)hitsame text: 850 characters, one chunkprocess_file(install.md)missits source changedembed(install.md, new chunks)miss ×7new textprocess_file(faq.md)missits source changedembed(faq.md, new chunks)miss ×4new text
Postgres doc_embeddings
id 1 intro.md 0–850no writeid 2–4 install.md 3 old chunksdelete ×3id 7–13 install.md 7 new chunksinsert ×7id 5–6 faq.md 2 old chunksdelete ×2id 14–17 faq.md 4 new chunksinsert ×4
Whychunk_size is part of process_file’s source, so its logic fingerprint changed and every file’s memo misses. intro.md is shorter than 1,000 characters: it splits into the same single chunk, so its embed call hits and its row stays.
ChangeProvide a different model for EMBEDDER in the lifespan.
- SentenceTransformerEmbedder("sentence-transformers/all-MiniLM-L6-v2")
+ SentenceTransformerEmbedder("sentence-transformers/all-MiniLM-L12-v2")- Files processed
- 3 of 3
- Embeddings computed
- 6 · 0 from memo
- Postgres writes
- 6 updates
Processing components
app_mainrunsroot, runs on every update: lists the filesintro.mdrunsEMBEDDER changedinstall.mdrunsEMBEDDER changedfaq.mdrunsEMBEDDER changed
Memoized calls
process_file(×3)miss ×3read EMBEDDER, which changedembed(all chunks)miss ×6the model is part of the key
Postgres doc_embeddings
id 1–6 3 files 6 rowsupdate ×6new embedding, same id
WhyEMBEDDER is a ContextKey with detect_change=True. process_file reads it through process_chunk, so a new model invalidates every file’s memo, and embed misses because the model is part of its key. The text and ids are the same, so each row is updated in place. Both models output 384 dimensions; a model with another dimension also changes the vector column’s type, which the managed target alters.
ChangeRename a local variable in process_chunk. Its output does not change.
- Files processed
- 3 of 3
- Embeddings computed
- 0 · 6 from memo
- Postgres writes
- none
Processing components
app_mainrunsroot, runs on every update: lists the filesintro.mdrunscallee logic changedinstall.mdrunscallee logic changedfaq.mdrunscallee logic changed
Memoized calls
process_file(×3)miss ×3process_chunk’s source changedembed(all chunks)hit ×6same model, same text
Postgres doc_embeddings
id 1–6 3 files 6 rowsno writedeclared again, identical
Whyprocess_chunk is a @coco.fn, and its logic fingerprint propagates to the memoized caller that ran it, so every file runs again. Logic propagates up to callers, not down: embed’s own logic and key are unchanged, so all 6 calls hit. The declared rows are identical to the last run, so the target diff is empty: no writes.
ChangeEdit query_once(), the search function in the same main.py.
- Files processed
- 0 of 3
- Embeddings computed
- none called
- Postgres writes
- none
Processing components
app_mainrunsroot, runs on every update: lists the filesintro.mdskippedmemo hit, body skippedinstall.mdskippedmemo hit, body skippedfaq.mdskippedmemo hit, body skipped
Memoized calls
process_file(intro.md)hitsame path, mtime and contentprocess_file(install.md)hitsame path, mtime and contentprocess_file(faq.md)hitsame path, mtime and content
Postgres doc_embeddings
id 1–6 3 files 6 rowsno write
Whyquery_once() is not a @coco.fn, and no pipeline function calls it, so it is not part of any logic fingerprint. Only app_main runs; every file’s memo is still valid.
Pipeline shapes V0 couldn’t express
A short tour of pipeline shapes the V1 model makes natural, drawn from the example gallery:
Multi-codebase summarization: fan out per project, fan out per file with coco.map, reduce back up to a project summary, write a markdown file per project. The control flow is plain Python; the engine decides which projects need re-summarizing.
coco.map, then reduce to a project summary.main.pyutils.pyapi.pydb.pya.mdlib.rsmain.rscli.rsb.mdapp.tsroutes.tsauth.tshooks.tscache.tsc.mdConversation-to-knowledge: three phases in one app_main: per-session extraction (use_mount per YouTube ID), cross-session entity resolution (use_mount per entity type), and knowledge-base assembly (one final mount). Each phase reads the outputs of the prior one through normal function returns.
yt_a1b2yt_c3d4yt_e5f6yt_g7h8PersonTopicClaimknowledge_basenodesedgesembeddingsCSV → Kafka live: a live filesystem watcher feeding a Kafka topic target, producing one message per changed row (a tombstone when a row is deleted), in about 60 lines. File-level source, row-level change events: one Kafka message per changed CSV row.
orders_topic.orders.csvwatched folder| id | user | total | ts |
|---|---|---|---|
| alice | 49.00 | 02:01 | |
| bob | 18.50 | 02:04 |
orders_topic{"id":102, "user":"bob", "total":18.50}Most V0 connectors came over to V1, and new ones joined them, including SurrealDB, SQLite, Kafka, Valkey, Snowflake, BigQuery and Iggy. Examples include:
- HN trending topics
- Image search
- PDF embedding
- Paper metadata extraction
- Amazon S3 + embeddings
- Google Drive + embeddings
- Code embedding to LanceDB
Try it
pip install cocoindex
Then either follow the Quickstart (PDF → Markdown in about 30 lines), or clone the repo and run any of the examples directly:
git clone https://github.com/cocoindex-io/cocoindex
cd cocoindex/examples/text_embedding
pip install -e .
cocoindex update main.py
The docs for V1 live at cocoindex.io/docs. The pieces most worth reading first:
- Core Concepts: state-driven processing, target states, processing components, memoization
- App: top-level entry point, lifespan, CLI
- Processing Component:
mount,use_mount,mount_each, component paths - Function:
@coco.fn, memoization, change detection - Live Mode: pipelines that keep watching for changes
Report bugs, request features, or suggest documentation changes on GitHub issues. Join the community on Discord.
Frequently asked questions
What changed in CocoIndex V1?
The headline change is that V1 has no DSL. Your whole pipeline is now regular async Python, growing organically as functions call each other. The Rust engine still manages targets, processes updates incrementally, and tracks changes. The state-driven mental model (declare the target as a function of the source) is unchanged.
What is an incremental engine and why is it hard to build?
An incremental engine does one job: keep derived data in sync with source data without redoing work that's already been done, even as both the source data and the processing code change. Doing it right requires reliable change detection across heterogeneous sources, stable-but-cheap content fingerprints, persistent state from the last run, memoization keyed on both data and code, managed target lifecycles, transactional multi-target writes, and recovery for partial failures.
Building this in-house is a large engineering project, and the maintenance continues as sources, targets, and schemas evolve. CocoIndex ships all of this in the engine. See What is an incremental engine, and why it's hard to build for production.
Does CocoIndex V1 still require Postgres?
No. V0's requirement to run Postgres for engine bookkeeping is gone. V1 stores its internal state in LMDB, an embedded key-value store in a local directory (set by COCOINDEX_DB). It needs no server process, schema migration, or exposed port. So pip install cocoindex, setting COCOINDEX_DB, and cocoindex update main.py is the whole setup. Postgres is still a first-class target (with pgvector), just no longer required for the engine to run. For a team deployment where workers on several hosts share that state, CocoIndex Plus keeps it in Postgres; see CocoIndex Plus.
What is state-driven programming in CocoIndex?
State-driven programming means you declare what the target should look like as a function of the source, and the engine figures out the transitions. React, spreadsheets, and SQL materialized views use the same model. You don't write "compute this delta and apply it"; you describe the target state and the engine syncs what changed.
Can CocoIndex V1 use any Python type like PIL Image or torch.Tensor?
Yes. V1 uses Python's type system directly. The types V0 supported through bindings (dataclass, Pydantic, NDArray, dict, list, tuple) still work with nothing to wire up, and types V0 couldn't express (a PIL.Image, a pyarrow array, a torch.Tensor, or an arbitrary class from a library you just imported) can be passed as function arguments the same way. The type hints you'd write anyway describe targets, arguments, return types, and memoization keys.
How does memoization work in CocoIndex V1?
Every @coco.fn function's code is fingerprinted, and that fingerprint propagates up the call chain. Add memo=True and the return value is also cached, keyed on the function's arguments plus its code fingerprint and any change-tracked context it reads, so the body is skipped when none of them has changed. Editing a @coco.fn helper invalidates only the components and memoized callers that depended on it.
See What we kept from V0.
Why did CocoIndex move away from the V0 DSL?
V0 worked, but four constraints kept recurring, all consequences of the DSL-first design: a split between the FlowBuilder/DataScope world and regular Python ("two worlds, one program"); a separate type system requiring bi-directional conversions; Postgres as a hard dependency for engine bookkeeping; and static topology declared before execution. Fixing them meant a redesign.
Why do AI agents need an incremental data engine?
At GTC 2026, Jeff Dean, in conversation with Bill Dally, described agents that operate 50 times faster than a human while using tools designed for human-speed interaction. The default "batch-rebuild overnight" indexing pattern was built for humans who check a dashboard every morning. For agents that write code, record decisions, update data while they run, and consume source data arriving in the background, that batch cadence is the bottleneck. They need an engine that treats derived data as a function of source data and keeps it in sync incrementally, re-embedding only changed chunks and re-upserting only changed rows.
See Why CocoIndex: the incremental engine for long-horizon agents.
Build fresh context for your agents.
CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.



