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]" 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) F
0 1 - Two pairs are accepted.
ServingClienttakesRegistryDeployment.LOCALwithServingDeployment.EMBEDDED, orRegistryDeployment.MANAGEDwithServingDeployment.ONPREM. Any other pair raisesValueErrorwhen the client is built. - The default is featuremeshd.
registrydefaults toLOCAL, butservingdefaults toONPREM, so set both. - No token. An embedded client takes no
access_token: passing one raisesValueError. - Production with featuremeshd pairs
RegistryDeployment.MANAGEDwithServingDeployment.ONPREM: featuremeshd syncs the definitions from the managed registry, and the client calls it ( From Python , Deploy ). - Close it.
withcloses the client, or callclient.close(). It releases the engine and the registry file. A closed client raisesRuntimeErroron every call. - One process. A client belongs to the process that created it. Used after a
fork, it raisesRuntimeError: 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") Two methods reach it:
client.translate(fql)compiles FeatureQL through the local registry. ACREATEit compiles is registered, and nothing runs.client.query(fql)translates, then runs what it got in the engine. ACREATEis 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) 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 SERVINGreturns one row per definition,FEATURE,KIND,STATUS,MESSAGEandSINCE. 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 SERVINGto 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,PARTIALorERROR) and itsfailures( 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. Therequest_timeargument ofexecute_prepared_statementis a featuremeshd test control, and an embedded client refuses it withValueError.- 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>'];andSHOW SERVING LOGS [LIKE '<logger>'] [LIMIT n];run throughclient.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) A LogBatch holds the rows one logger keeps for one call:
| Field | Content |
|---|---|
logger | the logger's name |
sink | the sink feature's name, empty for a sink written inline |
dsn | the sink's URL (s3://…, file://…, stdout://): a routing key |
format | the sink's FORMAT, jsonl or parquet |
records | one 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, andfile://sinks withFORMAT = 'jsonl', as JSON lines. A logger to any other sink isERRORinSHOW SERVING STATUS( Logging ). - A handler never fails the call. An exception it raises is caught, warned once, and counted.
client.log_statscounts what the client did with log rows since it was created:records_handled,records_written,handler_errors,write_errors, andlast_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
- Hooks and views in Python : run hooks and materialized views in the same process.
- Differences from featuremeshd .
- Python library : install the library and run batch queries.