skrawcz commented on code in PR #666:
URL: https://github.com/apache/burr/pull/666#discussion_r2937801076
##########
burr/tracking/server/backend.py:
##########
@@ -162,6 +162,31 @@ def snapshot_interval_milliseconds(self) -> Optional[int]:
pass
+class EventDrivenBackendMixin(abc.ABC):
+ """Mixin for backends that support event-driven updates via SQS.
Review Comment:
**Blocker — Vendor neutrality:** This mixin is part of the **core backend
abstraction layer**, but it leaks AWS-specific concepts. The class name is
fine, but `start_sqs_consumer` names a specific AWS service, and the docstrings
reference SQS throughout.
For an Apache project, this should be vendor-neutral:
- Rename `start_sqs_consumer()` → `start_event_consumer()`
- Update docstrings to describe generic event-driven updates, not SQS
specifically
- The `is_event_driven()` method name is already good
This would allow a GCP Pub/Sub or Azure Event Grid implementation to use the
same mixin without the naming being misleading.
##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +709,104 @@ async def get_application_logs(
application=graph_data,
)
+ # BIP-0042: Event-driven tracking methods
+ async def _handle_s3_event(self, s3_key: str, event_time:
datetime.datetime) -> None:
+ """Handle a single S3 event notification - index the file immediately.
+
+ :param s3_key: The S3 object key from the event
+ :param event_time: When the event occurred
+ """
+ try:
+ data_file = DataFile.from_path(s3_key, created_date=event_time)
+ # Path structure:
data/{project}/yyyy/mm/dd/hh/minutes/pk/app_id/filename
+ project_name = s3_key.split("/")[1]
+
+ project = await Project.filter(name=project_name).first()
+ if project is None:
+ logger.info(f"Creating project {project_name} from S3 event")
+ project = await Project.create(
+ name=project_name,
+ uri=None,
+ created_at=event_time,
+ indexed_at=event_time,
+ updated_at=event_time,
+ )
+
+ all_applications = await
self._ensure_applications_exist([data_file], project)
+ await self._update_all_applications(all_applications, [data_file])
+ await self.update_log_files([data_file], all_applications)
+
+ logger.info(f"Indexed S3 event: {s3_key}")
+ except Exception as e:
+ logger.error(f"Failed to handle S3 event {s3_key}: {e}")
+
+ async def start_sqs_consumer(self) -> None:
+ """Start the SQS consumer for event-driven tracking.
+
+ BIP-0042: This method runs indefinitely, processing S3 event
notifications
+ from the configured SQS queue. It handles both EventBridge and direct
S3
+ notification formats.
+ """
+ if self._tracking_mode != "SQS" or not self._sqs_queue_url:
+ logger.info("SQS consumer not configured, skipping")
+ return
+
+ logger.info(f"Starting SQS consumer for queue: {self._sqs_queue_url}")
+
+ async with self._session.create_client("sqs",
region_name=self._sqs_region) as sqs_client:
+ while True:
+ try:
Review Comment:
**High — No graceful shutdown:** This `while True` loop runs as a
fire-and-forget `asyncio.create_task()` (see `run.py`). When the server shuts
down, this task will be cancelled, but `asyncio.CancelledError` is not handled.
The outer `except Exception` won't catch it (in Python 3.9+, `CancelledError`
inherits from `BaseException`).
Recommendation:
```python
try:
while True:
...
except asyncio.CancelledError:
logger.info("SQS consumer shutting down")
raise
```
Also, the task reference in `run.py` is not stored anywhere — it could be
garbage collected. Store it and cancel it in the shutdown path of the lifespan
context manager.
##########
burr/tracking/server/s3/backend.py:
##########
@@ -140,6 +166,12 @@ class S3Settings(BurrSettings):
snapshot_interval_milliseconds: int = 3_600_000
load_snapshot_on_start: bool = True
prior_snapshots_to_keep: int = 5
+ # BIP-0042: Event-driven tracking settings
+ tracking_mode: str = "POLLING" # "POLLING" or "SQS" - POLLING is default
for backward compatibility
+ sqs_queue_url: Optional[str] = None
Review Comment:
**Medium — Use an Enum instead of magic strings:** `"POLLING"` and `"SQS"`
are magic strings that are error-prone (e.g., typo `"Polling"` would silently
fall through). Consider:
```python
from enum import Enum
class TrackingMode(str, Enum):
POLLING = "POLLING"
EVENT_DRIVEN = "EVENT_DRIVEN"
```
Also, `"SQS"` is an AWS-specific name. Since this setting is in the S3
backend (already AWS-specific), it's less critical than the core mixin, but
`"EVENT_DRIVEN"` would still be more descriptive of the *behavior* rather than
the *implementation*.
##########
terraform/.terraform.lock.hcl:
##########
@@ -0,0 +1,45 @@
+# This file is maintained automatically by "terraform init".
+# Manual edits may be lost in future updates.
Review Comment:
**Blocker — Should not be committed:** `.terraform.lock.hcl` is a generated
file specific to the contributor's Terraform version and platform. It should be
added to `.gitignore` (or the terraform `.gitignore`), not committed to the
repo.
More broadly: the entire `terraform/` directory (including `dev.tfvars`,
`prod.tfvars` with hardcoded `us-east-1`) should live under
`examples/deployment/aws/` or `contrib/aws/` rather than at the repo root. Burr
is a Python framework library — shipping infrastructure-as-code at the top
level makes the project appear AWS-first rather than vendor-neutral.
##########
burr/tracking/server/run.py:
##########
@@ -127,13 +128,18 @@ async def save_snapshot():
@asynccontextmanager
async def lifespan(app: FastAPI):
+ import asyncio
+
# Download if it does it
# For now we do this before the lifespan
await download_snapshot()
# No yield from allowed
await backend.lifespan(app).__anext__()
await sync_index() # this will trigger the repeat every N seconds
await save_snapshot() # this will trigger the repeat every N seconds
+ # BIP-0042: Start SQS consumer for event-driven tracking when configured
+ if isinstance(backend, EventDrivenBackendMixin) and
backend.is_event_driven():
+ asyncio.create_task(backend.start_sqs_consumer())
global initialized
Review Comment:
**High — Task reference not stored:** `asyncio.create_task()` returns a task
reference that isn't assigned to anything. This means:
1. The task could be garbage collected
2. There's no way to cancel it during shutdown
3. Exceptions in the task will be silently lost
Store the task and cancel it in the shutdown path:
```python
sqs_task = None
if isinstance(backend, EventDrivenBackendMixin) and
backend.is_event_driven():
sqs_task = asyncio.create_task(backend.start_event_consumer())
yield
if sqs_task:
sqs_task.cancel()
try:
await sqs_task
except asyncio.CancelledError:
pass
```
Also, `import asyncio` should be a top-level import, not inside the function.
##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +709,104 @@ async def get_application_logs(
application=graph_data,
)
+ # BIP-0042: Event-driven tracking methods
+ async def _handle_s3_event(self, s3_key: str, event_time:
datetime.datetime) -> None:
+ """Handle a single S3 event notification - index the file immediately.
+
+ :param s3_key: The S3 object key from the event
+ :param event_time: When the event occurred
+ """
+ try:
+ data_file = DataFile.from_path(s3_key, created_date=event_time)
+ # Path structure:
data/{project}/yyyy/mm/dd/hh/minutes/pk/app_id/filename
+ project_name = s3_key.split("/")[1]
+
+ project = await Project.filter(name=project_name).first()
+ if project is None:
+ logger.info(f"Creating project {project_name} from S3 event")
+ project = await Project.create(
+ name=project_name,
+ uri=None,
+ created_at=event_time,
+ indexed_at=event_time,
+ updated_at=event_time,
+ )
+
+ all_applications = await
self._ensure_applications_exist([data_file], project)
+ await self._update_all_applications(all_applications, [data_file])
+ await self.update_log_files([data_file], all_applications)
+
+ logger.info(f"Indexed S3 event: {s3_key}")
+ except Exception as e:
+ logger.error(f"Failed to handle S3 event {s3_key}: {e}")
+
Review Comment:
**Medium — Silent error swallowing:** Catching `Exception` and only logging
means data loss can go completely unnoticed. If indexing fails for a file, that
tracking data is permanently skipped.
Consider either:
1. Re-raising after logging (letting the message go back to SQS for retry,
eventually to DLQ)
2. At minimum, emitting a metric/counter so operators can alert on indexing
failures
Currently the message gets deleted from SQS even if `_handle_s3_event` fails
(the `delete_message` call is outside this try/except), so failed events are
lost forever.
##########
burr/integrations/bedrock.py:
##########
@@ -0,0 +1,227 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Amazon Bedrock integration for Burr.
+
+BIP-0042: This module provides Action classes for invoking Amazon Bedrock
models
+within Burr applications.
+
+Example usage:
+ from burr.integrations.bedrock import BedrockAction
+
+ def prompt_mapper(state):
+ return {
+ "messages": [{"role": "user", "content": state["user_input"]}],
+ "system": [{"text": "You are a helpful assistant."}],
+ }
+
+ action = BedrockAction(
+ model_id="anthropic.claude-3-sonnet-20240229-v1:0",
+ input_mapper=prompt_mapper,
+ reads=["user_input"],
+ writes=["response"],
+ )
+"""
+
+import logging
+from typing import Any, Dict, Generator, List, Optional, Protocol, Tuple
+
+from burr.core.action import SingleStepAction, StreamingAction
+from burr.core.state import State
+from burr.integrations.base import require_plugin
+
+logger = logging.getLogger(__name__)
+
+try:
+ import boto3
+ from botocore.config import Config
+ from botocore.exceptions import ClientError
+except ImportError as e:
+ require_plugin(e, "bedrock")
+
+
+class StateToPromptMapper(Protocol):
+ """Protocol for mapping Burr state to Bedrock prompt format."""
+
+ def __call__(self, state: State) -> Dict[str, Any]:
+ ...
+
+
+class BedrockAction(SingleStepAction):
+ """Action that invokes Amazon Bedrock models using the Converse API."""
+
+ def __init__(
+ self,
+ model_id: str,
+ input_mapper: StateToPromptMapper,
+ reads: List[str],
+ writes: List[str],
+ name: str = "bedrock_invoke",
+ region: Optional[str] = None,
+ guardrail_id: Optional[str] = None,
+ guardrail_version: Optional[str] = None,
+ inference_config: Optional[Dict[str, Any]] = None,
+ max_retries: int = 3,
+ ):
+ super().__init__()
+ self._model_id = model_id
+ self._input_mapper = input_mapper
+ self._reads = reads
+ self._writes = writes
+ self._name = name
+ self._region = region
+ self._guardrail_id = guardrail_id
+ self._guardrail_version = guardrail_version or "DRAFT"
+ self._inference_config = inference_config or {"maxTokens": 4096}
+
+ config = Config(retries={"max_attempts": max_retries, "mode":
"adaptive"})
+ self._client = boto3.client("bedrock-runtime", region_name=region,
config=config)
+
Review Comment:
**Medium — Client created at construction time:** The boto3 client is
created eagerly in `__init__`, which means:
1. The action can't be serialized/pickled (relevant for distributed
execution)
2. Testing requires mocking at construction time or having valid AWS
credentials
3. Credentials are captured at construction, not at invocation
Consider lazy client creation (create on first `run_and_update` call) or
accepting a client/session as a parameter for testability.
##########
tests/integrations/test_bip0042_bedrock.py:
##########
@@ -0,0 +1,168 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""BIP-0042: Tests for Bedrock integration."""
+
+import inspect
+
+import pytest
+
+
+class TestBedrockImports:
+ """Test that Bedrock classes can be imported via lazy loading."""
+
+ def test_lazy_import_bedrock_action(self):
+ """Verify BedrockAction can be imported from burr.integrations."""
+ try:
+ from burr.integrations import BedrockAction
+
+ assert BedrockAction is not None
+ except ImportError as e:
+ assert "bedrock" in str(e).lower() or "boto3" in str(e).lower()
Review Comment:
**Medium — Tests are no-ops without boto3:** Every test is wrapped in
`try/except ImportError` with an assertion on the error message. When boto3
isn't installed (which is the case in CI unless explicitly added), all tests
silently pass without testing anything.
Better approaches:
1. Use `pytest.importorskip("boto3")` to clearly skip tests when the
dependency is missing
2. Mock `boto3` for unit tests so they run regardless of whether boto3 is
installed
3. For integration tests that need real AWS, mark them with
`@pytest.mark.integration` and skip in CI
##########
burr/integrations/bedrock.py:
##########
@@ -0,0 +1,227 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+"""Amazon Bedrock integration for Burr.
+
+BIP-0042: This module provides Action classes for invoking Amazon Bedrock
models
+within Burr applications.
+
+Example usage:
+ from burr.integrations.bedrock import BedrockAction
+
+ def prompt_mapper(state):
+ return {
+ "messages": [{"role": "user", "content": state["user_input"]}],
+ "system": [{"text": "You are a helpful assistant."}],
+ }
+
+ action = BedrockAction(
+ model_id="anthropic.claude-3-sonnet-20240229-v1:0",
+ input_mapper=prompt_mapper,
+ reads=["user_input"],
+ writes=["response"],
+ )
+"""
+
+import logging
+from typing import Any, Dict, Generator, List, Optional, Protocol, Tuple
+
+from burr.core.action import SingleStepAction, StreamingAction
+from burr.core.state import State
+from burr.integrations.base import require_plugin
+
+logger = logging.getLogger(__name__)
+
+try:
+ import boto3
+ from botocore.config import Config
+ from botocore.exceptions import ClientError
+except ImportError as e:
+ require_plugin(e, "bedrock")
+
+
+class StateToPromptMapper(Protocol):
+ """Protocol for mapping Burr state to Bedrock prompt format."""
+
+ def __call__(self, state: State) -> Dict[str, Any]:
+ ...
+
+
+class BedrockAction(SingleStepAction):
+ """Action that invokes Amazon Bedrock models using the Converse API."""
+
+ def __init__(
+ self,
+ model_id: str,
+ input_mapper: StateToPromptMapper,
+ reads: List[str],
+ writes: List[str],
+ name: str = "bedrock_invoke",
+ region: Optional[str] = None,
+ guardrail_id: Optional[str] = None,
+ guardrail_version: Optional[str] = None,
+ inference_config: Optional[Dict[str, Any]] = None,
+ max_retries: int = 3,
+ ):
+ super().__init__()
+ self._model_id = model_id
+ self._input_mapper = input_mapper
+ self._reads = reads
+ self._writes = writes
+ self._name = name
+ self._region = region
+ self._guardrail_id = guardrail_id
+ self._guardrail_version = guardrail_version or "DRAFT"
+ self._inference_config = inference_config or {"maxTokens": 4096}
+
+ config = Config(retries={"max_attempts": max_retries, "mode":
"adaptive"})
+ self._client = boto3.client("bedrock-runtime", region_name=region,
config=config)
+
+ @property
+ def reads(self) -> List[str]:
+ return self._reads
+
+ @property
+ def writes(self) -> List[str]:
+ return self._writes
+
+ @property
+ def name(self) -> str:
+ return self._name
+
+ def run_and_update(self, state: State, **run_kwargs) -> Tuple[dict, State]:
+ prompt = self._input_mapper(state)
+
+ request: Dict[str, Any] = {
+ "modelId": self._model_id,
+ "messages": prompt["messages"],
+ "inferenceConfig": self._inference_config,
+ }
+
+ if "system" in prompt:
+ request["system"] = prompt["system"]
+
+ if self._guardrail_id:
+ request["guardrailConfig"] = {
+ "guardrailIdentifier": self._guardrail_id,
+ "guardrailVersion": self._guardrail_version,
+ }
+
+ try:
+ response = self._client.converse(**request)
+ except ClientError as e:
+ logger.error(f"Bedrock API error: {e}")
+ raise
+
+ output_message = response["output"]["message"]
+ content_blocks = output_message.get("content", [])
+ text = content_blocks[0]["text"] if content_blocks else ""
+
+ result: Dict[str, Any] = {
+ "response": text,
+ "usage": response.get("usage", {}),
+ "stop_reason": response.get("stopReason"),
+ }
+
+ updates = {key: result[key] for key in self._writes if key in result}
+ new_state = state.update(**updates)
+
+ return result, new_state
+
+
+class BedrockStreamingAction(StreamingAction):
+ """Streaming variant of BedrockAction using Converse Stream API."""
Review Comment:
**High — Code duplication:** `BedrockStreamingAction` duplicates ~90% of
`BedrockAction`:
- Identical `__init__` (all parameters, client creation, instance variable
assignments)
- Identical `reads`, `writes`, `name` properties
- Identical request-building logic in `stream_run` vs `run_and_update`
Consider extracting a shared base class:
```python
class _BedrockBase:
def __init__(self, model_id, input_mapper, reads, writes, ...):
# shared init
def _build_request(self, state: State) -> Dict[str, Any]:
# shared request building
class BedrockAction(_BedrockBase, SingleStepAction): ...
class BedrockStreamingAction(_BedrockBase, StreamingAction): ...
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]