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.

Concept18 min read
How CocoIndex works: the primitives behind every app. A tree of processing components: app_main mounts one component for each of handbook.md, faq.md and roadmap.md, and each component owns one HTML file. faq.md was edited, so its component is reprocessed and out/faq.html is written again; the other two components and their files are unchanged. The update reports 1 reprocessed and 2 unchanged.
Enlarge cover

How CocoIndex works: the primitives behind every app

Zoom in to see details.

How CocoIndex works: the primitives behind every app. A tree of processing components: app_main mounts one component for each of handbook.md, faq.md and roadmap.md, and each component owns one HTML file. faq.md was edited, so its component is reprocessed and out/faq.html is written again; the other two components and their files are unchanged. The update reports 1 reprocessed and 2 unchanged.

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 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.

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:

PrimitiveWhat it isThe question it answers
AppThe unit that you run: a main function and its arguments, under a nameWhat runs, and which saved state belongs to it?
Processing componentOne instance of a function at a stable path, usually for one source itemIs this the same item as last time? Which outputs came from it?
Target stateOne thing that should exist in an external system, such as a file or a rowWhat should the target contain now?
Function and memoizationA function whose code and inputs CocoIndex tracks. With memo=True, CocoIndex reuses its result while they and the tracked context values are unchangedCan this work be skipped?
ContextA shared value, such as a model or a connection, that functions read by keyWhich values do functions share, and which of them change the results?
Live modeA way to run an app: it keeps running and reacts to each source changeWhen 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. 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 example and renders with 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:

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. 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.

Select a stage to see what happens in it

Your codeCocoIndexSaved between runsonce for each componentLive mode:a file changesmisshitDone:outputs keptState databasememo results and target state records, by component pathreadsreads, then saves1 Startcocoindex update2 Listfiles.items()3 Mountmount_each()4 Check the memomemo=True5 Run and declaredeclare_file()6 Synccompare, apply, save

Whole run

Read the map from left to right. Your code is in stages 2, 3 and 5. CocoIndex does stages 1, 4 and 6. Stages 4 to 6 run once for each component. On a memo hit, a component is done after stage 4.

1StartCocoIndex

The CLI loads app from main.py and runs app_main with the arguments that coco.App holds. That call is the root processing component, at the path /.

app = coco.App("DocsToHtml", app_main, sourcedir=..., outdir=...)

State databaseThe app name selects this app’s saved state.

2ListYour codelocalfs connector

walk_dir() describes the source, and items() gives one (key, file) pair for each Markdown file. The key is the file’s relative path. No content is read.

files = localfs.walk_dir(sourcedir, path_matcher=...)
files.items()  # ("faq.md", file), ("handbook.md", file), ...

3MountYour codeCocoIndex

mount_each() mounts one processing component for each pair, at /@process_file/<key>, and returns when they are scheduled. A component whose key is not in the list is not mounted, and CocoIndex removes it.

await coco.mount_each(process_file, files.items(), outdir)

4Check the memoCocoIndex

CocoIndex looks up the memo result for this component. It is a hit when the code of process_file and its arguments are the same as before. On a hit, the component is done: its saved declarations are kept, and stages 5 and 6 do not run.

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

State databaseReads the memo result saved for this path.

5Run and declareYour codelocalfs connector

On a miss, the body runs. It reads the file, renders the HTML and declares one file. declare_file() records a target state in memory and writes nothing.

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)

6SyncCocoIndexlocalfs connector

When the body finishes, CocoIndex pairs each declaration with the record saved for the same path. The connector writes or deletes the files that differ. CocoIndex then saves the new records.

State databaseReads the saved target state records, then saves the new ones.

  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"
ComponentsTarget states they own/app_main · ran: listed docs//@process_file/"handbook.md"ranownsout/handbook.htmlcreated/@process_file/"faq.md"ranout/faq.htmlcreated/@process_file/"roadmap.md"ranout/roadmap.htmlcreated

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:

Switch between the two runs

Run 2. faq.md was edited, roadmap.md was deleted and onboarding.md was added. CocoIndex reports 1 added, 1 reprocessed, 1 deleted and 1 unchanged.

ComponentsTarget states they own/app_main · ran: listed docs//@process_file/"handbook.md"ranownsout/handbook.htmlcreated/@process_file/"faq.md"ranout/faq.htmlcreated/@process_file/"roadmap.md"ranout/roadmap.htmlcreatedComponentsTarget states they own/app_main · ran again: listed docs//@process_file/"handbook.md"memo hit, body skippedownsout/handbook.htmlnot touched/@process_file/"faq.md"memo miss, ran againout/faq.htmlwritten again/@process_file/"roadmap.md"not mounted, removedout/roadmap.htmldeleted/@process_file/"onboarding.md"new, ranout/onboarding.htmlcreated
Source fileChangeIts component in run 2Its output
handbook.mdnonemounted again, memo hit, body skippedhandbook.html not touched
faq.mdeditedmounted again, memo miss, body runsfaq.html written again
onboarding.mdaddedmounted for the first time, body runsonboarding.html created
roadmap.mddeletednot mountedroadmap.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 reduce the choice to one question: does the caller need a value back?

coco.mount()coco.mount_each()coco.use_mount()
Components created11 per (key, item) pair1
The caller waitsNo. It returns when the child is scheduledNoYes, until the child has finished and synced
What comes backA handle. await handle.ready() waits for the child1 handle for all the childrenThe child’s return value
If the child failsThe error is logged. The parent and the other children continueThe sameThe 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, 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() 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 and Write a Custom Source in Python. The 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: “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 changeWhat CocoIndex comparesIn the example (main.py)
InputsThe function’s argumentsThe file and outdir arguments of process_file()
LogicThe code of the function and of each @coco.fn function that the call reaches, plus deps= valuesThe body of process_file()
ContextEach context value that the call reads, if its key has detect_change=TrueNone 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:

ChangeResultWhy
touch docs/handbook.md, with the same bytes3 unchangedThe time changed, but the content hash did not
A comment added in process_file()3 unchangedA comment does not change the logic
The first line of process_file() split into 2 lines, with the same HTML3 reprocessedThe logic changed. No output file was written, because each declaration was equal to the saved one
MarkdownIt("gfm-like") changed to MarkdownIt("commonmark")3 unchangedCocoIndex did not see the change, so the HTML files are out of date
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=, 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? 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:

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 example has the same shape with chunks and an embedding model. The docs give one rule for where to put a memo: 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.
  • 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.

Terms that are easy to mix up

TermWhat it isNot the same as
Processing componentOne instance of a function for one item, at a pathThe function. One function can have many components
Component pathThe identifier of a component, such as /@process_file/"faq.md"The path of a file on disk
TargetThe external system that you write toA target state, which is one thing that should exist in it

Where to go next

Frequently asked questions

What is a processing component in CocoIndex?

A processing component is one instance of a function for one source item, stored under a stable path such as /@process_file/"faq.md". It is not the function: one function can have many components, one for each item. The path tells CocoIndex whether an item is the same as on the last run, and the component owns the target states that it declares.

See Processing component: a function at a stable path.

How does CocoIndex delete outputs when a source file is deleted?

You write no delete code. On each update the parent component lists the source again and mounts one component for each item it finds. In a plain update, a component that its parent runs without mounting is removed with every target state it owned. In the example, deleting roadmap.md removed out/roadmap.html on the next run.

See Run 2: the parent decides which children exist and Target state: declared, then compared and applied.

What makes a memoized CocoIndex function run again?

A function with @coco.fn(memo=True) runs again when one of three things changed: its inputs (the arguments), its logic (its code, the code of each @coco.fn function that the call reaches, and deps= values), or a context value that it read whose key has detect_change=True. For a file argument, CocoIndex compares the modification time first and a content hash second, so a file that was touched with the same bytes is not processed again.

See Memoization: what makes a function run again?.

Why did a change to a module-level value not reprocess my files?

A module-level value is not an argument and is not part of the function's code, so a memoized function does not see it change. In the example, changing MarkdownIt("gfm-like") to MarkdownIt("commonmark") gave 3 unchanged and HTML that was out of date. Declare the value with deps= on the function, or provide it as a context value with detect_change=True.

See Memoization and Context.

What is the difference between mount_each() and map() in CocoIndex?

coco.mount_each() creates one processing component for each item, each with its own path, outputs and sync. coco.map() creates no component: it runs a function on each item concurrently inside the current component and returns the results. Use mount_each() for items that come and go on their own, such as files or rows, and map() for steps in the work of one larger item, such as the sections of a file.

See Mounting.

What does detect_change=True do on a ContextKey?

It makes CocoIndex track the value provided under that key. When the value changes, every memoized function that read it runs again, including functions that read it through a function they call. Change detection is off by default. Turn it on for values that affect results, such as models and configuration, and leave it off for values such as database pools.

See Context: shared values that CocoIndex can track.

What is the difference between catch-up mode and live mode?

In catch-up mode, cocoindex update scans the source, processes what changed, syncs the target and exits. In live mode, cocoindex update -L keeps the app running and applies each source change when it happens, if the source can watch for changes. The memo check, the declarations and the sync are the same in both modes.

See Live mode: the same app, kept running.

Build fresh context for your agents.

CocoIndex keeps derived data in sync with its sources. Only what changed re-runs.