The CocoIndex App
Apps are the top-level runnable unit in CocoIndex. Learn how to create an App, trigger updates, configure the database path, and wire up lifespan-managed resources.
Read Core Concepts for the App and source → transform → target-state model, with diagrams.
An App is the top-level runnable unit in CocoIndex.
It names your pipeline and binds a main function with its parameters. When you call app.update(), CocoIndex runs that main function as the root processing component which can mount child processing components to do work and declare target states.
Creating an app
To create an App, provide:
- An
AppConfig(or just a name string) — identifies the pipeline - A main function — the entry point for your pipeline
- Arguments — any additional arguments to pass to the main function
import cocoindex as coco
@coco.fn
async def app_main(sourcedir: pathlib.Path) -> None:
# ... your pipeline logic ...
app = coco.App(
coco.AppConfig(name="MyPipeline"),
app_main,
sourcedir=pathlib.Path("./data"),
)AppConfig:
app = coco.App("MyPipeline", app_main, sourcedir=pathlib.Path("./data"))The main function is usually async. See How Sync and Async Work Together for details.
Updating an app
Callupdate() to execute the pipeline. It returns an UpdateHandle that is also Awaitable, so the simplest usage stays the same:
# Async — await the result directly (backward-compatible)
result = await app.update()# Sync (blocking) API
result = app.update_blocking()Parameters:
liveoption keeps the app running after the initial scan so live components can continue watching for changes. See Live Mode.report_to_stdoutoption prints periodic progress updates during execution. PassTruefor the default refresh interval, or atimedeltato set it.full_reprocessoption reprocesses everything, bypassing all memoization: every component and every memoized function re-executes, and all target states are re-applied even if unchanged. Mind the cost — this includes every paid external call (embedding and LLM APIs re-run for all content). To force re-running just one function’s work, bump itsversioninstead.previewoption computes the target actions without applying them, and returns them in place of the main function’s value. See Previewing an update.component_selectoroption runs only the components you name. See Updating part of an app.
handle = app.update(live=True)
await handle.result()When you update an App, CocoIndex:
- Runs the lifespan setup (if not already done)
- Executes the main function (the root processing component), which mounts child processing components
- Compares the declared target states with the previous run and applies only the necessary changes to external systems
Given the same logic and inputs, updates are repeatable. When logic or inputs change, only the affected parts re-execute.
To watch progress beyond thereport_to_stdout flag, the UpdateHandle returned by app.update() also exposes stats programmatically — poll with handle.stats() or stream with handle.watch(). For those structured APIs, and for splitting a run into separately-reported scopes with coco.stats_group(), see Progress monitoring.
Previewing an update
A preview runs the update without applying it, and returns the actions the update would take on its targets: app.update(preview=True), or cocoindex update --preview from the command line. It lists every action the update takes, including the deletion of the target states of the components the app no longer mounts, down their whole subtree: the outputs of a deleted source file, or of a child whose key changed. It writes nothing to the targets or to CocoIndex’s records, so as long as the sources stay the same, the next update, or the next preview, plans the same actions again.
A failure that happens only when a sink applies its actions, such as a database rejecting a row, shows up only in the update.
Updating part of an app
Pass component_selector to run a slice of the app: the components at the given paths and what it takes to reach them. Every other component stays exactly as it is. This is what you want to inspect or debug a few components without processing the rest, for example the rows on one page of an observability UI.
paths = [coco.ROOT_PATH / coco.Symbol("process_file") / name for name in page_of_files]
await app.update(component_selector=paths)
# Preview what they would declare, without applying it.
actions = await app.update(component_selector=paths, preview=True)A selector is a set of component paths, each a StablePath built from the keys of the mount calls: in Python, a mount without a subpath adds the Symbol of the function’s name (in Rust, a Str key), coco.component_subpath("process", key) adds its keys, and a key keeps its type (1 is not "1"). A path names one component and everything below it, so coco.ROOT_PATH / "process" selects everything mounted under it. Selecting a path that does not exist is not an error: it selects nothing, so check that a path you built is one the app has.
To get the paths of an app, call await cocoindex.inspect.list_stable_paths(app) (or list_stable_paths_sync(app)): it returns StablePath values that you can pass to component_selector as they are. cocoindex show prints the same paths for reading: @name is a Symbol (@"name" when the name is not a plain word, such as @"cocoindex/mount_target"), a quoted part is a string, and a bare number is an int. cocoindex show PATH and cocoindex update --select PATH read that text back.
From the command line, pass the paths as cocoindex show prints them to cocoindex update --select, once per path. Quote each one for the shell:
cocoindex update main.py --select '/@process_file/"docs/a.md"' --select '/@process_file/"docs/b.md"'
For a Rust app, the cocoindex CLI for Rust takes the same flag; a Rust mount key is a string, so write '/"process_file"/"docs/a.md"'. --select works with --preview, --live and --full-reprocess, but not with --reset. A path that is not written as cocoindex show prints it, such as /process_file/docs/a.md, is an error.
What each component does in such an update:
| Component | What happens |
|---|---|
| Selected, or under a selected path | Runs as in a plain update: memoization applies, its target states sync, and if its source item is gone, it is deleted. |
| An ancestor of a selected path | Runs, to reach the selected path. Its own target states sync. |
The root, and a use_mount child | Always run, since a value they return may be needed. Their own target states sync. What they mount is filtered in turn. |
| Anything else | Not run, and not treated as gone: no target state changes and nothing about it changes in CocoIndex’s records, even if its source item changed or was deleted. A live component does not start. |
A selector skips components, not target states. A pipeline that runs each item with use_mount (to collect the results), or whose parent declares the rows of its items, runs every item and syncs every row under any selector. Only what is mounted with mount or mount_each can be left out.
Details to rely on:
- The next plain update catches up. An unselected component is processed by the next update that covers it, including its deletion if its source item is still gone. To make that possible, a component with a child that the selector left out, and each of its ancestors, stores no memo and drops the one it had, so it runs again next time. What it mounted hits its own memo as usual.
- A container change needs a plain update when it affects left-out rows. A change to a container target state (a table, a dict) that rebuilds it, converts its data or removes it also affects the rows of its children. If a selective update would apply one while a component it does not run owns a row of that container, the component that declares the container fails before it applies anything, because the update would not declare that row again, and the update fails with the same error when it ends, even if that component runs in the background. Other selected components may already have applied their changes. The error names the container target state and asks for a full update: run one without
component_selector. A preview with the same selector fails with the same error, so it never shows what the update would refuse. When the update runs every component that owns a row of the container, for example--select '/@process_file'in a pipeline whose rows all come fromprocess_file, the change applies as in a plain update.- A change that keeps the data, such as a new nullable column or an index change, is not refused. It applies, and the rows of unselected components show it (a new column reads
NULL) until they run again. - A connector that cannot trust the previous state, as under
full_reprocess, may report a lossy change for a container that did not change. That is not refused. - A selected component that is gone still removes its containers, rows of unselected components included, since nothing can declare under them any more. The next plain update cleans up their records.
- A change that keeps the data, such as a new nullable column or an index change, is not refused. It applies, and the rows of unselected components show it (a new column reads
- A memo hit stands in for the subtree. As in a plain update, a memoized ancestor whose inputs did not change is not run, and neither is anything below it. Add
full_reprocess=Trueto force the selected components to run: it applies only to them and to the ancestors that reach them. - An ancestor component that is no longer mounted stays whole. If an ancestor component of a selected path is gone from the source, nothing below it is deleted, selected or not, because deleting it would delete unselected components too. The next update that covers it does. A directory (a
component_subpathprefix) is not a component: a selected path below a directory that is gone is deleted. So is a selected path below a directory, such as the path of amount_each(), that the update mounts where a component used to be. The old component itself stays until an update covers it. - Live mode: the selector holds for the whole update, including
operator.updateandoperator.deletecalls from later live events. A live component already running in another update keeps running if this update is a preview or a one-shot update, or if the component is unselected or only an ancestor of a selected path. A one-shot update that selects the component runs its own instance beside the running one, as a plain one-shot update does (see A catch-up update beside a running live update). A live update that selects the component replaces it, as any second live update does. A source that allows one watcher at a time can fail the second run. Values that a live component writes withwrite_committed_stateunder a selector are not persisted unless the component is selected, because a partial run has not earned a marker such as “full scan done”. - State of the components that run.
coco.use_statevalues of the components that run, ancestors included, are persisted as usual. Don’t store a marker that claims the whole subtree ran (such as “full scan done”) withuse_statein a component that a selector can run partly. - Preview returns the actions the selective update would take: those of the components that run (the selected ones, plus any changes to the own target states of the ancestors and
use_mountchildren that run), and the deletions of the selected components that are no longer mounted, by the rules above. As in any preview, a failure that happens only when a sink applies its actions shows up only in the update. - Taking over a target state. A selected component that declares a target state another component owns takes it over, as it would in a plain update. The other component and its ancestors lose their memos, so that the next update that covers them runs them: even a selected component may not run, for example below an ancestor component that is no longer mounted. The rest of the other component is left alone.
- Empty selector.
component_selector=[]selects nothing: the root and itsuse_mountchildren run, and no other component does.None, the default, is a plain update. - A source is read only as far as needed. A
mount_each()that the selector leaves out does not read its items at all. One that is only an ancestor of selected paths reads just the selected keys from a source that can read by key, such aslocalfs.walk_dir(...).items()outside live mode, which checks the selected files instead of walking the directory. A selected key that the source no longer has is deleted, as in a plain update. Any other source is listed in full, andmount_each()skips the unselected items. Amount_each()that is not read cannot report a duplicate key, so a key used twice may only show up in a plain update. - In Rust, the selector filters
ctx.mount,ctx.mount_eachand live components.ctx.scope,use_mount!anduse_mount_each!return values, so they always run.
How an app runs
An App is the top-level runner and entry point. A processing component is the unit of incremental execution within an app.
- Your app’s main function runs as the root processing component at the root path.
-
Each call to
mount()oruse_mount()declares a child processing component at a child path. Sugar APIs likemount_each()andmount_target()also create child components. - Each processing component declares a set of target states, and CocoIndex syncs them as a unit when that component finishes — all writes happen after processing completes, and each target backend applies its batch atomically when supported.
This is why app.update() does not “run everything from scratch”: CocoIndex uses the component path tree to decide what can be reused and what must re-run.
For example, an app that processes files might mount one component per file — the per-file fan-out from Core Concepts, shown here as a path tree:
(root) ← app_main component
└── process_file
├── "hello.md" ← process_file component
└── "world.md" ← process_file component
See Processing Component for how mounting and component paths define these boundaries.
Database path
CocoIndex needs a database path (db_path) to store its internal state. This database tracks target states and memoized results from previous runs, enabling CocoIndex to compute what changed and apply only the necessary updates.
The simplest way to configure the database path is via the COCOINDEX_DB environment variable:
export COCOINDEX_DB=./cocoindex.db
With COCOINDEX_DB set, you can create and run apps without any additional configuration:
import cocoindex as coco
@coco.fn
def app_main() -> None:
# ... your pipeline logic ...
app = coco.App("MyPipeline", app_main)
app.update_blocking() # Uses COCOINDEX_DB for storageFor details on what the internal database stores and how to tune its LMDB settings (the database grows automatically; map_size only sets where it starts), see Internal Storage.
Lifespan (optional)
A lifespan function defines the CocoIndex runtime lifecycle: its setup runs when the runtime starts (automatically before the first app.update()), and its cleanup runs when the runtime stops. Use it to configure CocoIndex settings programmatically or to initialize shared resources that processing components can reuse.
If you only need to set the database path, using the COCOINDEX_DB environment variable is simpler than defining a lifespan function.
Defining a lifespan
Use the@lifespan decorator to register a lifespan function. By default, all apps share the same lifespan (unless you explicitly specify an app in a different Environment). The function receives an EnvironmentBuilder for configuration and uses yield to separate setup from cleanup:
import pathlib
from typing import AsyncIterator
import cocoindex as coco
@coco.lifespan
async def coco_lifespan(builder: coco.EnvironmentBuilder) -> AsyncIterator[None]:
# Configure CocoIndex's internal database location (overrides COCOINDEX_DB if set)
builder.settings.db_path = pathlib.Path("./cocoindex.db")
# Setup: initialize resources here
yield
# Cleanup happens automatically when the context exitsSetting db_path in the lifespan takes precedence over the COCOINDEX_DB environment variable. If neither is provided, CocoIndex will raise an error.
The lifespan function can be sync or async:
import cocoindex as coco
@coco.lifespan
def coco_lifespan(builder: coco.EnvironmentBuilder) -> Iterator[None]:
builder.settings.db_path = pathlib.Path("./cocoindex.db")
yieldYou can also use the lifespan to provide resources (like database connections) that processing components can access. See Context for details on sharing resources across your pipeline.
Explicit lifecycle control (optional)
The lifespan runs automatically the first time any App updates — most users don’t need to do anything beyond defining the lifespan and calling app.update().
If you need more explicit control (for example, to know when startup completes for health checks, or to explicitly trigger shutdown) you can manage the lifecycle directly:
# Async API
await coco.start() # Run lifespan setup
# ... run apps or other operations ...
await coco.stop() # Run lifespan cleanup# Sync (blocking) API
coco.start_blocking() # Run lifespan setup
# ... run apps or other operations ...
coco.stop_blocking() # Run lifespan cleanupOr use the runtime() context manager, which supports both sync and async usage:
# Async
async with coco.runtime():
await app.update()# Sync (blocking)
with coco.runtime():
app.update_blocking()The same App can be retained and reused across sequential runtime lifecycles. After
stop() returns (or a runtime() block exits), its next update or drop starts a new
lifespan and uses freshly initialized resources. Persisted memoization and target-state
tracking in the internal database remain available across these cycles.
This restart guarantee applies to Apps using the default lazy environment (the default
when AppConfig.environment is omitted). An App explicitly bound to the concrete
Environment returned by await coco.default_env() stays bound to it, and stop() closes
that Environment, so the App’s later updates and drops fail, even after a restart. Apps
using a separate explicit Environment are unaffected by starting or stopping the default
runtime.
Finish update and drop operations before stopping the runtime. Shutdown concurrent with in-flight operations is not supported.
Managing apps with CLI
CocoIndex provides a CLI for managing your apps without writing additional code.
Update an app
Run your app once to sync all target states:
cocoindex update main.pyThis executes your pipeline and applies all declared target states to external systems. Add --live (or -L) to keep the app running and react to source changes continuously — see Live Mode.
Drop an app
Remove an app and revert all its target states:
cocoindex drop main.pyThis will delete all target states created by the app (e.g., drop tables, delete rows) and clear its internal state.
drop is an explicit, foreground operation — any failure during the recursive delete (root or any descendant) raises rather than being silently logged. The internal tracking record for a component whose delete failed is preserved so the next drop (with the underlying problem fixed) can complete the cleanup. See Error Handling for the general principle.
See CLI Reference for more commands and options.