Guides · Models & ML
Model serving
Assemble live model features in one query, score requests synchronously or in background jobs and log every prediction.
- In the schema
ext::napalm::Job
What you’ll build#
You will serve your own model from the same database your product already uses across four guarantees.
- Single-query features
- Live application rows supply model inputs directly under caller policies with no separate feature store to synchronize.
- Synchronous scoring
- Clients call one deployed action query and receive the model’s score and verdict in the response.
- Queued document scoring
- Longer OCR and packet-scoring tasks run in background jobs with automatic retries and live UI updates.
- Logged predictions
- Every prediction row stores the exact input feature snapshot alongside the model version that scored it.
Inference runs on your own GPU infrastructure while Napalm hydrates features under your access rules, invokes your endpoint and records every prediction.
Before you start#
- An inference endpoint
- Your own HTTPS endpoint: a model server, a GPU platform endpoint or a thin service in front of either.
- An action
- An action pairs a deployed query with an HTTPS handler. The query selects the rows the caller may score, and the handler calls the model.
- A service key
- The handler writes predictions with the service key. Set the branch’s service globals to
{ "default::role": "service" }so the schema can distinguish the key from a user session. - File storage
- Required when your model reads file records such as scanned claim packets.
Declare your domain types alongside Model, Slot and Prediction so feature queries and logged verdicts share one schema:
using extension auth;using extension files;using extension napalm;using future simple_scoping; module default { global caller := global ext::auth::ClientTokenIdentity; global role: str; scalar type PredictionStatus extending enum<Pending, Completed, Failed>; type Customer { # Optional so service keys (which cannot read ext::auth::Identity) still read Customer. identity: ext::auth::Identity { constraint exclusive; }; required tier: str { default := 'standard'; }; required risk_limit_cents: int64 { default := 500000; }; access policy self_can_read allow select using (.identity ?= global caller); access policy service_can_read allow select using (global role ?= 'service'); } type Claim extending ext::files::File { required claimant: Customer; required amount_cents: int64; created: datetime { rewrite insert using (datetime_of_statement()); }; constraint expression on (std::contains([ext::files::Format.Pdf], .file_format)) { errmessage := 'a PDF is required'; }; access policy claimant_has_full_access allow all using (.claimant.identity ?= global caller); access policy service_can_read allow select using (global role ?= 'service'); } type Model { required name: str; required version: str; constraint exclusive on ((.name, .version)); access policy anyone_can_read allow select; access policy service_has_full_access allow all using (global role ?= 'service'); } type Slot { required name: str { constraint exclusive; }; required serving: Model; previous: Model; shadow: Model; access policy anyone_can_read allow select; access policy service_has_full_access allow all using (global role ?= 'service'); } type Prediction { required claim: Claim { on target delete delete source; }; required model: str; required status: PredictionStatus { default := PredictionStatus.Pending; }; features: json; score: float64; verdict: str; latency_ms: int32; shadow_of: Prediction { on target delete delete source; }; access policy claimant_can_read allow select using (.claim.claimant.identity ?= global caller and not exists .shadow_of); access policy claimant_can_ask allow insert using ( .claim.claimant.identity ?= global caller and .status = PredictionStatus.Pending and not exists .verdict and not exists .shadow_of ); access policy service_has_full_access allow all using (global role ?= 'service'); } type EvalCase { required name: str { constraint exclusive; }; required features: json; required expected: str; access policy service_has_full_access allow all using (global role ?= 'service'); } type EvalResult { required eval_case: EvalCase { on target delete delete source; }; required model: str; required verdict: str; required latency_ms: int32; passed := (.verdict = .eval_case.expected); constraint exclusive on ((.eval_case, .model)); access policy service_has_full_access allow all using (global role ?= 'service'); }}Each claimant can read predictions on their own claims and request a new prediction, while only the service key may write a score or verdict. Model and Slot track the active serving version, as covered in Model registry.
Hydrate features in one query#
A model rarely takes a single flat row. This model needs the claim, the claimant’s tier and risk limit, a recent claim count across reverse backlinks and prior review verdicts. One deployed EdgeQL query hydrates every feature and compiles to a single SQL statement under the requesting caller’s select policies.
Single-query feature hydration
One statement joins related rows, backlink aggregates and active model slots.
Save that feature projection as a deployed query in dbschema/:
select Claim { id, amount_cents, tier := .claimant.tier, risk_limit_cents := .claimant.risk_limit_cents, claims_90_days := count(( select .claimant.<claimant[is Claim] filter .created > datetime_of_statement() - <duration>'2160 hours' )), was_sent_to_review := exists ( select .claimant.<claimant[is Claim].<claim[is Prediction] filter .verdict = 'review' ), model := assert_single((select Slot filter .name = 'claims-risk')).serving.version, shadow := assert_single((select Slot filter .name = 'claims-risk')).shadow.version,}filter .id = <uuid>$claimHydrating features inside the gatekeeper query enforces three serving invariants:
- Live row reads
- Features are read on demand from live application rows rather than copied into an external feature cache that can lag behind.
- Gated before inference
- The query returns only claims the caller may read. For any other caller, the call answers
403 nothing_foundand never reaches the model. - Logged input snapshot
- Store the exact input payload on
Prediction.features. Training on the features the model received prevents training-serving skew.
Score synchronously in an action#
Attach your inference endpoint to turn scoreClaim into a gatekeeper action. When a client calls POST /query/scoreClaim, the query reads features as that caller and sends matching rows in a signed HTTPS request, returning your handler’s JSON payload directly to the app.
Gated synchronous inference
Actions forward permitted features to your model and persist every prediction.
Register your HTTPS handler URL against scoreClaim with an explicit request timeout:
napalm actions add notes scoreClaim https:// ml.example.com/ actions/ scoreClaim --timeout 20Inside the handler, call your model endpoint with the hydrated features, persist the returned verdict with a service key and return the result to the caller:
// app/actions/[action]/route.tsimport { handleCalls, NapalmClient } from 'napalm-client' type Features = { id: string amount_cents: number tier: string risk_limit_cents: number claims_90_days: number was_sent_to_review: boolean model: string shadow: string | null} // Dedicated service client used to persist completed predictions.const service = new NapalmClient('https://notes.napalmdata.com', { token: process.env.NAPALM_KEY }) export const POST = handleCalls( { async scoreClaim(call) { const [{ model, shadow, ...features }] = call.rows as Features[] const started = performance.now() const scored = await fetch(`${process.env.MODEL_URL}/v1/predict`, { method: 'POST', headers: { Authorization: `Bearer ${process.env.MODEL_KEY}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ model, features }), }) if (!scored.ok) throw new Error(`The model answered ${scored.status}`) const { score, verdict } = (await scored.json()) as { score: number; verdict: string } const recorded = await service.fetch('https://notes.napalmdata.com/query/recordPrediction', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ variables: { claim: features.id, model, shadow, features, score, verdict, latency_ms: Math.round(performance.now() - started), }, }), }) if (!recorded.ok) throw new Error(`The prediction wasn't recorded: ${recorded.status}`) return { score, verdict } }, }, { address: 'https://notes.napalmdata.com', handlers: 'https://ml.example.com/actions', secret: process.env.NAPALM_ACTION_SECRET, },)recordPrediction stores the scored Prediction row and queues a background shadow job whenever Slot.shadow is set:
with made := (insert Prediction { claim := <Claim><uuid>$claim, model := <str>$model, status := PredictionStatus.Completed, features := <json>$features, score := <float64>$score, verdict := <str>$verdict, latency_ms := <int32>$latency_ms, }), shadowed := ( for version in {<optional str>$shadow} union ( insert ext::napalm::Job { query := 'shadowScore', variables := <json>(prediction := <str>made.id, model := version), } ) ),select made { id };A handler runs for up to 30 seconds, and the feature rows sent to a handler can total 64 KiB at most, so pass files by reference rather than inline bytes. Evals covers the shadow job, which evaluates a candidate version on live traffic.
Queue slow scoring with retries#
Extracting and scoring a scanned packet takes longer than an interactive request should wait, so queue the task in the background. The pending Prediction and its job commit in one statement, so neither ever exists without the other:
with prediction := (insert Prediction { claim := <Claim><uuid>$claim, model := assert_single((select Slot filter .name = 'claims-reader')).serving.version, }), job := (insert ext::napalm::Job { query := 'readClaimPacket', variables := <json>(prediction := <str>prediction.id), }),select prediction { id };Once that statement commits, background scoring proceeds in three steps:
Run the gatekeeper query as the claimant
readClaimPacketis an action whose gatekeeper query executes under the claimant’s identity, returning only permitted packets along with a signedfile_url:dbschema/queries/readClaimPacket.edgeql select Prediction { id, model, claim: { amount_cents, file_url },}filter .id = <uuid>$prediction and .status = PredictionStatus.PendingScore the file and persist the verdict
The handler streams
file_urlfrom object storage, invokes your model and marks the predictionCompletedusing the service key. Failed attempts retry after 10 seconds with exponential backoff, andjob.idstays constant across attempts as an idempotency key:dbschema/queries/completePrediction.edgeql update Predictionfilter .id = <uuid>$prediction and .status = PredictionStatus.Pendingset { status := PredictionStatus.Completed, verdict := <str>$verdict, score := <float64>$score,}Stream the completed verdict to the UI
Subscribe to
predictionStatuswithuseLiveQueryto render the verdict on commit without polling:dbschema/queries/predictionStatus.edgeql select Prediction { status, score, verdict }filter .id = <uuid>$predictionPass that query name to
useLiveQueryin your React component:components/ClaimVerdict.tsx// components/ClaimVerdict.tsx'use client' import { useLiveQuery } from 'napalm-client/react' type Status = { status: 'Pending' | 'Completed' | 'Failed'; score: number | null; verdict: string | null } export function ClaimVerdict({ prediction }: { prediction: string }) { const { rows } = useLiveQuery<Status, { prediction: string }>({ name: 'predictionStatus' }, { prediction }) const current = rows?.[0] return <p>{current?.status === 'Completed' ? current.verdict : 'Reading your claim…'}</p>}
Serve your own embedding model#
Hybrid search indexes can also call a custom embedding endpoint that you host. Register your endpoint as a custom model provider and reference that model on your ext::ai::index. See Models & embeddings.
Check the scoring#
# 1. Score a claim as its signed-in owner and record the prediction with input features.curl https://notes.napalmdata.com/query/scoreClaim \ -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \ -d '{ "variables": { "claim": "'$CLAIM'" } }' # 2. Calling scoreClaim as another user returns 403 nothing_found without invoking the model.curl -i https://notes.napalmdata.com/query/scoreClaim \ -H "Authorization: Bearer $OTHER_SESSION" -H "Content-Type: application/json" \ -d '{ "variables": { "claim": "'$CLAIM'" } }' # 3. Attempting to overwrite a verdict from a user session updates zero rows.curl https://notes.napalmdata.com/query \ -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \ -d '{ "query": "update Prediction set { verdict := \"approve\" }" }'The first request returns a score and verdict while logging a Prediction row. The second fails with 403 nothing_found before calling your model, and the third updates zero rows because user policies deny direct writes on Prediction.