Skip to content

armgit / burr

Public Imported from GitHub
0

Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.

WIP: adding persister

Stefan Krawczykcb48f981e7c8
diff --git a/burr/core/application.py b/burr/core/application.py
index 5b03cd0a..2acc2b1e 100644
--- a/burr/core/application.py
+++ b/burr/core/application.py
@@ -3,6 +3,7 @@ import dataclasses
import functools
import logging
import pprint
+import uuid
from typing import (
Any,
AsyncGenerator,
@@ -31,7 +32,8 @@ from burr.core.action import (
create_action,
default,
)
-from burr.core.state import State
+from burr.core.state import BasicStatePersistence, State
+from burr.lifecycle import PostRunStepHook
from burr.lifecycle.base import LifecycleAdapter
from burr.lifecycle.internal import LifecycleAdapterSet
@@ -235,8 +237,14 @@ class Application:
transitions: List[Transition],
state: State,
initial_step: str,
+ partition_key: str,
+ id: str,
+ sequence_id: int,
adapter_set: Optional[LifecycleAdapterSet] = None,
):
+ self._partition_key = partition_key
+ self._id = id
+ self._sequence_id = sequence_id
self._action_map = {action.name: action for action in actions}
self._adjacency_map = Application._create_adjacency_map(transitions)
self._transitions = transitions
@@ -270,12 +278,11 @@ class Application:
:param inputs: Inputs to the action -- this is if this action requires an input that is passed in from the outside world
:return: Tuple[Function, dict, State] -- the function that was just ran, the result of running it, and the new state
"""
-
- try:
- out = self._step(inputs=inputs, _run_hooks=True)
- return out
- finally:
- self._increment_sequence_id()
+ # we need to increment the sequence before we start computing
+ # that way if we're replaying from state, we don't get stuck
+ self._increment_sequence_id()
+ out = self._step(inputs=inputs, _run_hooks=True)
+ return out
def _step(
self, inputs: Optional[Dict[str, Any]], _run_hooks: bool = True
@@ -316,6 +323,8 @@ class Application:
if _run_hooks:
self._adapter_set.call_all_lifecycle_hooks_sync(
"post_run_step",
+ app_id=self._id,
+ partition_key=self._partition_key,
action=next_action,
state=new_state,
result=result,
@@ -370,6 +379,8 @@ class Application:
:return: Tuple[Function, dict, State] -- the action that was just ran, the result of running it, and the new state
"""
+ # we want to increment regardless of failure
+ self._increment_sequence_id()
next_action = self.get_next_action()
if next_action is None:
return None
@@ -418,8 +429,6 @@ class Application:
sequence_id=self.sequence_id,
exception=exc,
)
- # we want to increment regardless of failure
- self._increment_sequence_id()
return next_action, result, new_state
@@ -991,10 +1000,19 @@ class Application:
:return:
"""
- return self._state.get(SEQUENCE_ID, 0)
+ return self._sequence_id
def _increment_sequence_id(self):
- self._state = self._state.update(**{SEQUENCE_ID: self.sequence_id + 1})
+ self._sequence_id = self._sequence_id + 1
+ self._state = self._state.update(**{SEQUENCE_ID: self.sequence_id})
+
+ @property
+ def id(self) -> str:
+ return self._id
+
+ @property
+ def partition_key(self) -> str:
+ return self._partition_key
def _assert_set(value: Optional[Any], field: str, method: str):
@@ -1039,6 +1057,14 @@ def _validate_start(start: Optional[str], actions: Set[str]):
)
+def _validate_app_id(app_id: Optional[str]):
+ if app_id is None:
+ raise ValueError(
+ "App ID was None. Please ensure that you set an app ID using with_identifiers(app_id=...), or default"
+ "not setting it and letting the system generate one for you."
+ )
+
+
def _validate_actions(actions: Optional[List[Action]]):
_assert_set(actions, "_actions", "with_actions")
if len(actions) == 0:
@@ -1052,6 +1078,23 @@ class ApplicationBuilder:
self.actions: Optional[List[Action]] = None
self.start: Optional[str] = None
self.lifecycle_adapters: List[LifecycleAdapter] = list()
+ self.app_id: str = str(uuid.uuid4())
+ self.partition_key: str = None
+ self.sequence_id: int = None
+ self.persister = None
+ self.use_entrypoint_from_save_state: bool = None
+ self.default_state: dict = None
+
+ def with_identifiers(
+ self, app_id: str = None, partition_key: str = None, sequence_id: int = None
+ ) -> "ApplicationBuilder":
+ if app_id is not None:
+ self.app_id = app_id
+ if partition_key is not None:
+ self.partition_key = partition_key
+ if sequence_id is not None:
+ self.sequence_id = sequence_id
+ return self
def with_state(self, **kwargs) -> "ApplicationBuilder":
"""Sets initial values in the state. If you want to load from a prior state,
@@ -1155,11 +1198,63 @@ class ApplicationBuilder:
if tracker == "local":
from burr.tracking.client import LocalTrackingClient
- self.lifecycle_adapters.append(LocalTrackingClient(project=project, **params))
+ kwargs = {"project": project, "app_id": self.app_id}
+ kwargs.update(params)
+ self.lifecycle_adapters.append(LocalTrackingClient(**kwargs))
else:
raise ValueError(f"Tracker {tracker} not supported")
return self
+
+ def initialize_from(
+ self,
+ persister: BasicStatePersistence,
+ resume_at_next_action: bool,
+ default_state: dict,
+ default_entry_point: str,
+ ) -> "ApplicationBuilder":
+ self.persister = persister
+ self.resume_at_next_action = resume_at_next_action
+ self.default_state = default_state
+ self.start = default_entry_point
+ return self
+
+ def with_state_persister(
+ self, persister: BasicStatePersistence, on_every: str = "step"
+ ) -> "ApplicationBuilder":
+ """Adds a state persister to the application. This is a way to persist state out to a database, file, etc...
+ at the specified interval.
+
+ :param persister: The persister to add
+ :param on_every: The interval to persist state. Currently only "step" is supported.
+ :return: The application builder for future chaining.
+ """
+ if on_every != "step":
+ raise ValueError(f"on_every {on_every} not supported")
+ # stick persister into a post_step_hook if it doesn't implement it already.
+ if hasattr(persister, "post_step_hook"):
+ if persister not in self.lifecycle_adapters:
+ self.lifecycle_adapters.append(persister)
+ else:
+ # TODO: wrap in one
+ class persisterWrapper(PostRunStepHook):
+ def post_run_step(
+ self,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
+ state: "State",
+ action: "Action",
+ result: Optional[Dict[str, Any]],
+ exception: Exception,
+ **future_kwargs: Any,
+ ):
+ if exception is None:
+ persister.save(partition_key, app_id, sequence_id, action.name, state)
+
+ self.lifecycle_adapters.append(persisterWrapper())
+ return self
+
@telemetry.capture_function_usage
def build(self) -> Application:
"""Builds the application.
@@ -1171,6 +1266,21 @@ class ApplicationBuilder:
all_actions = set(actions_by_name.keys())
_validate_transitions(self.transitions, all_actions)
_validate_start(self.start, all_actions)
+ _validate_app_id(self.app_id)
+
+ loaded_sequence_id = None
+ if self.persister:
+ # load state from persister
+ load_result = self.persister.load(self.partition_key, self.app_id, self.sequence_id)
+ if load_result is None:
+ self.state = self.state.update(**self.default_state)
+ else:
+ last_position, self.state, loaded_sequence_id = load_result
+ if self.resume_at_next_action:
+ self.state = self.state.update(**{PRIOR_STEP: last_position})
+
+ if self.sequence_id is None:
+ self.sequence_id = loaded_sequence_id if loaded_sequence_id else 0
return Application(
actions=self.actions,
transitions=[
@@ -1183,5 +1293,8 @@ class ApplicationBuilder:
],
state=self.state,
initial_step=self.start,
+ id=self.app_id,
+ partition_key=self.partition_key,
+ sequence_id=self.sequence_id,
adapter_set=LifecycleAdapterSet(*self.lifecycle_adapters),
)
diff --git a/burr/core/state.py b/burr/core/state.py
index ec9ecdc2..8dc3db84 100644
--- a/burr/core/state.py
+++ b/burr/core/state.py
@@ -1,8 +1,10 @@
import abc
import copy
import dataclasses
+import json
import logging
-from typing import Any, Dict, Iterator, Mapping
+import sqlite3
+from typing import Any, Dict, Iterator, Mapping, Optional, Tuple
logger = logging.getLogger(__name__)
@@ -196,3 +198,197 @@ class State(Mapping):
def __repr__(self):
return self.get_all().__repr__() # quick hack
+
+
+class BasicStatePersistence(abc.ABC):
+ """Basic Interface for state persistence.
+
+ A persister's job is to store and retrieve state.
+ """
+
+ def initialize(self):
+ """Initializes the persistence."""
+ pass
+
+ @abc.abstractmethod
+ def list_app_ids(self, partition_key: str) -> list[str]:
+ """Returns list of app IDs for a given primary key"""
+ pass
+
+ @abc.abstractmethod
+ def load(
+ self, partition_key: str, app_id: Optional[str], sequence_id: Optional[int] = None
+ ) -> Optional[Tuple[str, State, int]]:
+ """Loads the state for a given app_id
+
+ :param partition_key: the partition key. Note this could be None, but it's up to the persistor to whether
+ that is a valid value it can handle.
+ :param app_id: the identifier for the app instance being recorded.
+ :param sequence_id: optional, the state corresponding to a specific point in time.
+ If not provided, should return the latest.
+ :return: position, state, sequence_id
+ """
+ pass
+
+ @abc.abstractmethod
+ def save(
+ self,
+ partition_key: Optional[str],
+ app_id: str,
+ sequence_id: int,
+ position: str,
+ state: State,
+ ):
+ """Saves the state for a given app_id, sequence_id, position
+
+ (PK, App_id, sequence_id, position) are a unique identifier for the state. Why not just
+ (PK, App_id, sequence_id)? Because we're over-engineering this here. We're always going to have
+ a position so might as well make it a quadruple.
+
+ :param partition_key: the partition key. Note this could be None, but it's up to the persistor to whether
+ that is a valid value it can handle.
+ :param app_id:
+ :param sequence_id:
+ :param position:
+ :param state:
+ """
+ pass
+
+
+class SQLLitePersistence(BasicStatePersistence):
+ """Class for SQLLite persistence of state. This is a simple implementation that uses SQLLite."""
+
+ def __init__(self, db_path: str, table_name: str = "burr_state"):
+ """Constructor
+
+ :param db_path: the path the DB will be stored.
+ :param table_name: the table name to store things under.
+ """
+ self.db_path = db_path
+ self.table_name = table_name
+
+ @staticmethod
+ def create_table_if_not_exists(db_path: str, table_name: str):
+ """Helper function to create the table where things are stored if it doesn't exist."""
+ conn = sqlite3.connect(db_path)
+ cursor = conn.cursor()
+
+ cursor.execute(
+ f"""
+ CREATE TABLE IF NOT EXISTS {table_name} (
+ partition_key TEXT NOT NULL,
+ app_id TEXT NOT NULL,
+ sequence_id INTEGER NOT NULL,
+ position TEXT NOT NULL,
+ state TEXT NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (partition_key, app_id, sequence_id, position)
+ )"""
+ )
+ cursor.execute(
+ f"""
+ CREATE INDEX IF NOT EXISTS {table_name}_created_at_index ON {table_name} (created_at);
+ """
+ )
+ conn.commit()
+ conn.close()
+
+ def initialize(self):
+ """Creates the table if it doesn't exist"""
+ # Usage
+ self.create_table_if_not_exists(self.db_path, self.table_name)
+
+ def list_app_ids(self, partition_key: str) -> list[str]:
+ conn = sqlite3.connect(self.db_path)
+ cursor = conn.cursor()
+ cursor.execute(
+ f"SELECT DISTINCT app_id FROM {self.table_name} "
+ f"WHERE partition_key = ? "
+ f"ORDER BY created_at DESC",
+ (partition_key,),
+ )
+ app_ids = [row[0] for row in cursor.fetchall()]
+ conn.close()
+ return app_ids
+
+ def load(
+ self, partition_key: str, app_id: str, sequence_id: int = None
+ ) -> Optional[Tuple[str, State, int]]:
+ """Loads state for a given partition id.
+
+ Depending on the parameters, this will return the last thing written, the last thing written for a given app_id,
+ or a specific sequence_id for a given app_id.
+
+ :param partition_key:
+ :param app_id:
+ :param sequence_id:
+ :return:
+ """
+ logger.debug("Loading %s, %s, %s", partition_key, app_id, sequence_id)
+ conn = sqlite3.connect(self.db_path)
+ cursor = conn.cursor()
+ if app_id is None:
+ # get latest for all app_ids
+ cursor.execute(
+ f"SELECT position, state, sequence_id, app_id, created_at FROM {self.table_name} "
+ f"WHERE partition_key = ? "
+ f"ORDER BY CREATED_AT DESC LIMIT 1",
+ (partition_key,),
+ )
+ elif sequence_id is None:
+ cursor.execute(
+ f"SELECT position, state, sequence_id, created_at FROM {self.table_name} "
+ f"WHERE partition_key = ? AND app_id = ? "
+ f"ORDER BY sequence_id DESC LIMIT 1",
+ (partition_key, app_id),
+ )
+ else:
+ cursor.execute(
+ f"SELECT position, state, seqeuence_id, created_at FROM {self.table_name} "
+ f"WHERE partition_key = ? AND app_id = ? AND sequence_id = ?",
+ (partition_key, app_id, sequence_id),
+ )
+ row = cursor.fetchone()
+ conn.close()
+ if row is None:
+ return None
+ _state = State(json.loads(row[1])["_state"])
+ return row[0], _state, row[2]
+
+ def save(self, partition_key: str, app_id: str, sequence_id: int, position: str, state: State):
+ """
+ Saves the state for a given app_id, sequence_id, and position.
+
+ This method connects to the SQLite database, converts the state to a JSON string, and inserts a new record
+ into the table with the provided partition_key, app_id, sequence_id, position, and state. After the operation,
+ it commits the changes and closes the connection to the database.
+
+ :param partition_key: The partition key. This could be None, but it's up to the persistor to whether
+ that is a valid value it can handle.
+ :param app_id: The identifier for the app instance being recorded.
+ :param sequence_id: The state corresponding to a specific point in time.
+ :param position: The position in the sequence of states.
+ :param state: The state to be saved, an instance of the State class.
+ :return: None
+ """
+ logger.debug(
+ "saving %s, %s, %s, %s, %s", partition_key, app_id, sequence_id, position, state
+ )
+ conn = sqlite3.connect(self.db_path)
+ cursor = conn.cursor()
+ json_state = json.dumps(state.__dict__)
+ cursor.execute(
+ f"INSERT INTO {self.table_name} (partition_key, app_id, sequence_id, position, state) "
+ f"VALUES (?, ?, ?, ?, ?)",
+ (partition_key, app_id, sequence_id, position, json_state),
+ )
+ conn.commit()
+ conn.close()
+
+
+if __name__ == "__main__":
+ s = SQLLitePersistence(db_path=".sqllite.db", table_name="test1")
+ s.initialize()
+ s.save("pk", "app_id", 1, "pos", State({"a": 1, "b": 2}))
+ print(s.list_app_ids("pk"))
+ print(s.load("pk", "app_id"))
diff --git a/burr/lifecycle/base.py b/burr/lifecycle/base.py
index 9a68474b..5253b41c 100644
--- a/burr/lifecycle/base.py
+++ b/burr/lifecycle/base.py
@@ -17,10 +17,12 @@ class PreRunStepHook(abc.ABC):
def pre_run_step(
self,
*,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
state: "State",
action: "Action",
inputs: Dict[str, Any],
- sequence_id: int,
**future_kwargs: Any,
):
"""Run before a step is executed.
@@ -42,10 +44,12 @@ class PreRunStepHookAsync(abc.ABC):
async def pre_run_step(
self,
*,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
state: "State",
action: "Action",
inputs: Dict[str, Any],
- sequence_id: int,
**future_kwargs: Any,
):
"""Async run before a step is executed.
@@ -67,10 +71,12 @@ class PostRunStepHook(abc.ABC):
def post_run_step(
self,
*,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
state: "State",
action: "Action",
result: Optional[Dict[str, Any]],
- sequence_id: int,
exception: Exception,
**future_kwargs: Any,
):
@@ -94,10 +100,12 @@ class PostRunStepHookAsync(abc.ABC):
async def post_run_step(
self,
*,
+ app_id: str,
+ partition_key: str,
+ sequence_id: int,
state: "State",
action: "Action",
result: Optional[dict],
- sequence_id: int,
exception: Exception,
**future_kwargs: Any,
):
@@ -120,7 +128,13 @@ class PostApplicationCreateHook(abc.ABC):
@abc.abstractmethod
def post_application_create(
- self, *, state: "State", application_graph: "ApplicationGraph", **future_kwargs: Any
+ self,
+ *,
+ app_id: str,
+ partition_key: str,
+ state: "State",
+ application_graph: "ApplicationGraph",
+ **future_kwargs: Any,
):
"""Runs after an "application" object is instantiated. This is run by the Application, in its constructor,
as the last step.
@@ -203,14 +217,18 @@ class PostEndSpanHookAsync(abc.ABC):
@lifecycle.base_hook("pre_run_application")
class PreRunApplicationHook(abc.ABC):
@abc.abstractmethod
- def pre_run_application(self, *, state: "State", **future_kwargs: Any):
+ def pre_run_application(
+ self, *, app_id: str, partition_key: str, state: "State", **future_kwargs: Any
+ ):
pass
@lifecycle.base_hook("pre_run_application")
class PreRunApplicationHookAsync(abc.ABC):
@abc.abstractmethod
- async def pre_run_application(self, *, state: "State", **future_kwargs):
+ async def pre_run_application(
+ self, *, app_id: str, partition_key: str, state: "State", **future_kwargs
+ ):
pass
@@ -218,7 +236,14 @@ class PreRunApplicationHookAsync(abc.ABC):
class PostRunApplicationHook(abc.ABC):
@abc.abstractmethod
def post_run_application(
- self, *, state: "State", until: list[str], results: list[dict], **future_kwargs
+ self,
+ *,
+ app_id: str,
+ partition_key: str,
+ state: "State",
+ until: list[str],
+ results: list[dict],
+ **future_kwargs,
):
pass
@@ -227,7 +252,14 @@ class PostRunApplicationHook(abc.ABC):
class PostRunApplicationHookAsync(abc.ABC):
@abc.abstractmethod
async def post_run_application(
- self, *, state: "State", until: list[str], results: list[dict], **future_kwargs
+ self,
+ *,
+ app_id: str,
+ partition_key: str,
+ state: "State",
+ until: list[str],
+ results: list[dict],
+ **future_kwargs,
):
pass
diff --git a/examples/counter/application.py b/examples/counter/application.py
index 5d7034fd..5ea04381 100644
--- a/examples/counter/application.py
+++ b/examples/counter/application.py
@@ -1,41 +1,61 @@
+import logging
from typing import List, Optional, Tuple
import burr.core
from burr.core import Application, Result, State, default, expr
from burr.core.action import action
+from burr.core.state import SQLLitePersistence
from burr.lifecycle import LifecycleAdapter
+logger = logging.getLogger(__name__)
+
@action(reads=["counter"], writes=["counter"])
def counter(state: State) -> Tuple[dict, State]:
result = {"counter": state["counter"] + 1}
+ # import random
+ # if random.random() < 0.5:
+ # raise ValueError("random error")
print(f"counted to {result['counter']}")
return result, state.update(**result)
def application(
count_up_to: int = 10,
+ partition_key: str = "demo-user",
app_id: Optional[str] = None,
storage_dir: Optional[str] = "~/.burr",
hooks: Optional[List[LifecycleAdapter]] = None,
) -> Application:
+ persister = SQLLitePersistence("demos.db", "counter")
+ persister.initialize()
+ logger.info(
+ f"{partition_key} has these prior invocations: {persister.list_app_ids(partition_key)}"
+ )
return (
burr.core.ApplicationBuilder()
- .with_state(counter=0)
.with_actions(counter=counter, result=Result("counter"))
.with_transitions(
("counter", "counter", expr(f"counter < {count_up_to}")),
("counter", "result", default),
)
- .with_entrypoint("counter")
- .with_tracker("demo:counter", params={"app_id": app_id, "storage_dir": storage_dir})
+ .with_identifiers(partition_key=partition_key, app_id=app_id)
+ .initialize_from(
+ persister,
+ resume_at_next_action=True,
+ default_state={"counter": 0},
+ default_entry_point="counter",
+ )
+ .with_state_persister(persister)
+ .with_tracker("demo:counter", params={"storage_dir": storage_dir})
.with_hooks(*hooks if hooks else [])
.build()
)
if __name__ == "__main__":
- app = application()
- action, state, result = app.run(halt_after=["result"])
+ logging.basicConfig(level=logging.DEBUG)
+ app = application(app_id="a7c8e525-58f9-4e84-b4b3-f5b80b5b0d0e")
+ action, result, state = app.run(halt_after=["result"])
# app.visualize(output_file_path="digraph", include_conditions=True, view=False, format="png")
print(state["counter"])