MESHFLOW_MOCK=1 python3 hands_on/17_cross_run_learning.pyBy the end of this lesson, you should be able to:
Estimated time: 40 to 55 minutes.
You have a pipeline that runs thousands of similar tasks. Each time, it uses the same agent configuration — the same roles, model, and number of steps — regardless of whether a cheaper configuration would have produced equally good results for that task type.
CORAL (Cross-run Optimized Reasoning and Learning) observes your runs over time, stores performance patterns, and recommends the most efficient agent strategy for new tasks that resemble past ones.
The result: after enough runs, CORAL can steer the pipeline toward configurations that cost less, emit less carbon, and finish faster — without sacrificing quality.
CORAL runs as part of the MeshFlow governance stack. When a run completes:
content (word vectors or token hashes).
agent roles, quality score (if available), and whether the run succeeded.
are similar to the current task (using cosine similarity).
recommends the agent configuration that produced the best outcome at the lowest cost.
The recommendation is advisory: you can read it from the run result and decide whether to follow it. CORAL does not automatically change the pipeline — you stay in control.
policy = Policy(
enable_cross_run_learning=True,
# Persist the pattern store to disk across restarts.
# Defaults to in-memory (:memory:) if not set.
)
Pass cross_run_db to persist across process restarts:
result = await Mesh(
agents=agents,
policy=policy,
).run(task, cross_run_db="coral.db")
After the run, any recommendations appear in the run result:
# result.context may contain CORAL recommendation keys
recommended = result.context.get("coral_recommendation")
if recommended:
print(f"CORAL recommends: {recommended}")
A task fingerprint answers: "What kind of task is this?"
Two tasks are similar if they have the same kind of content — both ask for contract summaries, both request technical analysis of code, both ask for financial risk assessment. The fingerprint does not care about specific names or numbers; it cares about the shape of the request.
In practice, CORAL computes a vector embedding of the task text and stores it. Cosine similarity between two vectors measures how similar they are in meaning. A similarity of 1.0 means identical; 0.0 means completely different.
You do not need to understand the mathematics. What matters is:
start seeing useful recommendations.
same agent configuration, CORAL has nothing to compare.
A CORAL recommendation looks like this:
CORAL recommendation:
Based on 12 similar past tasks:
- Efficient strategy (3 agents, researcher+executor+critic) → avg cost $0.003, avg carbon 0.4gCO₂
- Thorough strategy (5 agents, full pipeline) → avg cost $0.021, avg carbon 1.2gCO₂
Recommendation: use efficient strategy (saves 86% cost and 67% carbon)
The recommendation shows you the options, their historical performance, and which one CORAL thinks is best for the current task. You decide.
CORAL is most powerful when combined with carbon budgets. If a run has a tight carbon budget, CORAL will prioritize strategies that historically ran within similar budgets:
policy = Policy(
enable_cross_run_learning=True,
enable_environmental=True,
carbon_budget_g=50.0,
)
Over time, CORAL learns which agent configurations can consistently complete similar tasks within 50g CO₂ and recommends those preferentially.
efficient strategy produces worse results for your task, CORAL will recommend it until you provide quality score feedback that teaches it otherwise.
and act on the recommendation.
cross_run_db pointing to a realdatabase) to be useful across restarts.
meaningful.
MESHFLOW_MOCK=1 python3 hands_on/17_cross_run_learning.py
Observe:
coral.db with sqlite3 to see the stored pattern table.CORAL learns from past runs by storing task fingerprints and performance metrics. It uses cosine similarity to find similar past tasks and recommends the most efficient agent strategy. Enable it with enable_cross_run_learning=True and provide a cross_run_db path for persistence. Recommendations improve with volume. Combine with enable_environmental=True and carbon_budget_g to steer toward carbon-efficient strategies over time.
Goal: Observe CORAL's behavior on a cold start (no prior runs) and on a warm start (with prior run data).
Instructions:
rm -f coral.db
python hands_on/17_cross_run_learning.py
- What recommendation (if any) CORAL returns when the pattern store is empty - What message or indicator CORAL uses to signal "no prior data" - Which agent strategy was actually chosen and used for this first run
coral.db: python hands_on/17_cross_run_learning.py
- The cosine similarity score between the current task fingerprint and the first run's fingerprint - The recommended strategy (should match the first run's strategy if similarity is high) - Whether the recommendation was accepted or whether CORAL chose a different strategy
Expected output: On the first run, a "no prior data" message and a default strategy choice. On the second run, a recommendation based on the first run's data, with a cosine similarity score and recommended agent configuration.
Goal: Watch CORAL's recommendation improve and potentially change as the pattern store accumulates more runs.
Instructions:
coral.db is empty (delete it): rm -f coral.db
coral.db between runs: for i in 1 2 3 4 5; do
echo "=== Run $i ===" && python hands_on/17_cross_run_learning.py
done
- Run number - Number of past runs in the pattern store at recommendation time - Cosine similarity score of the best match - Recommended strategy (which agent or configuration was recommended) - Actual strategy used (did CORAL's recommendation change the decision?) - Estimated cost from the recommendation vs. actual cost after the run
- Did the recommended strategy change between runs 2 and 5? If so, at which run did it change? - Did the confidence of the recommendation increase as more data accumulated? - Was there any run where CORAL recommended a strategy that performed worse than the default?
Expected output: A 5-row table showing recommendation drift over time, with a clear narrative of how CORAL's confidence and accuracy changed as the pattern store grew.
Goal: Understand the internal schema of the CORAL pattern store by reading it directly.
Instructions:
coral.db with at least two runs. sqlite3 coral.db
.tables
.schema
.mode column
.headers on
SELECT * FROM coral_patterns ORDER BY created_at DESC LIMIT 10;
- The fingerprint column: what data type is it stored as? (text, blob, JSON?) - The strategy column: what does a strategy entry look like? What fields does it contain? - The outcome column: what metrics are recorded? (cost, tokens, carbon, duration, quality score?) - The created_at column: is this a Unix timestamp, ISO8601, or another format?
SELECT run_id, strategy, actual_cost_usd
FROM coral_patterns
ORDER BY actual_cost_usd ASC
LIMIT 1;
Expected output: A description of every table and column in coral.db, the results of at least three SQL queries, and three schema improvement observations.
Goal: See how CORAL and the carbon budget guard interact when optimizing for both cost and emissions.
Instructions:
app = MeshFlow(
enable_cross_run_learning=True,
cross_run_db="coral.db",
carbon_budget_g=5.0 # 5 grams CO2e per run maximum
)
coral.db with at least 3 runs using a high-carbon agent strategy (one that exceeds 5g CO2e per run). This simulates a history where past runs were expensive in carbon terms.2.0 grams and run the script again. Observe:- Does CORAL recommend the same high-carbon strategy as before? - Does the carbon budget guard override CORAL's recommendation? - What message does the system emit when a recommendation violates the budget?
SELECT run_id, strategy, carbon_g FROM coral_patterns ORDER BY carbon_g ASC LIMIT 1;
Does CORAL recommend this run's strategy when the carbon budget is tight? Why or why not (consider the similarity score)?
Expected output: Evidence of the carbon budget overriding a CORAL recommendation, the fallback strategy that was used, and a clear description of whether the carbon budget is a hard or soft constraint.
Goal: Apply CORAL's recommendation mechanism to a real problem from your own domain by designing a strategy comparison experiment.
Instructions:
- Summarizing customer support tickets - Classifying incoming emails into categories - Generating first-draft marketing copy for product listings - Extracting structured data from PDF invoices
- Strategy A: GPT-4o-mini, zero-shot prompt, single agent. Expected: fast and cheap, medium quality. - Strategy B: Claude Sonnet, few-shot prompt with 3 examples, single agent. Expected: slower, higher quality. - Strategy C: Claude Sonnet planner + Claude Haiku writer + Claude Sonnet reviewer, multi-agent. Expected: highest quality, highest cost and carbon.
- What task fingerprint features would you use? (e.g., input length, topic category, urgency flag, customer tier) - What outcome metrics would you track? (e.g., quality score from a human rater, cost, latency, carbon_g) - How many runs per strategy would you need before CORAL's recommendations converge? - What similarity threshold would you use to consider two tasks "similar enough" for a recommendation?
Expected output: A written experiment plan (minimum one page) covering all six sections, with clear justification for the fingerprint features and outcome metrics chosen.