andreahlert commented on code in PR #677:
URL: https://github.com/apache/burr/pull/677#discussion_r2983015748


##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +736,114 @@ 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("Creating project %s from S3 event", project_name)
+                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("Indexed S3 event: %s", s3_key)
+        except Exception as e:
+            logger.error("Failed to handle S3 event %s: %s", s3_key, e)
+            raise  # Re-raise so message stays in queue for retry / DLQ
+
+    async def start_event_consumer(self) -> None:
+        """Start the event consumer for event-driven tracking.
+
+        Runs indefinitely, processing S3 event notifications from the 
configured
+        message queue. Handles both EventBridge and direct S3 notification 
formats.
+        """
+        if self._tracking_mode != TrackingMode.EVENT_DRIVEN or not 
self._sqs_queue_url:
+            logger.info("Event consumer not configured, skipping")
+            return
+
+        logger.info("Starting event consumer for queue: %s", 
self._sqs_queue_url)
+
+        async with self._session.create_client("sqs", 
region_name=self._sqs_region) as sqs_client:
+            try:
+                while True:
+                    try:
+                        response = await sqs_client.receive_message(
+                            QueueUrl=self._sqs_queue_url,
+                            MaxNumberOfMessages=10,
+                            WaitTimeSeconds=self._sqs_wait_time_seconds,
+                            VisibilityTimeout=300,
+                        )
+
+                        messages = response.get("Messages", [])
+                        for message in messages:
+                            try:
+                                body = json.loads(message["Body"])
+                                s3_key = None
+                                event_time = None
+
+                                # Handle EventBridge wrapped S3 events (one 
event per message)
+                                if "detail" in body:
+                                    s3_keys_with_times = [
+                                        (
+                                            body["detail"]["object"]["key"],
+                                            datetime.datetime.fromisoformat(
+                                                body["time"].replace("Z", 
"+00:00")
+                                            ),
+                                        )
+                                    ]
+                                elif "Records" in body:
+                                    s3_keys_with_times = [
+                                        (
+                                            record["s3"]["object"]["key"],
+                                            datetime.datetime.fromisoformat(
+                                                
record["eventTime"].replace("Z", "+00:00")
+                                            ),
+                                        )
+                                        for record in body["Records"]
+                                    ]
+                                else:
+                                    logger.warning("Unknown message format: 
%s", body)
+                                    continue
+
+                                for s3_key, event_time in s3_keys_with_times:
+                                    if s3_key and s3_key.endswith(".jsonl"):
+                                        await self._handle_s3_event(s3_key, 
event_time)
+
+                                await sqs_client.delete_message(

Review Comment:
   nit: `s3_key = None` and `event_time = None` are dead. They're assigned here 
but never read, the actual values come from `s3_keys_with_times` on line 855.



##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +736,114 @@ 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("Creating project %s from S3 event", project_name)
+                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("Indexed S3 event: %s", s3_key)
+        except Exception as e:
+            logger.error("Failed to handle S3 event %s: %s", s3_key, e)
+            raise  # Re-raise so message stays in queue for retry / DLQ
+
+    async def start_event_consumer(self) -> None:
+        """Start the event consumer for event-driven tracking.
+
+        Runs indefinitely, processing S3 event notifications from the 
configured
+        message queue. Handles both EventBridge and direct S3 notification 
formats.
+        """
+        if self._tracking_mode != TrackingMode.EVENT_DRIVEN or not 
self._sqs_queue_url:
+            logger.info("Event consumer not configured, skipping")
+            return
+
+        logger.info("Starting event consumer for queue: %s", 
self._sqs_queue_url)
+
+        async with self._session.create_client("sqs", 
region_name=self._sqs_region) as sqs_client:
+            try:
+                while True:
+                    try:
+                        response = await sqs_client.receive_message(
+                            QueueUrl=self._sqs_queue_url,
+                            MaxNumberOfMessages=10,
+                            WaitTimeSeconds=self._sqs_wait_time_seconds,
+                            VisibilityTimeout=300,
+                        )
+
+                        messages = response.get("Messages", [])
+                        for message in messages:
+                            try:
+                                body = json.loads(message["Body"])
+                                s3_key = None
+                                event_time = None
+
+                                # Handle EventBridge wrapped S3 events (one 
event per message)
+                                if "detail" in body:
+                                    s3_keys_with_times = [
+                                        (
+                                            body["detail"]["object"]["key"],
+                                            datetime.datetime.fromisoformat(
+                                                body["time"].replace("Z", 
"+00:00")
+                                            ),
+                                        )
+                                    ]
+                                elif "Records" in body:
+                                    s3_keys_with_times = [
+                                        (
+                                            record["s3"]["object"]["key"],
+                                            datetime.datetime.fromisoformat(
+                                                
record["eventTime"].replace("Z", "+00:00")
+                                            ),
+                                        )
+                                        for record in body["Records"]
+                                    ]
+                                else:
+                                    logger.warning("Unknown message format: 
%s", body)
+                                    continue
+
+                                for s3_key, event_time in s3_keys_with_times:
+                                    if s3_key and s3_key.endswith(".jsonl"):
+                                        await self._handle_s3_event(s3_key, 
event_time)
+
+                                await sqs_client.delete_message(
+                                    QueueUrl=self._sqs_queue_url,
+                                    ReceiptHandle=message["ReceiptHandle"],
+                                )
+                            except Exception as e:
+                                logger.error("Failed to process SQS message: 
%s", e)
+
+                    except Exception as e:
+                        logger.error("Event consumer error: %s", e)
+                        await asyncio.sleep(5)
+            except asyncio.CancelledError:
+                logger.info("Event consumer shutting down")
+                raise
+
+    def is_event_driven(self) -> bool:
+        """Check if this backend is configured for event-driven updates."""
+        return self._tracking_mode == TrackingMode.EVENT_DRIVEN and 
self._sqs_queue_url is not None
+
     async def indexing_jobs(
         self, offset: int = 0, limit: int = 100, filter_empty: bool = True
     ) -> Sequence[schema.IndexingJob]:

Review Comment:
   blocker: if `_handle_s3_event` raises on the Nth record of a multi-record 
SQS message, records 0..N-1 get re-indexed on retry with no dedup. Make 
`_handle_s3_event` idempotent (check if `s3_path` exists in `LogFile` before 
insert).



##########
burr/integrations/bedrock.py:
##########
@@ -0,0 +1,261 @@
+# 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.
+
+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."}],
+        }
+
+    # With default client (created lazily on first use):
+    action = BedrockAction(
+        model_id="anthropic.claude-3-sonnet-20240229-v1:0",
+        input_mapper=prompt_mapper,
+        reads=["user_input"],
+        writes=["response"],
+    )
+
+    # With injected client (for tests or distributed execution):
+    # client = boto3.client("bedrock-runtime", region_name="us-east-1")
+    # action = BedrockAction(..., client=client)
+"""
+
+import logging
+from typing import Any, Generator, Optional, Protocol
+
+from burr.core.action import SingleStepAction, StreamingAction
+from burr.core.state import State
+from burr.integrations.base import require_plugin
+
+logger = logging.getLogger(__name__)
+
+# Type for injected Bedrock client (avoids boto3 import at type-check time)
+BedrockClient = Any
+
+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,
+        client: Optional[BedrockClient] = None,
+    ):
+        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"

Review Comment:
   `guardrail_version or "DRAFT"` silently defaults to DRAFT when only 
`guardrail_id` is set. Is that intentional? Feels risky for prod, someone could 
set a guardrail ID and not realize they're running against an unpublished 
draft. Same at line 191.



##########
burr/integrations/bedrock.py:
##########
@@ -0,0 +1,261 @@
+# 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.
+
+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."}],
+        }
+
+    # With default client (created lazily on first use):
+    action = BedrockAction(
+        model_id="anthropic.claude-3-sonnet-20240229-v1:0",
+        input_mapper=prompt_mapper,
+        reads=["user_input"],
+        writes=["response"],
+    )
+
+    # With injected client (for tests or distributed execution):
+    # client = boto3.client("bedrock-runtime", region_name="us-east-1")
+    # action = BedrockAction(..., client=client)
+"""
+
+import logging
+from typing import Any, Generator, Optional, Protocol
+
+from burr.core.action import SingleStepAction, StreamingAction
+from burr.core.state import State
+from burr.integrations.base import require_plugin
+
+logger = logging.getLogger(__name__)
+
+# Type for injected Bedrock client (avoids boto3 import at type-check time)
+BedrockClient = Any
+
+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,
+        client: Optional[BedrockClient] = None,
+    ):
+        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}

Review Comment:
   just a small nit: `inference_config or {"maxTokens": 4096}` means 
`inference_config={}` gives you the default because empty dict is falsy. Use 
`if inference_config is not None` if you want to allow empty configs.



##########
.github/workflows/python-package.yml:
##########
@@ -69,7 +69,7 @@ jobs:
 
       - name: Install dependencies
         run: |
-          python -m pip install -e ".[tests,tracking-client,graphviz]"
+          python -m pip install -e 
".[tests,tracking-client,graphviz,tracking-server-s3]"

Review Comment:
   `tracking-server-s3` in the main CI install and `apache-burr[bedrock]` in 
`[tests]` (pyproject.toml:101) means every contributor now pulls `boto3`, 
`aiobotocore`, `tortoise-orm`, `aerich` even for unrelated PRs. Keep AWS deps 
in a separate CI job and test group, like the existing `test-persister-dbs` 
pattern.



##########
burr/integrations/bedrock.py:
##########
@@ -0,0 +1,261 @@
+# 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.
+
+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."}],
+        }
+
+    # With default client (created lazily on first use):
+    action = BedrockAction(
+        model_id="anthropic.claude-3-sonnet-20240229-v1:0",
+        input_mapper=prompt_mapper,
+        reads=["user_input"],
+        writes=["response"],
+    )
+
+    # With injected client (for tests or distributed execution):
+    # client = boto3.client("bedrock-runtime", region_name="us-east-1")
+    # action = BedrockAction(..., client=client)
+"""
+
+import logging
+from typing import Any, Generator, Optional, Protocol
+
+from burr.core.action import SingleStepAction, StreamingAction
+from burr.core.state import State
+from burr.integrations.base import require_plugin
+
+logger = logging.getLogger(__name__)
+
+# Type for injected Bedrock client (avoids boto3 import at type-check time)
+BedrockClient = Any
+
+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,
+        client: Optional[BedrockClient] = None,
+    ):
+        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}
+        self._max_retries = max_retries
+        self._client = client
+
+    def _get_client(self) -> BedrockClient:
+        """Return the Bedrock client, creating lazily if not injected."""
+        if self._client is not None:
+            return self._client
+        config = Config(
+            retries={"max_attempts": self._max_retries, "mode": "adaptive"}
+        )
+        self._client = boto3.client(
+            "bedrock-runtime", region_name=self._region, config=config
+        )
+        return self._client
+
+    @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._get_client().converse(**request)
+        except ClientError as e:
+            logger.error("Bedrock API error: %s", 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):

Review Comment:
   IMHO `BedrockStreamingAction` is a copy-paste of `BedrockAction`. 
`__init__`, `_get_client`, `reads/writes/name` properties are all identical, 
~70 lines duplicated. Pull them into a `_BedrockBase` and let each subclass 
just implement its execution method.



##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +736,114 @@ 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("Creating project %s from S3 event", project_name)
+                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("Indexed S3 event: %s", s3_key)
+        except Exception as e:
+            logger.error("Failed to handle S3 event %s: %s", s3_key, e)
+            raise  # Re-raise so message stays in queue for retry / DLQ
+
+    async def start_event_consumer(self) -> None:
+        """Start the event consumer for event-driven tracking.
+
+        Runs indefinitely, processing S3 event notifications from the 
configured
+        message queue. Handles both EventBridge and direct S3 notification 
formats.
+        """
+        if self._tracking_mode != TrackingMode.EVENT_DRIVEN or not 
self._sqs_queue_url:
+            logger.info("Event consumer not configured, skipping")
+            return
+
+        logger.info("Starting event consumer for queue: %s", 
self._sqs_queue_url)
+
+        async with self._session.create_client("sqs", 
region_name=self._sqs_region) as sqs_client:
+            try:
+                while True:
+                    try:
+                        response = await sqs_client.receive_message(
+                            QueueUrl=self._sqs_queue_url,
+                            MaxNumberOfMessages=10,
+                            WaitTimeSeconds=self._sqs_wait_time_seconds,

Review Comment:
   Nice, auto-creating the project from the S3 event is a good call for the 
event-driven flow.



##########
examples/deployment/aws/terraform/modules/sqs/main.tf:
##########
@@ -0,0 +1,44 @@
+# 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.
+
+resource "aws_sqs_queue" "main" {
+  name                       = var.queue_name
+  message_retention_seconds  = var.message_retention_seconds
+  visibility_timeout_seconds = var.visibility_timeout_seconds
+  receive_wait_time_seconds  = var.receive_wait_time_seconds
+
+  tags = merge(var.tags, {
+    Name = var.queue_name
+  })
+}
+
+resource "aws_sqs_queue" "dlq" {
+  name                      = "${var.queue_name}-dlq"
+  message_retention_seconds = var.dlq_message_retention_seconds
+
+  tags = merge(var.tags, {
+    Name = "${var.queue_name}-dlq"
+  })
+}
+
+resource "aws_sqs_queue_redrive_policy" "main" {

Review Comment:
   +1 on the DLQ + redrive policy setup, clean separation into modules.



##########
burr/tracking/server/s3/backend.py:
##########
@@ -656,6 +736,114 @@ 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("Creating project %s from S3 event", project_name)
+                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("Indexed S3 event: %s", s3_key)
+        except Exception as e:
+            logger.error("Failed to handle S3 event %s: %s", s3_key, e)
+            raise  # Re-raise so message stays in queue for retry / DLQ
+
+    async def start_event_consumer(self) -> None:
+        """Start the event consumer for event-driven tracking.
+
+        Runs indefinitely, processing S3 event notifications from the 
configured
+        message queue. Handles both EventBridge and direct S3 notification 
formats.
+        """
+        if self._tracking_mode != TrackingMode.EVENT_DRIVEN or not 
self._sqs_queue_url:
+            logger.info("Event consumer not configured, skipping")
+            return

Review Comment:
   Is the `data/{project}/...` prefix structure guaranteed for all event 
sources? WDYT about getting the project name from `data_file.prefix` (you 
already parse it via `DataFile.from_path` one line above) instead of a raw 
split?



-- 
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]

Reply via email to