Build applications that make decisions (chatbots, agents, simulations, etc...). Monitor, trace, persist, and execute on your own infrastructure.
Python aiburrchatbot-frameworkdagsgenerative-aigraphshacktoberfestllmopsllmsmlopspersistent-data-structurestate-machinestate-managementvisibility
Adds ability to save/load snapshot of DB
elijahbenizzyc351176d9ed3
diff --git a/burr/cli/__main__.py b/burr/cli/__main__.pyindex a686933e..2f952278 100644--- a/burr/cli/__main__.py+++ b/burr/cli/__main__.py@@ -130,7 +130,7 @@ def build_ui():BACKEND_MODULES = {"local": "burr.tracking.server.backend.LocalBackend",- "s3": "burr.tracking.server.s3.backend.S3Backend",+ "s3": "burr.tracking.server.s3.backend.SQLiteS3Backend",}diff --git a/burr/tracking/server/backend.py b/burr/tracking/server/backend.pyindex e520ed3b..e017b43e 100644--- a/burr/tracking/server/backend.py+++ b/burr/tracking/server/backend.py@@ -64,8 +64,35 @@ class IndexingBackendMixin(abc.ABC):pass+class SnapshottingBackendMixin(abc.ABC):+ """Mixin for backend that conducts snapshotting -- e.g. saves+ the data to a file or database."""++ @abc.abstractmethod+ async def load_snapshot(self):+ """Loads the snapshot if it exists.++ :return:+ """+ pass++ @abc.abstractmethod+ async def snapshot(self):+ """Snapshots the data"""+ pass++ @abc.abstractmethod+ def snapshot_interval_milliseconds(self) -> Optional[int]:+ """Returns the snapshot interval in milliseconds"""+ pass++class BackendBase(abc.ABC):async def lifespan(self, app: FastAPI):+ """Quick tool to allow plugin to the app's lifecycle.+ This is fine given that it's an internal API, but if we open it up more+ we should make this less flexible. For now this allows us to do clever+ initializations in the right order."""yield@abc.abstractmethoddiff --git a/burr/tracking/server/run.py b/burr/tracking/server/run.pyindex c06931fe..bde037a5 100644--- a/burr/tracking/server/run.py+++ b/burr/tracking/server/run.py@@ -9,7 +9,7 @@ from typing import Sequencefrom hamilton.log_setup import setup_loggingfrom starlette import status-from burr.tracking.server.backend import BackendBase, IndexingBackendMixin+from burr.tracking.server.backend import BackendBase, IndexingBackendMixin, SnapshottingBackendMixinsetup_logging(logging.INFO)@@ -52,11 +52,6 @@ except ImportError as e:SERVE_STATIC = os.getenv("BURR_SERVE_STATIC", "true").lower() == "true"-# TODO -- get based on a config-# backend = backend_module.LocalBackend()-# backend = s3_backend.S3Backend(-# bucket="burr-prod-test",-# )backend = BackendBase.create_from_env()@@ -67,17 +62,46 @@ backend = BackendBase.create_from_env()# TODO -- add a health check for intialization-async def update():+async def sync_index():if app_spec.indexing:- logger.info("Updating backend")+ logger.info("Updating backend index...")await backend.update()+ logger.info("Updated backend index...")+++async def download_snapshot():+ if app_spec.snapshotting:+ logger.info("Downloading snapshot of DB for backend to use")+ await backend.load_snapshot()+ logger.info("Downloaded snapshot of DB for backend to use")+++first_snapshot = True+++async def save_snapshot():+ # is_first is due to the weirdness of the repeat_every decorator+ # It has to be called but we don't want this to run every time+ # So we just skip the first+ global first_snapshot+ if first_snapshot:+ first_snapshot = False+ return+ if app_spec.snapshotting:+ logger.info("Saving snapshot of DB for recovery")+ await backend.snapshot()+ logger.info("Saved snapshot of DB for recovery")@asynccontextmanagerasync def lifespan(app: FastAPI):+ # Download if it does it+ # For now we do this before the lifespan+ await download_snapshot()# No yield from allowedawait backend.lifespan(app).__anext__()- await update() # this will trigger the repeat every N seconds+ await sync_index() # this will trigger the repeat every N seconds+ await save_snapshot() # this will trigger the repeat every N secondsyieldawait backend.lifespan(app).__anext__()@@ -88,7 +112,8 @@ app = FastAPI(lifespan=lifespan)@app.get("/api/v0/metadata/app_spec", response_model=BackendSpec)def get_app_spec():is_indexing_backend = isinstance(backend, IndexingBackendMixin)- return BackendSpec(indexing=is_indexing_backend)+ is_snapshotting_backend = isinstance(backend, SnapshottingBackendMixin)+ return BackendSpec(indexing=is_indexing_backend, snapshotting=is_snapshotting_backend)app_spec = get_app_spec()@@ -104,17 +129,21 @@ logger = logging.getLogger(__name__)if app_spec.indexing:update_interval = backend.update_interval_milliseconds() / 1000 if app_spec.indexing else None- update = repeat_every(+ sync_index = repeat_every(seconds=backend.update_interval_milliseconds() / 1000,wait_first=True,logger=logger,- )(update)-+ )(sync_index)[email protected]_event("startup")-async def startup_event():- if app_spec.indexing:- await update()+if app_spec.snapshotting:+ snapshot_interval = (+ backend.snapshot_interval_milliseconds() / 1000 if app_spec.snapshotting else None+ )+ save_snapshot = repeat_every(+ seconds=backend.snapshot_interval_milliseconds() / 1000,+ wait_first=True,+ logger=logger,+ )(save_snapshot)@app.get("/api/v0/projects", response_model=Sequence[schema.Project])diff --git a/burr/tracking/server/s3/backend.py b/burr/tracking/server/s3/backend.pyindex f87c94e3..7f21a57a 100644--- a/burr/tracking/server/s3/backend.py+++ b/burr/tracking/server/s3/backend.py@@ -5,6 +5,7 @@ import itertoolsimport jsonimport loggingimport operator+import os.pathimport uuidfrom collections import Counterfrom typing import List, Literal, Optional, Sequence, Tuple, Type, TypeVar, Union@@ -20,7 +21,12 @@ from tortoise.expressions import Qfrom burr.tracking.common.models import ApplicationModelfrom burr.tracking.server import schema-from burr.tracking.server.backend import BackendBase, BurrSettings, IndexingBackendMixin+from burr.tracking.server.backend import (+ BackendBase,+ BurrSettings,+ IndexingBackendMixin,+ SnapshottingBackendMixin,+)from burr.tracking.server.s3 import settings, utilsfrom burr.tracking.server.s3.models import (Application,@@ -113,19 +119,95 @@ class S3Settings(BurrSettings):s3_bucket: strupdate_interval_milliseconds: int = 60_000aws_max_concurrency: int = 100+ snapshot_interval_milliseconds: int = 3_600_000+ load_snapshot_on_start: bool = True+ prior_snapshots_to_keep: int = 5-class S3Backend(BackendBase, IndexingBackendMixin):- @classmethod- def settings_model(cls) -> Type[BaseSettings]:- return S3Settings+def timestamp_to_reverse_alphabetical(timestamp: datetime) -> str:+ # Get the inverse of the timestamp+ epoch = datetime.datetime(1970, 1, 1, tzinfo=datetime.timezone.utc)+ total_seconds = int((timestamp - epoch).total_seconds())++ # Invert the seconds (latest timestamps become smallest values)+ inverted_seconds = 2**32 - total_seconds++ # Convert the inverted seconds to a zero-padded string+ inverted_str = str(inverted_seconds).zfill(10)- def __init__(self, s3_bucket: str, update_interval_milliseconds: int, aws_max_concurrency: int):- self._backend_id = datetime.datetime.utcnow().isoformat() + str(uuid.uuid4())+ return inverted_str + "-" + timestamp.isoformat()+++class SQLiteS3Backend(BackendBase, IndexingBackendMixin, SnapshottingBackendMixin):+ def __init__(+ self,+ s3_bucket: str,+ update_interval_milliseconds: int,+ aws_max_concurrency: int,+ snapshot_interval_milliseconds: int,+ load_snapshot_on_start: bool,+ prior_snapshots_to_keep: int,+ ):+ self._backend_id = datetime.datetime.now(datetime.UTC).isoformat() + str(uuid.uuid4())self._bucket = s3_bucketself._session = session.get_session()self._update_interval_milliseconds = update_interval_millisecondsself._aws_max_concurrency = aws_max_concurrency+ self._snapshot_interval_milliseconds = snapshot_interval_milliseconds+ self._data_prefix = "data"+ self._snapshot_prefix = "snapshots"+ self._load_snapshot_on_start = load_snapshot_on_start+ self._snapshot_key_history = []+ self._prior_snapshots_to_keep = prior_snapshots_to_keep++ async def load_snapshot(self):+ if not self._load_snapshot_on_start:+ return+ path = settings.DB_PATH+ # if it already exists then return+ if os.path.exists(path):+ return+ async with self._session.create_client("s3") as client:+ objects = await client.list_objects_v2(+ Bucket=self._bucket, Prefix=self._snapshot_prefix, MaxKeys=1+ )+ # nothing there+ # TODO --+ if len(objects["Contents"]) == 0:+ return+ # get the latest snapshot -- it's organized by alphabetical order+ latest_snapshot = objects["Contents"][0]+ # download the snapshot+ response = await client.get_object(Bucket=self._bucket, Key=latest_snapshot["Key"])+ async with response["Body"] as stream:+ with open(path, "wb") as file:+ file.write(await stream.read())++ def snapshot_interval_milliseconds(self) -> Optional[int]:+ return self._snapshot_interval_milliseconds++ @classmethod+ def settings_model(cls) -> Type[BaseSettings]:+ return S3Settings++ async def snapshot(self):+ path = settings.DB_PATH+ timestamp = timestamp_to_reverse_alphabetical(datetime.datetime.now(datetime.UTC))+ # latest+ s3_key = f"{self._snapshot_prefix}/{timestamp}/{self._backend_id}/snapshot.db"+ # TODO -- copy the path at snapshot_path to s3 using aiobotocore+ session = self._session+ logger.info(f"Saving db snapshot at: {s3_key}")+ async with session.create_client("s3") as s3_client:+ with open(path, "rb") as file_data:+ await s3_client.put_object(Bucket=self._bucket, Key=s3_key, Body=file_data)++ self._snapshot_key_history.append(s3_key)+ if len(self._snapshot_key_history) > 5:+ old_snapshot_to_remove = self._snapshot_key_history.pop(0)+ logger.info(f"Removing old snapshot: {old_snapshot_to_remove}")+ async with session.create_client("s3") as s3_client:+ await s3_client.delete_object(Bucket=self._bucket, Key=old_snapshot_to_remove)def update_interval_milliseconds(self) -> Optional[int]:return self._update_interval_milliseconds@@ -134,7 +216,10 @@ class S3Backend(BackendBase, IndexingBackendMixin):async with self._session.create_client("s3") as client:paginator = client.get_paginator("list_objects_v2")async for result in paginator.paginate(- Bucket=self._bucket, Prefix=f"data/{project_id}/", Delimiter="/", MaxKeys=1+ Bucket=self._bucket,+ Prefix=f"{self._data_prefix}/{project_id}/",+ Delimiter="/",+ MaxKeys=1,):if "Contents" in result:first_object = result["Contents"][0]@@ -150,7 +235,7 @@ class S3Backend(BackendBase, IndexingBackendMixin):async with self._session.create_client("s3") as client:paginator = client.get_paginator("list_objects_v2")async for result in paginator.paginate(- Bucket=self._bucket, Prefix="data/", Delimiter="/"+ Bucket=self._bucket, Prefix=f"{self._data_prefix}/", Delimiter="/"):for prefix in result.get("CommonPrefixes", []):project_name = prefix.get("Prefix").split("/")[-2]@@ -247,7 +332,7 @@ class S3Backend(BackendBase, IndexingBackendMixin):paginator = client.get_paginator("list_objects_v2")async for result in paginator.paginate(Bucket=self._bucket,- Prefix=f"data/{project.name}/",+ Prefix=f"{self._data_prefix}/{project.name}/",StartAfter=high_watermark_s3_path,):for content in result.get("Contents", []):@@ -557,3 +642,14 @@ class S3Backend(BackendBase, IndexingBackendMixin):))return out+++if __name__ == "__main__":+ os.environ["BURR_LOAD_SNAPSHOT_ON_START"] = "True"+ import asyncio++ be = SQLiteS3Backend.from_settings(S3Settings())+ # coro = be.snapshot() # save to s3+ # asyncio.run(coro)+ coro = be.load_snapshot() # load from s3+ asyncio.run(coro)diff --git a/burr/tracking/server/schema.py b/burr/tracking/server/schema.pyindex 950a911c..c707c99f 100644--- a/burr/tracking/server/schema.py+++ b/burr/tracking/server/schema.py@@ -72,7 +72,7 @@ class Step(pydantic.BaseModel):@staticmethoddef from_logs(log_lines: List[bytes]) -> List["Step"]:steps_by_sequence_id = collections.defaultdict(PartialStep)- spans_by_id = collections.defaultdict(Span)+ spans_by_id = collections.defaultdict(PartialSpan)for line in log_lines:json_line = safe_json_load(line)# TODO -- make these into constants@@ -84,7 +84,7 @@ class Step(pydantic.BaseModel):steps_by_sequence_id[step_end_log.sequence_id].step_end_log = step_end_logelif json_line["type"] == "begin_span":span = BeginSpanModel.parse_obj(json_line)- spans_by_id[span.span_id] = Span(+ spans_by_id[span.span_id] = PartialSpan(begin_entry=span,end_entry=None,)@@ -102,7 +102,12 @@ class Step(pydantic.BaseModel):steps_by_sequence_id[sequence_id] if sequence_id in steps_by_sequence_id else None)if step is not None:- step.spans.append(span)+ if span.begin_entry is not None:+ full_span = Span(+ begin_entry=span.begin_entry,+ end_entry=span.end_entry,+ )+ step.spans.append(full_span)# filter out all the non-null start stepsreturn [Step(@@ -145,3 +150,4 @@ class BackendSpec(pydantic.BaseModel):"""Generic link for indexing job -- can be exposed in 'admin mode' in the UI"""indexing: bool+ snapshotting: bool