You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/10/16 14:05:08 UTC

(maka) branch rust-preview updated: perf(event-log): stream ordered archive proof pages

This is an automated email from the ASF dual-hosted git repository.

M4n5ter pushed a commit to branch rust-preview
in repository https://gitbox.apache.org/repos/asf/maka.git


The following commit(s) were added to refs/heads/rust-preview by this push:
     new 313e42bedc perf(event-log): stream ordered archive proof pages
313e42bedc is described below

commit 313e42bedc600359a6499a8e8c30ab6a91921e62
Author: Wang <m4...@gmail.com>
AuthorDate: Fri Oct 16 22:04:50 2026 +0800

    perf(event-log): stream ordered archive proof pages
    
    Merge indexed native and copied target branches, retain cross-page corruption checks, and index archive/checkpoint owner lookups. Extend release benchmarks for archive-heavy contexts and large checkpointed histories.
    
    Generated-by: Codex
---
 .../migrations/0023_archive_proof_lookup.sql       |  27 ++
 platform/event-log/src/archive/candidates.rs       |  20 +-
 platform/event-log/src/archive/effective.rs        |  79 ++++--
 platform/event-log/src/archive/target.rs           |  14 +
 platform/event-log/tests/archive.rs                |   4 +
 .../event-log/tests/archive/context_performance.rs | 113 ++++++++
 platform/event-log/tests/archive/digest.rs         | 229 +++++++++++++++
 platform/event-log/tests/archive/performance.rs    |   1 +
 .../engine/tests/integration/long_task_perf.rs     | 314 +++++++++++++++++----
 scripts/rust/benchmark-long-task.py                |  24 +-
 10 files changed, 725 insertions(+), 100 deletions(-)

diff --git a/platform/event-log/migrations/0023_archive_proof_lookup.sql b/platform/event-log/migrations/0023_archive_proof_lookup.sql
new file mode 100644
index 0000000000..a88eb81446
--- /dev/null
+++ b/platform/event-log/migrations/0023_archive_proof_lookup.sql
@@ -0,0 +1,27 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+-- Proving absence must not scan all model observations in a long session.
+CREATE INDEX checkpoint_session_sequence ON event_log(
+    json_extract(event_json, '$.invocation.session_id'), sequence
+) WHERE kind = 'context_checkpoint_recorded';
+
+CREATE INDEX archive_session_sequence ON event_log(
+    json_extract(event_json, '$.invocation.session_id'), sequence
+) WHERE kind = 'tool_result_archived';
diff --git a/platform/event-log/src/archive/candidates.rs b/platform/event-log/src/archive/candidates.rs
index d6db71bde1..05a1c21bad 100644
--- a/platform/event-log/src/archive/candidates.rs
+++ b/platform/event-log/src/archive/candidates.rs
@@ -92,20 +92,24 @@ async fn scan(
         .expect("prune requires a Session");
     let filter = Selection::predicate("t", "?4");
     let archive_filter = Selection::archive_predicate("t", "a", "9223372036854775807", "?4");
-    let query = format!(
-        "SELECT t.sequence,t.event_id,
+    let branches = target::SOURCES.map(|source| format!(
+        "SELECT t.sequence AS sequence,t.event_id,
            COALESCE(length(CAST(json_extract(t.event_json,'$.fact.outcome.model_projection') AS BLOB)),
                     length(CAST(json_extract(t.event_json,'$.fact.outcome.message') AS BLOB)),0)
-         FROM session_history_events t JOIN runtime_events d ON d.invocation_id=t.invocation_id AND d.operation_id=t.operation_id AND d.kind='tool_dispatched'
-         WHERE t.kind='tool_settled' AND t.sequence>?1 AND t.sequence<=?3 AND t.owner_session_id=?2
+         FROM ({source}) t CROSS JOIN runtime_events d
+         WHERE d.invocation_id=t.invocation_id AND d.operation_id=t.operation_id AND d.kind='tool_dispatched'
+           AND t.sequence>?1 AND t.sequence<=?3 AND t.owner_session_id=?2
            AND {filter} AND json_extract(d.event_json,'$.fact.call.origin.kind')='provider'
-           AND NOT EXISTS(SELECT 1 FROM runtime_events a WHERE a.kind='tool_result_archived' AND CAST(json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id') AS TEXT)=t.event_id AND {archive_filter})
-         ORDER BY t.sequence LIMIT ?5"
+           AND NOT EXISTS(SELECT 1 FROM runtime_events a WHERE a.kind='tool_result_archived' AND CAST(json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id') AS TEXT)=t.event_id AND {archive_filter})"
+    ));
+    let query = format!(
+        "{} ORDER BY sequence LIMIT ?5",
+        branches.join(" UNION ALL ")
     );
     let mut after = cursor.after_sequence as i64;
     let mut used = 0_usize;
-    // Fetch bounded metadata once: the union's ordering must not be repeated
-    // for every candidate. Keep the cursor at the last admitted result.
+    // Merge the indexed branches into bounded metadata, stopping at the page.
+    // Keep the cursor at the last admitted result.
     let rows: Vec<(i64, String, i64)> = sqlx::query_as(sqlx::AssertSqlSafe(query))
         .bind(after)
         .bind(session)
diff --git a/platform/event-log/src/archive/effective.rs b/platform/event-log/src/archive/effective.rs
index 06f9bf2e5e..7357f20dff 100644
--- a/platform/event-log/src/archive/effective.rs
+++ b/platform/event-log/src/archive/effective.rs
@@ -17,7 +17,7 @@
  * under the License.
  */
 
-use super::{ArchiveError, accepted};
+use super::{ArchiveError, accepted, target};
 use crate::{
     StoreError,
     context::{SourceEvidence, selection::Selection},
@@ -46,7 +46,7 @@ pub(crate) async fn digest_selected(
            JOIN runtime_events t ON t.sequence=h.sequence
            LEFT JOIN runtime_events a ON a.sequence=h.archive_sequence
            WHERE h.session_id=?2 AND h.sequence<=?5 AND h.archive_sequence IS NOT NULL AND {pinned_filter}
-             AND (a.kind IS NOT 'tool_result_archived' OR a.sequence<=t.sequence
+             AND (t.kind!='tool_settled' OR a.kind IS NOT 'tool_result_archived' OR a.sequence<=t.sequence
                OR json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id') IS NOT t.event_id))"
     ))).bind(before as i64).bind(session).bind(session).bind(&selection.lineage)
         .bind(source.high_water as i64).fetch_one(&mut *connection).await?;
@@ -54,38 +54,61 @@ pub(crate) async fn digest_selected(
         return Err(ArchiveError::Corrupt.into());
     }
     let archive_filter = Selection::archive_predicate("t", "a", "?1", "?5");
+    let branches = target::SOURCES.map(|source| format!(
+        "SELECT t.sequence AS sequence,t.event_id,json_extract(a.event_json,'$.invocation.session_id'),a.sequence+1
+         FROM ({source}) t CROSS JOIN runtime_events a
+         WHERE a.kind='tool_result_archived'
+           AND CAST(json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id') AS TEXT)=t.event_id
+           AND t.owner_session_id=?2 AND t.sequence>?3 AND t.sequence<=?4
+           AND {archive_filter} AND {target_filter}"
+    ));
+    let query = format!(
+        "{} ORDER BY sequence LIMIT 129",
+        branches.join(" UNION ALL ")
+    );
     let mut hash = Sha256::new();
     hash.update(b"maka.effective-context.v1\0");
     hash.update(source.digest.as_bytes());
     let mut after = 0_i64;
     loop {
-        let next: Option<(i64,String,String,i64)> = sqlx::query_as(sqlx::AssertSqlSafe(format!(
-            "SELECT t.sequence,t.event_id,json_extract(a.event_json,'$.invocation.session_id'), a.sequence + 1
-             FROM runtime_events a JOIN session_history_events t
-             ON t.event_id=CAST(json_extract(a.event_json,'$.fact.placeholder.identity.runtime_event_id') AS TEXT)
-             WHERE a.kind='tool_result_archived' AND t.owner_session_id=?2
-               AND t.sequence > ?3 AND t.sequence <= ?4 AND {archive_filter} AND {target_filter} ORDER BY t.sequence LIMIT 1"
-        ))).bind(before as i64).bind(session).bind(after).bind(source.high_water as i64).bind(&selection.lineage).fetch_optional(&mut *connection).await?;
-        let Some((sequence, id, source_session, archive_before)) = next else {
+        let rows: Vec<(i64, String, String, i64)> =
+            sqlx::query_as(sqlx::AssertSqlSafe(query.clone()))
+                .bind(before as i64)
+                .bind(session)
+                .bind(after)
+                .bind(source.high_water as i64)
+                .bind(&selection.lineage)
+                .fetch_all(&mut *connection)
+                .await?;
+        if rows.is_empty() {
             break;
-        };
-        let (_, placeholder) = accepted::find(
-            connection,
-            &source_session,
-            &id,
-            crate::sequence_number(archive_before)?,
-        )
-        .await?
-        .ok_or(ArchiveError::Corrupt)?;
-        let replacement = placeholder
-            .to_model_projection()
-            .map_err(|_| ArchiveError::Corrupt)?;
-        let replacement_digest =
-            projection_digest(&replacement).map_err(|_| ArchiveError::Corrupt)?;
-        let encoded = serde_json::to_vec(&(sequence, &id, &placeholder, replacement_digest))?;
-        hash.update((encoded.len() as u64).to_le_bytes());
-        hash.update(encoded);
-        after = sequence;
+        }
+        // The extra row makes duplicate detection independent of page edges.
+        if rows.windows(2).any(|pair| pair[0].0 >= pair[1].0) {
+            return Err(ArchiveError::Corrupt.into());
+        }
+        for (sequence, id, source_session, archive_before) in rows.into_iter().take(128) {
+            if sequence <= after {
+                return Err(ArchiveError::Corrupt.into());
+            }
+            let (_, placeholder) = accepted::find(
+                connection,
+                &source_session,
+                &id,
+                crate::sequence_number(archive_before)?,
+            )
+            .await?
+            .ok_or(ArchiveError::Corrupt)?;
+            let replacement = placeholder
+                .to_model_projection()
+                .map_err(|_| ArchiveError::Corrupt)?;
+            let replacement_digest =
+                projection_digest(&replacement).map_err(|_| ArchiveError::Corrupt)?;
+            let encoded = serde_json::to_vec(&(sequence, &id, &placeholder, replacement_digest))?;
+            hash.update((encoded.len() as u64).to_le_bytes());
+            hash.update(encoded);
+            after = sequence;
+        }
     }
     Ok(format!("sha256:{:x}", hash.finalize()))
 }
diff --git a/platform/event-log/src/archive/target.rs b/platform/event-log/src/archive/target.rs
index d204859de4..a134a80a2c 100644
--- a/platform/event-log/src/archive/target.rs
+++ b/platform/event-log/src/archive/target.rs
@@ -25,6 +25,20 @@ use maka_agent_facts::tool_call::ToolOrigin;
 use maka_agent_facts::tool_output::DurableToolProjection;
 use sqlx::{Row, SqliteConnection};
 
+// Keep native and copied targets as separate ordered branches. Joining the
+// combined history view makes SQLite sort the entire remainder on every page.
+// The copied branch exposes h.sequence so its membership index supplies order.
+pub(super) const SOURCES: [&str; 2] = [
+    "SELECT e.sequence,e.event_id,e.invocation_id,e.operation_id,e.event_json,
+       json_extract(e.event_json,'$.invocation.session_id') AS owner_session_id,
+       0 AS inherited,NULL AS archive_sequence
+     FROM runtime_events e WHERE e.kind='tool_settled'",
+    "SELECT h.sequence,e.event_id,e.invocation_id,e.operation_id,e.event_json,
+       h.session_id AS owner_session_id,1 AS inherited,h.archive_sequence
+     FROM session_history_members h CROSS JOIN runtime_events e
+     WHERE e.sequence=h.sequence AND e.kind='tool_settled'",
+];
+
 pub(super) struct Target {
     pub sequence: u64,
     pub event_id: String,
diff --git a/platform/event-log/tests/archive.rs b/platform/event-log/tests/archive.rs
index b516f0036f..6eeeda50a5 100644
--- a/platform/event-log/tests/archive.rs
+++ b/platform/event-log/tests/archive.rs
@@ -39,6 +39,10 @@ use maka_event_log::{
     context::{ContextEvent, HistoryCapture, HistoryCut, LatestMainContext, ModelContextSource},
 };
 use serde_json::json;
+#[path = "archive/context_performance.rs"]
+mod context_performance;
+#[path = "archive/digest.rs"]
+mod digest;
 #[path = "archive/fixtures.rs"]
 mod fixtures;
 #[path = "archive/lineage.rs"]
diff --git a/platform/event-log/tests/archive/context_performance.rs b/platform/event-log/tests/archive/context_performance.rs
new file mode 100644
index 0000000000..492c026663
--- /dev/null
+++ b/platform/event-log/tests/archive/context_performance.rs
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use std::time::Instant;
+
+// Save release test executables at each revision, then alternate invocations of
+// this test with MAKA_CONTEXT_BENCH_REPETITIONS=1 for at least five A/B pairs.
+// Timings include only read_model_context, after one unmeasured warmup.
+#[tokio::test]
+#[ignore = "release archive-heavy context performance regression harness"]
+#[allow(clippy::assertions_on_constants)] // Compile in debug; reject only execution.
+async fn archive_heavy_context() {
+    assert!(!cfg!(debug_assertions), "run this benchmark with --release");
+    let sizes = std::env::var("MAKA_CONTEXT_BENCH_ARCHIVES").unwrap_or("128,512".into());
+    let repetitions: usize = std::env::var("MAKA_CONTEXT_BENCH_REPETITIONS")
+        .unwrap_or("5".into())
+        .parse()
+        .unwrap();
+    assert!(repetitions > 0);
+    for count in sizes.split(',').map(|n| n.trim().parse::<usize>().unwrap()) {
+        assert!(count > 0);
+        let directory = tempfile::tempdir().unwrap();
+        let log = EventLog::open(&directory.path().join("context-performance.sqlite"))
+            .await
+            .unwrap();
+        open(&log, "history", false).await;
+        let mut results = Vec::with_capacity(count);
+        for index in 0..count {
+            results.push(tool(&log, "history", &format!("step-{index}"), "x".repeat(8192)).await);
+        }
+        end(&log, "history").await;
+        open(&log, "writer", false).await;
+        for result in &results {
+            log.append(&archive("writer", result)).await.unwrap();
+        }
+        let mut expected = None;
+        let mut samples = Vec::with_capacity(repetitions);
+        for sample in 0..=repetitions {
+            let start = Instant::now();
+            let context = log.read_model_context("session", Some("writer")).await;
+            let context_ms = start.elapsed().as_secs_f64() * 1000.0;
+            let context = match context {
+                Ok(context) => context,
+                Err(error) => {
+                    eprintln!(
+                        "{}",
+                        json!({"benchmark":"archive_context", "archives":count, "sample":sample, "context_ms":context_ms, "errors":1, "error":format!("{error:?}")})
+                    );
+                    panic!("context benchmark failed");
+                }
+            };
+            let archived: Vec<_> = context
+                .tail
+                .iter()
+                .filter_map(|entry| match entry {
+                    ContextEvent::Archived(entry) => Some(entry),
+                    _ => None,
+                })
+                .collect();
+            assert_eq!(archived.len(), count);
+            for (actual, result) in archived.iter().zip(&results) {
+                assert_eq!(actual.event_id, result.event().id);
+                assert!(!actual.is_error);
+            }
+            let projection_bytes: usize = archived
+                .iter()
+                .map(|entry| serde_json::to_vec(&entry.replacement).unwrap().len())
+                .sum();
+            assert!(projection_bytes > 0);
+            let evidence = (
+                context.source_evidence.high_water,
+                context.source_evidence.digest,
+                context.effective_source_digest,
+                projection_bytes,
+            );
+            if let Some(expected) = &expected {
+                assert_eq!(&evidence, expected);
+            } else {
+                expected = Some(evidence.clone());
+            }
+            if sample > 0 {
+                samples.push(context_ms);
+                eprintln!(
+                    "{}",
+                    json!({"benchmark":"archive_context", "sample":sample, "context_ms":context_ms, "archived_count":archived.len(), "archived_projection_bytes":projection_bytes, "source_high_water":evidence.0, "errors":0})
+                );
+            }
+        }
+        samples.sort_by(f64::total_cmp);
+        eprintln!(
+            "{}",
+            json!({"benchmark":"archive_context", "summary":true, "archived_count":count, "samples":repetitions, "min_ms":samples[0], "median_ms":samples[repetitions / 2], "max_ms":samples[repetitions - 1], "errors":0})
+        );
+        log.close().await.unwrap();
+    }
+}
diff --git a/platform/event-log/tests/archive/digest.rs b/platform/event-log/tests/archive/digest.rs
new file mode 100644
index 0000000000..b162a18712
--- /dev/null
+++ b/platform/event-log/tests/archive/digest.rs
@@ -0,0 +1,229 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+use super::*;
+use maka_agent_facts::archive::projection_digest;
+use sha2::{Digest, Sha256};
+
+#[tokio::test]
+async fn effective_digest_covers_archives_beyond_the_first_page() {
+    let directory = tempfile::tempdir().unwrap();
+    let path = directory.path().join("digest.sqlite");
+    let log = EventLog::open(&path).await.unwrap();
+    log.create_session("session", "create", &json!({}), 1)
+        .await
+        .unwrap();
+    open(&log, "history", false).await;
+    let mut archives = Vec::new();
+    for index in 0..129 {
+        let result = tool(&log, "history", &format!("step-{index}"), "x".repeat(8192)).await;
+        archives.push(archive("writer", &result));
+    }
+    end(&log, "history").await;
+    open(&log, "writer", false).await;
+    for archived in &archives {
+        log.append(archived).await.unwrap();
+    }
+    let after = log
+        .read_model_context("session", Some("writer"))
+        .await
+        .unwrap();
+    let archived: Vec<_> = after
+        .tail
+        .iter()
+        .filter_map(|entry| match entry {
+            ContextEvent::Archived(entry) => Some(entry),
+            _ => None,
+        })
+        .collect();
+    assert_eq!(archived.len(), 129);
+    // Check the durable digest contract against the exact append inputs and
+    // exposed replacements, including the record past the old page boundary.
+    let mut hash = Sha256::new();
+    hash.update(b"maka.effective-context.v1\0");
+    hash.update(after.source_evidence.digest.as_bytes());
+    for (actual, written) in archived.iter().zip(&archives) {
+        let Fact::ToolResultArchived { placeholder } = &written.event().fact else {
+            panic!()
+        };
+        assert_eq!(actual.event_id, placeholder.identity.runtime_event_id);
+        let encoded = serde_json::to_vec(&(
+            actual.sequence,
+            &actual.event_id,
+            placeholder,
+            projection_digest(&actual.replacement).unwrap(),
+        ))
+        .unwrap();
+        hash.update((encoded.len() as u64).to_le_bytes());
+        hash.update(encoded);
+    }
+    assert_eq!(
+        after.effective_source_digest,
+        format!("sha256:{:x}", hash.finalize())
+    );
+    let database = rusqlite::Connection::open(&path).unwrap();
+    end(&log, "writer").await;
+    let revision = log
+        .get_session::<serde_json::Value>("session")
+        .await
+        .unwrap()
+        .unwrap()
+        .revision;
+    assert!(matches!(
+        log.copy_session(
+            maka_event_log::sessions::SessionCopy {
+                source_session_id: "session".into(),
+                target_session_id: "copy".into(),
+                expected_source_revision: revision,
+                purpose: maka_agent_facts::session::CopyPurpose::Branch {
+                    turn_id: Some("history".into()),
+                    side_conversation: false,
+                },
+            },
+            &json!({}),
+            2,
+        )
+        .await
+        .unwrap(),
+        maka_event_log::sessions::SessionCopyResult::Committed(_)
+    ));
+    let writer = event(
+        "copy-writer",
+        Fact::InvocationOpened {
+            configuration: None,
+            input: InvocationInput::Message {
+                source_messages: Vec::new(),
+                content: "question".into(),
+                request_fingerprint: None,
+            },
+        },
+    );
+    let mut writer = writer.event().clone();
+    writer.invocation.session_id = "copy".into();
+    log.append(&EventWrite::plain(writer.clone()).unwrap())
+        .await
+        .unwrap();
+    log.read_model_context("copy", Some("copy-writer"))
+        .await
+        .unwrap();
+    // A copied target may match its pinned archive and an owner archive. Put
+    // the duplicate exactly across the 128/129 boundary without dropping the
+    // per-owner unique index or introducing an invalid archive writer.
+    assert_eq!(
+        database
+            .execute(
+                "INSERT INTO event_log(event_id,invocation_id,kind,operation_id,event_json)
+         SELECT 'duplicate-archive','copy-writer',kind,operation_id,
+           json_set(event_json,'$.id','duplicate-archive','$.invocation',json(?2))
+         FROM event_log WHERE event_id=?1",
+                [
+                    &archives[127].event().id,
+                    &serde_json::to_string(&writer.invocation).unwrap()
+                ],
+            )
+            .unwrap(),
+        1
+    );
+    assert!(matches!(
+        log.read_model_context("copy", Some("copy-writer")).await,
+        Err(StoreError::Archive(
+            maka_event_log::archive::ArchiveError::Corrupt
+        ))
+    ));
+    assert_eq!(database.execute(
+        "UPDATE event_log SET event_json=json_set(event_json,'$.fact.placeholder.page.content','corrupted archive') WHERE event_id=?",
+        [&archives[128].event().id],
+    ).unwrap(), 1);
+    assert!(matches!(
+        log.read_model_context("session", None).await,
+        Err(StoreError::Archive(
+            maka_event_log::archive::ArchiveError::Corrupt
+        ))
+    ));
+    log.close().await.unwrap();
+}
+
+#[tokio::test]
+async fn copied_archive_rejects_target_with_wrong_event_kind() {
+    use maka_event_log::sessions::{SessionCopy, SessionCopyResult};
+    let directory = tempfile::tempdir().unwrap();
+    let path = directory.path().join("copy-digest.sqlite");
+    let log = EventLog::open(&path).await.unwrap();
+    log.create_session("session", "create", &json!({}), 1)
+        .await
+        .unwrap();
+    open(&log, "history", false).await;
+    let result = tool(&log, "history", "step", "x".repeat(8192)).await;
+    end(&log, "history").await;
+    open(&log, "writer", false).await;
+    log.append(&archive("writer", &result)).await.unwrap();
+    end(&log, "writer").await;
+    let revision = log
+        .get_session::<serde_json::Value>("session")
+        .await
+        .unwrap()
+        .unwrap()
+        .revision;
+    assert!(matches!(
+        log.copy_session(
+            SessionCopy {
+                source_session_id: "session".into(),
+                target_session_id: "copy".into(),
+                expected_source_revision: revision,
+                purpose: maka_agent_facts::session::CopyPurpose::Branch {
+                    turn_id: Some("history".into()),
+                    side_conversation: false,
+                },
+            },
+            &json!({}),
+            2
+        )
+        .await
+        .unwrap(),
+        SessionCopyResult::Committed(_)
+    ));
+    let context = log.read_model_context("copy", None).await.unwrap();
+    let archived: Vec<_> = context
+        .tail
+        .iter()
+        .filter_map(|entry| match entry {
+            ContextEvent::Archived(entry) => Some(entry),
+            _ => None,
+        })
+        .collect();
+    assert_eq!(archived.len(), 1);
+    assert_eq!(archived[0].event_id, result.event().id);
+    let database = rusqlite::Connection::open(&path).unwrap();
+    assert_eq!(
+        database
+            .execute(
+                "UPDATE event_log SET kind='model_observed' WHERE event_id=?",
+                [&result.event().id],
+            )
+            .unwrap(),
+        1
+    );
+    assert!(matches!(
+        log.read_model_context("copy", None).await,
+        Err(StoreError::Archive(
+            maka_event_log::archive::ArchiveError::Corrupt
+        ))
+    ));
+    log.close().await.unwrap();
+}
diff --git a/platform/event-log/tests/archive/performance.rs b/platform/event-log/tests/archive/performance.rs
index ef1733dd9f..eb112a8a2e 100644
--- a/platform/event-log/tests/archive/performance.rs
+++ b/platform/event-log/tests/archive/performance.rs
@@ -28,6 +28,7 @@ use std::time::Instant;
 // not end-to-end pruning; no machine-dependent timing assertion is made.
 #[tokio::test]
 #[ignore = "release performance regression harness; creates substantial durable history"]
+#[allow(clippy::assertions_on_constants)] // Compile in debug; reject only execution.
 async fn long_history_prune() {
     assert!(!cfg!(debug_assertions), "run this benchmark with --release");
     let sizes = std::env::var("MAKA_PRUNE_BENCH_TURNS").unwrap_or("250,1000".into());
diff --git a/plugins/agent/engine/tests/integration/long_task_perf.rs b/plugins/agent/engine/tests/integration/long_task_perf.rs
index 38c19d90f6..3c70710705 100644
--- a/plugins/agent/engine/tests/integration/long_task_perf.rs
+++ b/plugins/agent/engine/tests/integration/long_task_perf.rs
@@ -23,6 +23,9 @@
 //! MAKA_ENGINE_PERF_CHECKPOINT=1 adds a real compact Run before each timed Run.
 //! MAKA_ENGINE_PERF_TOOL_EVERY=20 MAKA_ENGINE_PERF_TOOLS_PER_TURN=1 models sparse tools.
 //! Set those to 1 and 8 for dense stress; MAKA_ENGINE_PERF_RESULT_BYTES=128 controls payloads.
+//! Optional MAKA_ENGINE_PERF_FIXTURE_DIR=/tmp/maka-perf and MAKA_ENGINE_PERF_FIXTURE_TAG=<revision>
+//! cache closed pristine databases, copied for every sample. Use separate tags/directories per build.
+//! Checkpoint histories compact every 1000 turns; raw requests retain the HTTP fixture's 16 MiB limit.
 use crate::support::{context as fixture, image_projection::identity};
 use maka_agent_facts::{
     context::ModelPurpose,
@@ -33,8 +36,10 @@ use maka_agent_facts::{
     tool_output::ToolOutput,
 };
 use maka_event_log::EventLog;
-use serde_json::json;
+use serde_json::{Value, json};
+use sha2::{Digest, Sha256};
 use std::{
+    path::{Path, PathBuf},
     sync::Arc,
     time::{Duration, Instant, SystemTime},
 };
@@ -51,14 +56,14 @@ fn setting(name: &str, default: usize) -> usize {
 // Batch each closed turn, keeping fixture setup out of the measured interval.
 async fn seed(
     log: &EventLog,
-    turns: usize,
+    range: std::ops::Range<usize>,
     result_bytes: usize,
     tool_every: usize,
     tools_per_turn: usize,
 ) -> (usize, usize) {
     let mut event_count = 0;
     let mut tool_results = 0;
-    for turn in 0..turns {
+    for turn in range {
         let invocation = identity(&format!("history-{turn}"));
         let step = format!("step-{turn}");
         let tool_count = if turn % tool_every == 0 {
@@ -97,7 +102,7 @@ async fn seed(
                 source_scope: LogScope::Session {
                     id: "session".into(),
                 },
-                source_high_water: (event_count + 1) as u64,
+                source_high_water: *log.subscribe_commits().borrow() + 1,
                 source_digest: "legacy".into(),
                 input_digest: "legacy".into(),
                 route_identity: "legacy".into(),
@@ -211,8 +216,120 @@ async fn seed(
     (event_count, tool_results)
 }
 
+// Only fixture setup uses compaction; never include it in the measured Run.
+async fn compact(worker: &maka_agent_engine::Engine, log: &EventLog, through_turn: usize) {
+    println!(
+        "{}",
+        json!({"phase":"compact_start", "through_turn":through_turn})
+    );
+    let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+    let base = format!("http://{}/v1", listener.local_addr().unwrap());
+    let server = tokio::spawn(async move {
+        let (mut socket, _) = listener.accept().await.unwrap();
+        let request = fixture::read_request(&mut socket).await;
+        assert!(request["messages"].as_array().unwrap().len() > 1);
+        fixture::respond(&mut socket, fixture::SUMMARY, "stop").await;
+    });
+    let before = *log.subscribe_commits().borrow();
+    let invocation = tokio::time::timeout(
+        Duration::from_secs(300),
+        worker.run(
+            fixture::input(&base, &format!("compact-{through_turn}"), true),
+            CancellationToken::new(),
+        ),
+    )
+    .await
+    .expect("compact timed out")
+    .expect("compact failed");
+    server.await.unwrap();
+    let through = *log.subscribe_commits().borrow();
+    let page = log
+        .session_events("session", before, through, 512, 1024 * 1024)
+        .await
+        .unwrap();
+    assert!(page.next_after.is_none(), "unexpectedly large compact Run");
+    assert!(
+        page.events
+            .iter()
+            .any(|event| event.event.invocation == invocation
+                && matches!(event.event.fact, Fact::ContextCheckpointRecorded { .. }))
+    );
+    println!(
+        "{}",
+        json!({"phase":"compact_done", "through_turn":through_turn})
+    );
+}
+
+async fn prepare(
+    log: &Arc<EventLog>,
+    turns: usize,
+    result_bytes: usize,
+    tool_every: usize,
+    tools_per_turn: usize,
+    checkpoint: bool,
+) -> (usize, usize) {
+    println!(
+        "{}",
+        json!({"phase":"seed_start", "history_turns":turns, "checkpoint":checkpoint})
+    );
+    let started = Instant::now();
+    let worker = fixture::engine(log.clone());
+    let mut counts = (0, 0);
+    for start in (0..turns).step_by(1000) {
+        let end = (start + 1000).min(turns);
+        let batch = seed(log, start..end, result_bytes, tool_every, tools_per_turn).await;
+        counts.0 += batch.0;
+        counts.1 += batch.1;
+        if checkpoint {
+            compact(&worker, log, end).await;
+        }
+        println!(
+            "{}",
+            json!({"phase":"seed_progress", "history_turns":end, "history_events":counts.0})
+        );
+    }
+    worker.drain().await;
+    println!(
+        "{}",
+        json!({"phase":"seed_done", "history_turns":turns, "setup_ms":started.elapsed().as_secs_f64()*1000.0})
+    );
+    counts
+}
+
+fn cache_directory() -> Option<PathBuf> {
+    let directory = PathBuf::from(std::env::var_os("MAKA_ENGINE_PERF_FIXTURE_DIR")?);
+    // Never accept an application-data location for benchmark fixture caches.
+    let allowed = [std::env::temp_dir(), PathBuf::from("/tmp")];
+    assert!(
+        allowed.iter().any(|root| directory.starts_with(root)),
+        "fixture directory must be under a temporary directory"
+    );
+    std::fs::create_dir_all(&directory).unwrap();
+    let directory = directory.canonicalize().unwrap();
+    assert!(
+        allowed
+            .iter()
+            .filter_map(|root| root.canonicalize().ok())
+            .any(|root| directory.starts_with(root)),
+        "fixture directory symlink escapes temporary storage"
+    );
+    Some(directory)
+}
+
+fn copy_new(source: &Path, destination: &Path) {
+    let mut source = std::fs::File::open(source).unwrap();
+    let mut destination = std::fs::OpenOptions::new()
+        .write(true)
+        .create_new(true)
+        .open(destination)
+        .unwrap();
+    std::io::copy(&mut source, &mut destination).unwrap();
+    destination.sync_all().unwrap();
+}
+
 #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
 #[ignore = "release performance harness: creates disposable long histories"]
+#[allow(clippy::assertions_on_constants)] // Compile in debug; reject only execution.
 async fn engine_long_history() {
     assert!(
         !cfg!(debug_assertions),
@@ -230,42 +347,129 @@ async fn engine_long_history() {
     assert!(tool_every > 0 && tools_per_turn > 0);
     let checkpoint = setting("MAKA_ENGINE_PERF_CHECKPOINT", 0) == 1;
     assert!(repetitions > 0 && turns.iter().all(|turns| *turns > 0));
+    let cache = cache_directory();
+    let tag = cache.as_ref().map(|_| {
+        std::env::var("MAKA_ENGINE_PERF_FIXTURE_TAG")
+            .expect("cached fixtures require an explicit revision tag")
+    });
+    let source_fingerprint = format!("{:x}", Sha256::digest(include_bytes!("long_task_perf.rs")));
     for turns in turns {
+        let settings = json!({"turns":turns, "result_bytes":result_bytes, "tool_every":tool_every,
+            "tools_per_turn":tools_per_turn, "checkpoint":checkpoint, "fixture_tag":tag,
+            "source_fingerprint":source_fingerprint, "compact_every":1000});
+        let cache_paths = cache.as_ref().map(|directory| {
+            let fingerprint = format!(
+                "{:x}",
+                Sha256::digest(serde_json::to_vec(&settings).unwrap())
+            );
+            let stem = format!(
+                "engine-t{turns}-b{result_bytes}-e{tool_every}-n{tools_per_turn}-c{}-{fingerprint}",
+                usize::from(checkpoint)
+            );
+            (
+                directory.join(format!("{stem}.sqlite")),
+                directory.join(format!("{stem}.json")),
+            )
+        });
+        if let Some((database, metadata)) = &cache_paths {
+            if !database.exists() && !metadata.exists() {
+                let staging = tempfile::tempdir_in(cache.as_ref().unwrap()).unwrap();
+                let staging_database = staging.path().join("events.sqlite");
+                let log = Arc::new(EventLog::open(&staging_database).await.unwrap());
+                let (events, tools) = prepare(
+                    &log,
+                    turns,
+                    result_bytes,
+                    tool_every,
+                    tools_per_turn,
+                    checkpoint,
+                )
+                .await;
+                let high_water = *log.subscribe_commits().borrow();
+                Arc::try_unwrap(log)
+                    .ok()
+                    .expect("fixture still has owners")
+                    .close()
+                    .await
+                    .unwrap();
+                copy_new(&staging_database, database);
+                let record = json!({"settings":settings, "history_events":events, "history_tool_results":tools, "high_water":high_water});
+                use std::io::Write;
+                let mut file = std::fs::OpenOptions::new()
+                    .write(true)
+                    .create_new(true)
+                    .open(metadata)
+                    .unwrap();
+                file.write_all(serde_json::to_string(&record).unwrap().as_bytes())
+                    .unwrap();
+                file.sync_all().unwrap();
+            }
+            assert!(
+                database.is_file() && metadata.is_file(),
+                "incomplete fixture cache; use a fresh cache directory"
+            );
+            let record: Value = serde_json::from_slice(&std::fs::read(metadata).unwrap()).unwrap();
+            assert_eq!(record["settings"], settings, "fixture settings mismatch");
+        }
         for repetition in 0..repetitions {
-            // Fresh store/engine per sample; seeding and optional compaction are untimed.
             let directory = tempfile::tempdir().unwrap();
+            let database = directory.path().join("events.sqlite");
+            let cached = cache_paths.as_ref().map(|(source, metadata)| {
+                println!("{}", json!({"phase":"fixture_copy_start", "history_turns":turns, "repetition":repetition}));
+                copy_new(source, &database);
+                let record: Value = serde_json::from_slice(&std::fs::read(metadata).unwrap()).unwrap();
+                println!("{}", json!({"phase":"fixture_copy_done", "history_turns":turns, "repetition":repetition}));
+                record
+            });
+            let open_started = Instant::now();
             let log = Arc::new(
-                EventLog::open(&directory.path().join("events.sqlite"))
+                EventLog::open(&database)
                     .await
-                    .unwrap(),
+                    .expect("fixture store open/schema validation failed"),
             );
-            let (history_events, history_tool_results) =
-                seed(&log, turns, result_bytes, tool_every, tools_per_turn).await;
-            let worker = fixture::engine(log.clone());
-            if checkpoint {
-                let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
-                let base = format!("http://{}/v1", listener.local_addr().unwrap());
-                let server = tokio::spawn(async move {
-                    let (mut socket, _) = listener.accept().await.unwrap();
-                    let request = fixture::read_request(&mut socket).await;
-                    assert!(request["messages"].as_array().unwrap().len() > 1);
-                    fixture::respond(&mut socket, fixture::SUMMARY, "stop").await;
-                });
-                tokio::time::timeout(
-                    Duration::from_secs(300),
-                    worker.run(
-                        fixture::input(&base, "compact", true),
-                        CancellationToken::new(),
-                    ),
+            let store_open_ms = open_started.elapsed().as_secs_f64() * 1000.0;
+            let (history_events, history_tool_results) = if let Some(record) = cached {
+                assert_eq!(
+                    *log.subscribe_commits().borrow(),
+                    record["high_water"].as_u64().unwrap()
+                );
+                (
+                    record["history_events"].as_u64().unwrap() as usize,
+                    record["history_tool_results"].as_u64().unwrap() as usize,
+                )
+            } else {
+                prepare(
+                    &log,
+                    turns,
+                    result_bytes,
+                    tool_every,
+                    tools_per_turn,
+                    checkpoint,
                 )
                 .await
-                .expect("compact timed out")
-                .expect("compact failed");
-                server.await.unwrap();
-            }
+            };
+            let (last, _) = log
+                .invocation_boundary("session", &format!("invocation-history-{}", turns - 1))
+                .await
+                .unwrap()
+                .unwrap();
+            assert!(matches!(
+                last.state.terminal_outcome(),
+                Some(InvocationOutcome::Completed)
+            ));
+            let database_bytes = std::fs::metadata(&database).unwrap().len();
+            let database_wal_bytes =
+                std::fs::metadata(database.with_file_name("events.sqlite-wal"))
+                    .map_or(0, |metadata| metadata.len());
+            let worker = fixture::engine(log.clone());
+            let before = *log.subscribe_commits().borrow();
             let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
             let base = format!("http://{}/v1", listener.local_addr().unwrap());
             let input = fixture::input(&base, "measured", false);
+            println!(
+                "{}",
+                json!({"phase":"measure_start", "history_turns":turns, "checkpoint":checkpoint, "repetition":repetition})
+            );
             let started = Instant::now();
             let server = tokio::spawn(async move {
                 let (mut socket, _) = listener.accept().await.unwrap();
@@ -304,39 +508,38 @@ async fn engine_long_history() {
             .expect("engine Run timed out")
             .expect("engine Run failed");
             let completion_ms = started.elapsed().as_secs_f64() * 1000.0;
+            println!(
+                "{}",
+                json!({"phase":"measure_done", "history_turns":turns, "repetition":repetition})
+            );
             let (receipt_ms, request_bytes, message_bytes, message_count, tool_message_count) =
                 server.await.unwrap();
             worker.drain().await;
             // Verification deliberately outside measured interval. run() success alone is insufficient.
-            let prefix = log
-                .prefix(history_events * 2 + 100, 256 * 1024 * 1024)
+            let (boundary, _) = log
+                .invocation_boundary("session", &invocation.invocation_id)
                 .await
+                .unwrap()
                 .unwrap();
-            let measured: Vec<_> = prefix
-                .events
-                .iter()
-                .filter(|event| event.event.invocation.invocation_id == invocation.invocation_id)
-                .collect();
-            assert!(measured.iter().any(|event| matches!(
-                event.event.fact,
-                Fact::InvocationEnded {
-                    outcome: InvocationOutcome::Completed
-                }
-            )));
-            assert!(measured.iter().any(|event| {
-                match &event.event.fact {
-                    Fact::ModelCompleted { output, .. } => serde_json::to_string(output)
-                        .unwrap()
-                        .contains("benchmark-done"),
-                    _ => false,
-                }
+            assert!(matches!(
+                boundary.state.terminal_outcome(),
+                Some(InvocationOutcome::Completed)
+            ));
+            let through = *log.subscribe_commits().borrow();
+            let page = log
+                .session_events("session", before, through, 512, 1024 * 1024)
+                .await
+                .unwrap();
+            assert!(page.next_after.is_none(), "unexpectedly large measured Run");
+            assert!(page.events.iter().any(|event| {
+                event.event.invocation == invocation
+                    && match &event.event.fact {
+                        Fact::ModelCompleted { output, .. } => serde_json::to_string(output)
+                            .unwrap()
+                            .contains("benchmark-done"),
+                        _ => false,
+                    }
             }));
-            if checkpoint {
-                assert!(prefix.events.iter().any(|event| matches!(
-                    event.event.fact,
-                    Fact::ContextCheckpointRecorded { .. }
-                )));
-            }
             println!(
                 "{}",
                 json!({
@@ -345,6 +548,7 @@ async fn engine_long_history() {
                     "history_tool_results":history_tool_results, "tool_every":tool_every, "tools_per_turn":tools_per_turn, "tool_result_content_bytes":result_bytes,
                     "repetition":repetition, "request_receipt_ms":receipt_ms,
                     "engine_completion_ms":completion_ms, "request_bytes":request_bytes,
+                    "store_open_ms":store_open_ms, "database_bytes":database_bytes, "database_wal_bytes":database_wal_bytes, "fixture_cached":cache.is_some(),
                     "request_messages":message_count, "request_tool_messages":tool_message_count,
                     // A wire-size proxy, not model tokenizer output or fake server's fixed usage.
                     "message_bytes_div_3_proxy":message_bytes.div_ceil(3),
diff --git a/scripts/rust/benchmark-long-task.py b/scripts/rust/benchmark-long-task.py
index aafa301bb6..603de23f49 100644
--- a/scripts/rust/benchmark-long-task.py
+++ b/scripts/rust/benchmark-long-task.py
@@ -39,16 +39,18 @@ def records(kind, output):
                 for m in PRUNE.finditer(output)]
     result = []
     for line in output.splitlines():
-        if line.startswith('{"benchmark":'):
+        if line.startswith('{'):
             row = json.loads(line)
-            if row.get("benchmark") == "engine_long_history":
+            if row.get("benchmark") in ("engine_long_history", "archive_context") and not row.get("summary"):
+                if kind == "context":
+                    row["history_turns"] = row["archived_count"]
                 result.append(row)
     return result
 
 
 def main():
     parser = argparse.ArgumentParser(description=__doc__)
-    parser.add_argument("--kind", choices=["prune", "engine"], required=True)
+    parser.add_argument("--kind", choices=["prune", "engine", "context"], required=True)
     parser.add_argument("--baseline", type=Path, required=True)
     parser.add_argument("--candidate", type=Path, required=True)
     parser.add_argument("--output", type=Path, required=True)
@@ -62,13 +64,15 @@ def main():
         parser.error("--checkpoint applies to the engine harness")
     args.output.mkdir(parents=True, exist_ok=True)
     environment = os.environ.copy()
-    prefix = "MAKA_PRUNE_BENCH" if args.kind == "prune" else "MAKA_ENGINE_PERF"
-    environment[prefix + "_TURNS"] = args.sizes
+    prefix = {"prune": "MAKA_PRUNE_BENCH", "engine": "MAKA_ENGINE_PERF",
+              "context": "MAKA_CONTEXT_BENCH"}[args.kind]
+    environment[prefix + ("_ARCHIVES" if args.kind == "context" else "_TURNS")] = args.sizes
     environment[prefix + "_REPETITIONS"] = "1"
     if args.kind == "engine":
         environment[prefix + "_CHECKPOINT"] = str(int(args.checkpoint))
-    test = ("performance::long_history_prune" if args.kind == "prune"
-            else "long_task_perf::engine_long_history")
+    test = {"prune": "performance::long_history_prune",
+            "engine": "long_task_perf::engine_long_history",
+            "context": "context_performance::archive_heavy_context"}[args.kind]
     evidence = {"kind": args.kind, "sizes": args.sizes, "checkpoint": args.checkpoint,
                 "runs": args.runs, "cpu_count": os.cpu_count(),
                 "load_average": list(os.getloadavg()),
@@ -92,7 +96,9 @@ def main():
                 result_file.write_text(json.dumps(evidence, indent=2) + "\n")
                 raise SystemExit(f"benchmark failed; inspect {output}")
             work = [{key: value for key, value in row.items()
-                     if not key.endswith("_ms") and key != "repetition"} for row in rows]
+                     if not key.endswith("_ms") and key not in
+                     ("repetition", "database_bytes", "database_wal_bytes", "fixture_cached")}
+                    for row in rows]
             if expected_work is None:
                 expected_work = work
             elif work != expected_work:
@@ -112,7 +118,7 @@ def main():
     summary = []
     for key, rows in groups.items():
         metrics = {}
-        for metric in ["prune_ms", "request_receipt_ms", "engine_completion_ms"]:
+        for metric in ["prune_ms", "context_ms", "request_receipt_ms", "engine_completion_ms"]:
             if metric in rows[0]:
                 values = [row[metric] for row in rows]
                 metrics[metric] = dict(n=len(values), median=statistics.median(values),


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org