MLflow Tracing, Evaluation and Monitoring
One loop from a recorded run to a tested fix: trace, collect cases, score, compare and watch production.
MLflow 3 gives agents a shared record. Tracing captures each model call, retrieval and tool call. Experiments and versions say what produced a result. Evaluation runs scorers, either code checks or model judges, over a dataset. Production monitoring applies registered scorers to a sample of live traces. The value comes from closing the loop: a failure found in production becomes a test that blocks its return.
What you will learn: traces and spans, instrumentation, experiment and version tracking, evaluation datasets, code scorers and judges, release comparison, production monitoring, privacy and a registry-based lifecycle.
Prerequisites: Agent Testing: Unit to End-to-End and agent tracing.
The example runs in November 2026 with Python 3.13 and only the standard library. It imitates traces and scorers with invented data and does not import MLflow. Platform facts come from Databricks documentation checked on November 28, 2026. API names and limits change between versions, so pin the version you use. OneSmartClick is independent of Databricks.
The quality loop
The MLflow 3 for GenAI documentation describes this cycle and presents the platform as joining tracking, evaluation and observability across development and production. The open-source MLflow project provides the core; the managed service adds governance, hosting and platform integration.
Terms you will meet
| Term | Meaning |
|---|---|
| Trace | The record of one request or agent run |
| Span | One step inside it, with timing, inputs, outputs and status |
| Experiment | A container that groups runs, traces and evaluations |
| Run | One recorded execution, such as an evaluation of a version |
| Scorer | A function or judge that assesses an output or trace |
| Assessment | The score or label attached to a trace |
| Evaluation dataset | Saved inputs and expectations used repeatedly |
Instrument the agent
Tracing integrations can capture many libraries and frameworks with little code. Automatic capture is a starting point. Add your own spans around the steps that matter to your business: permission checks, routing decisions, validation, approvals and calls to your own services. For each, record what you would need to explain a bad answer.
| Span | Useful attributes |
|---|---|
| Model call | Endpoint, model version, token counts, stop reason |
| Retrieval | Index, query, document identifiers and scores |
| Tool call | Tool name and version, validated arguments, status, retries |
| Routing | Chosen path and the rule or reason |
| Approval | What was requested, who decided and when |
| Whole run | Agent version, prompt version, user group and outcome |
Record identifiers rather than full sensitive content where an identifier is enough. You can look up a permitted record later; you cannot easily remove a secret copied into thousands of traces.
Read a trace
Start at the outcome and work backward. Was the final answer wrong, or the action? Did the evidence support it? Was the evidence retrieved at all, and from the right version? Did a tool fail and get ignored? Did the run hit a limit? A trace turns "the agent is unreliable" into a specific fault such as "the lookup failed once and the retry returned an older record". Debugging agents gives a fuller method.
Track experiments and versions
An evaluation result is meaningful only if you know what produced it. For each run record the code commit, prompt versions, model endpoint, tool versions, retrieval index and data snapshot, plus scorer versions. MLflow documentation describes application and prompt versioning so that versions can be compared. Change one thing at a time when you can; when several change together, you learn whether the bundle is better but not why.
Build the dataset
Good cases come from real use, expert knowledge and known failures. Each case holds an input, any needed context and an expectation: an exact value, required facts, permitted actions or a behavior such as asking for clarification. Keep metadata for topic, difficulty and risk so that results can be broken down. Remove or mask personal data, restrict access and version the dataset. Hold some cases back from the people tuning prompts. Datasets and simulation covers sampling and synthetic cases.
Choose scorers
MLflow 3 includes built-in judges and supports custom ones. Documentation names scorers such as Correctness, RelevanceToQuery, Safety, RetrievalGroundedness, RetrievalRelevance, RetrievalSufficiency and Guidelines, which judges pass or fail against written criteria. Code-based scorers are ordinary functions marked with a decorator.
| Use | Best scorer | Reason |
|---|---|---|
| Format, required fields, forbidden tool | Code | Exact, cheap and repeatable |
| Latency, tokens, step count | Code over trace spans | Measured directly |
| Numeric or database result | Code against reference | No judgment needed |
| Whether text answers the question | Model judge | Needs language understanding |
| Whether claims follow from sources | Model judge, calibrated | Subtle and error-prone |
| High-impact correctness | Human review | Accountability |
Calibrate model judges
A judge is a model with its own errors. Before it gates a release, have qualified people label a sample, compare their labels with the judge and study disagreements. Measure missed failures separately from false alarms, since they cost differently. Recheck when you change the judge model or its instructions. Judge instructions that mention a format or a length can be gamed by an agent tuned against them. Judges and human review explains the method.
Run an evaluation
Documentation places the evaluation function under the mlflow.genai namespace, as mlflow.genai.evaluate(), and notes that code moving from the earlier agent evaluation interface must name the scorers to run because they are no longer applied automatically. You can pass saved outputs or have the function call your agent. Calling the agent tests the current system; scoring saved traces tests the scorers or compares judgments without new model calls. Make sure evaluation runs cannot trigger real side effects: point tools at test systems or stubs.
Code scorers over traces
The program applies three checks to two versions of an agent on the same three cases, then shows stable sampling.
"""Score recorded agent traces with code checks and compare two versions."""
import hashlib
def trace(tid, answer, spans, cites):
return {"id": tid, "answer": answer, "spans": spans, "cites": cites}
# Each span: (kind, name, milliseconds, ok)
V1 = [
trace("t1", "Refunds take 5 days.", [("llm", "plan", 600, True),
("tool", "search", 300, True), ("llm", "answer", 900, True)], ["kb-12"]),
trace("t2", "Yes, it is covered.", [("llm", "answer", 700, True)], []),
trace("t3", "Order 8 is delayed.", [("tool", "lookup", 200, False),
("tool", "lookup", 210, True), ("llm", "answer", 800, True)], ["db-8"]),
]
V2 = [
trace("t1", "Refunds take 5 days.", [("llm", "plan", 500, True),
("tool", "search", 320, True), ("llm", "answer", 850, True)], ["kb-12"]),
trace("t2", "Yes, it is covered.", [("tool", "search", 350, True),
("llm", "answer", 900, True)], ["kb-30"]),
trace("t3", "Order 8 is delayed.", [("tool", "lookup", 220, True),
("llm", "answer", 3400, True)], ["db-8"]),
]
def cites_source(t):
return bool(t["cites"])
def no_tool_errors(t):
return all(ok for kind, _, _, ok in t["spans"] if kind == "tool")
def fast_enough(t, limit_ms=3000):
return sum(ms for _, _, ms, _ in t["spans"]) <= limit_ms
SCORERS = [cites_source, no_tool_errors, fast_enough]
def evaluate(traces):
return {s.__name__: {t["id"]: s(t) for t in traces} for s in SCORERS}
def sampled(trace_id, rate):
"""Stable sampling: the same trace is always in or out."""
first = hashlib.sha256(trace_id.encode()).digest()[0]
return first < rate * 256
old, new = evaluate(V1), evaluate(V2)
for name in old:
before, after = sum(old[name].values()), sum(new[name].values())
broke = [i for i, ok in new[name].items() if old[name][i] and not ok]
note = f" regressed: {', '.join(broke)}" if broke else ""
print(f"{name:<15} {before}/3 -> {after}/3{note}")
ids = [f"trace-{n}" for n in range(1000)]
print("sampled at 20%:", sum(sampled(i, 0.2) for i in ids), "of", len(ids))
Output:
cites_source 2/3 -> 3/3
no_tool_errors 2/3 -> 3/3
fast_enough 3/3 -> 2/3 regressed: t3
sampled at 20%: 211 of 1000
The new version fixes two problems and introduces a slow response in the third case. A single combined score would show improvement and hide the regression. Review per case, and decide in advance which regressions block release. Note also that these checks are shallow: citing a source says nothing about whether the source supports the answer. Pair cheap checks with judged and human ones. Sampling by a hash of the identifier means the same trace is always included or excluded, which makes comparisons repeatable.
Turn scores into release gates
- Set a threshold for each scorer and risk group, agreed with the owner.
- Require zero failures on critical safety cases.
- Compare with the current production version on the same data.
- Run several trials where outputs vary, and report the spread.
- Review every case that moved from pass to fail.
- Store the results with the release record.
Small datasets produce noisy percentages. A change from 90 to 93 percent on thirty cases is one case. See reliability and release testing.
Production monitoring
With production monitoring, registered scorers run on a sample of incoming traces in an experiment and attach results to each evaluated trace. A sampling configuration sets the share, and multi-turn judges can assess whole conversations. Documentation lists conditions that matter in practice:
- The application must log traces with MLflow.
- Custom scorers must be defined and registered in the documented way, from a Databricks notebook.
- Class-based scorer subclasses cannot be registered; use the decorator form.
- A documented limit applies to the number of scorers per experiment; one page states 20.
Check the current page before designing around any limit.
Set sampling rates by risk
| Check | Sampling idea |
|---|---|
| Cheap code checks | All or most traces |
| Safety judge | High share, especially public users |
| Costly quality judge | A modest share, weighted to important topics |
| Human review | Flagged traces plus a small random set |
Keep a random portion even when you target flagged cases. Targeted samples find known problems; random ones estimate overall quality and find new problems. Remember that judge calls cost money and send trace content to a model, so include them in cost and privacy reviews.
Human feedback
MLflow documentation describes collecting end-user feedback, developer annotations and expert review sessions. Ratings alone are thin: few users give them and unhappy users are overrepresented. Capture useful implicit signals too, such as corrections, retries, abandoned tasks and handoffs. Give reviewers a short rubric, measure how often they agree and show them that their labels change the product.
Alerts and response
Alert on changes that need action: a falling pass rate for a critical scorer, rising tool errors, more runs hitting limits, latency or cost jumps. State the owner and first step for each alert. When a real failure occurs, contain it, find affected traces, add cases to the dataset, fix, evaluate and release. Incidents and maturity describes the process.
Registry and lifecycle
MLflow's model registry, integrated with Unity Catalog on the platform, can version models and packaged agents with permissions and lineage, and prompts can be versioned as well. Agents deployed as applications are also versioned through source control. Whatever mix you use, keep one record that links a running deployment to its code commit, prompt and model versions, evaluation results and approver, so that you can answer what was running on a given day and roll back. See versioning and registry and delivery pipelines.
Moving from older evaluation code
Documentation states that the earlier Agent Evaluation methods are now part of MLflow 3 under the new namespace, and that traces logged with MLflow 2 work with the newer monitoring. A migration is still a change to your measuring instrument. Run old and new evaluation on the same saved traces, explain differences in scores and only then replace the thresholds.
Privacy and retention
Traces and datasets contain what users said and what systems returned. Limit who can read experiments, mask sensitive fields before logging, set retention periods and make deletion possible. Do not copy production traces into broadly readable development spaces. Safe logging covers the controls, and your privacy team decides what rules apply to your data.
A worked example from complaint to gate
Suppose a user reports that an agent said an item was in stock when it was not. The steps below show the loop in practice.
- Find the trace by time, user group or conversation identifier, using access you are permitted to have.
- Read the spans. The retrieval returned a product page from last month, and the live stock tool was never called.
- Name the fault: stock questions are being answered from documents.
- Add cases to the dataset: this question, two other phrasings and one where documents and stock disagree.
- Write a code scorer that fails any stock answer without a successful stock lookup span.
- Change the tool description and routing, then evaluate old and new versions on the full dataset.
- Release when the new cases pass and nothing important regresses, then watch the scorer in production.
The scorer in step five is the lasting asset. It checks behavior, so it keeps working when the wording of answers changes, and it can run on a large share of traffic at almost no cost. Prefer checks of this kind whenever a failure leaves a visible mark in the trace.
Where evaluation fits in the working day
| Moment | Run | Aim |
|---|---|---|
| While editing | A handful of affected cases | Fast feedback |
| Before merging | Fast code scorers on the core set | Stop obvious breakage |
| Before release | The full set with judges and repeats | Decide to ship |
| After release | Sampled scorers on live traces | Confirm behavior with real use |
| On a schedule | The full set against the current system | Catch changes in models or data |
Keep the quick loops genuinely quick. If every edit waits many minutes for judges, people stop running evaluation and rely on impressions, which is how regressions reach users.
Common mistakes
| Mistake | Consequence | Instead |
|---|---|---|
| Only automatic spans | Business decisions are invisible | Add spans for routing and checks |
| Unversioned datasets | Scores cannot be compared | Version cases and scorers |
| Trusting a judge untested | False confidence | Calibrate with people |
| One average score | Regressions hidden | Per case and per group |
| Evaluation with live tools | Real side effects | Test systems and stubs |
| Logging everything forever | Privacy risk and cost | Minimize and expire |
Checklist
- Each important step produces a span with useful attributes.
- Code, prompt, model and data versions are recorded per run.
- A reviewed, versioned dataset covers normal, hard and forbidden cases.
- Judges are calibrated against human labels.
- Release gates include per-case regression review.
- Sampled monitoring has owners, alerts and a response routine.
- Trace access and retention are defined.
Frequently asked questions
Can I use MLflow without Databricks?
MLflow is open source and can be run elsewhere. Managed features, permissions and monitoring differ, so check the documentation for the setup you choose.
How many evaluation cases do I need?
Start with a few dozen real and difficult cases and grow from failures. Add enough per important group that one case does not swing the result.
Should every production trace be judged?
Usually not. Sampling controls cost and exposure, while cheap code checks can run widely. Choose rates by risk.
Is tracing the same as logging?
A trace links the steps of one run with timing and relationships. Logs are separate events. Both are useful, and both need privacy controls.
References
- Databricks: MLflow 3 for GenAI
- Databricks: evaluate and monitor agents
- Databricks: production monitoring
- Databricks: evaluate and improve
Where to go next
Continuous Evaluation, Statistics and Scorecards
Make evaluation a routine.
Deployment, CI/CD and Troubleshooting
Put gates into delivery.
What to Measure: Metrics, Dashboards and SLOs
Choose what to watch.