Incremental engine for long horizon agents π Star if you like it!
Rust agentic-data-frameworkaiai-agentschange-data-capturecodebase-intelligencecontext-engineeringdata-engineeringdata-indexingdata-processingetlhelp-wantedindexingknowledge-graphllmlong-horizon-agentpythonragreal-timerustsemantic-search
perf(core): cut decode work and allocations on the submit and memo paths (#2784)
LJ π₯₯π΄ea86701f8b46
diff --git a/rust/core/src/engine/component.rs b/rust/core/src/engine/component.rsindex 919941fb..8b4f5c16 100644--- a/rust/core/src/engine/component.rs+++ b/rust/core/src/engine/component.rs@@ -840,6 +840,9 @@ async fn lookup_component_memo<Prof: EngineProfile>(states_changed: true,}) = &own_validation{+ let row_fp = row_fp.ok_or_else(|| {+ internal_error!("memo states changed for a memo row that stores none")+ })?;update_component_memo_states(comp_ctx.app_store(), comp_ctx.stable_path(), states, row_fp).await?;}diff --git a/rust/core/src/engine/execution.rs b/rust/core/src/engine/execution.rsindex f89f1924..3f47c5a6 100644--- a/rust/core/src/engine/execution.rs+++ b/rust/core/src/engine/execution.rs@@ -92,8 +92,9 @@ pub(crate) struct RestoredComponentMemo<Prof: EngineProfile> {pub target_provider_deps: TargetProviderDeps,/// Fingerprint of the row bytes this memo was decoded from. A later/// refresh of its memo states applies only while the row still has it- /// (see `update_component_memo_states`).- pub row_fp: Fingerprint,+ /// (see `update_component_memo_states`). `None` when the memo stores no+ /// states, so there is nothing to refresh: the row is then not hashed.+ pub row_fp: Option<Fingerprint>,/// See `db_schema::ComponentMemoizationInfo::has_open_descendants`.pub has_open_descendants: bool,/// See `db_schema::ComponentMemoizationInfo::open_children`.@@ -110,7 +111,6 @@ pub(crate) async fn use_or_invalidate_component_memoization<Prof: EngineProfile>let Some(memo_bytes) = app_store.read_component_memo(path).await? else {return Ok(None);};- let row_fp = Fingerprint::from_bytes(&memo_bytes);let memo_info: db_schema::ComponentMemoizationInfo<'_> = from_msgpack_slice(&memo_bytes)?;if let Some(processor_fp) = processor_fp&& memo_info.processor_fp == processor_fp@@ -127,6 +127,10 @@ pub(crate) async fn use_or_invalidate_component_memoization<Prof: EngineProfile>let ret = Prof::FunctionData::from_bytes(bytes.as_ref());match ret {Ok(ret) => {+ let has_states = !memo_info.memo_states.is_empty()+ || !memo_info.context_memo_states.is_empty()+ || !memo_info.data_deps.is_empty();+ let row_fp = has_states.then(|| Fingerprint::from_bytes(&memo_bytes));let memo_states = deserialize_memo_values::<Prof>(&memo_info.memo_states)?;let context_memo_states =deserialize_context_memo_states::<Prof>(&memo_info.context_memo_states)?;@@ -1788,7 +1792,6 @@ pub(crate) async fn submit<Prof: EngineProfile>(wtxn,PrecommitReadPlan {self_path: c.stable_path.clone(),- self_token: process_token,},).await?;diff --git a/rust/core/src/state/db_schema.rs b/rust/core/src/state/db_schema.rsindex aa04e805..890109b6 100644--- a/rust/core/src/state/db_schema.rs+++ b/rust/core/src/state/db_schema.rs@@ -251,8 +251,14 @@ impl<'a> storekey::Decode for DbEntryKey<'a> {impl<'a> DbEntryKey<'a> {pub fn encode(&self) -> Result<Vec<u8>> {- storekey::encode_vec(self)- .map_err(|e| internal_error!("Failed to encode DbEntryKey: {}", e))+ // Room for a typical key up front: `storekey` writes byte by byte, so+ // an empty buffer would grow (and reallocate) several times per key.+ let mut buf = Vec::with_capacity(64);+ storekey::encode(&mut buf, self).map_err(|e| match e {+ storekey::EncodeError::Custom(e) => internal_error!("Failed to encode DbEntryKey: {e}"),+ storekey::EncodeError::Io(e) => internal_error!("Failed to encode DbEntryKey: {e}"),+ })?;+ Ok(buf)}pub fn decode(data: &[u8]) -> Result<Self> {@@ -365,17 +371,69 @@ pub struct FunctionMemoizationEntry<'a> {pub data_deps: Vec<DataDepEntry<'a>>,}+/// Stored as the string `"D"` (`Deleted`) or as the state's bytes+/// (`Existing`, a msgpack `bin`). Deserialized by hand: the derived form of+/// this tagged-plus-untagged enum buffered every value and first tried it as+/// the tagged variant, building (and discarding) a serde error for every+/// `Existing` state of every tracking record it decoded.#[serde_as]-#[derive(Serialize, Deserialize, Debug)]+#[derive(Serialize, Debug)]pub enum TargetStateInfoItemState<'a> {#[serde(rename = "D")]Deleted,#[serde(untagged)]- Existing(- #[serde_as(as = "Bytes")]- #[serde(borrow)]- Cow<'a, [u8]>,- ),+ Existing(#[serde_as(as = "Bytes")] Cow<'a, [u8]>),+}++impl<'de: 'a, 'a> Deserialize<'de> for TargetStateInfoItemState<'a> {+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {+ struct StateVisitor<'a>(std::marker::PhantomData<&'a ()>);++ impl<'de: 'a, 'a> serde::de::Visitor<'de> for StateVisitor<'a> {+ type Value = TargetStateInfoItemState<'a>;++ fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {+ f.write_str("the deleted marker \"D\" or a target state's bytes")+ }++ fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {+ if v == "D" {+ Ok(TargetStateInfoItemState::Deleted)+ } else {+ Err(E::invalid_value(serde::de::Unexpected::Str(v), &self))+ }+ }++ fn visit_borrowed_bytes<E: serde::de::Error>(+ self,+ v: &'de [u8],+ ) -> Result<Self::Value, E> {+ Ok(TargetStateInfoItemState::Existing(Cow::Borrowed(v)))+ }++ fn visit_bytes<E: serde::de::Error>(self, v: &[u8]) -> Result<Self::Value, E> {+ Ok(TargetStateInfoItemState::Existing(Cow::Owned(v.to_vec())))+ }++ fn visit_byte_buf<E: serde::de::Error>(self, v: Vec<u8>) -> Result<Self::Value, E> {+ Ok(TargetStateInfoItemState::Existing(Cow::Owned(v)))+ }++ fn visit_seq<A: serde::de::SeqAccess<'de>>(+ self,+ mut seq: A,+ ) -> Result<Self::Value, A::Error> {+ // `serde_with::Bytes` also reads a sequence of byte values.+ let mut bytes = Vec::with_capacity(seq.size_hint().unwrap_or(0));+ while let Some(byte) = seq.next_element::<u8>()? {+ bytes.push(byte);+ }+ Ok(TargetStateInfoItemState::Existing(Cow::Owned(bytes)))+ }+ }++ deserializer.deserialize_any(StateVisitor(std::marker::PhantomData))+ }}impl<'a> TargetStateInfoItemState<'a> {@@ -535,6 +593,64 @@ mod tests {use super::*;use std::io::Cursor;+ /// The stored forms of both `TargetStateInfoItemState` variants, as the+ /// derived (tagged-plus-untagged) implementation wrote them: `"D"` as a+ /// msgpack fixstr, a state as a msgpack `bin`. Serialization still+ /// produces exactly these bytes, and the hand-written deserializer reads+ /// them back, borrowing the state bytes.+ #[test]+ fn target_state_info_item_state_stored_form() {+ let deleted_bytes: &[u8] = &[0xa1, b'D'];+ let existing_bytes: &[u8] = &[0xc4, 2, b'x', b'y'];++ assert_eq!(+ rmp_serde::to_vec_named(&TargetStateInfoItemState::Deleted).unwrap(),+ deleted_bytes+ );+ assert_eq!(+ rmp_serde::to_vec_named(&TargetStateInfoItemState::Existing(Cow::Borrowed(b"xy")))+ .unwrap(),+ existing_bytes+ );++ let deleted: TargetStateInfoItemState<'_> = rmp_serde::from_slice(deleted_bytes).unwrap();+ assert!(deleted.is_deleted());+ let existing: TargetStateInfoItemState<'_> = rmp_serde::from_slice(existing_bytes).unwrap();+ assert!(matches!(+ existing,+ TargetStateInfoItemState::Existing(Cow::Borrowed(b"xy"))+ ));++ let other_str: &[u8] = &[0xa1, b'X'];+ assert!(rmp_serde::from_slice::<TargetStateInfoItemState<'_>>(other_str).is_err());+ }++ /// A whole tracking item round-trips, versions and both states included.+ #[test]+ fn target_state_info_item_roundtrip() {+ let item = TargetStateInfoItem {+ key: Cow::Borrowed(b"k"),+ states: vec![+ (1, TargetStateInfoItemState::Deleted),+ (+ 2,+ TargetStateInfoItemState::Existing(Cow::Borrowed(b"\x00\x01state")),+ ),+ ],+ provider_schema_version: 3,+ provider_generation: None,+ };+ let bytes = rmp_serde::to_vec_named(&item).unwrap();+ let decoded: TargetStateInfoItem<'_> = rmp_serde::from_slice(&bytes).unwrap();+ assert_eq!(decoded.key.as_ref(), b"k");+ assert_eq!(decoded.provider_schema_version, 3);+ assert_eq!(decoded.states.len(), 2);+ assert!(decoded.states[0].1.is_deleted() && decoded.states[0].0 == 1);+ assert_eq!(decoded.states[1].0, 2);+ assert_eq!(decoded.states[1].1.as_ref(), Some(&b"\x00\x01state"[..]));+ assert_eq!(rmp_serde::to_vec_named(&decoded).unwrap(), bytes);+ }+fn roundtrip_entry_key(key: &StablePathEntryKey) -> StablePathEntryKey {let bytes = storekey::encode_vec(key).expect("encode");storekey::decode(Cursor::new(bytes)).expect("decode")diff --git a/rust/core/src/state_store/submit_session.rs b/rust/core/src/state_store/submit_session.rsindex d2a64f01..728d972f 100644--- a/rust/core/src/state_store/submit_session.rs+++ b/rust/core/src/state_store/submit_session.rs@@ -97,9 +97,6 @@ use crate::state_store::WriteTxn;pub struct PrecommitReadPlan {/// Self path. Stage marker scope.pub self_path: StablePath,- /// This process's stage token. Stored in the on-disk tracking-info- /// blob's `pending_process_token` field.- pub self_token: u128,}/// Output of [`PrecommitSession::precommit_read`]. Pure read β the@@ -111,13 +108,6 @@ pub struct PrecommitReadResult {/// Existing committed tracking-info bytes for `self_path`. `None`/// if no row yet.pub existing_tracking_info: Option<Vec<u8>>,- /// Pending-stage token observed on `self_path` β `self_token` if no- /// other writer is in flight, otherwise the other writer's token.- /// The engine compares it to `self_token` to detect the "another- /// process is in flight on this same component" case. (Intra-process- /// is already serialized by the per-component semaphore, so a- /// mismatch implies a different process.)- pub post_stage_token: u128,}/// Inputs to [`PrecommitSession::precommit_claim_targets`].@@ -236,18 +226,8 @@ impl PrecommitSession {.app_store.read_tracking_info_in_txn(wtxn, &plan.self_path).await?;- let existing_pending = match raw.as_deref() {- Some(bytes) => {- let info: StablePathEntryTrackingInfo<'_> = from_msgpack_slice(bytes)?;- info.pending_process_token- }- None => None,- };- let post_stage_token = existing_pending.unwrap_or(plan.self_token);-Ok(PrecommitReadResult {existing_tracking_info: raw,- post_stage_token,})}