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 S3-based server
elijahbenizzyc90c1bf49134
diff --git a/burr/cli/__main__.py b/burr/cli/__main__.pyindex 51793715..a686933e 100644--- a/burr/cli/__main__.py+++ b/burr/cli/__main__.py@@ -1,5 +1,6 @@import importlib.utilimport json+import loggingimport osimport shutilimport subprocess@@ -27,21 +28,46 @@ except ImportError as e:)+class InterceptHandler(logging.Handler):+ def emit(self, record):+ # Get corresponding Loguru level if it exists+ try:+ level = logger.level(record.levelname).name+ except ValueError:+ level = record.levelno++ # Find caller from where originated the log message+ frame, depth = logging.currentframe(), 2+ while frame.f_code.co_filename == logging.__file__:+ frame = frame.f_back+ depth += 1++ logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())+++# Clear default handlers+logging.basicConfig(handlers=[InterceptHandler()], level=logging.INFO)++# TODO -- add this as a general callback to the CLIdef _telemetry_if_enabled(event: str):if telemetry.is_telemetry_enabled():telemetry.create_and_send_cli_event(event)-def _command(command: str, capture_output: bool) -> str:+def _command(command: str, capture_output: bool, addl_env: dict = None) -> str:"""Runs a simple command"""+ if addl_env is None:+ addl_env = {}+ env = os.environ.copy()+ env.update(addl_env)logger.info(f"Running command: {command}")if isinstance(command, str):command = command.split(" ")if capture_output:try:return (- subprocess.check_output(command, stderr=subprocess.PIPE, shell=False)+ subprocess.check_output(command, stderr=subprocess.PIPE, shell=False, env=env).decode().strip())@@ -49,7 +75,7 @@ def _command(command: str, capture_output: bool) -> str:print(e.stdout.decode())print(e.stderr.decode())raise e- subprocess.run(command, shell=False, check=True)+ subprocess.run(command, shell=False, check=True, env=env)def _get_git_root() -> str:@@ -102,6 +128,12 @@ def build_ui():_build_ui()+BACKEND_MODULES = {+ "local": "burr.tracking.server.backend.LocalBackend",+ "s3": "burr.tracking.server.s3.backend.S3Backend",+}++def _run_server(port: int,dev_mode: bool,@@ -109,6 +141,7 @@ def _run_server(no_copy_demo_data: bool,initial_page="",host: str = "127.0.0.1",+ backend: str = "local",):_telemetry_if_enabled("run_server")# TODO: Implement server running logic here@@ -142,7 +175,10 @@ def _run_server(daemon=True,)thread.start()- _command(cmd, capture_output=False)+ env = {+ "BURR_BACKEND_IMPL": BACKEND_MODULES[backend],+ }+ _command(cmd, capture_output=False, addl_env=env)@cli.command()@@ -156,8 +192,16 @@ def _run_server(help="Host to run the server on -- use 0.0.0.0 if you want ""to expose it to the network (E.G. in a docker image)",)-def run_server(port: int, dev_mode: bool, no_open: bool, no_copy_demo_data: bool, host: str):- _run_server(port, dev_mode, no_open, no_copy_demo_data, host=host)+ "--backend",+ default="local",+ help="Backend to use for the server.",+ type=click.Choice(["local", "s3"]),+)+def run_server(+ port: int, dev_mode: bool, no_open: bool, no_copy_demo_data: bool, host: str, backend: str+):+ _run_server(port, dev_mode, no_open, no_copy_demo_data, host=host, backend=backend)@cli.command()@@ -186,7 +230,17 @@ def build_and_publish(prod: bool, no_wipe_dist: bool):@cli.command(help="generate demo data for the UI")-def generate_demo_data():+ "--s3-bucket", help="S3 URI to save to, will use the s3 tracker, not local mode", required=False+)+ "--data-dir",+ help="Local directory to save to",+ required=False,+ default="burr/tracking/server/demo_data",+)[email protected]("--unique-app-names", help="Use unique app names", is_flag=True)+def generate_demo_data(s3_bucket, data_dir, unique_app_names: bool):_telemetry_if_enabled("generate_demo_data")git_root = _get_git_root()# We need to add the examples directory to the path so we have all the imports@@ -194,10 +248,14 @@ def generate_demo_data():sys.path.extend([git_root, f"{git_root}/examples/multi-modal-chatbot"])from burr.cli.demo_data import generate_all- with cd(git_root):- logger.info("Removing old demo data")- shutil.rmtree("burr/tracking/server/demo_data", ignore_errors=True)- generate_all("burr/tracking/server/demo_data")+ # local mode+ if s3_bucket is None:+ with cd(git_root):+ logger.info("Removing old demo data")+ shutil.rmtree(data_dir, ignore_errors=True)+ generate_all(data_dir=data_dir, unique_app_names=unique_app_names)+ else:+ generate_all(s3_bucket=s3_bucket, unique_app_names=unique_app_names)def _transform_state_to_test_case(state: dict, action_name: str, test_name: str) -> dict:diff --git a/burr/tracking/common/models.py b/burr/tracking/common/models.pyindex c66b7641..e4ed8a4d 100644--- a/burr/tracking/common/models.py+++ b/burr/tracking/common/models.py@@ -175,6 +175,10 @@ class BeginSpanModel(IdentifyingModel):span_dependencies: list[str]type: str = "begin_span"+ @property+ def sequence_id(self) -> int:+ return self.action_sequence_id+class EndSpanModel(IdentifyingModel):"""Pydantic model that represents an entry for the end of a span"""@@ -183,3 +187,7 @@ class EndSpanModel(IdentifyingModel):action_sequence_id: intspan_id: str # unique among the applicationtype: str = "end_span"++ @property+ def sequence_id(self) -> int:+ return self.action_sequence_iddiff --git a/burr/tracking/server/backend.py b/burr/tracking/server/backend.pyindex 1316279e..e520ed3b 100644--- a/burr/tracking/server/backend.py+++ b/burr/tracking/server/backend.py@@ -1,11 +1,15 @@import abc+import importlibimport jsonimport os.path-from typing import Sequence, TypeVar+import sys+from typing import Any, Optional, Sequence, Type, TypeVarimport aiofilesimport aiofiles.os as aiofilesosimport fastapi+from fastapi import FastAPI+from pydantic_settings import BaseSettings, SettingsConfigDictfrom burr.tracking.common import modelsfrom burr.tracking.common.models import (@@ -20,7 +24,6 @@ from burr.tracking.server.schema import ApplicationLogs, ApplicationSummaryT = TypeVar("T")-# The following is a backend for the server.# Note this is not a fixed API yet, and thus not documented (in Burr's documentation)# Specifically, this does not have:@@ -29,7 +32,42 @@ T = TypeVar("T")# - Authentication/Authorization+if sys.version_info <= (3, 11):+ Self = Any+else:+ from typing import Self+++class BurrSettings(BaseSettings):+ model_config = SettingsConfigDict(env_prefix="burr_")+++class IndexingBackendMixin(abc.ABC):+ """Base mixin for an indexing backend -- one that index from+ logs (E.G. s3)"""++ @abc.abstractmethod+ async def update(self):+ """Updates the index"""+ pass++ @abc.abstractmethod+ async def update_interval_milliseconds(self) -> Optional[int]:+ """Returns the update interval in milliseconds"""+ pass++ @abc.abstractmethod+ async def indexing_jobs(+ self, offset: int = 0, limit: int = 100, filter_empty: bool = True+ ) -> Sequence[schema.IndexingJob]:+ """Returns the indexing jobs"""+ pass++class BackendBase(abc.ABC):+ async def lifespan(self, app: FastAPI):+ yield+@abc.abstractmethodasync def list_projects(self, request: fastapi.Request) -> Sequence[schema.Project]:"""Lists out all projects -- this relies on the paginate function to work properly.@@ -63,6 +101,39 @@ class BackendBase(abc.ABC):"""pass+ @classmethod+ @abc.abstractmethod+ def settings_model(cls) -> Type[BaseSettings]:+ """Gives a settings model that tells us how to configure the backend.+ This is a class of pydantic BaseSettings type++ :return: the settings model+ """+ pass++ @classmethod+ def from_settings(cls, settings_model: BaseSettings) -> Self:+ """Creates a backend from settings, of the type of settings_model above+ This defaults to assuming the constructor takes in settings parameters++ :param settings_model:+ :return:+ """+ return cls(**settings_model.dict())++ @classmethod+ def create_from_env(cls, dotenv_path: Optional[str] = None) -> Self:+ cls_path = os.environ.get("BURR_BACKEND_IMPL", "burr.tracking.server.backend.LocalBackend")+ mod_path = ".".join(cls_path.split(".")[:-1])+ mod = importlib.import_module(mod_path)+ cls_name = cls_path.split(".")[-1]+ if not hasattr(mod, cls_name):+ raise ValueError(f"Could not find {cls_name} in {mod_path}")+ cls = getattr(mod, cls_name)+ return cls.from_settings(+ cls.settings_model()(_env_file=dotenv_path, _env_file_encoding="utf-8")+ )+def safe_json_load(line: bytes):# Every once in a while we'll hit a non-utf-8 character@@ -80,11 +151,13 @@ def get_uri(project_id: str) -> str:return project_id_map.get(project_id, "")+DEFAULT_PATH = os.path.expanduser("~/.burr")++class LocalBackend(BackendBase):"""Quick implementation of a local backend for testing purposes. This is not a production backend."""# TODO -- make this configurable through an env variable- DEFAULT_PATH = os.path.expanduser("~/.burr")def __init__(self, path: str = DEFAULT_PATH):self.path = path@@ -180,6 +253,7 @@ class LocalBackend(BackendBase):str_graph = await f.read()steps_by_sequence_id = {}spans_by_id = {}+ # TODO -- use the Step.from_logs methodif os.path.exists(log_file):async with aiofiles.open(log_file, "rb") as f:for line in await f.readlines():@@ -206,6 +280,7 @@ class LocalBackend(BackendBase):span = spans_by_id[end_span.span_id]span.end_entry = end_spanfor span in spans_by_id.values():+ # They should have one, the other, or both setstep = steps_by_sequence_id[span.begin_entry.action_sequence_id]step.spans.append(span)children = []@@ -223,3 +298,14 @@ class LocalBackend(BackendBase):spawning_parent_pointer=metadata.spawning_parent_pointer,children=children,)++ class BackendSettings(BurrSettings):+ path: str = DEFAULT_PATH++ @classmethod+ def settings_model(cls) -> Type[BurrSettings]:+ return cls.BackendSettings++ @classmethod+ def from_settings(cls, settings_model: BurrSettings) -> Self:+ return cls(**settings_model.dict())diff --git a/burr/tracking/server/requirements-s3.txt b/burr/tracking/server/requirements-s3.txtnew file mode 100644index 00000000..e1f4632b--- /dev/null+++ b/burr/tracking/server/requirements-s3.txt@@ -0,0 +1,4 @@+aerich+aiobotocore+fastapi-utils+tortoise-orm[accel, asyncmy]diff --git a/burr/tracking/server/run.py b/burr/tracking/server/run.pyindex be99070a..c06931fe 100644--- a/burr/tracking/server/run.py+++ b/burr/tracking/server/run.py@@ -1,19 +1,32 @@import importlib+import loggingimport os+from contextlib import asynccontextmanagerfrom importlib.resources import filesfrom typing import Sequence-from burr.integrations.base import require_plugin+# TODO -- remove this, just for testing+from hamilton.log_setup import setup_logging+from starlette import status++from burr.tracking.server.backend import BackendBase, IndexingBackendMixin++setup_logging(logging.INFO)++logger = logging.getLogger(__name__)try:import uvicorn- from fastapi import FastAPI, Request+ from fastapi import FastAPI, HTTPException, Requestfrom fastapi.staticfiles import StaticFiles+ from fastapi_utils.tasks import repeat_everyfrom starlette.templating import Jinja2Templates- from burr.tracking.server import backend as backend_modulefrom burr.tracking.server import schema- from burr.tracking.server.schema import ApplicationLogs++ # from burr.tracking.server import backend as backend_module+ # from burr.tracking.server.s3 import backend as s3_backend+ from burr.tracking.server.schema import ApplicationLogs, BackendSpec, IndexingJob# dynamic importing due to the dashes (which make reading the examples on github easier)email_assistant = importlib.import_module("burr.examples.email-assistant.server")@@ -21,26 +34,87 @@ try:streaming_chatbot = importlib.import_module("burr.examples.streaming-fastapi.server")except ImportError as e:- require_plugin(- e,- [- "click",- "fastapi",- "uvicorn",- "pydantic",- "fastapi-pagination",- "aiofiles",- "requests",- "jinja2",- ],- "tracking",- )--app = FastAPI()+ raise e+ # require_plugin(+ # e,+ # [+ # "click",+ # "fastapi",+ # "uvicorn",+ # "pydantic",+ # "fastapi-pagination",+ # "aiofiles",+ # "requests",+ # "jinja2",+ # ],+ # "tracking",+ # )SERVE_STATIC = os.getenv("BURR_SERVE_STATIC", "true").lower() == "true"-backend = backend_module.LocalBackend()+# TODO -- get based on a config+# backend = backend_module.LocalBackend()+# backend = s3_backend.S3Backend(+# bucket="burr-prod-test",+# )++backend = BackendBase.create_from_env()+++# if it is an indexing backend we want to expose a few endpoints+++# TODO -- add a health check for intialization+++async def update():+ if app_spec.indexing:+ logger.info("Updating backend")+ await backend.update()+++@asynccontextmanager+async def lifespan(app: FastAPI):+ # No yield from allowed+ await backend.lifespan(app).__anext__()+ await update() # this will trigger the repeat every N seconds+ yield+ await backend.lifespan(app).__anext__()+++app = FastAPI(lifespan=lifespan)++[email protected]("/api/v0/metadata/app_spec", response_model=BackendSpec)+def get_app_spec():+ is_indexing_backend = isinstance(backend, IndexingBackendMixin)+ return BackendSpec(indexing=is_indexing_backend)+++app_spec = get_app_spec()++logger = logging.getLogger(__name__)++# @repeat_every(+# seconds=update_interval if update_interval is not None else float("inf"),+# wait_first=True,+# logger=logger,+# )+++if app_spec.indexing:+ update_interval = backend.update_interval_milliseconds() / 1000 if app_spec.indexing else None+ update = repeat_every(+ seconds=backend.update_interval_milliseconds() / 1000,+ wait_first=True,+ logger=logger,+ )(update)++[email protected]_event("startup")+async def startup_event():+ if app_spec.indexing:+ await update()@app.get("/api/v0/projects", response_model=Sequence[schema.Project])@@ -72,7 +146,7 @@ async def get_application_logs(request: Request, project_id: str, app_id: str) -:param request: FastAPI:param project_id: ID of the project- :param app_id: ID of the associated application+ :param app_id: ID of the assIndociated application:return: A list of steps with all associated step data"""return await backend.get_application_logs(request, project_id=project_id, app_id=app_id)@@ -83,6 +157,18 @@ async def ready() -> bool:return True[email protected]("/api/v0/indexing_jobs", response_model=Sequence[IndexingJob])+async def get_indexing_jobs(+ offset: int = 0, limit: int = 100, filter_empty: bool = True+) -> Sequence[IndexingJob]:+ if not app_spec.indexing:+ raise HTTPException(+ status_code=status.HTTP_404_NOT_FOUND,+ detail="This backend does not support indexing jobs.",+ )+ return await backend.indexing_jobs(offset=offset, limit=limit, filter_empty=filter_empty)++@app.get("/api/v0/version")async def version() -> dict:"""Returns the burr version"""@@ -100,7 +186,6 @@ app.include_router(chatbot.router, prefix="/api/v0/chatbot")app.include_router(email_assistant.router, prefix="/api/v0/email_assistant")app.include_router(streaming_chatbot.router, prefix="/api/v0/streaming_chatbot")-if SERVE_STATIC:BASE_ASSET_DIRECTORY = str(files("burr").joinpath("tracking/server/build"))diff --git a/burr/tracking/server/s3/README.md b/burr/tracking/server/s3/README.mdnew file mode 100644index 00000000..43f5a6b2--- /dev/null+++ b/burr/tracking/server/s3/README.md@@ -0,0 +1,25 @@+# S3-backed server++## Architecture++## Deployment++## Migrating/Initializing++- make sure aerich is installed++To reset, do:+```bash+rm -rf ~/.burr_server &&+mkdir ~/.burr_server &&+rm -rf ./burr/tracking/server/s3/migrations &&+aerich init -t burr.tracking.server.s3.settings.TORTOISE_ORM --location ./burr/tracking/server/s3/migrations &&+aerich init-db &&+AWS_PROFILE=dagworks burr --no-open+```+```+- `rm -rf ~/.burr_server` (will be turned to an env variable)+- `mkdir ~/.burr_server` (ditto)+- (from git root) `rm -rf ./burr/tracking/server/s3/migrations`+- (from git root) `aerich init -t burr.tracking.server.s3.settings.TORTOISE_ORM --location ./burr/tracking/server/s3/migrations`+- (from git root) `aerich init-db`diff --git a/burr/tracking/server/s3/__init__.py b/burr/tracking/server/s3/__init__.pynew file mode 100644index 00000000..e69de29bdiff --git a/burr/tracking/server/s3/backend.py b/burr/tracking/server/s3/backend.pynew file mode 100644index 00000000..f87c94e3--- /dev/null+++ b/burr/tracking/server/s3/backend.py@@ -0,0 +1,559 @@+import dataclasses+import datetime+import functools+import itertools+import json+import logging+import operator+import uuid+from collections import Counter+from typing import List, Literal, Optional, Sequence, Tuple, Type, TypeVar, Union++import fastapi+import pydantic+from aiobotocore import session+from fastapi import FastAPI+from pydantic_settings import BaseSettings+from tortoise import functions, transactions+from tortoise.contrib.fastapi import RegisterTortoise+from tortoise.expressions import Q++from burr.tracking.common.models import ApplicationModel+from burr.tracking.server import schema+from burr.tracking.server.backend import BackendBase, BurrSettings, IndexingBackendMixin+from burr.tracking.server.s3 import settings, utils+from burr.tracking.server.s3.models import (+ Application,+ IndexingJob,+ IndexingJobStatus,+ IndexStatus,+ LogFile,+ Project,+)+from burr.tracking.server.schema import ApplicationLogs, Step++logger = logging.getLogger(__name__)++FileType = Literal["log", "metadata", "graph"]++ContentsModel = TypeVar("ContentsModel", bound=pydantic.BaseModel)+++async def _query_s3_file(+ bucket: str,+ key: str,+ client: session.AioBaseClient,+) -> Union[ContentsModel, List[ContentsModel]]:+ response = await client.get_object(Bucket=bucket, Key=key)+ body = await response["Body"].read()+ return body+++class DataFile:+ """Generic data file object meant to represent a file in the s3 bucket. This has a few possible roles (log, metadata, and graph file)"""++ prefix: str+ yyyy: str+ mm: str+ dd: str+ hh: str+ minutes_string: str+ partition_key: str+ application_id: str+ file_type: FileType+ path: str+ created_date: datetime.datetime++ @classmethod+ def from_path(cls, path: str, created_date: datetime.datetime) -> "DataFile":+ parts = path.split("/")++ # Validate that there are enough parts to extract the needed fields+ if len(parts) < 9:+ raise ValueError(f"Path '{path}' is not valid")++ prefix = "/".join(parts[:-8]) # Everything before the year part+ yyyy = parts[2]+ mm = parts[3]+ dd = parts[4]+ hh = parts[5]+ minutes_string = parts[6]+ application_id = parts[8]+ partition_key = parts[7]+ filename = parts[9]+ file_type = (+ "graph"+ if filename.endswith("graph.json")+ else "metadata"+ if filename.endswith("_metadata.json")+ else "log"+ )++ # # Validate the date parts+ # if not (yyyy.isdigit() and mm.isdigit() and dd.isdigit() and hh.isdigit()):+ # raise ValueError(f"Date components in the path '{path}' are not valid")++ return cls(+ prefix=prefix,+ yyyy=yyyy,+ mm=mm,+ dd=dd,+ hh=hh,+ minutes_string=minutes_string,+ application_id=application_id,+ partition_key=partition_key,+ file_type=file_type,+ path=path,+ created_date=created_date,+ )+++class S3Settings(BurrSettings):+ s3_bucket: str+ update_interval_milliseconds: int = 60_000+ aws_max_concurrency: int = 100+++class S3Backend(BackendBase, IndexingBackendMixin):+ @classmethod+ def settings_model(cls) -> Type[BaseSettings]:+ return S3Settings++ def __init__(self, s3_bucket: str, update_interval_milliseconds: int, aws_max_concurrency: int):+ self._backend_id = datetime.datetime.utcnow().isoformat() + str(uuid.uuid4())+ self._bucket = s3_bucket+ self._session = session.get_session()+ self._update_interval_milliseconds = update_interval_milliseconds+ self._aws_max_concurrency = aws_max_concurrency++ def update_interval_milliseconds(self) -> Optional[int]:+ return self._update_interval_milliseconds++ async def _s3_get_first_write_date(self, project_id: str):+ 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+ ):+ if "Contents" in result:+ first_object = result["Contents"][0]+ return first_object["LastModified"]+ return (+ datetime.datetime.utcnow()+ ) # This should never be hit unless someone is concurrently deleting...++ async def _update_projects(self):+ current_projects = await Project.all()+ project_names = {project.name for project in current_projects}+ logger.info(f"Current projects: {project_names}")+ 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="/"+ ):+ for prefix in result.get("CommonPrefixes", []):+ project_name = prefix.get("Prefix").split("/")[-2]+ if project_name not in project_names:+ now = datetime.datetime.utcnow()+ logger.info(f"Creating project: {project_name}")+ await Project.create(+ name=project_name,+ uri=None,+ created_at=await self._s3_get_first_write_date(project_id=project_name),+ indexed_at=now,+ updated_at=now,+ )++ async def query_applications_by_key(+ self, application_keys: Sequence[tuple[str, Optional[str]]]+ ):+ conditions = [+ Q(name=app_id, partition_key=partition_key)+ for app_id, partition_key in application_keys+ ]++ # Combine the conditions with an OR operation+ query = Application.filter(functools.reduce(operator.or_, conditions))++ # Execute the query+ applications = await query.all()+ return applications++ async def _gather_metadata_files(+ self,+ metadata_files: List[DataFile],+ ) -> Sequence[dict]:+ """Gives a list of metadata files so we can update the application"""++ async def _query_metadata_file(metadata_file: DataFile) -> dict:+ async with self._session.create_client("s3") as client:+ response = await client.head_object(+ Bucket=self._bucket,+ Key=metadata_file.path,+ )+ # metadata = await response['Body'].read()+ parent_pointer_raw = response["Metadata"].get("parent_pointer")+ spawning_parent_pointer_raw = response["Metadata"].get("spawning_parent_pointer")+ return dict(+ partition_key=metadata_file.partition_key,+ parent_pointer=json.loads(parent_pointer_raw)+ if parent_pointer_raw != "None"+ else None,+ spawning_parent_pointer=json.loads(spawning_parent_pointer_raw)+ if spawning_parent_pointer_raw != "None"+ else None,+ )++ out = await utils.gather_with_concurrency(+ self._aws_max_concurrency,+ *[_query_metadata_file(metadata_file) for metadata_file in metadata_files],+ )+ return out++ async def _gather_log_file_data(self, log_files: List[DataFile]) -> Sequence[dict]:+ """Gives a list of log files so we can update the application"""++ async def _query_log_file(log_file: DataFile) -> dict:+ async with self._session.create_client("s3") as client:+ response = await client.head_object(+ Bucket=self._bucket,+ Key=log_file.path,+ )+ # TODO -- consider the default cases, we should not have them and instead mark this as failed+ return {+ "min_sequence_id": response["Metadata"].get("min_sequence_id", 0),+ "max_sequence_id": response["Metadata"].get("max_sequence_id", 0),+ "tracker_id": response["Metadata"].get("tracker_id", "unknown"),+ }++ out = await utils.gather_with_concurrency(+ self._aws_max_concurrency, *[_query_log_file(log_file) for log_file in log_files]+ )+ return out++ async def _gather_paths_to_update(+ self, project: Project, high_watermark_s3_path: str+ ) -> Sequence[DataFile]:+ """Gathers all paths to update in s3 -- we store file pointers in the db for these.+ This allows us to periodically scan for more files to index.++ :return: list of paths to update+ """+ logger.info(f"Scanning db with highwatermark: {high_watermark_s3_path}")+ paths_to_update = []+ logger.info(f"Scanning log data for project: {project.name}")+ 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.name}/",+ StartAfter=high_watermark_s3_path,+ ):+ for content in result.get("Contents", []):+ key = content["Key"]+ last_modified = content["LastModified"]+ # Created == last_modified as we have an immutable data model+ logger.info(f"Found new file: {key}")+ paths_to_update.append(DataFile.from_path(key, created_date=last_modified))+ logger.info(f"Found {len(paths_to_update)} new files to index")+ return paths_to_update++ async def _ensure_applications_exist(+ self, paths_to_update: Sequence[DataFile], project: Project+ ):+ """Given the paths to update, ensure that all corresponding applications exist in the database.++ :param paths_to_update:+ :param project:+ :return:+ """+ all_application_keys = sorted(+ {(path.application_id, path.partition_key) for path in paths_to_update}+ )+ counter = Counter([path.file_type for path in paths_to_update])+ logger.info(+ f"Found {len(all_application_keys)} applications in the scan, "+ f"including: {counter['log']} log files, "+ f"{counter['metadata']} metadata files, and {counter['graph']} graph files, "+ f"and {len(paths_to_update) - len(all_application_keys)} other files."+ )++ # First, let's create all applications, ignoring them if they exist++ # first let's create all the applications if they don't exist+ existing_applications = {+ (app.name, app.partition_key): app+ for app in await self.query_applications_by_key(all_application_keys)+ }+ # all_applications = await Application.all()++ apps_to_create = [+ Application(+ name=app_id,+ partition_key=pk,+ project=project,+ created_at=datetime.datetime.utcnow(),+ )+ for app_id, pk in all_application_keys+ if (app_id, pk) not in existing_applications+ ]++ logger.info(+ f"Creating {len(apps_to_create)} new applications, with keys: {[(app.name, app.partition_key) for app in apps_to_create]}"+ )+ await Application.bulk_create(apps_to_create)+ all_applications = await self.query_applications_by_key(all_application_keys)+ return all_applications++ async def _update_all_applications(+ self, all_applications: Sequence[Application], paths_to_update: Sequence[DataFile]+ ) -> Sequence[Application]:+ """Updates all application with associate metadata and graph files++ :param all_applications: All applications that are relevant+ :param paths_to_update: All paths to update+ :return:+ """+ logger.info(f"found: {len(all_applications)} applications to update in the db")+ metadata_data = [path for path in paths_to_update if path.file_type == "metadata"]+ graph_data = [path for path in paths_to_update if path.file_type == "graph"]+ metadata_objects = await self._gather_metadata_files(metadata_data)+ key_to_application_map = {(app.name, app.partition_key): app for app in all_applications}+ # For every metadata file we want to add the metadata file+ for metadata, datafile in zip(metadata_objects, metadata_data):+ key = (datafile.application_id, datafile.partition_key)+ app = key_to_application_map[key]+ app.metadata_file_pointer = datafile.path++ # TODO -- download the metadata file and update the application++ # for every graph file, we want to add the pointer+ for graph_file in graph_data:+ key = (graph_file.application_id, graph_file.partition_key)+ app = key_to_application_map[key]+ app.graph_file_pointer = graph_file.path+ # Go through every application and save them+ async with transactions.in_transaction():+ # TODO -- look at bulk saving, instead of transactions+ for app in all_applications:+ await app.save()+ return all_applications++ async def update_log_files(+ self, paths_to_update: Sequence[DataFile], all_applications: Sequence[Application]+ ):+ log_data = [path for path in paths_to_update if path.file_type == "log"]+ logfile_objects = await self._gather_log_file_data(log_data)+ key_to_application_map = {(app.name, app.partition_key): app for app in all_applications}++ # TODO -- gather referenced apps (parent pointers) and get the map of IDs to names++ # Go through every log file we've stored and update the appropriate item in the db+ logfiles_to_save = []+ for logfile, datafile in zip(logfile_objects, log_data):+ # get the application for the log file+ app = key_to_application_map[(datafile.application_id, datafile.partition_key)]+ # create the log file object+ logfiles_to_save.append(+ LogFile(+ s3_path=datafile.path,+ application=app,+ tracker_id=logfile["tracker_id"],+ min_sequence_id=logfile["min_sequence_id"],+ max_sequence_id=logfile["max_sequence_id"],+ created_at=datafile.created_date,+ )+ )+ # Save all the log files+ await LogFile.bulk_create(logfiles_to_save)++ async def _update_high_watermark(+ self, paths_to_update: Sequence[DataFile], project: Project, indexing_job: IndexingJob+ ):+ new_high_watermark = max(paths_to_update, key=lambda x: x.path).path+ next_status = IndexStatus(s3_highwatermark=new_high_watermark, project=project)+ await next_status.save()+ return next_status++ async def _scan_and_update_db_for_project(+ self, project: Project, indexing_job: IndexingJob+ ) -> Tuple[IndexStatus, int]:+ """Scans and updates the database for a project.++ TODO -- break this up into functions++ :param project: Project to scan/update+ :param max_length: Maximum length of the scan -- will pause and return after this. This is so we don't block for too long.+ :return: tuple of index status/num files processed+ """+ # get the current status+ current_status = (+ await IndexStatus.filter(project=project).order_by("-captured_time").first()+ )+ # This way we can sort by the latest captured time+ high_watermark = current_status.s3_highwatermark if current_status is not None else ""+ logger.info(f"Scanning db with highwatermark: {high_watermark}")+ paths_to_update = await self._gather_paths_to_update(+ project=project, high_watermark_s3_path=high_watermark+ )+ # Nothing new to see here+ if len(paths_to_update) == 0:+ return current_status, 0++ all_applications = await self._ensure_applications_exist(paths_to_update, project)+ await self._update_all_applications(all_applications, paths_to_update)+ await self.update_log_files(paths_to_update, all_applications)+ next_status = await self._update_high_watermark(paths_to_update, project, indexing_job)+ return next_status, len(paths_to_update)++ async def _scan_and_update_db(self):+ for project in await Project.all():+ indexing_job = IndexingJob(+ records_processed=0, # start with zero+ end_time=None,+ status=IndexingJobStatus.RUNNING,+ )+ await indexing_job.save()++ # TODO -- add error catching+ status, num_files = await self._scan_and_update_db_for_project(project, indexing_job)+ logger.info(f"Scanned: {num_files} files with status stored at ID={status.id}")++ indexing_job.records_processed = num_files+ indexing_job.end_time = datetime.datetime.utcnow()+ # TODO -- handle failure+ indexing_job.status = IndexingJobStatus.SUCCESS+ indexing_job.index_status = status+ await indexing_job.save()++ async def update(self):+ await self._update_projects()+ await self._scan_and_update_db()++ async def lifespan(self, app: FastAPI):+ async with RegisterTortoise(app, config=settings.TORTOISE_ORM, add_exception_handlers=True):+ yield++ async def list_projects(self, request: fastapi.Request) -> Sequence[schema.Project]:+ project_query = await Project.all()+ out = []+ for project in project_query:+ latest_logfile = (+ await LogFile.filter(application__project=project).order_by("-created_at").first()+ )+ out.append(+ schema.Project(+ name=project.name,+ id=project.name,+ uri=project.uri if project.uri is not None else "TODO",+ last_written=latest_logfile.created_at+ if latest_logfile is not None+ else project.created_at,+ created=project.created_at,+ num_apps=await Application.filter(project=project).count(),+ )+ )+ return out++ async def list_apps(+ self, request: fastapi.Request, project_id: str, limit: int = 100, offset: int = 0+ ) -> Sequence[schema.ApplicationSummary]:+ # TODO -- distinctify between project name and project ID+ # Currently they're the same in the UI but we'll want to have them decoupled+ applications = (+ await Application.filter(project__name=project_id)+ .annotate(+ latest_logfile_created_at=functions.Max("log_files__created_at"),+ logfile_count=functions.Max("log_files__max_sequence_id"),+ )+ .order_by("created_at")+ .offset(offset)+ .limit(limit)+ .prefetch_related("log_files", "project")+ )+ out = []+ for application in applications:+ last_written = (+ datetime.datetime.fromisoformat(application.latest_logfile_created_at)+ if (application.latest_logfile_created_at is not None)+ else application.created_at+ )+ out.append(+ schema.ApplicationSummary(+ app_id=application.name,+ partition_key=application.partition_key,+ first_written=application.created_at,+ last_written=last_written,+ num_steps=application.logfile_count,+ tags={},+ )+ )+ return out++ async def get_application_logs(+ self, request: fastapi.Request, project_id: str, app_id: str+ ) -> ApplicationLogs:+ # TODO -- handle partition keys+ applications = await Application.filter(name=app_id, project__name=project_id).all()+ application = applications[0]+ application_logs = await LogFile.filter(application__id=application.id).order_by(+ "-created_at"+ )+ async with self._session.create_client("s3") as client:+ # Get all the files+ files = await utils.gather_with_concurrency(+ 1,+ _query_s3_file(self._bucket, application.graph_file_pointer, client),+ # _query_s3_files(self.bucket, application.metadata_file_pointer, client),+ *itertools.chain(+ _query_s3_file(self._bucket, log_file.s3_path, client)+ for log_file in application_logs+ ),+ )+ graph_data = ApplicationModel.parse_raw(files[0])+ # TODO -- deal with what happens if the application is None+ # TODO -- handle metadata+ # metadata = ApplicationMetadataModel.parse_raw(files[1])+ steps = Step.from_logs(list(itertools.chain(*[f.splitlines() for f in files[1:]])))++ return ApplicationLogs(+ children=[],+ steps=steps,+ # TODO -- get this in+ parent_pointer=None,+ spawning_parent_pointer=None,+ application=graph_data,+ )++ async def indexing_jobs(+ self, offset: int = 0, limit: int = 100, filter_empty: bool = True+ ) -> Sequence[schema.IndexingJob]:+ indexing_jobs_query = (+ IndexingJob.all().order_by("-start_time").prefetch_related("index_status__project")+ )++ # Apply filter conditionally+ if filter_empty:+ indexing_jobs_query = indexing_jobs_query.filter(records_processed__gt=0)+ indexing_jobs = await indexing_jobs_query.offset(offset).limit(limit)+ out = []+ for indexing_job in indexing_jobs:+ out.append(+ schema.IndexingJob(+ id=indexing_job.id,+ start_time=indexing_job.start_time,+ end_time=indexing_job.end_time,+ status=indexing_job.status,+ records_processed=indexing_job.records_processed,+ metadata={+ "project": indexing_job.index_status.project.name+ if indexing_job.index_status+ else "unknown",+ "s3_highwatermark": indexing_job.index_status.s3_highwatermark+ if indexing_job.index_status+ else "unknown",+ },+ )+ )+ return outdiff --git a/burr/tracking/server/s3/initialize_db.py b/burr/tracking/server/s3/initialize_db.pynew file mode 100644index 00000000..2bbbf65e--- /dev/null+++ b/burr/tracking/server/s3/initialize_db.py@@ -0,0 +1,28 @@+import os+from pathlib import Path++from tortoise import Tortoise++from burr.tracking.server.s3 import settings++DB_PATH = Path("~/.burr_server/db.sqlite3").expanduser()+++async def connect():+ if not os.path.exists(DB_PATH):+ os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)+ await Tortoise.init(+ config=settings.TORTOISE_ORM,+ )+++#+# async def first_time_init():+# await connect()+# # Generate the schema+# await Tortoise.generate_schemas()+#+#+# if __name__ == '__main__':+# # db_path = sys.argv[1]+# run_async(first_time_init())diff --git a/burr/tracking/server/s3/migrations/models/0_20240730151503_init.py b/burr/tracking/server/s3/migrations/models/0_20240730151503_init.pynew file mode 100644index 00000000..b6461010--- /dev/null+++ b/burr/tracking/server/s3/migrations/models/0_20240730151503_init.py@@ -0,0 +1,70 @@+from tortoise import BaseDBAsyncClient+++async def upgrade(db: BaseDBAsyncClient) -> str:+ return """+ CREATE TABLE IF NOT EXISTS "project" (+ "created_at" TIMESTAMP NOT NULL,+ "indexed_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "name" VARCHAR(255) NOT NULL UNIQUE,+ "uri" VARCHAR(255)+) /* Static model representing a project */;+CREATE INDEX IF NOT EXISTS "idx_project_name_4d952a" ON "project" ("name");+CREATE TABLE IF NOT EXISTS "application" (+ "created_at" TIMESTAMP NOT NULL,+ "indexed_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "name" VARCHAR(255) NOT NULL,+ "partition_key" VARCHAR(255) NOT NULL,+ "graph_file_pointer" VARCHAR(255),+ "metadata_file_pointer" VARCHAR(255),+ "fork_parent_id" INT REFERENCES "application" ("id") ON DELETE CASCADE,+ "project_id" INT NOT NULL REFERENCES "project" ("id") ON DELETE CASCADE,+ "spawning_parent_id" INT REFERENCES "application" ("id") ON DELETE CASCADE,+ CONSTRAINT "uid_application_name_488894" UNIQUE ("name", "partition_key")+);+CREATE INDEX IF NOT EXISTS "idx_application_name_18706d" ON "application" ("name");+CREATE INDEX IF NOT EXISTS "idx_application_partiti_d302c8" ON "application" ("partition_key");+CREATE INDEX IF NOT EXISTS "idx_application_project_13a4e1" ON "application" ("project_id");+CREATE TABLE IF NOT EXISTS "indexstatus" (+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "s3_highwatermark" VARCHAR(1023) NOT NULL,+ "captured_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "project_id" INT NOT NULL REFERENCES "project" ("id") ON DELETE CASCADE+) /* Status to index. These are per-project and the latest is chosen */;+CREATE INDEX IF NOT EXISTS "idx_indexstatus_capture_d2163c" ON "indexstatus" ("captured_time");+CREATE INDEX IF NOT EXISTS "idx_indexstatus_project_52e6eb" ON "indexstatus" ("project_id");+CREATE TABLE IF NOT EXISTS "indexingjob" (+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "start_time" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "records_processed" INT NOT NULL,+ "end_time" TIMESTAMP,+ "status" VARCHAR(7) NOT NULL /* SUCCESS: SUCCESS\nFAILURE: FAILURE\nRUNNING: RUNNING */,+ "index_status_id" INT REFERENCES "indexstatus" ("id") ON DELETE CASCADE+) /* Job for indexing data in s3. Records only if there's something to index */;+CREATE TABLE IF NOT EXISTS "logfile" (+ "created_at" TIMESTAMP NOT NULL,+ "indexed_at" TIMESTAMP DEFAULT CURRENT_TIMESTAMP,+ "updated_at" TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "s3_path" VARCHAR(1024) NOT NULL,+ "tracker_id" VARCHAR(255) NOT NULL,+ "min_sequence_id" INT NOT NULL,+ "max_sequence_id" INT NOT NULL,+ "application_id" INT NOT NULL REFERENCES "application" ("id") ON DELETE CASCADE+);+CREATE INDEX IF NOT EXISTS "idx_logfile_applica_9633be" ON "logfile" ("application_id");+CREATE TABLE IF NOT EXISTS "aerich" (+ "id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ "version" VARCHAR(255) NOT NULL,+ "app" VARCHAR(100) NOT NULL,+ "content" JSON NOT NULL+);"""+++async def downgrade(db: BaseDBAsyncClient) -> str:+ return """+ """diff --git a/burr/tracking/server/s3/models.py b/burr/tracking/server/s3/models.pynew file mode 100644index 00000000..1290b677--- /dev/null+++ b/burr/tracking/server/s3/models.py@@ -0,0 +1,96 @@+import enum++from tortoise import fields+from tortoise.models import Model+++class IndexingJobStatus(enum.Enum):+ SUCCESS = "SUCCESS"+ FAILURE = "FAILURE"+ RUNNING = "RUNNING"+++class IndexedModel(Model):+ """Base model for all models that are indexed in s3. Contains data on creating/updating"""++ created_at = fields.DatetimeField(null=False)+ indexed_at = fields.DatetimeField(null=True, auto_now_add=True)+ updated_at = fields.DatetimeField(null=False, auto_now=True)++ class Meta:+ abstract = True+++class IndexingJob(Model):+ """Job for indexing data in s3. Records only if there's something to index"""++ id = fields.IntField(pk=True)+ start_time = fields.DatetimeField(auto_now_add=True)+ records_processed = fields.IntField()+ end_time = fields.DatetimeField(null=True)+ status = fields.CharEnumField(IndexingJobStatus)+ index_status = fields.ForeignKeyField(+ "models.IndexStatus", related_name="index_status", null=True+ )++ def __str__(self):+ return f"{self.start_time} - {self.end_time}"+++class IndexStatus(Model):+ """Status to index. These are per-project and the latest is chosen"""++ id = fields.IntField(pk=True)+ s3_highwatermark = fields.CharField(max_length=1023)+ captured_time = fields.DatetimeField(index=True, auto_now_add=True)+ project = fields.ForeignKeyField("models.Project", related_name="project", index=True)++ def __str__(self):+ return f"{self.project} - {self.captured_time}"+++class Project(IndexedModel):+ """Static model representing a project"""++ id = fields.IntField(pk=True)+ name = fields.CharField(index=True, max_length=255, unique=True)+ uri = fields.CharField(max_length=255, null=True)++ def __str__(self):+ return self.name+++class Application(IndexedModel):+ id = fields.IntField(pk=True)+ name = fields.CharField(index=True, max_length=255)+ partition_key = fields.CharField(max_length=255, index=True, null=False)+ project = fields.ForeignKeyField("models.Project", related_name="applications", index=True)+ graph_file_pointer = fields.CharField(max_length=255, null=True)+ metadata_file_pointer = fields.CharField(max_length=255, null=True)+ fork_parent = fields.ForeignKeyField("models.Application", related_name="forks", null=True)+ spawning_parent = fields.ForeignKeyField("models.Application", related_name="spawns", null=True)++ class Meta:+ # App name is unique together+ unique_together = (("name", "partition_key"),)++ def graph_file_indexed(self) -> bool:+ return self.graph_file_pointer is not None++ def metadata_file_indexed(self) -> bool:+ return self.metadata_file_pointer is not None+++class LogFile(IndexedModel):+ # s3 path is named+ # <tracker_id>-<logfile_sequence>-<min_sequence_id>-<max_sequence_id>.jsonl+ id = fields.IntField(pk=True)+ s3_path = fields.CharField(max_length=1024)+ application = fields.ForeignKeyField(+ "models.Application",+ related_name="log_files",+ index=True,+ )+ tracker_id = fields.CharField(max_length=255)+ min_sequence_id = fields.IntField()+ max_sequence_id = fields.IntField()diff --git a/burr/tracking/server/s3/pyproject.toml b/burr/tracking/server/s3/pyproject.tomlnew file mode 100644index 00000000..36b1df16--- /dev/null+++ b/burr/tracking/server/s3/pyproject.toml@@ -0,0 +1,4 @@+[tool.aerich]+tortoise_orm = "burr.tracking.server.s3.settings.TORTOISE_ORM"+location = "./burr/tracking/server/s3/migrations"+src_folder = "./."diff --git a/burr/tracking/server/s3/settings.py b/burr/tracking/server/s3/settings.pynew file mode 100644index 00000000..fe172ed9--- /dev/null+++ b/burr/tracking/server/s3/settings.py@@ -0,0 +1,13 @@+from pathlib import Path++DB_PATH = Path("~/.burr_server/db.sqlite3").expanduser()++TORTOISE_ORM = {+ "connections": {"default": f"sqlite:///{DB_PATH}"},+ "apps": {+ "models": {+ "models": ["burr.tracking.server.s3.models", "aerich.models"],+ "default_connection": "default",+ },+ },+}diff --git a/burr/tracking/server/s3/utils.py b/burr/tracking/server/s3/utils.pynew file mode 100644index 00000000..52f6f655--- /dev/null+++ b/burr/tracking/server/s3/utils.py@@ -0,0 +1,14 @@+import asyncio+from typing import Awaitable, TypeVar++AwaitableType = TypeVar("AwaitableType")+++async def gather_with_concurrency(n, *coros: Awaitable[AwaitableType]) -> tuple[AwaitableType, ...]:+ semaphore = asyncio.Semaphore(n)++ async def sem_coro(coro: Awaitable[AwaitableType]) -> AwaitableType:+ async with semaphore:+ return await coro++ return await asyncio.gather(*(sem_coro(c) for c in coros))diff --git a/burr/tracking/server/schema.py b/burr/tracking/server/schema.pyindex 61989c6e..950a911c 100644--- a/burr/tracking/server/schema.py+++ b/burr/tracking/server/schema.py@@ -1,7 +1,9 @@+import collectionsimport datetime-from typing import Dict, List, Optional+from typing import Any, Dict, List, Optionalimport pydantic+from pydantic import fieldsfrom burr.tracking.common.models import (ApplicationModel,@@ -12,15 +14,16 @@ from burr.tracking.common.models import (EndSpanModel,PointerModel,)+from burr.tracking.utils import safe_json_loadclass Project(pydantic.BaseModel):name: strid: str # defaults to name for local, not for remote- uri: str # TODO -- figure out whatlast_written: datetime.datetimecreated: datetime.datetimenum_apps: int+ uri: strclass ApplicationSummary(pydantic.BaseModel):@@ -40,6 +43,11 @@ class ApplicationModelWithChildren(pydantic.BaseModel):type: str = "application_with_children"+class PartialSpan(pydantic.BaseModel):+ begin_entry: Optional[BeginSpanModel] = fields.Field(default_factory=lambda: None)+ end_entry: Optional[EndSpanModel] = fields.Field(default_factory=lambda: None)++class Span(pydantic.BaseModel):"""Represents a span. These have action sequence IDs associated withthem to put them in order."""@@ -48,6 +56,12 @@ class Span(pydantic.BaseModel):end_entry: Optional[EndSpanModel]+class PartialStep(pydantic.BaseModel):+ step_start_log: Optional[BeginEntryModel] = fields.Field(default_factory=lambda: None)+ step_end_log: Optional[EndEntryModel] = fields.Field(default_factory=lambda: None)+ spans: List[Span] = fields.Field(default_factory=list)++class Step(pydantic.BaseModel):"""Log of astep -- has a start and an end."""@@ -55,6 +69,55 @@ class Step(pydantic.BaseModel):step_end_log: Optional[EndEntryModel]spans: List[Span]+ @staticmethod+ def from_logs(log_lines: List[bytes]) -> List["Step"]:+ steps_by_sequence_id = collections.defaultdict(PartialStep)+ spans_by_id = collections.defaultdict(Span)+ for line in log_lines:+ json_line = safe_json_load(line)+ # TODO -- make these into constants+ if json_line["type"] == "begin_entry":+ begin_step = BeginEntryModel.parse_obj(json_line)+ steps_by_sequence_id[begin_step.sequence_id].step_start_log = begin_step+ elif json_line["type"] == "end_entry":+ step_end_log = EndEntryModel.parse_obj(json_line)+ steps_by_sequence_id[step_end_log.sequence_id].step_end_log = step_end_log+ elif json_line["type"] == "begin_span":+ span = BeginSpanModel.parse_obj(json_line)+ spans_by_id[span.span_id] = Span(+ begin_entry=span,+ end_entry=None,+ )+ elif json_line["type"] == "end_span":+ end_span = EndSpanModel.parse_obj(json_line)+ span = spans_by_id[end_span.span_id]+ span.end_entry = end_span+ for span in spans_by_id.values():+ sequence_id = (+ span.begin_entry.action_sequence_id+ if span.begin_entry+ else span.end_entry.action_sequence_id+ )+ step = (+ 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)+ # filter out all the non-null start steps+ return [+ Step(+ step_start_log=value.step_start_log,+ step_end_log=value.step_end_log,+ spans=[Span(**span.dict()) for span in value.spans if span.begin_entry is not None],+ )+ for key, value in sorted(steps_by_sequence_id.items())+ if value.step_start_log is not None+ ]+++class StepWithMinimalData(Step):+ step_start_log: Optional[BeginEntryModel]+class ApplicationLogs(pydantic.BaseModel):"""Application logs are purely flat --@@ -65,3 +128,20 @@ class ApplicationLogs(pydantic.BaseModel):steps: List[Step]parent_pointer: Optional[PointerModel] = Nonespawning_parent_pointer: Optional[PointerModel] = None+++class IndexingJob(pydantic.BaseModel):+ """Generic link for indexing job -- can be exposed in 'admin mode' in the UI"""++ id: int+ start_time: datetime.datetime+ end_time: Optional[datetime.datetime]+ status: str+ records_processed: int+ metadata: Dict[str, Any]+++class BackendSpec(pydantic.BaseModel):+ """Generic link for indexing job -- can be exposed in 'admin mode' in the UI"""++ indexing: bool