Guides · Models & ML
Model serving
Serve your own model from the database your product uses. Read features in one query, score on request or in the background and keep 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.
- Features in one query
- The model’s inputs come from live rows read as the caller. No second store needs to stay in step.
- Scores on request
- An app calls one deployed query and gets the model’s answer back.
- Slow work queued
- A document is read in the background and retried on failure. The screen updates when the verdict lands.
- Every answer kept
- Each prediction is a row with the input features and the model version.
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 person. - File storage
- Needed only if the model reads files, such as the claim packets here.
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 { # Not required: a caller reads their own identity alone, and the service reads none. 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. Only the service key may write a score or verdict, so no claimant scores a claim directly. Model and Slot record the serving version. Model registry covers both types.
Read a model’s 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.
Live feature hydration across links and backlinks
scoreClaim traverses forward links (.claimant.tier), reverse backlinks (.<claim[is Prediction]) and Slot.serving in one snapshot, without separate feature caches that drift out of date.
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>$claim- No second store
- Features are read on demand from live application rows rather than copied into an external feature cache that can lag behind.
- Refused before the model
- The query returns only claims the caller may read. For any other caller, the call answers
403 nothing_foundand never reaches the model. - Kept with the answer
- Store the exact input payload on
Prediction.features. Training on the features the model actually received prevents training-serving skew.
Score while the caller waits#
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.
Policy-gated model inference and provenance
POST /query/scoreClaim forwards permitted feature rows and Slot.serving.version to your HTTPS model server, then persists Prediction.features, model and verdict with the service key.
napalm actions add notes scoreClaim https:// ml.example.com/ actions/ scoreClaim --timeout 20// 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} // The service's own key: only it may write a prediction.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, },)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 has up to 30 seconds. The feature rows sent to a handler can be 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.
Score later, with retries#
Extracting and scoring a scanned packet takes longer than an interactive request should wait, so queue it 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 };The job runs as the claimant
readClaimPacketis an action too, and its query runs as the claimant. The query returns only the claimant’s packet along with a signed link to its bytes.dbschema/queries/readClaimPacket.edgeql select Prediction { id, model, claim: { amount_cents, file_url },}filter .id = <uuid>$prediction and .status = PredictionStatus.PendingThe handler reads the file and writes the verdict
The handler fetches
file_urlstraight from object storage, runs the model and completes the prediction with the service key. Failed or timed-out attempts retry after 10 seconds with exponential backoff. Becausejob.idstays the same on every attempt, pass it as an idempotency key so the work runs once.dbschema/queries/completePrediction.edgeql update Predictionfilter .id = <uuid>$prediction and .status = PredictionStatus.Pendingset { status := PredictionStatus.Completed, verdict := <str>$verdict, score := <float64>$score,}The screen updates from the row
The app subscribes to the prediction and shows the verdict at commit. Nothing polls.
dbschema/queries/predictionStatus.edgeql select Prediction { status, score, verdict }filter .id = <uuid>$predictioncomponents/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#
Search can embed with a model you serve. Declare it as an embedding model under your own provider and attach it to the index. Models & embeddings covers the declaration and the cost of changing an index’s model.
Check the scoring#
# 1. As a signed-in claimant: a score comes back, and a prediction is recorded with its features.curl https://notes.napalmdata.com/query/scoreClaim \ -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \ -d '{ "variables": { "claim": "'$CLAIM'" } }' # 2. As anyone else: nothing is found, and the model is never called.curl -i https://notes.napalmdata.com/query/scoreClaim \ -H "Authorization: Bearer $OTHER_SESSION" -H "Content-Type: application/json" \ -d '{ "variables": { "claim": "'$CLAIM'" } }' # 3. The claimant can't write a verdict of their own.curl https://notes.napalmdata.com/query \ -H "Authorization: Bearer $SESSION" -H "Content-Type: application/json" \ -d '{ "query": "update Prediction set { verdict := \"approve\" }" }'The first call answers a score and a verdict. The second answers 403 nothing_found. The third changes nothing. No rule lets a claimant update a prediction, so the update finds no rows.