Use one validated predictor for the analyst’s batch and a loopback HTTP endpoint, with the selected bundle attached to every prediction.
Problem
When you need this. The analyst needs a daily list of return estimates. An HTTP service is unnecessary for producing that list, so start with a batch command that loads one selected bundle and predicts for all requested observations.
When another application needs request/response prediction, reuse the same predictor behind FastAPI, a Python framework for HTTP APIs. The exercise starts the HTTP server in a fresh local process and compares its probability with the batch result. It does not deploy a public service.
Concepts
Inference applies fitted parameters to inputs. Here the scaler transforms recent_event_count and the saved weights produce a return probability. The 0.5 threshold converts that probability into a decision. No fitting happens during prediction.
The request identifies the observation, user, prediction cutoff, feature cutoff and count. The count must be an integer from 0 to 1000, and its calculation cutoff must match the prediction cutoff. A matching timestamp is part of the input contract. The caller still has to get the count from the trusted feature computation.
Batch validation checks all rows before returning predictions and refuses duplicate observation IDs. The optional HTTP endpoint uses the same request validator. It rejects null, arrays, extra fields, booleans as counts, duplicate JSON keys and non-finite JSON values.
Every result carries the bundle ID and the model and policy hashes. The 48 demonstration requests reuse validation observations. The batch predicts all 48, and the HTTP check compares the first request with its batch result. They are not a new evaluation set.
Architecture
Working code
Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. Install the pinned platform dependencies for this workshop.
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txtOn PowerShell, activate with .venv\Scripts\Activate.ps1.
Continue from Register and select an explicit model version; keep the same lab directory and outputs.
Share the prediction contract
A Predictor loads and checks the bundle before accepting requests. The batch function validates every row before it predicts any row, so an invalid batch produces no partial output.
def request(value):
required={'id','entity','predict_at','feature_at','recent_event_count'}
if not isinstance(value,dict) or set(value)!=required:raise ValueError('prediction needs exactly the declared fields')
for key in ['id','entity']:w.availability.check_id(value[key])
at=w.availability.instant(value['predict_at']);feature=w.availability.instant(value['feature_at'])
if at!=feature:raise ValueError('feature must be calculated for this prediction cutoff')
w.count(value['recent_event_count'])
return valueclass Predictor:
def __init__(self,bundle):
self.bundle=Path(bundle);self.model,self.manifest,self.decision=release.load_bundle(bundle)
if not self.decision['passed']:raise ValueError('failed candidate cannot serve')
self.bundle_id=f.digest(self.manifest)
def predict(self,value):
value=request(value);start=time.perf_counter()
result=w.predict(self.model,value['recent_event_count'])
return {'id':value['id'],'entity':value['entity'],'predict_at':value['predict_at'],
'feature_at':value['feature_at'],'recent_event_count':value['recent_event_count'],
**result,'bundle_id':self.bundle_id,'model_sha256':self.manifest['model_sha256'],
'policy_sha256':self.manifest['policy_sha256'],
'prediction_ms':(time.perf_counter()-start)*1000}def batch(bundle,rows):
# Validate the entire batch before generating output; reject duplicate requests.
if not isinstance(rows,list) or not 1<=len(rows)<=1000:raise ValueError('batch requires 1 to 1000 rows')
checked=[request(row) for row in rows]
if len({r['id'] for r in checked})!=len(checked):raise ValueError('duplicate prediction ID')
predictor=Predictor(bundle)
return {'bundle_id':predictor.bundle_id,'predictions':[predictor.predict(row) for row in checked],
'execution':'actual local batch prediction; authored feature inputs'}The predictor keeps the same arithmetic as the manual workflow. The batch contains 48 estimates and their observation and release identities.
Exercise a fresh local HTTP process
The workshop starts uvicorn on loopback and polls /health until it returns 200. It then submits a valid request and sends null as a bad request. Finally it stops the server process.
def create_app(bundle):
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
app=FastAPI();predictor=Predictor(bundle)
@app.get('/health')
def health():return {'status':'ready','bundle_id':predictor.bundle_id}
@app.post('/predict')
async def predict_http(http:Request):
try:
if int(http.headers.get('content-length','0'))>65536:return JSONResponse({'error':'request too large'},status_code=413)
raw=await http.body()
if len(raw)>65536:return JSONResponse({'error':'request too large'},status_code=413)
# Reuse strict JSON semantics, including duplicate fields and NaN rejection.
def unique(pairs):
result={}
for k,v in pairs:
if k in result:raise ValueError('duplicate field')
result[k]=v
return result
def invalid(x):raise ValueError('non-finite JSON')
data=json.loads(raw,object_pairs_hook=unique,parse_constant=invalid)
return predictor.predict(data)
except (ValueError,UnicodeError):return JSONResponse({'error':'invalid prediction request'},status_code=422)
return apppython course.py serving --workspace work/course{
"batch_rows": 48,
"fresh_http_process": true,
"http_status": 200,
"null_status": 422,
"batch_http_probability_equal": true,
"bundle_id": "c93a6048839f362f0ad902ff6b4480f293cc2af0ac593c2c06ffba954b60c90a",
"external_service_deployed": false
}The saved result shows HTTP 200 for the valid request and 422 for null, with equal batch and HTTP probabilities. Other malformed cases are checked in the integration tests.
The saved run wrote its outputs to recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt; the command refuses to overwrite earlier outputs.
Failure cases
test_http_null_booleans_nonfinite_duplicate_fields_and_parity checks the rejected JSON shapes and direct/HTTP agreement. test_batch_uses_same_predictor_and_rejects_duplicate_ids checks the full batch contract.
The endpoint cannot check which historical events a caller counted. Keep feature construction in the trusted application path. The HTTP interface here accepts features that the caller has already computed.
python -m unittest -v test_platform.pyRunning and scaling the workshop
Run python serving.py –bundle work/course/bundle-v1 –input work/course/requests.json –out work/daily-predictions.json for another batch. The same file contract can feed the analyst’s report.
For a persistent local endpoint, add –http and optionally –port to the bundle command. It binds to 127.0.0.1. A public deployment still needs authentication, rate limiting and a request-size limit that applies while the body streams in. This workshop checks the Content-Length header, then checks the body size only after it reads the full body.
The CPU model is tiny. Measure total request latency, model loading and concurrency separately before choosing worker counts. This exercise does not build or run a Docker image.
Key takeaways
- Batch and HTTP consumers can share one predictor.
- Inference uses saved preprocessing and weights.
- Observation and release identities make later outcome joins possible.
Best practices
Start with the interface the consumer actually needs.
Reject malformed requests before generating a result and keep prediction IDs unique.
Load and check the bundle once, when the process starts. Predictor refuses a bundle whose files changed or whose gate decision did not pass, so the HTTP server fails before it accepts a request.
Before you rely on the endpoint, compare its probability with the batch probability for the same request. The course.py serving command stops with an error when the two probabilities differ or when null is not rejected with 422.
Check your understanding
Why does a matching feature_at field not prove the count is correct?
Show the explanation
It states the caller’s claimed cutoff. Only the trusted feature calculation and its retained inputs can establish which events were counted.
Read the explanation
The request must be a JSON object containing exactly the declared fields. JSON null fails validation and the HTTP boundary returns 422.