---
title: "How CocoIndex works: the primitives behind every app"
description: "The primitives behind a CocoIndex v1 app: App, processing component, target state, memoization, context and live mode, each shown at work in one example app."
published: 2026-12-01
last_updated: 2026-12-01
doc_version: "2026-12-01"
canonical: https://cocoindex.io/blogs/how-cocoindex-works/
---
# How CocoIndex works: the primitives behind every app

> The primitives behind a CocoIndex v1 app: App, processing component, target state, memoization, context and live mode, each shown at work in one example app.

Published: 2026-12-01 · Canonical: https://cocoindex.io/blogs/how-cocoindex-works/

The first run of a data pipeline is simple: read each source item, transform it, write the result. The second run is harder. By then the data has changed, and often the code too, and the pipeline has three questions to answer:

- Which source items changed, and which are gone?
- Which results are still valid?
- Which outputs must be written or deleted?

CocoIndex v1 answers these with a small set of primitives. The [docs](https://cocoindex.io/docs/programming_guide/core_concepts/) define each one on its own page. This post explains how they fit together, then shows each one at work in one example app. It is for people who use CocoIndex or are evaluating it.

I ran every command in this post on CocoIndex 1.3.1 and copied each output block from that run.

## Why you should care

- **Unchanged work is skipped.** A memoized function does not run again while its code, its inputs and the tracked context values are the same. In the example, an edit to 1 of 1,000 files ran 1 function body and skipped 999.
- **Outputs of deleted sources are removed.** Each processing component owns the target states that it declares. When its source item is gone, CocoIndex deletes them, with no delete code from you.
- **A change is visible before it is written.** The compare step is separate from the apply step, so `cocoindex update --preview` prints the planned writes and deletes and applies none of them.

## The model: declare target states, CocoIndex syncs them

In most pipelines you write the steps: insert this row, update that one, delete the old file. In CocoIndex you write a function that says what should exist in the target for the current source. CocoIndex runs the function, compares the result with its record of the last run, and applies the difference. The docs write the model as *TargetState = Transform(SourceState)*.

A spreadsheet works the same way. You write a formula, and the cell is correct again after an input changes. You do not write the steps that refresh the cell.

Two things follow from this model:

- Your code has no update logic and no delete logic. CocoIndex deletes an output when the current run no longer declares it.
- CocoIndex must remember the last run. It keeps that record in a local [state database](https://cocoindex.io/docs/programming_guide/app/#database-path).

## The primitives, and how they fit

The docs give the short version: "An App runs processing components. Each component calls functions and declares target states, which describe the output CocoIndex keeps in sync."

Each primitive answers one question about a run:

| Primitive | What it is | The question it answers |
|---|---|---|
| [App](https://cocoindex.io/docs/programming_guide/app/) | The unit that you run: a main function and its arguments, under a name | What runs, and which saved state belongs to it? |
| [Processing component](https://cocoindex.io/docs/programming_guide/processing_component/) | One instance of a function at a stable path, usually for one source item | Is this the same item as last time? Which outputs came from it? |
| [Target state](https://cocoindex.io/docs/programming_guide/target_state/) | One thing that should exist in an external system, such as a file or a row | What should the target contain now? |
| [Function](https://cocoindex.io/docs/programming_guide/function/) and memoization | A function whose code and inputs CocoIndex tracks. With `memo=True`, CocoIndex reuses its result while they and the tracked context values are unchanged | Can this work be skipped? |
| [Context](https://cocoindex.io/docs/programming_guide/context/) | A shared value, such as a model or a connection, that functions read by key | Which values do functions share, and which of them change the results? |
| [Live mode](https://cocoindex.io/docs/programming_guide/live_mode/) | A way to run an app: it keeps running and reacts to each source change | When does the work run? |

Three more terms go with the figure:

- **Mount.** To mount a function is to start it as a child processing component at its own path. The main function runs as the root component. In the example, it mounts one child for each source item.
- **Key and path.** A source gives each item a stable key, such as a file name. CocoIndex builds the component's path from the function name and that key.
- **[Connector](https://cocoindex.io/docs/connectors/).** A source connector supplies the items to process. A target connector creates, updates and deletes target states in one kind of external system.

The rest of this post uses one example app. Each section below shows one primitive at work in it.

## The example: Markdown files in, HTML files out

The example app turns a folder of Markdown files into a folder of HTML files. It is small on purpose, about 30 lines, so that you can read all of it. Two later sections add a few lines to it. It needs no credentials and no database server. It is based on the [`files_transform`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/files_transform) example and renders with [markdown-it-py](https://github.com/executablebooks/markdown-it-py).

The setup is three lines:

```sh
pip install -U cocoindex "markdown-it-py[linkify,plugins]"
mkdir docs-to-html && cd docs-to-html
echo "COCOINDEX_DB=./cocoindex.db" > .env
```

`COCOINDEX_DB` is the path of the state database. This is `main.py`:

```python title="main.py"
import pathlib

import cocoindex as coco
from cocoindex.connectors import localfs
from cocoindex.resources.file import FileLike, PatternFilePathMatcher
from markdown_it import MarkdownIt

_markdown_it = MarkdownIt("gfm-like")

@coco.fn(memo=True)
async def process_file(file: FileLike, outdir: pathlib.Path) -> None:
    html = _markdown_it.render(await file.read_text())
    outname = file.file_path.path.stem + ".html"
    localfs.declare_file(outdir / outname, html, 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=["*.md"]),
    )
    await coco.mount_each(process_file, files.items(), outdir)

app = coco.App(
    "DocsToHtml",
    app_main,
    sourcedir=pathlib.Path("./docs"),
    outdir=pathlib.Path("./out"),
)
```

The figure marks where 4 of the 6 primitives enter `main.py`, and where the source is:

`localfs.walk_dir()` and `localfs.declare_file()` are the source side and the target side of the [`localfs` connector](https://cocoindex.io/docs/connectors/localfs/). Context and live mode are not in this file. They each take a few more lines, in their own sections below.

With 3 Markdown files in `docs/`, the first run gives 3 HTML files:

```text
$ ls docs
faq.md
handbook.md
roadmap.md

$ cocoindex update main.py

CocoIndex 1.3.1 · Updating DocsToHtml · default · cocoindex.db

✓ Done in <0.1s
  ✓ app_main      1 added
  ✓ process_file  3 added

$ ls out
faq.html
handbook.html
roadmap.html
```

## App: what does one run do?

An App is "the top-level runnable unit in CocoIndex", in the words of the docs. It binds a main function to its arguments under a name, and the name identifies the app's saved state. `cocoindex update main.py` runs it once.

A run has 6 stages. Your code is in 3 of them, and CocoIndex does the other 3. Select a stage in the figure to see its code and what it saves.

1. **Start.** `cocoindex update main.py` loads `app` and runs `app_main()`. That call is the root processing component, at the path `/`.
2. **List.** `files.items()` gives one `(key, file)` pair for each Markdown file, such as `("faq.md", <file>)`. The file's content is not read at this stage.
3. **Mount.** `mount_each()` mounts `process_file()` once for each pair, at the path `/@process_file/<key>`. It returns when the components are scheduled, and they run concurrently.
4. **Check the memo.** For each component, CocoIndex looks for a memo result with the same function code and the same file. A hit means that CocoIndex can reuse the result. The component is then done, and its saved declarations stay as they are. On the first run every check is a miss.
5. **Run and declare.** On a miss, the body of `process_file()` runs. It reads the file, renders it, and calls `declare_file()`. The declaration is a record in memory. No file is written at this stage.
6. **Sync.** When the body finishes, CocoIndex pairs each declaration with the record saved for the same path on the last run. The connector applies the difference, and CocoIndex saves the new record.

Stages 4 and 6 use the state database. It holds the memo results and the record of what each component declared. That saved state is why the second run can do less work than the first.

## Processing component: a function at a stable path

A processing component "owns the work and target states for one source item", as the docs put it. It has an identity that lasts from one run to the next, and it owns outputs.

A function and a component are different things. `process_file()` is one function, but the first run has 3 `process_file()` components. A function is a set of instructions. A processing component is one instance of those instructions for one item, stored under its own path.

The docs call the component path "the stable identifier for a processing component across runs". `cocoindex show` prints the paths of an app:

```text
$ cocoindex show main.py

Stable paths:
  /
  /@process_file
  /@process_file/"faq.md"
  /@process_file/"handbook.md"
  /@process_file/"roadmap.md"
```

`/` is the root component, which ran `app_main()`. `@process_file` is the name of the mounted function, and `mount_each()` adds it for you. `"faq.md"` is the key that came from the source. CocoIndex builds the path from the function name and the key. The same file therefore gets the same path on every run.

A component owns the target states that it declares. The state database keeps that link, and `cocoindex show --target-states` prints it:

```text
$ cocoindex show --target-states main.py

Target states:
  /@cocoindex/localfs/[null,"out/handbook.html"]
    owner:/@process_file/"handbook.md"
  /@cocoindex/localfs/[null,"out/roadmap.html"]
    owner:/@process_file/"roadmap.md"
  /@cocoindex/localfs/[null,"out/faq.html"]
    owner:/@process_file/"faq.md"
```

These two records answer the component's two questions on the next run. The path says whether an item is the same as last time. The ownership says which outputs came from it.

### Run 2: the parent decides which children exist

Run 2 starts from 3 changes to the source: `faq.md` is edited, `roadmap.md` is deleted and `onboarding.md` is added. `handbook.md` stays as it is. The command is the same:

```text
$ cocoindex update main.py

CocoIndex 1.3.1 · Updating DocsToHtml · default · cocoindex.db

✓ Done in <0.1s
  ✓ app_main      1 reprocessed
  ✓ process_file  1 added · 1 reprocessed · 1 deleted · 1 unchanged

$ ls out
faq.html
handbook.html
onboarding.html
```

The 4 files cover the 4 cases. Switch between the runs in the figure to see what changed:

| Source file | Change | Its component in run 2 | Its output |
|---|---|---|---|
| `handbook.md` | none | mounted again, memo hit, body skipped | `handbook.html` not touched |
| `faq.md` | edited | mounted again, memo miss, body runs | `faq.html` written again |
| `onboarding.md` | added | mounted for the first time, body runs | `onboarding.html` created |
| `roadmap.md` | deleted | not mounted | `roadmap.html` deleted |

The last row has no code behind it in `main.py`. The root component is not memoized, so `app_main()` runs on every update and lists the folder again. `roadmap.md` is not in the list, so `mount_each()` does not mount `/@process_file/"roadmap.md"`. CocoIndex then removes that component and everything that it owned.

In a plain update, the rule is this: when a parent's body finishes and has not mounted a component, CocoIndex removes that component. A memoized parent whose memo hits does not run, so CocoIndex keeps its children as they were.

The same rule works for a deeper tree. Suppose that an app mounts one component per repository, and each of those mounts one component per file. When you remove a repository from the list, its component is not mounted. CocoIndex removes it, every file component below it, and every row or file that they declared.

## Mounting: which calls create components

Four functions mount a component. `coco.mount()`, `coco.use_mount()` and `coco.mount_each()` are the general ones. `coco.mount_target()` is a shortcut over `use_mount()` for one job: it sets up a target, such as a table. For `mount()` and `use_mount()`, the [docs](https://cocoindex.io/docs/programming_guide/processing_component/#mount) reduce the choice to one question: does the caller need a value back?

| | `coco.mount()` | `coco.mount_each()` | `coco.use_mount()` |
|---|---|---|---|
| Components created | 1 | 1 per `(key, item)` pair | 1 |
| The caller waits | No. It returns when the child is scheduled | No | Yes, until the child has finished and synced |
| What comes back | A handle. `await handle.ready()` waits for the child | 1 handle for all the children | The child's return value |
| If the child fails | The error is logged. The parent and the other children continue | The same | The error is raised in the parent |

In catch-up mode, `cocoindex update` exits with status 1 when a failure in a background child has no [exception handler](https://cocoindex.io/docs/advanced_topics/exception_handlers/), or when every handler raises again.

`mount_each()` is `mount()` in a loop over keyed items. It also accepts a live source, which the section on live mode uses. Connectors wrap `mount_target()` in helpers such as `postgres.mount_table_target()`, which creates a table and returns an object with `declare_row()`.

[`coco.map()`](https://cocoindex.io/docs/programming_guide/processing_component/#using-cocoindex-map-to-apply-transformations) creates no component. It runs a function on each item concurrently, inside the current component, and returns the results. The section on memoization uses it for the sections of a file.

For the second question in the figure, these are the usual signs:

- Use `mount_each()` when items come and go on their own. It also fits when one failure must not stop the other items. Each item's outputs then appear when that item is done. Files, rows and messages are typical.
- Use `map()` when the items are steps in the work of one larger item. It also fits when you need the results back. The sections of a file are typical.

## Target state: declared, then compared and applied

A target state "represents what you want to exist in an external system", in the docs' definition. The target is the system, such as a directory or a database table. A target state is one thing in it, such as a file or a row.

`declare_file()` does not write a file. It adds a record to the component that is running. The write comes after the body finishes, in three steps:

1. **Compare.** CocoIndex pairs each target state declared in this run with the record saved for the same component path. The connector decides what must change.
2. **Apply.** The connector creates, updates or deletes what is different. A target state that is equal to the saved one causes no write.
3. **Save.** CocoIndex saves the new record for the next run.

One case skips these steps. A component with a memo hit is not compared at all, because its saved declarations stay as they are. A component that is no longer mounted goes through the same steps with nothing declared, so the connector deletes every target state that it owned. That is how run 2 deleted `roadmap.html`. The figure shows all 4 files:

The compare step is separate from the apply step, so you can stop after the compare. `cocoindex update --preview` prints the planned changes and applies none of them. Before run 2 it reported the 3 changes that run 2 then made. These are the first lines of its output:

```text
$ cocoindex update --preview main.py

CocoIndex 1.3.1 · Previewing DocsToHtml · default · cocoindex.db
● 3 planned changes (preview · <0.1s)
```

The lines below that header list one action each: write `out/faq.html`, write `out/onboarding.html` and remove `out/roadmap.html`.

This split also limits what a failure can do. A function that raises has only made declarations in memory, so there is nothing to undo. If a write fails partway, CocoIndex does not roll back. The next run computes the declared state again and brings the target to it.

The connector holds the logic for the compare and the apply. To write a connector of your own, see [Write a Custom Target](/blogs/custom-targets/) and [Write a Custom Source in Python](/blogs/custom-source/). The [custom target connector](https://cocoindex.io/docs/advanced_topics/custom_target_connector/) docs have the reference.

## Memoization: what makes a function run again?

Memoization stores a function's result and reuses it while nothing that the function depends on has changed. `memo=True` on `process_file()` is the reason that run 2 skipped `handbook.md`. The docs give the [mental model](https://cocoindex.io/docs/programming_guide/function/#change-detection-and-memoization): "A function's behavior is determined by its **logic** (source code, `deps`, `version`), its **inputs** (arguments), and the **context values** it reads via `use_context()`. If none of those have changed, a memoized function returns its cached result without re-executing."

| Kind of change | What CocoIndex compares | In the example (`main.py`) |
|---|---|---|
| Inputs | The function's arguments | The `file` and `outdir` arguments of `process_file()` |
| Logic | The code of the function and of each `@coco.fn` function that the call reaches, plus `deps=` values | The body of `process_file()` |
| Context | Each context value that the call reads, if its key has `detect_change=True` | None yet (see the next section) |

For a file input, CocoIndex first compares the modification time. If the time is different, it compares a hash of the content. I ran 4 cases on the app above:

| Change | Result | Why |
|---|---|---|
| `touch docs/handbook.md`, with the same bytes | <span style={{ whiteSpace: 'nowrap' }}>`3 unchanged`</span> | The time changed, but the content hash did not |
| A comment added in `process_file()` | <span style={{ whiteSpace: 'nowrap' }}>`3 unchanged`</span> | A comment does not change the logic |
| The first line of `process_file()` split into 2 lines, with the same HTML | <span style={{ whiteSpace: 'nowrap' }}>`3 reprocessed`</span> | The logic changed. No output file was written, because each declaration was equal to the saved one |
| `MarkdownIt("gfm-like")` changed to `MarkdownIt("commonmark")` | <span style={{ whiteSpace: 'nowrap' }}>`3 unchanged`</span> | CocoIndex did not see the change, so the HTML files are out of date |

:::warning[Module-level values are not tracked]
`_markdown_it` is a module-level value. It is not an argument, and it is not part of the function's code. CocoIndex therefore does not see it change. Declare such a value with [`deps=`](https://cocoindex.io/docs/programming_guide/function/#deps), or provide it as a context value (the next section).
:::

With `deps=`, the fix is 1 new line and 2 changed lines:

```python
PRESET = "gfm-like"
_markdown_it = MarkdownIt(PRESET)

@coco.fn(memo=True, deps=PRESET)
async def process_file(file: FileLike, outdir: pathlib.Path) -> None:
    ...
```

With this declaration, a change to `PRESET` gives `3 reprocessed`. The post [What Is Incremental Processing?](/blogs/incremental-processing/#cache) has an interactive demo of the memo check for more cases.

A memo does not remove all work. I ran the same app on 1,000 generated Markdown files (4.1 MB) on an Apple M3. The first run took 1.8 s. After an edit to 1 file, the next run took 0.2 s and reported `1 reprocessed · 999 unchanged`. A run with no change also took 0.2 s, because each run still lists every file and checks its memo. Markdown rendering is cheap, so 999 skipped bodies save little time here. The saving grows with the cost of the body. With an embedding or an LLM call in `process_file()`, the same run would skip 999 expensive calls and pay for only 1.

### Two levels of memo

A memo can sit on a mounted function, as above, or on a function that a component calls. `main_v2.py` has both. It splits each file at its `##` headings and renders each section in its own memoized call. These are the parts of `main_v2.py` that differ from `main.py`, apart from two more imports:

```python title="main_v2.py"
MD_PRESET = coco.ContextKey[str]("md_preset", detect_change=True)

@coco.lifespan
def coco_lifespan(builder: coco.EnvironmentBuilder) -> Iterator[None]:
    builder.provide(MD_PRESET, "gfm-like")
    yield

@coco.fn(memo=True)
async def render_section(text: str) -> str:
    print("  render_section:", text.splitlines()[0])
    return MarkdownIt(coco.use_context(MD_PRESET)).render(text)

@coco.fn(memo=True)
async def process_file(file: FileLike, outdir: pathlib.Path) -> None:
    sections = re.split(r"(?m)^(?=## )", await file.read_text())
    html = "".join(await coco.map(render_section, sections))
    outname = file.file_path.path.stem + ".html"
    localfs.declare_file(outdir / outname, html, create_parent_dirs=True)
```

`MD_PRESET`, `coco_lifespan()` and `use_context()` belong to the next section, on context. `render_section()` prints a line each time its body runs. The 3 files have 9 sections, so the first run prints 9 lines. After a change to one answer in `faq.md`, the next run prints 1:

```text
$ sed -i '' 's/#help/#support/' docs/faq.md

$ cocoindex update main_v2.py

CocoIndex 1.3.1 · Updating DocsToHtml · default · cocoindex.db
  render_section: ## Where do I ask for help?

✓ Done in <0.1s
  ✓ app_main      1 reprocessed
  ✓ process_file  1 reprocessed · 2 unchanged
```

The memo on `process_file()` skipped 2 whole files. In the third file, the component ran again and split the text again. There, the memo on `render_section()` skipped 2 of the 3 sections.

`render_section()` is called, not mounted, so it is not a component. `cocoindex show main_v2.py` prints the same 5 paths as before. The HTML that the calls return becomes part of the file that the enclosing component declares.

Rendering Markdown is cheap, so this memo saves little. It stands in for a step that costs money or time, such as an embedding or an LLM call. The [`text_embedding`](https://github.com/cocoindex-io/cocoindex/tree/main/examples/text_embedding) example has the same shape with chunks and an embedding model. The docs give one [rule for where to put a memo](https://cocoindex.io/docs/programming_guide/function/#when-to-memoize): memoize a function only if its memo can hit while every memo that encloses it misses. A memo per file plus a memo per section follows that rule.

## Context: shared values that CocoIndex can track

Context is "a **context** mechanism for sharing resources across your pipeline", in the docs' words. You provide a context value once, under a key. Any function can then read it with `coco.use_context()`. Models, API clients and database connections are typical.

`main_v2.py` uses one for the Markdown preset. Three lines do the work:

- `coco.ContextKey[str]("md_preset", detect_change=True)` declares the key and the type of its value.
- `builder.provide(MD_PRESET, "gfm-like")` provides the value. It is in a function with `@coco.lifespan`, which runs before the first update. The code after its `yield` runs at shutdown, which is where you close a connection. The docs cover this under [Lifespan](https://cocoindex.io/docs/programming_guide/app/#lifespan-optional).
- `coco.use_context(MD_PRESET)` reads the value inside `render_section()`.

`detect_change=True` is the part that fixes the pitfall from the previous section. With `"commonmark"` in place of `"gfm-like"` in `coco_lifespan()`, the next run prints all 9 `render_section` lines and reports `3 reprocessed`. `process_file()` does not read the key itself. The read happens in `render_section()`, which `process_file()` calls. That is enough for the memo on `process_file()` to depend on the value.

Change detection is off by default, and the docs give the rule for when to turn it on: "Use `detect_change=True` for resources that affect computation results", such as models and configuration objects. A database connection changes how you reach a system. It does not change the result, so it keeps the default. A new database password then causes no reprocessing.

`deps=` and context both make a memo see a value. As a rule of thumb, I use `deps=` for a value that one function reads. I use context for a value that many functions share, or for an object that needs setup and cleanup.

## Live mode: the same app, kept running

Each run so far was in catch-up mode: scan the source, process the changes, sync, exit. The docs define the other mode: "**Live mode** keeps the app running after catch-up finishes and lets components stream changes continuously from their sources", such as a file system watcher. In this app it needs two things: a source that can watch for changes, and the `-L` flag.

```python
    files = localfs.walk_dir(
        sourcedir,
        path_matcher=PatternFilePathMatcher(included_patterns=["*.md"]),
        live=True,
    )
```

```sh
cocoindex update -L main.py
```

With the app running, an edit to `docs/faq.md` updated `out/faq.html`. When I deleted a source file, CocoIndex removed its HTML file. Neither needed a second command. `process_file()` did not change. Live mode changes the time at which a component runs. The memo check, the declarations and the sync are the same as in catch-up mode.

The tree changes in one place. `cocoindex show` lists `/@process_file` in both modes. Without a live source it is only a part of the path. With a live source it is a component of its own. It watches the folder, and it mounts or removes one child when one file changes. For more on live sources, see [Keep an AI agent's context in sync with live mode](/blogs/continuous-updates/).

## Terms that are easy to mix up

| Term | What it is | Not the same as |
|---|---|---|
| Processing component | One instance of a function for one item, at a path | The function. One function can have many components |
| Component path | The identifier of a component, such as `/@process_file/"faq.md"` | The path of a file on disk |
| Target | The external system that you write to | A target state, which is one thing that should exist in it |

## Where to go next

- [Quickstart](https://cocoindex.io/docs/getting_started/quickstart/): build and run a first app.
- [Core concepts](https://cocoindex.io/docs/programming_guide/core_concepts/): the same ideas with the docs' own diagrams and a playground.
- [Processing component](https://cocoindex.io/docs/programming_guide/processing_component/) and [Function](https://cocoindex.io/docs/programming_guide/function/): the full reference for mounting and memoization.
- [Examples](https://github.com/cocoindex-io/cocoindex/tree/main/examples): larger apps built from the same primitives.
- [CocoIndex on GitHub](https://github.com/cocoindex-io/cocoindex).

## Sitemap

- [Blog index](https://cocoindex.io/blogs/)
- [Site index (llms.txt)](https://cocoindex.io/llms.txt)
- [Full blog corpus](https://cocoindex.io/llms-full.txt)
- [Markdown sitemap](https://cocoindex.io/sitemap.md)
- [XML sitemap](https://cocoindex.io/sitemap.xml)
- [RSS feed](https://cocoindex.io/blogs/rss.xml)
