Datakey cache rebuild scripts

Both scripts run against a managed FeatureMesh project, because only the managed registry registers cache rows (CACHE-MANAGED-ONLY otherwise). They connect the client to the warehouse that holds the tutorial tables, here a DuckDB file; swap the executor for your warehouse driver. Setup: managed mode .

Rebuild one date

This script repeats steps 2 to 4 of the tutorial for each date it is given. The FeatureQL is exactly what you ran there, with the date filled in. Run it for a new date, or again for a date whose source changed.

from datetime import date
import duckdb
from featuremesh import BatchClient, RegistryDeployment, set_default

# Caches register in the managed registry only: a project access token, and an
# executor connected to the warehouse that holds docs_cache.* (here, a DuckDB file).
set_default("registry", RegistryDeployment.MANAGED)
warehouse = duckdb.connect("warehouse.duckdb")

client = BatchClient(
    access_token="your_project_access_token",
    backend="duckdb",
    sql_executor=lambda sql: warehouse.execute(sql).df(),
)

TABLE = "docs_cache.cache_per_country"
KEY_COLUMN = "country"
# Feature returned by the island -> column of the cache table that stores it.
VALUE_COLUMNS = {
    "FM.DOCS.CACHE.COUNTRY_REVENUE": "country_revenue",
    "FM.DOCS.CACHE.COUNTRY_ORDERS": "country_orders",
}

def island(ds: date) -> str:
    # NO-CACHE: a build always computes from the source tables.
    return f"""
    /* NO-CACHE */
    CONST
        DS := DATE '{ds}'
    RETURN
        PARTITION_DATE := @eval_as_literal(DS),
        COUNTRY,
        COUNTRY_REVENUE,
        COUNTRY_ORDERS
    FROM FM.DOCS.CACHE
    FOR
        COUNTRY := @BIND_KEYSET(KS_COUNTRIES, ROW(ds := DS)),
        NESTED ORDER_ID := @BIND_KEYSET(KS_ORDERS, ROW(ds := DS))
    """

def rebuild(ds: date) -> None:
    # 1. Empty the partition, so that a re-run does not duplicate keys.
    client.query(f"/* SQL */ DELETE FROM {TABLE} WHERE ds = DATE '{ds}';")

    # 2. Build the partition from the source tables.
    build = client.query(f"/* SQL */ INSERT INTO {TABLE} SELECT * FROM FEATUREQL({island(ds)});")

    # 3. Read the datakeys from the response of the build: one entry per island.
    outputs = build.to_dict()["full_response"]["data"]["featureql_queries"][0]["query_outputs_data_keys"]
    data_keys = {output["name"]: output["data_key"] for output in outputs}

    missing = [name for name in VALUE_COLUMNS if not data_keys.get(name)]
    if missing:
        raise RuntimeError(f"No datakey for {missing} on {ds}: these values cannot be cached.")

    # 4. Register the partition. Rows already registered return EXISTS.
    rows = ",\n".join(
        f"(DATAKEY = '{data_keys[name]}', BACKEND = 'duckdb', TABLE_NAME = '{TABLE}', "
        f"KEY_COLUMN = '{KEY_COLUMN}', VALUE_COLUMN = '{column}', "
        f"FILTER_COLUMN = 'ds', FILTER_VALUE = DATE '{ds}')"
        for name, column in VALUE_COLUMNS.items()
    )
    client.query(f"CREATE CACHES {rows};")

if __name__ == "__main__":
    for ds in [date(2026, 10, 7), date(2026, 10, 8)]:
        rebuild(ds)
python

Step 3 of the script runs on every build on purpose. If someone changes ORDER_COUNTRY, the datakey of COUNTRY_REVENUE changes and every old row stops matching. Queries compute until the next build registers the new datakey. Nothing serves a value computed with the old logic. Rows with old datakeys are never read: list them with SHOW CACHES and drop them with DROP CACHES.

Between steps 1 and 2 of the script, the partition is empty but still registered, so a query for that date reads NULL. If readers run during rebuilds, write the new rows to a staging table first and swap the partition in one transaction.

Build one day and backfill a range

With partitioned keysets ( Ranges of days ), the daily job is one CREATE CACHES … AS per day, and the backfill reads the days to build from the dashboard's own query:

from datetime import date, timedelta
import duckdb
from featuremesh import BatchClient, RegistryDeployment, set_default

# Caches register in the managed registry only: a project access token, and an
# executor connected to the warehouse that holds docs_cache.* (here, a DuckDB file).
set_default("registry", RegistryDeployment.MANAGED)
warehouse = duckdb.connect("warehouse.duckdb")

client = BatchClient(
    access_token="your_project_access_token",
    backend="duckdb",
    sql_executor=lambda sql: warehouse.execute(sql).df(),
)

def build_day(ds: date) -> None:
    # Builds the partition of one day and registers one row per feature. Safe to rerun.
    client.query(f"""
    CREATE CACHES
        (FEATURE = DAY_REVENUE, BACKEND = 'duckdb', TABLE_NAME = 'docs_cache.cache_per_day',
         KEY_COLUMN = 'day', VALUE_COLUMN = 'day_revenue', FILTER_COLUMN = 'ds'),
        (FEATURE = DAY_ORDERS, BACKEND = 'duckdb', TABLE_NAME = 'docs_cache.cache_per_day',
         KEY_COLUMN = 'day', VALUE_COLUMN = 'day_orders', FILTER_COLUMN = 'ds')
    AS (
        RETURN DAY, DAY_REVENUE, DAY_ORDERS
        FROM FM.DOCS.DAILY
        FOR
            DAY := @BIND_KEYSET(KS_DAYS, ROW(ds := DATE '{ds}')),
            NESTED ORDER_ID := @BIND_KEYSET(KS_ORDERS, ROW(ds := DATE '{ds}'))
    );
    """)

def backfill(dashboard_query: str) -> None:
    # Translate the dashboard query and build every day it reports as missing.
    response = client.translate(dashboard_query).full_response["data"]
    missing = {value for entry in response["cache_missing_partitions"] for value in entry["missing"]}
    for value in sorted(missing):
        # FeatureQL literal "DATE '2026-10-09'" -> date(2026, 10, 9)
        build_day(date.fromisoformat(value.split("'")[1]))

if __name__ == "__main__":
    # The daily job: yesterday, in the business timezone, once its partition is closed.
    build_day(date.today() - timedelta(days=1))
python

A late order in a closed day means running build_day again for that day, and for the days whose windows contain it.

Next

For the SQL side of the build, see hybrid queries . For the populations a datakey depends on, see @BIND_KEYSET() and RELATED() . For CONST and @eval_as_literal(), see metaprogramming .