Skip to content

armgit / letta

Public Imported from GitHub
0

Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.

fix(core): skip no-op block writes and unnecessary prompt rebuilds (#9960)

Kian Jones7a58f3c25c8c
diff --git a/letta/services/block_manager.py b/letta/services/block_manager.py
index b47f8fef6..e0257df1b 100644
--- a/letta/services/block_manager.py
+++ b/letta/services/block_manager.py
@@ -29,6 +29,8 @@ from letta.validators import raise_on_invalid_id
logger = get_logger(__name__)
+PROMPT_AFFECTING_BLOCK_FIELDS = {"description", "label", "limit", "read_only", "value"}
+
def validate_block_limit_constraint(update_data: dict, existing_block: BlockModel) -> None:
"""
@@ -277,12 +279,35 @@ class BlockManager:
# Validate limit constraints before updating
validate_block_limit_constraint(update_data, block)
- for key, value in update_data.items():
- setattr(block, key, value)
+ current_tags: Optional[List[str]] = None
+ if new_tags is not None:
+ result = await session.execute(select(BlocksTags.tag).where(BlocksTags.block_id == block_id))
+ current_tags = sorted(row[0] for row in result.fetchall())
- await block.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)
+ has_scalar_changes = any(getattr(block, key) != value for key, value in update_data.items())
+ has_prompt_changes = any(
+ key in PROMPT_AFFECTING_BLOCK_FIELDS and getattr(block, key) != value for key, value in update_data.items()
+ )
+ has_tag_changes = new_tags is not None and sorted(new_tags) != (current_tags or [])
- if new_tags is not None:
+ if not has_scalar_changes and not has_tag_changes:
+ logger.debug(f"Skipping no-op block update for block {block_id}")
+ pydantic_block = block.to_pydantic()
+
+ if current_tags is None:
+ result = await session.execute(select(BlocksTags.tag).where(BlocksTags.block_id == block_id))
+ current_tags = [row[0] for row in result.fetchall()]
+
+ pydantic_block.tags = current_tags
+ return pydantic_block
+
+ if has_scalar_changes:
+ for key, value in update_data.items():
+ setattr(block, key, value)
+
+ await block.update_async(db_session=session, actor=actor, no_commit=True, no_refresh=True)
+
+ if has_tag_changes:
await self._replace_block_pivot_rows_async(
session,
BlocksTags.__table__,
@@ -301,7 +326,8 @@ class BlockManager:
# await session.commit()
# Recompile system prompts for all agents connected to this block
- await self._rebuild_system_prompts_for_connected_agents(block_id, actor)
+ if has_prompt_changes:
+ await self._rebuild_system_prompts_for_connected_agents(block_id, actor)
return pydantic_block
diff --git a/tests/test_block_manager_noop_update.py b/tests/test_block_manager_noop_update.py
new file mode 100644
index 000000000..7582db489
--- /dev/null
+++ b/tests/test_block_manager_noop_update.py
@@ -0,0 +1,146 @@
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock, patch
+
+import pytest
+
+from letta.schemas.block import Block as PydanticBlock, BlockUpdate
+from letta.schemas.user import User as PydanticUser
+from letta.services.block_manager import BlockManager
+
+
+def _mock_session_ctx(mock_session: AsyncMock) -> AsyncMock:
+ ctx = AsyncMock()
+ ctx.__aenter__.return_value = mock_session
+ ctx.__aexit__.return_value = None
+ return ctx
+
+
+def _mock_block(block_id: str, value: str, organization_id: str) -> SimpleNamespace:
+ block = SimpleNamespace(
+ id=block_id,
+ label="persona",
+ value=value,
+ description="Original Description",
+ limit=10_000,
+ read_only=False,
+ metadata_={},
+ project_id=None,
+ organization_id=organization_id,
+ )
+ block.update_async = AsyncMock()
+ block.to_pydantic = Mock(side_effect=lambda: PydanticBlock(id=block.id, label=block.label, value=block.value))
+ return block
+
+
+async def test_update_block_skips_rebuild_for_noop_update():
+ actor = PydanticUser(id="user-00000000-0000-4000-8000-000000000001", name="test-user", organization_id="org-1")
+ block_manager = BlockManager()
+ block = _mock_block("block-00000000-0000-4000-8000-000000000001", "Original Content", actor.organization_id)
+
+ mock_result = Mock()
+ mock_result.fetchall.return_value = [("existing-tag",)]
+
+ mock_session = AsyncMock()
+ mock_session.execute = AsyncMock(return_value=mock_result)
+
+ with patch("letta.services.block_manager.db_registry.async_session", return_value=_mock_session_ctx(mock_session)), patch(
+ "letta.services.block_manager.BlockModel.read_async",
+ new=AsyncMock(return_value=block),
+ ), patch.object(BlockManager, "_rebuild_system_prompts_for_connected_agents", new_callable=AsyncMock) as mock_rebuild:
+ updated_block = await block_manager.update_block_async(
+ block_id=block.id,
+ block_update=BlockUpdate(value="Original Content"),
+ actor=actor,
+ )
+
+ block.update_async.assert_not_awaited()
+ mock_rebuild.assert_not_awaited()
+ assert updated_block.value == "Original Content"
+ assert updated_block.tags == ["existing-tag"]
+
+
+async def test_update_block_rebuilds_for_real_update():
+ actor = PydanticUser(id="user-00000000-0000-4000-8000-000000000002", name="test-user", organization_id="org-1")
+ block_manager = BlockManager()
+ block = _mock_block("block-00000000-0000-4000-8000-000000000002", "Original Content", actor.organization_id)
+
+ mock_result = Mock()
+ mock_result.fetchall.return_value = [("existing-tag",)]
+
+ mock_session = AsyncMock()
+ mock_session.execute = AsyncMock(return_value=mock_result)
+
+ with patch("letta.services.block_manager.db_registry.async_session", return_value=_mock_session_ctx(mock_session)), patch(
+ "letta.services.block_manager.BlockModel.read_async",
+ new=AsyncMock(return_value=block),
+ ), patch.object(BlockManager, "_rebuild_system_prompts_for_connected_agents", new_callable=AsyncMock) as mock_rebuild:
+ updated_block = await block_manager.update_block_async(
+ block_id=block.id,
+ block_update=BlockUpdate(value="Updated Content"),
+ actor=actor,
+ )
+
+ block.update_async.assert_awaited_once()
+ mock_rebuild.assert_awaited_once_with(block.id, actor)
+ assert updated_block.value == "Updated Content"
+
+
+async def test_update_block_tags_only_skips_rebuild():
+ actor = PydanticUser(id="user-00000000-0000-4000-8000-000000000003", name="test-user", organization_id="org-1")
+ block_manager = BlockManager()
+ block = _mock_block("block-00000000-0000-4000-8000-000000000003", "Original Content", actor.organization_id)
+
+ mock_result = Mock()
+ mock_result.fetchall.return_value = [("existing-tag",)]
+
+ mock_session = AsyncMock()
+ mock_session.execute = AsyncMock(return_value=mock_result)
+
+ with patch("letta.services.block_manager.db_registry.async_session", return_value=_mock_session_ctx(mock_session)), patch(
+ "letta.services.block_manager.BlockModel.read_async",
+ new=AsyncMock(return_value=block),
+ ), patch.object(BlockManager, "_replace_block_pivot_rows_async", new_callable=AsyncMock) as mock_replace_tags, patch.object(
+ BlockManager, "_rebuild_system_prompts_for_connected_agents", new_callable=AsyncMock
+ ) as mock_rebuild:
+ updated_block = await block_manager.update_block_async(
+ block_id=block.id,
+ block_update=BlockUpdate(tags=["new-tag"]),
+ actor=actor,
+ )
+
+ block.update_async.assert_not_awaited()
+ mock_replace_tags.assert_awaited_once()
+ mock_rebuild.assert_not_awaited()
+ assert updated_block.value == "Original Content"
+ assert updated_block.tags == ["new-tag"]
+
+
+async def test_update_block_metadata_only_skips_rebuild():
+ actor = PydanticUser(id="user-00000000-0000-4000-8000-000000000004", name="test-user", organization_id="org-1")
+ block_manager = BlockManager()
+ block = _mock_block("block-00000000-0000-4000-8000-000000000004", "Original Content", actor.organization_id)
+
+ mock_result = Mock()
+ mock_result.fetchall.return_value = [("existing-tag",)]
+
+ mock_session = AsyncMock()
+ mock_session.execute = AsyncMock(return_value=mock_result)
+
+ with patch("letta.services.block_manager.db_registry.async_session", return_value=_mock_session_ctx(mock_session)), patch(
+ "letta.services.block_manager.BlockModel.read_async",
+ new=AsyncMock(return_value=block),
+ ), patch.object(BlockManager, "_rebuild_system_prompts_for_connected_agents", new_callable=AsyncMock) as mock_rebuild:
+ updated_block = await block_manager.update_block_async(
+ block_id=block.id,
+ block_update=BlockUpdate(metadata={"foo": "bar"}),
+ actor=actor,
+ )
+
+ block.update_async.assert_awaited_once()
+ mock_rebuild.assert_not_awaited()
+ assert block.metadata_ == {"foo": "bar"}
+ assert updated_block.tags == ["existing-tag"]