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
docs(getting-started): replace the overview with a "Why CocoIndex" page (#2890)
Jiangzhou260e3b1428e9
diff --git a/docs/src/components/UseCase.astro b/docs/src/components/UseCase.astronew file mode 100644index 00000000..68c19aae--- /dev/null+++ b/docs/src/components/UseCase.astro@@ -0,0 +1,50 @@+---+// One use-case card: an illustration, then the page's own Markdown. The first+// paragraph is the card's title (write it in bold), then a short description+// and a link to an example. The title is not a heading, so the cards stay out+// of the table of contents. The text stays in the page so that the Markdown+// twin keeps it.+import UseCaseArt from './diagrams/concepts/UseCaseArt.astro';++interface Props {+ art: Parameters<typeof UseCaseArt>[0]['kind'];+}+const { art } = Astro.props;+---+<div class="uc-card">+ <div class="uc-card__art"><UseCaseArt kind={art} /></div>+ <div class="uc-card__body"><slot /></div>+</div>++<style>+ .uc-card {+ display: flex;+ flex-direction: column;+ min-width: 0;+ border: 1px solid var(--rule-strong);+ border-radius: var(--r-2xl);+ background: var(--cream-soft);+ overflow: hidden;+ }+ .uc-card__art {+ padding: 14px 14px 10px;+ background: var(--card-ink);+ border-bottom: 1px solid var(--rule);+ }+ .uc-card__body { padding: 16px 18px 18px; }+ /* The body is Markdown from the page, so these reach past the scope. */+ :global(.prose) .uc-card__body :global(p) {+ margin: 0 0 8px;+ max-width: none;+ font-size: 0.9375rem;+ line-height: 1.5;+ color: var(--muted);+ }+ :global(.prose) .uc-card__body :global(p:first-child) {+ font-size: 1rem;+ line-height: 1.3;+ letter-spacing: -0.01em;+ color: var(--maroon-ink);+ }+ :global(.prose) .uc-card__body :global(p:last-child) { margin-bottom: 0; }+</style>diff --git a/docs/src/components/UseCaseGrid.astro b/docs/src/components/UseCaseGrid.astronew file mode 100644index 00000000..59672be6--- /dev/null+++ b/docs/src/components/UseCaseGrid.astro@@ -0,0 +1,14 @@+---+// A grid of use-case cards. Each child is a <UseCase>; the cards wrap to as+// many columns as the page column holds.+---+<div class="uc-grid"><slot /></div>++<style>+ .uc-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));+ gap: 16px;+ margin: 24px 0;+ }+</style>diff --git a/docs/src/components/diagrams/README.md b/docs/src/components/diagrams/README.mdindex 31a6c96c..020eeddd 100644--- a/docs/src/components/diagrams/README.md+++ b/docs/src/components/diagrams/README.md@@ -67,8 +67,9 @@ src/components/diagrams/├── ComponentPerFile.astro # Drive → per-file PC (Convert → a.md) → Drive├── FileProcess.astro # thin wrapper around ComponentPerFile w/ highlight├── ComponentsFanout.astro # thin wrapper around ComponentPerFile w/ highlight- └── ComponentWithChunks.astro # Drive → App(PC→Split→chunks→Embed→vectors) → VDB- # accepts `memoized` and `scenario` props+ ├── ComponentWithChunks.astro # Drive → App(PC→Split→chunks→Embed→vectors) → VDB+ │ # accepts `memoized`, `scenario` and `componentLabel` props+ └── UseCaseArt.astro # abstract card art for a use case (overview); wrapped by components/UseCase.astro```## The `ShapeGroup` basediff --git a/docs/src/components/diagrams/concepts/ComponentWithChunks.astro b/docs/src/components/diagrams/concepts/ComponentWithChunks.astroindex 69888691..da54fedb 100644--- a/docs/src/components/diagrams/concepts/ComponentWithChunks.astro+++ b/docs/src/components/diagrams/concepts/ComponentWithChunks.astro@@ -38,8 +38,11 @@ export interface Scenario {interface Props {memoized?: boolean;scenario?: Scenario;+ /** Header of each component box. Defaults to "Processing Component";+ a page that has not introduced that term passes the function's name. */+ componentLabel?: string;}-const { memoized = false, scenario } = Astro.props;+const { memoized = false, scenario, componentLabel } = Astro.props;const defaultRows: RowEntry[] = [{ file: 'a.md', chunks: [@@ -108,8 +111,8 @@ const PC_X = FILE_X + FILE_W + FILE_TO_PC_GAP;<DiagramFrameviewBox={`0 0 ${VB_W} ${VB_H}`}maxWidth={960}- title="Processing component with chunks"- desc="Each file is split into chunks; the processing component produces one target state per chunk and syncs them as a unit."+ title={`${componentLabel ?? 'Processing component'} with chunks`}+ desc={`Each file is split into chunks; ${componentLabel ?? 'the processing component'} produces one target state per chunk and syncs them as a unit.`}><LogicBox x={DRIVE.x} y={DRIVE.y} w={DRIVE.w} h={DRIVE.h} label="Drive Folder" /><AppContainer x={APP.x} y={APP.y} w={APP.w} h={APP.h} />@@ -150,6 +153,7 @@ const PC_X = FILE_X + FILE_W + FILE_TO_PC_GAP;<ProcessingComponentx={PC_X} y={pcY} w={PC_W} h={PC_H}+ label={componentLabel}memoized={memoized}status={row.pcStatus}state={row.pcState}diff --git a/docs/src/components/diagrams/concepts/UseCaseArt.astro b/docs/src/components/diagrams/concepts/UseCaseArt.astronew file mode 100644index 00000000..05c38646--- /dev/null+++ b/docs/src/components/diagrams/concepts/UseCaseArt.astro@@ -0,0 +1,170 @@+---+/** Abstract illustration for a use-case card: it shows what the target looks+ like, not how the pipeline runs. Neutral shapes; periwinkle marks the one+ part that a change touches, as in the other diagrams. Decorative: the+ card's heading names the use case, so the SVG is hidden from assistive+ technology. */+import '../diagrams.css';++interface Props {+ kind: 'search' | 'code' | 'graph' | 'extract' | 'table' | 'stream';+}+const { kind } = Astro.props;++// Knowledge graph: a hub, its neighbours, and the edges between them.+const HUB = { x: 120, y: 72 };+const NODES = [+ { x: 56, y: 38, r: 8 },+ { x: 54, y: 106, r: 8 },+ { x: 120, y: 20, r: 6 },+ { x: 184, y: 34, r: 8 },+ { x: 124, y: 124, r: 7 },+];+const DELTA_NODE = { x: 192, y: 98, r: 9 };+const SIDE_EDGES = [[0, 2], [2, 3], [0, 1]];+---+<svg class="uc-art" viewBox="0 0 240 144" aria-hidden="true">+ {kind === 'search' && (+ <g>+ {/* a query, and ranked results; the top result is the fresh one */}+ <rect class="dg-box" x="36" y="14" width="168" height="26" rx="13" />+ <circle class="uc-line" cx="53" cy="26" r="5" />+ <path class="uc-line" d="M57 30 L61 34" />+ <rect class="uc-bar" x="70" y="24.5" width="76" height="5" rx="2.5" />++ <g class="dg-state-new"><rect class="dg-box" x="36" y="52" width="168" height="24" rx="6" /></g>+ <rect class="uc-bar uc-bar--delta" x="48" y="58.5" width="84" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="48" y="67" width="126" height="4" rx="2" />++ <rect class="dg-box" x="36" y="82" width="168" height="24" rx="6" />+ <rect class="uc-bar" x="48" y="88.5" width="104" height="5" rx="2.5" />+ <rect class="uc-bar" x="48" y="97" width="72" height="4" rx="2" />++ <rect class="dg-box" x="36" y="112" width="168" height="24" rx="6" />+ <rect class="uc-bar" x="48" y="118.5" width="66" height="5" rx="2.5" />+ <rect class="uc-bar" x="48" y="127" width="112" height="4" rx="2" />+ </g>+ )}++ {kind === 'code' && (+ <g>+ {/* a source file; one function is one chunk */}+ <rect class="dg-box" x="34" y="12" width="172" height="120" rx="8" />+ <circle class="uc-dot" cx="47" cy="23" r="2.5" />+ <circle class="uc-dot" cx="56" cy="23" r="2.5" />+ <circle class="uc-dot" cx="65" cy="23" r="2.5" />+ <path class="uc-rule" d="M34 34 H206" />++ <rect class="uc-bar" x="46" y="44" width="62" height="5" rx="2.5" />+ <g class="dg-state-new"><rect class="dg-box" x="52" y="56" width="142" height="40" rx="5" /></g>+ <rect class="uc-bar uc-bar--delta" x="60" y="63" width="70" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="70" y="73.5" width="98" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="70" y="84" width="52" height="5" rx="2.5" />+ <rect class="uc-bar" x="46" y="104" width="86" height="5" rx="2.5" />+ <rect class="uc-bar" x="58" y="115" width="112" height="5" rx="2.5" />+ </g>+ )}++ {kind === 'graph' && (+ <g>+ {/* entities and relationships; one entity and its edge are new */}+ {NODES.map((n) => <path class="uc-line" d={`M${HUB.x} ${HUB.y} L${n.x} ${n.y}`} />)}+ {SIDE_EDGES.map(([a, b]) => (+ <path class="uc-line" d={`M${NODES[a].x} ${NODES[a].y} L${NODES[b].x} ${NODES[b].y}`} />+ ))}+ <path class="uc-line uc-line--delta" d={`M${HUB.x} ${HUB.y} L${DELTA_NODE.x} ${DELTA_NODE.y}`} />+ {NODES.map((n) => <circle class="dg-box" cx={n.x} cy={n.y} r={n.r} />)}+ <circle class="dg-box" cx={HUB.x} cy={HUB.y} r="12" />+ <g class="dg-state-new"><circle class="dg-box" cx={DELTA_NODE.x} cy={DELTA_NODE.y} r={DELTA_NODE.r} /></g>+ </g>+ )}++ {kind === 'extract' && (+ <g>+ {/* a document on the left; the fields found in it become a row */}+ <path class="dg-box" d="M28 22 a6 6 0 0 1 6 -6 H82 L100 34 V122 a6 6 0 0 1 -6 6 H34 a6 6 0 0 1 -6 -6 Z" />+ <path class="uc-line" d="M82 16 V34 H100" />+ <rect class="uc-bar" x="38" y="44" width="46" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="38" y="56" width="32" height="5" rx="2.5" />+ <rect class="uc-bar" x="38" y="68" width="52" height="5" rx="2.5" />+ <rect class="uc-bar" x="38" y="80" width="40" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="38" y="92" width="44" height="5" rx="2.5" />+ <rect class="uc-bar" x="38" y="104" width="28" height="5" rx="2.5" />++ <path class="uc-line" d="M110 72 H134 M129 67 L134 72 L129 77" />++ <rect class="dg-box" x="144" y="36" width="78" height="72" rx="6" />+ <g class="dg-state-new"><rect class="dg-box" x="144" y="72" width="78" height="18" /></g>+ <path class="uc-rule" d="M144 54 H222 M144 72 H222 M144 90 H222 M183 36 V108" />+ <rect class="uc-bar" x="152" y="42.5" width="20" height="5" rx="2.5" />+ <rect class="uc-bar" x="191" y="42.5" width="22" height="5" rx="2.5" />+ <rect class="uc-bar" x="152" y="60.5" width="24" height="5" rx="2.5" />+ <rect class="uc-bar" x="191" y="60.5" width="16" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="152" y="78.5" width="18" height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="191" y="78.5" width="24" height="5" rx="2.5" />+ <rect class="uc-bar" x="152" y="96.5" width="22" height="5" rx="2.5" />+ <rect class="uc-bar" x="191" y="96.5" width="14" height="5" rx="2.5" />+ </g>+ )}++ {kind === 'table' && (+ <g>+ {/* a source table, and a target table with one derived column */}+ <rect class="dg-box" x="20" y="34" width="72" height="76" rx="6" />+ <path class="uc-rule" d="M20 53 H92 M20 72 H92 M20 91 H92 M56 34 V110" />+ {[0, 1, 2, 3].map((r) => (+ <g>+ <rect class="uc-bar" x="28" y={41 + r * 19} width={[18, 20, 14, 22][r]} height="5" rx="2.5" />+ <rect class="uc-bar" x="64" y={41 + r * 19} width={[20, 14, 22, 16][r]} height="5" rx="2.5" />+ </g>+ ))}++ <path class="uc-line" d="M102 72 H126 M121 67 L126 72 L121 77" />++ <rect class="dg-box" x="136" y="34" width="86" height="76" rx="6" />+ <g class="dg-state-new"><path class="dg-box" d="M194 34 H216 a6 6 0 0 1 6 6 V104 a6 6 0 0 1 -6 6 H194 Z" /></g>+ <path class="uc-rule" d="M136 53 H194 M136 72 H194 M136 91 H194 M165 34 V110" />+ {[0, 1, 2, 3].map((r) => (+ <g>+ <rect class="uc-bar" x="143" y={41 + r * 19} width={[14, 16, 12, 16][r]} height="5" rx="2.5" />+ <rect class="uc-bar" x="172" y={41 + r * 19} width={[16, 12, 16, 14][r]} height="5" rx="2.5" />+ <rect class="uc-bar uc-bar--delta" x="201" y={41 + r * 19} width="14" height="5" rx="2.5" />+ </g>+ ))}+ </g>+ )}++ {kind === 'stream' && (+ <g>+ {/* messages on a topic; each one goes to the store that matches it */}+ <path class="uc-rule" d="M18 72 H132" />+ <rect class="dg-box" x="20" y="64" width="24" height="16" rx="8" />+ <rect class="dg-box" x="50" y="64" width="24" height="16" rx="8" />+ <rect class="dg-box" x="80" y="64" width="24" height="16" rx="8" />+ <g class="dg-state-new"><rect class="dg-box" x="110" y="64" width="24" height="16" rx="8" /></g>++ <path class="uc-line uc-line--delta" d="M138 72 C154 72 152 40 168 40 M163 35.5 L168 40 L162.5 44" />+ <path class="uc-line" d="M138 72 C154 72 152 104 168 104 M162.5 100 L168 104 L163 108.5" />++ <g class="dg-state-new">+ <path class="dg-box" d="M174 32 V50 a22 6 0 0 0 44 0 V32" />+ <ellipse class="dg-box" cx="196" cy="32" rx="22" ry="6" />+ </g>+ <path class="dg-box" d="M174 96 V114 a22 6 0 0 0 44 0 V96" />+ <ellipse class="dg-box" cx="196" cy="96" rx="22" ry="6" />+ </g>+ )}+</svg>++<style>+ .uc-art { display: block; width: 100%; height: auto; }+ /* strokes without a fill: arrows, edges, the magnifier */+ .uc-line { fill: none; stroke: var(--text-3); stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }+ .uc-line--delta { stroke: var(--coral); stroke-width: 1.6; }+ /* hairlines inside a shape: table grid, title bar, the topic's track */+ .uc-rule { fill: none; stroke: var(--rule-strong); stroke-width: 1; }+ /* a line of text */+ .uc-bar { fill: var(--cream-dim); }+ .uc-bar--delta { fill: var(--coral); }+ .uc-dot { fill: var(--cream-dim); }+</style>diff --git a/docs/src/content/docs/getting_started/overview.mdx b/docs/src/content/docs/getting_started/overview.mdxindex f1a614a9..f7655047 100644--- a/docs/src/content/docs/getting_started/overview.mdx+++ b/docs/src/content/docs/getting_started/overview.mdx@@ -1,78 +1,351 @@----title: CocoIndex *overview*-rust_description: >- CocoIndex is a real-time data transformation framework for AI with incremental processing,- with a Rust SDK that builds pipelines into your own binary: only the data that actually- changed is reprocessed, and lineage is observable end to end.+title: Why *CocoIndex*description: >- CocoIndex is a real-time data transformation framework for AI with incremental processing:- only the data that actually changed is reprocessed, lineage is observable end to end,- and the schema is known up front.+ CocoIndex keeps derived data, such as a search index or a knowledge graph, in sync+ with a source that changes. This page shows the problem it solves, the code you write,+ and where it fits.+rust_description: >+ CocoIndex keeps derived data, such as a search index or a knowledge graph, in sync+ with a source that changes. This page shows the problem it solves, the Rust code you+ write, and where it fits.----CocoIndex is a framework for building data processing pipelines for AI workloads, with built-in incremental processing.+import ComponentWithChunks from '/src/components/diagrams/concepts/ComponentWithChunks.astro';+import UseCaseGrid from '/src/components/UseCaseGrid.astro';+import UseCase from '/src/components/UseCase.astro';++CocoIndex builds materialized views over data that changes, structured or unstructured.+A materialized view is a stored result that a system keeps in sync with the data it came from.++- The **target** is the view. It is usually context for an AI agent or application: a search index, a knowledge graph, or tables. It is in your own store, such as Postgres or a vector database, and your application queries it there.+- The **source** is a codebase, a folder of documents, chat messages, or rows in a database.++You define the view in <Lang only="python">Python</Lang><Lang only="rust">Rust</Lang> instead of SQL:++**Target = F(Source)**++`F` is a set of <Lang only="python">Python</Lang><Lang only="rust">Rust</Lang> functions that you write, with your own libraries and control flow.+CocoIndex keeps the target up to date when the source changes, and when `F` changes.++## What people build with it++<UseCaseGrid>+<UseCase art="search">++**Search and RAG indexes**++Chunk and embed documents into a vector store. An edit replaces only the chunks that changed.++Example: [Semantic search 101](/docs/examples/text-embedding/)++</UseCase>+<UseCase art="code">++**Code indexes for coding agents**++Split code along its syntax and embed it. A commit runs only the files that changed.++Example: [Index your codebase for AI agents](/docs/examples/index-codebase/)++</UseCase>+<UseCase art="graph">++**Knowledge graphs**++Extract entities and relationships with an LLM into a graph database. Only an edited note goes through the LLM again.++Example: [Turn meeting notes into a knowledge graph](/docs/examples/meeting-notes-to-knowledge-graph/)++</UseCase>+<UseCase art="extract">++**Structured extraction**++Turn PDFs, forms and transcripts into typed rows with an LLM. A run skips the documents that did not change.++Example: [Patient intake extraction](/docs/examples/patient-intake-dspy/)++</UseCase>+<UseCase art="table">++**Derived tables**++Read rows from a database, derive new fields, and write them to a table or a vector store. Only the rows that changed run again.++Example: [Postgres as a source](/docs/examples/postgres-source/)++</UseCase>+<UseCase art="stream">++**Message streams**++Consume a Kafka topic as keyed messages, and write each message to a table chosen by its fields. A newer message for a key updates its row, and a tombstone deletes it.++Example: [Consume Kafka into LanceDB](/docs/examples/kafka-to-lancedb/)++</UseCase>+</UseCaseGrid>++The [examples](/docs/examples/) page has more.<Lang only="rust"> The examples there are in Python. Many of them have a Rust port in [`examples/rust`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust).</Lang>++## The second run is the hard one-## Programming model+The first version of a pipeline is short. It reads each item, transforms it, and writes the result.+That version is correct once. After that, the source changes, and so does your code.-CocoIndex uses a *declarative*, state-driven programming model. You specify *what* your target should look like as a function of your source data — not *how* to incrementally update it. CocoIndex handles change detection and applies only the necessary updates automatically.+One way to keep the target current is to rebuild everything on a schedule.+Each rebuild runs every embedding and every LLM call again, and the data is stale between rebuilds.-If you've used React, spreadsheets, or materialized views, this will feel familiar:-- **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](../programming_guide/target_state) as a function of source → CocoIndex syncs what changed+The other way is to make the pipeline incremental yourself. Your code then has five more jobs.-## CocoIndex features+**1. Turn each source change into the right target changes.**+One source item usually produces several target items.+For example, one document becomes many chunks, and each chunk is one row.-### Rust engine-<Lang only="python">CocoIndex executes pipelines with a Rust engine and a Python API.</Lang><Lang only="rust">CocoIndex executes pipelines with a Rust engine. The Rust SDK calls that engine directly, in your own binary, with no Python runtime.</Lang>+| The source change | What your code must do to the target |+|---|---|+| A new document | Insert one row for each chunk. |+| An edited document | Compare the new chunks with the old rows. Insert some rows, update some, delete some, and leave the rest. |+| A deleted document | Find every row that came from the document, and delete it. |++For an edit or a delete, your code must know which rows each document produced before.+It therefore needs a record of the earlier runs.++**2. Handle a change to your own code.**+A new prompt, chunk size or model makes existing rows out of date.+Your code must find those rows, compute them again, and replace them.+A new field in a row also changes the table.++**3. Find the changes, completely and quickly.**+A scan finds every change, but it takes time, so the target is stale between scans.+Change events, such as file system notifications or a database change feed, arrive immediately. But the pipeline sees them only while it runs.+A pipeline that needs fresh data needs both, and both must run the same processing logic.++**4. Do not repeat expensive work.**+The pipeline needs a cache for each embedding and each LLM result, so that unchanged text costs nothing.++**5. Recover from a run that stops halfway.**+The target is then between two states. Your code must find which writes completed, and finish or repair the rest.++With CocoIndex, your code stays close to the first version. It reads, transforms, and declares the result.+CocoIndex records what each run did, in a local database. The next run uses that record to do only the work that a change requires.++## What you write++This pipeline builds a search index over a folder of Markdown files.+It splits each file into chunks, embeds each chunk, and keeps one row for each chunk in a Postgres table.<Lang only="python">-### Python transformations-Write transformations in Python with your existing libraries.-Write batch-style code; CocoIndex tracks dependencies and applies incremental updates in batch and live mode.+The code is a shortened version of the [text embedding example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/text_embedding).+It leaves out the imports and the row class. It also leaves out the setup of the Postgres connection (`PG_DB`), the embedding model (`EMBEDDER`) and the text splitter (`_splitter`).</Lang><Lang only="rust">-### Rust transformations-Write transformations as ordinary async Rust functions with your existing crates.-Write batch-style code; CocoIndex tracks dependencies and applies incremental updates in batch and live mode.-Attribute macros add logic tracking, memoization and batching to a function; row types derive their schema.+The code is from the [text embedding example](https://github.com/cocoindex-io/cocoindex/tree/main/examples/rust/text_embedding).+It leaves out the imports, the row type and the table setup. It also leaves out the setup of the Postgres connection and the embedding model (`EMBEDDER`).</Lang>-### Incremental processing-CocoIndex tracks fine-grained dependencies and recomputes work affected by changes to source data or processing code.+{/* Rust: examples/rust/text_embedding/src/main.rs (process_chunk and process_file as they are there, without the doc comments; the end of index(), without the comments) */}+<LangTabs>+<Fragment slot="python">++```python title="main.py"[email protected](memo=True)+async def process_file(file: FileLike, table: postgres.TableTarget[DocChunk]) -> None:+ text = await file.read_text()+ embedder = coco.use_context(EMBEDDER)+ id_gen = IdGenerator()+ for chunk in _splitter.split(text, chunk_size=2000, language="markdown"):+ table.declare_row(+ row=DocChunk(+ id=await id_gen.next_id(chunk.text),+ filename=str(file.file_path.path),+ text=chunk.text,+ embedding=await embedder.embed(chunk.text),+ )+ )+++async def app_main(sourcedir: pathlib.Path) -> None:+ table = await postgres.mount_table_target(+ PG_DB,+ table_name="doc_chunks",+ table_schema=await postgres.TableSchema.from_class(DocChunk, primary_key=["id"]),+ )+ files = localfs.walk_dir(+ sourcedir,+ recursive=True,+ path_matcher=PatternFilePathMatcher(included_patterns=["**/*.md"]),+ live=True,+ )+ await coco.mount_each(process_file, files.items(), table)+++app = coco.App("DocSearch", app_main, sourcedir=pathlib.Path("./docs"))+```++</Fragment>+<Fragment slot="rust">++```rust+#[cocoindex::function]+async fn process_chunk(+ ctx: &Ctx,+ chunk: Chunk,+ text: &str,+ filename: &str,+ id_gen: &IdGenerator,+ table: &postgres::TableTarget,+) -> Result<()> {+ let chunk_text = chunk.text(text);+ let id = i64::try_from(id_gen.next_id(ctx, chunk_text).await?)+ .map_err(|_| Error::engine("generated id does not fit in BIGINT"))?;+ table.declare_row(+ ctx,+ &DocEmbedding {+ id,+ filename: filename.to_string(),+ chunk_start: chunk.start.char_offset as i32,+ chunk_end: chunk.end.char_offset as i32,+ text: chunk_text.to_string(),+ embedding: ctx.get_key(&EMBEDDER)?.embed(ctx, chunk_text).await?,+ },+ )+}++#[cocoindex::function(memo, memo_key(table = skip))]+async fn process_file(ctx: &Ctx, file: &FileEntry, table: &postgres::TableTarget) -> Result<()> {+ let text = file.read_text().await?;+ let chunks = RecursiveSplitter::new()?.split_with(+ &text,+ RecursiveChunkConfig {+ chunk_size: CHUNK_SIZE,+ min_chunk_size: None,+ chunk_overlap: Some(CHUNK_OVERLAP),+ language: Some("markdown".to_string()),+ },+ );+ let filename = file.key();+ let id_gen = IdGenerator::new();+ ctx.map(chunks, async |chunk| {+ process_chunk(ctx, chunk, &text, &filename, &id_gen, &table).await+ })+ .await?;+ Ok(())+}+```++The main function lists the files and runs `process_file` for each one:++```rust+let files = walk_dir(sourcedir)+ .recursive(true)+ .path_matcher(PatternFilePathMatcher::include(["**/*.md"])?)+ .live()+ .poll_interval(Duration::from_secs(1));+ctx.mount_each_live(&"process_file", files, move |ctx, file: FileEntry| {+ let target_table = target_table.clone();+ async move { process_file(&ctx, &file, &target_table).await }+})+.await+```++</Fragment>+</LangTabs>++<Lang only="python">`process_file` is still a loop over the chunks of one file. The last line makes the pipeline an app that the `cocoindex` command can run. </Lang>The code has no logic for the five jobs. A few declarations hand each job to CocoIndex:++1. **Target changes.** `declare_row()` states that a row must [exist in the target](../programming_guide/target_state), and writes nothing yet. <Lang only="python">`mount_table_target()` states the same for the table.</Lang><Lang only="rust">In the full example, `postgres::mount_table_target()` states the same for the table.</Lang> <Lang only="python">`mount_each()`</Lang><Lang only="rust">`mount_each_live()`</Lang> *mounts* `process_file` for each file: CocoIndex calls it once for that file and tracks what it declares. CocoIndex therefore knows which rows belong to which file.+2. **Code changes.** <Lang only="python">`memo=True`</Lang><Lang only="rust">`memo`</Lang> keeps the rows that `process_file` declared for each file. CocoIndex reuses them while the file and the code are unchanged. When either one changes, it calls `process_file` again.+3. **Finding changes.** <Lang only="python">`cocoindex update main.py`</Lang><Lang only="rust">`cocoindex update`</Lang> scans the folder and exits. With `-L`, it scans the folder and then [keeps watching](../programming_guide/live_mode). <Lang only="python">`live=True`</Lang><Lang only="rust">`.live()`</Lang> makes the file listing able to watch, and has no effect without `-L`.+4. **Repeated work.** The built-in `embed()` caches its results, and <Lang only="python">`memo=True`</Lang><Lang only="rust">`memo`</Lang> does the same for your own functions. `IdGenerator` gives each chunk a [stable id](../common_resources/id_generation). An unchanged chunk therefore costs no model call and no write.+5. **Failures.** One failed file does not stop the other files. After a crash, you start the run again, and it [brings the table to the declared state](../advanced_topics/exception_handlers#interrupted-updates-and-recovery).++## What CocoIndex does when something changes++Two things change over time: the source data and your code.+Either one can require changes to rows (insert, update, delete) and to the table itself (create, alter, drop).+CocoIndex works them out from what your functions declare.++The diagrams use the example above with two files, `a.md` and `b.md`.+Each file has two chunks.++### The source changes++Someone edits `b.md`, and the edit changes its second chunk.++<ComponentWithChunks memoized={true} componentLabel="process_file" scenario={{ rows: [+ { file: 'a.md', pcStatus: 'cache-ready', chunks: [+ { label: 'chunk1', vectorLabel: 'vector1', embedStatus: 'cache-ready' },+ { label: 'chunk2', vectorLabel: 'vector2', embedStatus: 'cache-ready' },+ ] },+ { file: 'b.md', fileState: 'updated', pcStatus: 'refreshing', pcState: 'updated', splitState: 'updated', chunks: [+ { label: 'chunk3', vectorLabel: 'vector3', embedStatus: 'cache-ready' },+ { label: 'chunk4', vectorLabel: 'vector4', state: 'removed' },+ { label: 'chunk5', vectorLabel: 'vector5', state: 'new' },+ ] },+]}} />++- `a.md` is unchanged, so CocoIndex skips `process_file` for it and keeps its rows.+- CocoIndex calls `process_file` again for `b.md`.+- The first chunk of `b.md` has the same text. Its embedding comes from the cache, and only the new chunk goes to the model.+- When `process_file` finishes, CocoIndex compares the rows that `b.md` declares now with its rows from the last run. It deletes the row of the old chunk and inserts the row of the new chunk. It does not write the other row again.++When someone deletes `b.md`, the listing no longer contains it, and CocoIndex deletes the rows that came from it.+For a new file, CocoIndex calls `process_file` and inserts the rows.++### Your code changes++You change how `process_file` splits the text.+With the new rule, `a.md` still splits into the same chunks, and `b.md` splits into different chunks.++<ComponentWithChunks memoized={true} componentLabel="process_file" scenario={{ rows: [+ { file: 'a.md', pcStatus: 'refreshing', pcState: 'updated', splitState: 'updated', chunks: [+ { label: 'chunk1', vectorLabel: 'vector1', embedStatus: 'cache-ready' },+ { label: 'chunk2', vectorLabel: 'vector2', embedStatus: 'cache-ready' },+ ] },+ { file: 'b.md', pcStatus: 'refreshing', pcState: 'updated', splitState: 'updated', chunks: [+ { label: 'chunk3', vectorLabel: 'vector3', state: 'removed' },+ { label: 'chunk4', vectorLabel: 'vector4', state: 'removed' },+ { label: 'chunk5', vectorLabel: 'vector5', state: 'new' },+ { label: 'chunk6', vectorLabel: 'vector6', state: 'new' },+ ] },+]}} />++- The code of `process_file` changed, so CocoIndex calls it again for both files.+- `a.md` produces the same chunks as before. CocoIndex reuses their embeddings, and the rows of `a.md` stay as they are.+- `b.md` produces two different chunks. CocoIndex embeds them, deletes the two old rows, and inserts two new rows.++You write no backfill script for this change.-### Lineage-Inspect processing steps, intermediate results, and execution paths to trace how the pipeline produced its output.+A code change can also change the table. For a new field in the row, CocoIndex [alters the table](../programming_guide/target_state#what-happens-when-a-targets-schema-changes) and fills the new column.-### Open integration model-Sources and targets use a standard, open interface.-<Lang only="python">Use Python models, functions, and libraries in your transformations.</Lang><Lang only="rust">Use Rust crates, models, and functions in your transformations.</Lang>+[Change detection](../programming_guide/function#change-detection) describes what CocoIndex tracks.-### Controlled concurrency-Pipelines run work concurrently with configurable limits and batch requests to external services and models.+## Where it fits-### Recovery-The engine retries transient failures and resumes from previous progress after interruptions.+CocoIndex fits a problem that has these properties:-### Managed state-CocoIndex manages change detection, cached results, target state reconciliation, execution concurrency, and backfills.+- The output is derived. You can compute it again from the source.+- The source changes through edits and deletes, as well as through new items.+- Each item costs time or money to process: an embedding, an LLM call, OCR, or a parser.+- Readers need current output, or you change the transformation often.-## Incremental data processing+[CocoIndex vs other compute frameworks](https://cocoindex.io/comparison/) shows how it relates to data processing engines, orchestrators and other tools.-CocoIndex stores state across runs to identify new or changed data.+## How it runs-What incremental processing means:-- Avoid unnecessarily recomputing work, based on multi-level change detection:- - **Component level**: only reprocess source items with changes- - **Function level**: within an item's processing, memoize expensive function calls and reuse when possible- - **Target level**: apply minimum necessary changes (insertions, updates, deletions) to the target-- Support multiple mechanisms to capture source changes (CDC, poll-based) out of the box+- **CocoIndex is an open-source library.** <Lang only="python">`pip install cocoindex` adds it to your project.</Lang><Lang only="rust">The `cocoindex` crate builds into your own binary, with no Python runtime.</Lang> Your code and the engine run in your own process. The license is Apache-2.0.+- **You operate no server for it.** CocoIndex keeps its record of previous runs in an embedded database, at a [local path](../programming_guide/app#database-path) that you set. Keep that path on storage that persists.+- **You choose when it runs.** A run processes the changes and exits, so a scheduler can start it. In live mode, the app stays running.+- **It has no hosted service.** CocoIndex reads your sources and writes your targets from your own process. The library sends [anonymous usage events](../about/telemetry) with no data from your pipeline, and you can turn them off.-Use the updated output for serving, training, or feature computation.+The embedded state is on one machine.+For team deployments with shared state in Postgres, see [CocoIndex Plus](https://cocoindex.io/enterprise/).<Lang only="rust">@@ -93,5 +366,6 @@ The crate is not on crates.io yet; [Installation](./installation) shows how to d## Next steps-- [Install CocoIndex](./installation) and follow the [Quickstart](./quickstart) to build your first pipeline-- Read [Core Concepts](../programming_guide/core_concepts) for the mental model behind CocoIndex+- <Lang only="python">[Quickstart](./quickstart)</Lang><Lang only="rust">[Quickstart](./rust_quickstart)</Lang>: build a first app, change its input, and see what runs again.+- [Core concepts](../programming_guide/core_concepts): the concepts behind this page, with diagrams.+- [How CocoIndex works](https://cocoindex.io/blogs/how-cocoindex-works/): one example app, followed through each primitive, with timings on 1,000 files.diff --git a/docs/src/content/docs/getting_started/quickstart.mdx b/docs/src/content/docs/getting_started/quickstart.mdxindex 7f4c1348..6fa83a13 100644--- a/docs/src/content/docs/getting_started/quickstart.mdx+++ b/docs/src/content/docs/getting_started/quickstart.mdx@@ -24,11 +24,13 @@ Build an app that converts PDF files to Markdown and saves them to a local direc2. Convert each file to Markdown using Docling3. Save the Markdown files to an output directory (as **target states**)-You declare the transformation logic with native Python without worrying about changes.+You write the transformation as ordinary Python functions. You write no code for updates or deletes.-Think: **target_state = transformation(source_state)**+**Target = F(Source)**-When your source data is updated, or your processing logic is changed (for example, switching parsers or tweaking conversion settings), CocoIndex reprocesses the affected files and updates their Markdown output.+When a PDF changes, CocoIndex converts it again and updates its Markdown output.+When you change the code of the transformation, CocoIndex does the same for every PDF.+[Why CocoIndex](./overview) describes the problem that this solves.## Setup@@ -58,6 +60,8 @@ When your source data is updated, or your processing logic is changed (for exampecho "COCOINDEX_DB=./cocoindex.db" > .env```+ CocoIndex records each run in this [database](../programming_guide/app#database-path). The next run compares against that record to find what changed.+## Define the appAt a high level, the app has three layers:@@ -109,7 +113,7 @@ def process_file(```- **`localfs.File`** — A file object returned by `localfs.walk_dir()`, implementing the [`FileLike`](../common_resources/data_types#filelike) base class. See the [localfs connector](../connectors/localfs) for full details.-- **`memo=True`** — Caches results; unchanged files are skipped on re-runs+- **`memo=True`** — Reuses the result of the last run. CocoIndex skips this function for a file when the file's content and the function's code are both unchanged. See [memoization](../programming_guide/function#memoization).- **`localfs.declare_file()`** — Declares a file [target state](../programming_guide/target_state); auto-deleted if source is removed. See [localfs as target](../connectors/localfs#as-target) for the full API.@@ -165,6 +169,17 @@ CocoIndex will:1. Create the `out/` directory2. Convert each PDF in `pdf_files/` to Markdown in `out/`+The first run also downloads Docling's models, so it takes longer than later runs.+The run ends with a summary. With two PDFs in `pdf_files/`, the summary is:++```text+✓ Done in 1m 30s+ ✓ app_main 1 added+ ✓ process_file 2 added+```++Each line reports one function. `app_main` ran one time, and `process_file` ran one time for each PDF.+Check the output:```bash@@ -174,36 +189,92 @@ ls out/## Incremental updates-The power of CocoIndex is **incremental processing**. Try these:+Each run does only the work that a change requires. This is **incremental processing**.+Make each change below, then run the same command again:++```bash+cocoindex update main.py+```++The summaries below are from a run that started with two PDFs. Your counts can differ.++**Change nothing:**++```text+✓ Done in <0.1s+ ✓ app_main 1 reprocessed+ ✓ process_file 2 unchanged+```++`app_main` runs on every update, because it must list the folder again.+Both PDFs are unchanged, so CocoIndex converts nothing.**Add a new file:**-Add a new PDF to `pdf_files/`, then run:+Add a new PDF to `pdf_files/`.-```bash-cocoindex update main.py+```text+✓ Done in 11.4s+ ✓ app_main 1 reprocessed+ ✓ process_file 1 added · 2 unchanged```-Only the new file is processed.+CocoIndex converts only the new file.**Modify a file:**-Replace a PDF in `pdf_files/` with an updated version, then run:+Replace a PDF in `pdf_files/` with an updated version.-```bash-cocoindex update main.py+```text+✓ Done in 9.1s+ ✓ app_main 1 reprocessed+ ✓ process_file 1 reprocessed · 2 unchanged```-Only the changed file is reprocessed.+CocoIndex converts only the changed file again.**Delete a file:**```bashrm pdf_files/example.pdf-cocoindex update main.py```-The corresponding Markdown file is automatically removed.+```text+✓ Done in <0.1s+ ✓ app_main 1 reprocessed+ ✓ process_file 1 deleted · 2 unchanged+```++CocoIndex removes the corresponding Markdown file from `out/`.+You wrote no delete code. `process_file` no longer runs for that PDF, so CocoIndex removes the file that its last run declared.++**Change the code:**++In `process_file`, change the name of the output file:++```python title="main.py"+ outname = file.file_path.path.stem + ".docling.md"+```++```text+✓ Done in 11.3s+ ✓ app_main 1 reprocessed+ ✓ process_file 2 reprocessed+```++The code of `process_file` changed, so CocoIndex runs it again for every PDF.+The function no longer declares the files with the old names, so CocoIndex removes them:++```bash+ls out/+# example.docling.md (example.md is gone)+```++:::note[What counts as a code change]+CocoIndex tracks the code of `process_file` itself. A change to a comment does not count.+A change to a module-level value, such as `_pipeline_options`, does not count either, because CocoIndex does not see it.+To make CocoIndex track a module-level value, declare it with [`deps`](../programming_guide/function#deps).+:::## Next stepsdiff --git a/docs/src/content/docs/programming_guide/core_concepts.mdx b/docs/src/content/docs/programming_guide/core_concepts.mdxindex 7f5bd56b..21cbdb31 100644--- a/docs/src/content/docs/programming_guide/core_concepts.mdx+++ b/docs/src/content/docs/programming_guide/core_concepts.mdx@@ -13,18 +13,19 @@ import ComponentWithChunks from '/src/components/diagrams/concepts/ComponentWith## Incremental processing-Data and code change over time. Incremental processing reruns affected work and updates targets, such as a search database.+Data and code change over time. With incremental processing, each run does only the work that a change requires.+It updates only the affected part of the target, such as a search database.-Manual implementations must track changes and preserve intermediate results.-They must also manage inserts, updates, deletes, schema changes, and backfills.+[Why CocoIndex](../getting_started/overview) describes the problem, and the code that you would otherwise write by hand.## State-driven programmingDeclare the target state you want from the current source data.CocoIndex computes and applies the changes needed to match it.-**TargetState = Transform(SourceState)**+**Target = F(Source)**+`F` is your transformation code.The target state is a pure function of the source state, with no other side effects.Transformations read sources and produce target data, such as database rows or files.diff --git a/docs/src/content/example-posts/pdf-to-markdown.md b/docs/src/content/example-posts/pdf-to-markdown.mdindex ff74689b..9ded0266 100644--- a/docs/src/content/example-posts/pdf-to-markdown.md+++ b/docs/src/content/example-posts/pdf-to-markdown.md@@ -23,9 +23,9 @@ Build an app that converts PDF files to Markdown and saves them to a local direcYou declare the transformation logic with native Python without worrying about changes.Think:-**target_state = transformation(source_state)**+**Target = F(Source)**-When your source data is updated, or your processing logic is changed (for example, switching parsers or tweaking conversion settings), CocoIndex reprocesses affected files and updates their Markdown output.+When a PDF changes, or when you change the code of the transformation, CocoIndex converts the affected files again and updates their Markdown output.## Setupdiff --git a/docs/src/data/docs-sidebar.ts b/docs/src/data/docs-sidebar.tsindex 566933ab..8040e16d 100644--- a/docs/src/data/docs-sidebar.ts+++ b/docs/src/data/docs-sidebar.ts@@ -28,9 +28,9 @@ export const sidebar: SidebarItem[] = [type: 'category',label: 'Getting Started',items: [- { type: 'doc', slug: 'getting_started/overview', label: 'Overview' },- { type: 'doc', slug: 'getting_started/installation', label: 'Installation' },+ { type: 'doc', slug: 'getting_started/overview', label: 'Why CocoIndex' },{ type: 'doc', slug: 'getting_started/quickstart', label: 'Quickstart' },+ { type: 'doc', slug: 'getting_started/installation', label: 'Installation' },{ type: 'doc', slug: 'getting_started/ai_coding_agents', label: 'Use with AI coding agents' },],},diff --git a/docs/src/pages/index.astro b/docs/src/pages/index.astroindex 8e11ddb0..2ec92a0b 100644--- a/docs/src/pages/index.astro+++ b/docs/src/pages/index.astro@@ -26,6 +26,8 @@ const canonical = new URL(`${base}/`, SITE_URL).toString();// Start here: labels and slugs match the sidebar exactly.const start = [+ { slug: 'getting_started/overview', label: 'Why CocoIndex', meta: 'Introduction',+ body: 'The problem CocoIndex solves, the code you write, what it does when data or code changes, and where it fits.' },{ slug: 'getting_started/quickstart', label: 'Quickstart', meta: 'Tutorial',body: 'Build one pipeline end to end: convert PDFs to Markdown, change a file, and watch only that file reprocess.' },{ slug: 'getting_started/installation', label: 'Installation', meta: 'Setup',@@ -170,7 +172,7 @@ app.update_blocking()`;<section class="dh-sec" aria-labelledby="dh-start"><div class="dh-head"><h2 id="dh-start">Start here</h2>- <p>Start with installation, a first pipeline, the core concepts, or the AI coding agent skill.</p>+ <p>Start with why CocoIndex exists, then a first pipeline, installation, the core concepts, or the AI coding agent skill.</p></div><ul class="dh-list">{start.map((c) => (