Vapora/docs/adrs/0019-temporal-execution-history.html

539 lines
22 KiB
HTML
Raw Normal View History

<!DOCTYPE HTML>
<html lang="en" class="light sidebar-visible" dir="ltr">
<head>
<!-- Book generated using mdBook -->
<meta charset="UTF-8">
<title>0019: Temporal Execution History - VAPORA Platform Documentation</title>
<!-- Custom HTML head -->
<meta name="description" content="Comprehensive documentation for VAPORA, an intelligent development orchestration platform built entirely in Rust.">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link rel="icon" href="../favicon.svg">
<link rel="shortcut icon" href="../favicon.png">
<link rel="stylesheet" href="../css/variables.css">
<link rel="stylesheet" href="../css/general.css">
<link rel="stylesheet" href="../css/chrome.css">
<link rel="stylesheet" href="../css/print.css" media="print">
<!-- Fonts -->
<link rel="stylesheet" href="../FontAwesome/css/font-awesome.css">
<link rel="stylesheet" href="../fonts/fonts.css">
<!-- Highlight.js Stylesheets -->
<link rel="stylesheet" id="highlight-css" href="../highlight.css">
<link rel="stylesheet" id="tomorrow-night-css" href="../tomorrow-night.css">
<link rel="stylesheet" id="ayu-highlight-css" href="../ayu-highlight.css">
<!-- Custom theme stylesheets -->
<!-- Provide site root and default themes to javascript -->
<script>
const path_to_root = "../";
const default_light_theme = "light";
const default_dark_theme = "dark";
</script>
<!-- Start loading toc.js asap -->
<script src="../toc.js"></script>
</head>
<body>
<div id="mdbook-help-container">
<div id="mdbook-help-popup">
<h2 class="mdbook-help-title">Keyboard shortcuts</h2>
<div>
<p>Press <kbd></kbd> or <kbd></kbd> to navigate between chapters</p>
<p>Press <kbd>S</kbd> or <kbd>/</kbd> to search in the book</p>
<p>Press <kbd>?</kbd> to show this help</p>
<p>Press <kbd>Esc</kbd> to hide this help</p>
</div>
</div>
</div>
<div id="body-container">
<!-- Work around some values being stored in localStorage wrapped in quotes -->
<script>
try {
let theme = localStorage.getItem('mdbook-theme');
let sidebar = localStorage.getItem('mdbook-sidebar');
if (theme.startsWith('"') && theme.endsWith('"')) {
localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
}
if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
}
} catch (e) { }
</script>
<!-- Set the theme before any content is loaded, prevents flash -->
<script>
const default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? default_dark_theme : default_light_theme;
let theme;
try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
if (theme === null || theme === undefined) { theme = default_theme; }
const html = document.documentElement;
html.classList.remove('light')
html.classList.add(theme);
html.classList.add("js");
</script>
<input type="checkbox" id="sidebar-toggle-anchor" class="hidden">
<!-- Hide / unhide sidebar before it is displayed -->
<script>
let sidebar = null;
const sidebar_toggle = document.getElementById("sidebar-toggle-anchor");
if (document.body.clientWidth >= 1080) {
try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
sidebar = sidebar || 'visible';
} else {
sidebar = 'hidden';
}
sidebar_toggle.checked = sidebar === 'visible';
html.classList.remove('sidebar-visible');
html.classList.add("sidebar-" + sidebar);
</script>
<nav id="sidebar" class="sidebar" aria-label="Table of contents">
<!-- populated by js -->
<mdbook-sidebar-scrollbox class="sidebar-scrollbox"></mdbook-sidebar-scrollbox>
<noscript>
<iframe class="sidebar-iframe-outer" src="../toc.html"></iframe>
</noscript>
<div id="sidebar-resize-handle" class="sidebar-resize-handle">
<div class="sidebar-resize-indicator"></div>
</div>
</nav>
<div id="page-wrapper" class="page-wrapper">
<div class="page">
<div id="menu-bar-hover-placeholder"></div>
<div id="menu-bar" class="menu-bar sticky">
<div class="left-buttons">
<label id="sidebar-toggle" class="icon-button" for="sidebar-toggle-anchor" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
<i class="fa fa-bars"></i>
</label>
<button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
<i class="fa fa-paint-brush"></i>
</button>
<ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
<li role="none"><button role="menuitem" class="theme" id="default_theme">Auto</button></li>
<li role="none"><button role="menuitem" class="theme" id="light">Light</button></li>
<li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
<li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
<li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
<li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
</ul>
<button id="search-toggle" class="icon-button" type="button" title="Search (`/`)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="/ s" aria-controls="searchbar">
<i class="fa fa-search"></i>
</button>
</div>
<h1 class="menu-title">VAPORA Platform Documentation</h1>
<div class="right-buttons">
<a href="../print.html" title="Print this book" aria-label="Print this book">
<i id="print-button" class="fa fa-print"></i>
</a>
<a href="https://github.com/vapora-platform/vapora" title="Git repository" aria-label="Git repository">
<i id="git-repository-button" class="fa fa-github"></i>
</a>
<a href="https://github.com/vapora-platform/vapora/edit/main/docs/src/../adrs/0019-temporal-execution-history.md" title="Suggest an edit" aria-label="Suggest an edit">
<i id="git-edit-button" class="fa fa-edit"></i>
</a>
</div>
</div>
<div id="search-wrapper" class="hidden">
<form id="searchbar-outer" class="searchbar-outer">
<input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
</form>
<div id="searchresults-outer" class="searchresults-outer hidden">
<div id="searchresults-header" class="searchresults-header"></div>
<ul id="searchresults">
</ul>
</div>
</div>
<!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
<script>
document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
});
</script>
<div id="content" class="content">
<main>
<h1 id="adr-019-temporal-execution-history-con-daily-windowing"><a class="header" href="#adr-019-temporal-execution-history-con-daily-windowing">ADR-019: Temporal Execution History con Daily Windowing</a></h1>
<p><strong>Status</strong>: Accepted | Implemented
<strong>Date</strong>: 2024-11-01
<strong>Deciders</strong>: Knowledge Graph Team
<strong>Technical Story</strong>: Tracking agent execution history with daily aggregation for learning curves</p>
<hr />
<h2 id="decision"><a class="header" href="#decision">Decision</a></h2>
<p>Implementar <strong>temporal execution history</strong> con daily windowed aggregations para computar learning curves.</p>
<hr />
<h2 id="rationale"><a class="header" href="#rationale">Rationale</a></h2>
<ol>
<li><strong>Learning Curves</strong>: Daily aggregations permiten ver trends (improving/stable/declining)</li>
<li><strong>Causal Reasoning</strong>: Histórico permite rastrear problemas a raíz</li>
<li><strong>Temporal Analysis</strong>: Comparer performance across days/weeks</li>
<li><strong>Efficient Queries</strong>: Daily windows permiten group-by queries eficientes</li>
</ol>
<hr />
<h2 id="alternatives-considered"><a class="header" href="#alternatives-considered">Alternatives Considered</a></h2>
<h3 id="-per-execution-only-no-aggregation"><a class="header" href="#-per-execution-only-no-aggregation">❌ Per-Execution Only (No Aggregation)</a></h3>
<ul>
<li><strong>Pros</strong>: Maximum detail</li>
<li><strong>Cons</strong>: Queries slow, hard to identify trends</li>
</ul>
<h3 id="-monthly-aggregation-only"><a class="header" href="#-monthly-aggregation-only">❌ Monthly Aggregation Only</a></h3>
<ul>
<li><strong>Pros</strong>: Compact</li>
<li><strong>Cons</strong>: Misses weekly trends, loses detail</li>
</ul>
<h3 id="-daily-windows-chosen"><a class="header" href="#-daily-windows-chosen">✅ Daily Windows (CHOSEN)</a></h3>
<ul>
<li>Good balance: detail + trend visibility</li>
</ul>
<hr />
<h2 id="trade-offs"><a class="header" href="#trade-offs">Trade-offs</a></h2>
<p><strong>Pros</strong>:</p>
<ul>
<li>✅ Trends visible at daily granularity</li>
<li>✅ Learning curves computable</li>
<li>✅ Efficient aggregation queries</li>
<li>✅ Retention policy compatible</li>
</ul>
<p><strong>Cons</strong>:</p>
<ul>
<li>⚠️ Storage overhead (daily windows)</li>
<li>⚠️ Intra-day trends hidden (needs hourly for detail)</li>
<li>⚠️ Rollup complexity</li>
</ul>
<hr />
<h2 id="implementation"><a class="header" href="#implementation">Implementation</a></h2>
<p><strong>Execution Record Model</strong>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>// crates/vapora-knowledge-graph/src/models.rs
pub struct ExecutionRecord {
pub id: String,
pub agent_id: String,
pub task_id: String,
pub task_type: String,
pub success: bool,
pub quality_score: f32,
pub latency_ms: u32,
pub cost_cents: u32,
pub timestamp: DateTime&lt;Utc&gt;,
pub daily_window: String, // YYYY-MM-DD
}
pub struct DailyAggregation {
pub id: String,
pub agent_id: String,
pub task_type: String,
pub day: String, // YYYY-MM-DD
pub execution_count: u32,
pub success_count: u32,
pub success_rate: f32,
pub avg_quality: f32,
pub avg_latency_ms: f32,
pub total_cost_cents: u32,
pub trend: TrendDirection, // Improving, Stable, Declining
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TrendDirection {
Improving,
Stable,
Declining,
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Recording Execution</strong>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub async fn record_execution(
db: &amp;Surreal&lt;Ws&gt;,
record: ExecutionRecord,
) -&gt; Result&lt;String&gt; {
// Set daily_window automatically
let mut record = record;
record.daily_window = record.timestamp.format("%Y-%m-%d").to_string();
// Insert execution record
let id = db
.create("executions")
.content(&amp;record)
.await?
.id
.unwrap();
// Trigger daily aggregation (async)
tokio::spawn(aggregate_daily_window(
db.clone(),
record.agent_id.clone(),
record.task_type.clone(),
record.daily_window.clone(),
));
Ok(id)
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Daily Aggregation</strong>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub async fn aggregate_daily_window(
db: Surreal&lt;Ws&gt;,
agent_id: String,
task_type: String,
day: String,
) -&gt; Result&lt;()&gt; {
// Query all executions for this day/agent/tasktype
let executions = db
.query(
"SELECT * FROM executions \
WHERE agent_id = $1 AND task_type = $2 AND daily_window = $3"
)
.bind((&amp;agent_id, &amp;task_type, &amp;day))
.await?
.take::&lt;Vec&lt;ExecutionRecord&gt;&gt;(0)?
.unwrap_or_default();
if executions.is_empty() {
return Ok(());
}
// Compute aggregates
let execution_count = executions.len() as u32;
let success_count = executions.iter().filter(|e| e.success).count() as u32;
let success_rate = success_count as f32 / execution_count as f32;
let avg_quality: f32 = executions.iter().map(|e| e.quality_score).sum::&lt;f32&gt;() / execution_count as f32;
let avg_latency_ms: f32 = executions.iter().map(|e| e.latency_ms as f32).sum::&lt;f32&gt;() / execution_count as f32;
let total_cost_cents: u32 = executions.iter().map(|e| e.cost_cents).sum();
// Compute trend (compare to yesterday)
let yesterday = (chrono::NaiveDate::parse_from_str(&amp;day, "%Y-%m-%d")?
- chrono::Duration::days(1))
.format("%Y-%m-%d")
.to_string();
let yesterday_agg = db
.query(
"SELECT success_rate FROM daily_aggregations \
WHERE agent_id = $1 AND task_type = $2 AND day = $3"
)
.bind((&amp;agent_id, &amp;task_type, &amp;yesterday))
.await?
.take::&lt;Vec&lt;DailyAggregation&gt;&gt;(0)?;
let trend = if let Some(prev) = yesterday_agg.first() {
let change = success_rate - prev.success_rate;
if change &gt; 0.05 {
TrendDirection::Improving
} else if change &lt; -0.05 {
TrendDirection::Declining
} else {
TrendDirection::Stable
}
} else {
TrendDirection::Stable
};
// Create or update aggregation record
let agg = DailyAggregation {
id: format!("{}-{}-{}", &amp;agent_id, &amp;task_type, &amp;day),
agent_id,
task_type,
day,
execution_count,
success_count,
success_rate,
avg_quality,
avg_latency_ms,
total_cost_cents,
trend,
};
db.upsert(&amp;agg.id).content(&amp;agg).await?;
Ok(())
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Learning Curve Query</strong>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub async fn get_learning_curve(
db: &amp;Surreal&lt;Ws&gt;,
agent_id: &amp;str,
task_type: &amp;str,
days: u32,
) -&gt; Result&lt;Vec&lt;DailyAggregation&gt;&gt; {
let since = (Utc::now() - chrono::Duration::days(days as i64))
.format("%Y-%m-%d")
.to_string();
let curve = db
.query(
"SELECT * FROM daily_aggregations \
WHERE agent_id = $1 AND task_type = $2 AND day &gt;= $3 \
ORDER BY day ASC"
)
.bind((agent_id, task_type, since))
.await?
.take::&lt;Vec&lt;DailyAggregation&gt;&gt;(0)?
.unwrap_or_default();
Ok(curve)
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Trend Analysis</strong>:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn analyze_trend(curve: &amp;[DailyAggregation]) -&gt; TrendAnalysis {
if curve.len() &lt; 2 {
return TrendAnalysis::InsufficientData;
}
let improving_days = curve.iter().filter(|d| d.trend == TrendDirection::Improving).count();
let declining_days = curve.iter().filter(|d| d.trend == TrendDirection::Declining).count();
if improving_days &gt; declining_days {
TrendAnalysis::Improving
} else if declining_days &gt; improving_days {
TrendAnalysis::Declining
} else {
TrendAnalysis::Stable
}
}
<span class="boring">}</span></code></pre></pre>
<p><strong>Key Files</strong>:</p>
<ul>
<li><code>/crates/vapora-knowledge-graph/src/models.rs</code> (models)</li>
<li><code>/crates/vapora-knowledge-graph/src/aggregation.rs</code> (daily aggregation)</li>
<li><code>/crates/vapora-knowledge-graph/src/learning.rs</code> (learning curves)</li>
</ul>
<hr />
<h2 id="verification"><a class="header" href="#verification">Verification</a></h2>
<pre><code class="language-bash"># Test execution recording with daily window
cargo test -p vapora-knowledge-graph test_execution_recording
# Test daily aggregation
cargo test -p vapora-knowledge-graph test_daily_aggregation
# Test learning curve computation (7 days)
cargo test -p vapora-knowledge-graph test_learning_curve_7day
# Test trend detection
cargo test -p vapora-knowledge-graph test_trend_detection
# Integration: full lifecycle
cargo test -p vapora-knowledge-graph test_temporal_history_lifecycle
</code></pre>
<p><strong>Expected Output</strong>:</p>
<ul>
<li>Executions recorded with daily_window set</li>
<li>Daily aggregations computed correctly</li>
<li>Learning curves show trends</li>
<li>Trends detected accurately (improving/stable/declining)</li>
<li>Queries efficient with daily windows</li>
</ul>
<hr />
<h2 id="consequences"><a class="header" href="#consequences">Consequences</a></h2>
<h3 id="data-retention"><a class="header" href="#data-retention">Data Retention</a></h3>
<ul>
<li>Daily aggregations permanent (minimal storage)</li>
<li>Individual execution records archived after 30 days</li>
<li>Trend analysis available indefinitely</li>
</ul>
<h3 id="trend-visibility"><a class="header" href="#trend-visibility">Trend Visibility</a></h3>
<ul>
<li>Daily trends visible immediately</li>
<li>Week-over-week comparisons possible</li>
<li>Month-over-month trends computable</li>
</ul>
<h3 id="performance"><a class="header" href="#performance">Performance</a></h3>
<ul>
<li>Aggregation queries use indexes (efficient)</li>
<li>Daily rollup automatic (background task)</li>
<li>No real-time overhead</li>
</ul>
<h3 id="monitoring"><a class="header" href="#monitoring">Monitoring</a></h3>
<ul>
<li>Trends inform agent selection decisions</li>
<li>Declining agents flagged for investigation</li>
<li>Improving agents promoted</li>
</ul>
<hr />
<h2 id="references"><a class="header" href="#references">References</a></h2>
<ul>
<li><code>/crates/vapora-knowledge-graph/src/aggregation.rs</code> (implementation)</li>
<li><code>/crates/vapora-knowledge-graph/src/learning.rs</code> (usage)</li>
<li>ADR-013 (Knowledge Graph)</li>
<li>ADR-014 (Learning Profiles)</li>
</ul>
<hr />
<p><strong>Related ADRs</strong>: ADR-013 (Knowledge Graph), ADR-014 (Learning Profiles), ADR-020 (Audit Trail)</p>
</main>
<nav class="nav-wrapper" aria-label="Page navigation">
<!-- Mobile navigation buttons -->
<a rel="prev" href="../../adrs/0018-swarm-load-balancing.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../adrs/0020-audit-trail.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
<div style="clear: both"></div>
</nav>
</div>
</div>
<nav class="nav-wide-wrapper" aria-label="Page navigation">
<a rel="prev" href="../../adrs/0018-swarm-load-balancing.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
<i class="fa fa-angle-left"></i>
</a>
<a rel="next prefetch" href="../../adrs/0020-audit-trail.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
<i class="fa fa-angle-right"></i>
</a>
</nav>
</div>
<script>
window.playground_copyable = true;
</script>
<script src="../elasticlunr.min.js"></script>
<script src="../mark.min.js"></script>
<script src="../searcher.js"></script>
<script src="../clipboard.min.js"></script>
<script src="../highlight.js"></script>
<script src="../book.js"></script>
<!-- Custom JS scripts -->
</div>
</body>
</html>