Embedded serving in Python

The Python library can run FeatureMesh's serving engine inside your own process, with no featuremeshd to deploy. This page shows how to set it up, how definitions reach the engine, and what a call reads.

The engine is the one featuremeshd runs, compiled into a native wheel. Sources, prepared statements and loggers behave as the Real-time data and Prepared statements pages describe. What a Python process does differently is in Differences from featuremeshd .

Install

The engine comes with the serving extra:

pip install "featuremesh[serving]"
bash

The extra installs featuremesh-serving-runtime, a native wheel built for a few platforms ( Platforms ). Without it, pip install featuremesh still gives batch analytics, and a client asking for embedded serving raises ImportError.

Create a client

Two defaults select embedded serving: a local registry, and the embedded engine.

from featuremesh import RegistryDeployment, ServingClient, ServingDeployment, set_default

set_default("registry", RegistryDeployment.LOCAL)
set_default("serving", ServingDeployment.EMBEDDED)

with ServingClient() as client:
    result = client.query("RETURN F := 1;")
    print(result.dataframe)
python
   F
0  1
text
  • Two pairs are accepted. ServingClient takes RegistryDeployment.LOCAL with ServingDeployment.EMBEDDED, or RegistryDeployment.MANAGED with ServingDeployment.ONPREM. Any other pair raises ValueError when the client is built.
  • The default is featuremeshd. registry defaults to LOCAL, but serving defaults to ONPREM, so set both.
  • No token. An embedded client takes no access_token: passing one raises ValueError.
  • Production with featuremeshd pairs RegistryDeployment.MANAGED with ServingDeployment.ONPREM: featuremeshd syncs the definitions from the managed registry, and the client calls it ( From Python , Deploy ).
  • Close it. with closes the client, or call client.close(). It releases the engine and the registry file. A closed client raises RuntimeError on every call.
  • One process. A client belongs to the process that created it. Used after a fork, it raises RuntimeError: create it in the child.

The local registry

Definitions live in a SQLite file, ./featuremesh.db by default, created on first use. local.db_path names another one:

set_default("local.db_path", "registry.db")
python

Two methods reach it:

  • client.translate(fql) compiles FeatureQL through the local registry. A CREATE it compiles is registered, and nothing runs.
  • client.query(fql) translates, then runs what it got in the engine. A CREATE is registered the same way.

Persisting works as with any registry ( Create features ).

Load definitions with RECOMPILE SERVING

The engine loads every served definition of the local registry when the client is created: sources, prepared statements, loggers, streams, hooks and materialized views. It never syncs on its own after that. A definition created later reaches the engine at the next RECOMPILE SERVING:

client = ServingClient()
client.query(open("score.fql").read())   # the CREATE FEATURES of Feature logging
client.query("RECOMPILE SERVING;")
result = client.execute_prepared_statement(
    "FM.TUTORIALS.LOGGING.SCORE_PS",
    {"input_1": [[1], [2], [3]]},
)
print(result.dataframe)
python

Here score.fql holds the scoring statement of Feature logging , with its sink and its logger, in one CREATE FEATURES. One call takes one statement: several statements in one text must be wrapped in START TRANSACTION; … COMMIT;. The call returns one row per key, as on featuremeshd: the inputs, then the statement's output.

  • The same answer as featuremeshd. RECOMPILE SERVING returns one row per definition, FEATURE, KIND, STATUS, MESSAGE and SINCE. A definition that fails to load does not stop the others ( Status and writes ).
  • A warning at creation. When definitions fail to load as the client is created, it warns once, naming up to five. SHOW SERVING STATUS; has the details.
  • One process at a time. Each process loads its own engine. A second process on the same registry file needs its own RECOMPILE SERVING to see a new definition.

What a call reads

  • A free-form query (client.query()) is translated through the local registry at each call, then run by the engine. It reads its sources as featuremeshd does ( How a call reads its sources ).
  • A prepared statement (client.execute_prepared_statement(id, inputs)) runs as loaded at the last load. Its inputs and response are featuremeshd's: one key per input table (input_1, input_2, …), result.full_response["status"] (OK, PARTIAL or ERROR) and its failures ( Call a prepared statement ). Wrong inputs get featuremeshd's codes: MISSING_PARAMETER, UNKNOWN_PARAMETER, ROW_COLUMN_COUNT_MISMATCH, SERVER_FILLED_PARAMETER.
  • REQUEST_TIME() is the time of the call. The request_time argument of execute_prepared_statement is a featuremeshd test control, and an embedded client refuses it with ValueError.
  • Secrets are read by your process: SECRET('env', …) from its environment, SECRET('file', …) from its files, each time the engine connects ( Credentials ).
  • Memory. Calls and view runs share the engine's memory limit, 1 GiB by default. Set it before creating the client, in bytes: set_default("serving.memory_limit_bytes", 4 * 1024**3).
  • Threads. One client serves several threads. The engine runs each call outside Python's global lock. The local registry takes one translation at a time, so free-form queries wait on each other there, and prepared statement calls do not.
  • Status and logs. SHOW SERVING STATUS [LIKE '<pattern>']; and SHOW SERVING LOGS [LIKE '<logger>'] [LIMIT n]; run through client.query() and answer for this process.

Logging from Python

The embedded engine runs the same loggers as featuremeshd, WHERE and EXCLUDE included ( Feature logging ). It hands each call's rows over synchronously, right after the call, to a log_handler you give the client:

import queue

from featuremesh import LogBatch, ServingClient

rows: queue.Queue[LogBatch] = queue.Queue()

def ship(batch: LogBatch) -> None:
    rows.put(batch)   # enqueue, don't ship, in the handler

client = ServingClient(log_handler=ship)
python

A LogBatch holds the rows one logger keeps for one call:

FieldContent
loggerthe logger's name
sinkthe sink feature's name, empty for a sink written inline
dsnthe sink's URL (s3://…, file://…, stdout://): a routing key
formatthe sink's FORMAT, jsonl or parquet
recordsone dict per row: call_id, call_index, call_time, call_details, then the inputs, output and captures, minus EXCLUDE ( A logged row )
  • With a handler, the sink is only a routing key. The client writes no file. The same definitions write to S3 when featuremeshd serves them.
  • Without a handler, the client writes stdout:// sinks, and file:// sinks with FORMAT = 'jsonl', as JSON lines. A logger to any other sink is ERROR in SHOW SERVING STATUS ( Logging ).
  • A handler never fails the call. An exception it raises is caught, warned once, and counted.
  • client.log_stats counts what the client did with log rows since it was created: records_handled, records_written, handler_errors, write_errors, and last_error.
  • The handler runs in the caller's thread, before the call returns, so its time adds to every call. Put the rows on a queue, and ship them from another thread.

Related