Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions docs/ml_ops/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,47 @@ using ``IngestionManagerPandas`` directly:
)
manager.run(data_frame=data, target_stores=["OnlineStore"])

**Tracing ingested records to AWS request IDs:**

When you open a support case about a specific record, AWS Support asks for the request ID of the
call that wrote it. Pass ``enable_write_audit=True`` to log one JSON line per record per
``PutRecord`` or ``BatchWriteRecord`` attempt on the ``sagemaker.mlops.feature_store.write_audit``
logger at ``INFO`` level. Each line holds the record identifier, event time, request ID, HTTP status,
per-entry outcome (``accepted``, ``error``, ``unprocessed``, ``request_failed`` or ``unknown``) and
client-side timestamps. Retried attempts each get their own line and request ID. Only the record
identifier and event time are logged, no other feature values. Record identifiers can be sensitive
(for example customer IDs), so handle these logs accordingly.

.. code-block:: python

import logging
from sagemaker.mlops.feature_store import ingest_dataframe

# Route the audit lines wherever your application sends its logs.
logging.basicConfig(level=logging.WARNING)
logging.getLogger("sagemaker.mlops.feature_store.write_audit").setLevel(logging.INFO)

ingest_dataframe(
feature_group_name="customer-features",
data_frame=data,
max_workers=4,
use_batch_write_record=True,
enable_write_audit=True,
)

# Example line:
# {"operation": "BatchWriteRecord", "feature_group_name": "customer-features",
# "record_id": "cust-2", "event_time": "2026-01-01T00:00:00Z", "entry_index": 1,
# "batch_size": 3, "entry_status": "accepted", "attempt": 1, "request_id": "...",
# "http_status": 200, "request_sent_at": "...", "response_received_at": "...", ...}

To turn this on without a code change, set the ``SAGEMAKER_FEATURE_STORE_WRITE_AUDIT=true``
environment variable. When using ``IngestionManagerPandas`` directly, pass
``write_audit_config=WriteAuditConfig(record_identifier_feature_name=..., event_time_feature_name=...)``.
Audit logging is off by default because it writes one line per record. Records that fail before any
request is sent (for example parameter validation), and writes still running after an ingestion
``timeout``, get no audit line.

**Listing records from the OnlineStore:**

Use ``list_records`` to retrieve record identifiers from a FeatureGroup's OnlineStore. Results are
Expand Down
2 changes: 2 additions & 0 deletions sagemaker-mlops/src/sagemaker/mlops/feature_store/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
IngestionError,
IngestionManagerPandas,
)
from sagemaker.mlops.feature_store.write_audit import WriteAuditConfig

__all__ = [
# Resources
Expand Down Expand Up @@ -134,4 +135,5 @@
"JoinComparatorEnum",
"JoinTypeEnum",
"TableType",
"WriteAuditConfig",
]
26 changes: 26 additions & 0 deletions sagemaker-mlops/src/sagemaker/mlops/feature_store/feature_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@
)
from sagemaker.mlops.feature_store.ingestion_manager_pandas import IngestionManagerPandas
from sagemaker.mlops.feature_store.inputs import TargetStoreEnum
from sagemaker.mlops.feature_store.write_audit import (
WriteAuditConfig,
_write_audit_enabled_from_env,
)

from sagemaker.core.utils import unique_name_from_base

Expand Down Expand Up @@ -508,6 +512,7 @@ def ingest_dataframe(
timeout: Union[int, float] = None,
use_batch_write_record: bool = False,
region: str = None,
enable_write_audit: Optional[bool] = None,
):
"""Ingest a pandas DataFrame to a FeatureGroup.

Expand All @@ -526,6 +531,15 @@ def ingest_dataframe(
describe the FeatureGroup and to write the records. If not specified, the
region is resolved by boto3 from the environment (``AWS_DEFAULT_REGION``,
``AWS_REGION``, or the active profile in ``~/.aws/config``). Default: None.
enable_write_audit: If True, log one JSON line per record per PutRecord or
BatchWriteRecord attempt on the ``sagemaker.mlops.feature_store.write_audit``
logger at INFO level, with the record identifier, event time, AWS request ID,
status and timestamps, so a record can be traced to the request that wrote it.
Only the record identifier and event time are logged, no other feature values;
record identifiers can be sensitive, so treat these logs accordingly. If None, the
``SAGEMAKER_FEATURE_STORE_WRITE_AUDIT`` environment variable decides
(``true``/``1``/``yes``/``on`` enables it). Default: None (disabled unless the
environment variable is set).

Returns:
IngestionManagerPandas instance.
Expand Down Expand Up @@ -560,13 +574,25 @@ def ingest_dataframe(
"CollectionType": collection_type,
}

if enable_write_audit is None:
enable_write_audit = _write_audit_enabled_from_env()
write_audit_config = (
WriteAuditConfig(
record_identifier_feature_name=fg.record_identifier_feature_name,
event_time_feature_name=fg.event_time_feature_name,
)
if enable_write_audit
else None
)

manager = IngestionManagerPandas(
feature_group_name=feature_group_name,
feature_definitions=feature_definitions,
max_workers=max_workers,
max_processes=max_processes,
use_batch_write_record=use_batch_write_record,
region=region,
write_audit_config=write_audit_config,
)
manager.run(data_frame=data_frame, wait=wait, timeout=timeout)
return manager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass, field
from multiprocessing import Pool
from typing import Any, Dict, Iterable, List, Union
from typing import Any, Dict, Iterable, List, Optional, Union

import pandas as pd
from pandas import DataFrame
Expand All @@ -18,13 +18,25 @@
from sagemaker.core.shapes import BatchWriteRecordEntry, FeatureValue
from sagemaker.core.utils.utils import Unassigned
from sagemaker.core.telemetry import Feature, _telemetry_emitter
from sagemaker.core.telemetry.telemetry_logging import TelemetryParamType
from sagemaker.mlops.feature_store.write_audit import (
WriteAuditConfig,
_request_id_from_exception,
_write_audit,
)

logger = logging.getLogger(__name__)

# Maximum number of records per BatchWriteRecord API call
BATCH_WRITE_MAX_ENTRIES = 25


def _request_id_suffix(error: BaseException) -> str:
"""Return ``" (request ID: <id>)"`` for errors that carry an AWS request ID, else ``""``."""
request_id = _request_id_from_exception(error)
return f" (request ID: {request_id})" if request_id else ""


class IngestionError(Exception):
"""Exception raised for errors during ingestion.

Expand Down Expand Up @@ -59,6 +71,11 @@ class IngestionManagerPandas:
If None, the region is resolved by boto3 from the environment
(``AWS_DEFAULT_REGION``, ``AWS_REGION``, or the active profile in
``~/.aws/config``).
write_audit_config (WriteAuditConfig): if set, log one JSON line per record per
PutRecord/BatchWriteRecord attempt (record identifier, event time, AWS request
ID, status, timestamps) on the ``sagemaker.mlops.feature_store.write_audit``
logger at INFO level. Only the record identifier and event time are logged, no
other feature values. Default: None (disabled).
"""

feature_group_name: str
Expand All @@ -67,6 +84,7 @@ class IngestionManagerPandas:
max_processes: int = 1
use_batch_write_record: bool = False
region: str = None
write_audit_config: Optional[WriteAuditConfig] = None
_async_result: Any = field(default=None, init=False)
_processing_pool: Pool = field(default=None, init=False)
_failed_indices: List[int] = field(default_factory=list, init=False)
Expand All @@ -80,7 +98,11 @@ def failed_rows(self) -> List[int]:
"""
return self._failed_indices

@_telemetry_emitter(Feature.FEATURE_STORE, "IngestionManagerPandas.run")
@_telemetry_emitter(
Feature.FEATURE_STORE,
"IngestionManagerPandas.run",
telemetry_params=[("write_audit_config", TelemetryParamType.ATTR_EXISTS)],
)
def run(
self,
data_frame: DataFrame,
Expand Down Expand Up @@ -150,34 +172,35 @@ def _run_single_process_single_thread(
"""Ingest utilizing a single process and a single thread."""
logger.info("Started single-threaded ingestion for %d rows", len(data_frame))

if self.use_batch_write_record:
logger.info(
"Using BatchWriteRecord API (batch size=%d). "
"Requires sagemaker:BatchWriteRecord AND sagemaker:PutRecord IAM permissions.",
BATCH_WRITE_MAX_ENTRIES,
)
failed_rows = IngestionManagerPandas._ingest_batch_write(
data_frame=data_frame,
feature_group_name=self.feature_group_name,
feature_definitions=self.feature_definitions,
start_index=0,
end_index=len(data_frame),
target_stores=target_stores,
region=self.region,
)
else:
failed_rows = []
fg = CoreFeatureGroup(feature_group_name=self.feature_group_name)
for row in data_frame.itertuples():
self._ingest_row(
with _write_audit(self.feature_group_name, self.write_audit_config, self.region):
if self.use_batch_write_record:
logger.info(
"Using BatchWriteRecord API (batch size=%d). "
"Requires sagemaker:BatchWriteRecord AND sagemaker:PutRecord IAM permissions.",
BATCH_WRITE_MAX_ENTRIES,
)
failed_rows = IngestionManagerPandas._ingest_batch_write(
data_frame=data_frame,
row=row,
feature_group=fg,
feature_group_name=self.feature_group_name,
feature_definitions=self.feature_definitions,
failed_rows=failed_rows,
start_index=0,
end_index=len(data_frame),
target_stores=target_stores,
region=self.region,
)
else:
failed_rows = []
fg = CoreFeatureGroup(feature_group_name=self.feature_group_name)
for row in data_frame.itertuples():
self._ingest_row(
data_frame=data_frame,
row=row,
feature_group=fg,
feature_definitions=self.feature_definitions,
failed_rows=failed_rows,
target_stores=target_stores,
region=self.region,
)

self._failed_indices = failed_rows
if self._failed_indices:
Expand Down Expand Up @@ -211,6 +234,7 @@ def _run_multi_process(
timeout,
self.use_batch_write_record,
self.region,
self.write_audit_config,
)
)

Expand Down Expand Up @@ -238,46 +262,53 @@ def _run_multi_threaded(
timeout: Union[int, float] = None,
use_batch_write_record: bool = False,
region: str = None,
write_audit_config: Optional[WriteAuditConfig] = None,
) -> List[int]:
"""Start multi-threaded ingestion within a single process."""
"""Start multi-threaded ingestion within a single process.

Runs inside each worker process, so write audit logging (if configured) is set up
here rather than inherited from the parent process.
"""
executor = ThreadPoolExecutor(max_workers=max_workers)
batch_size = math.ceil(data_frame.shape[0] / max_workers)

futures = {}
for i in range(max_workers):
start_index = min(i * batch_size, data_frame.shape[0])
end_index = min(i * batch_size + batch_size, data_frame.shape[0])
if use_batch_write_record:
future = executor.submit(
IngestionManagerPandas._ingest_batch_write,
data_frame=data_frame,
feature_group_name=feature_group_name,
feature_definitions=feature_definitions,
start_index=start_index,
end_index=end_index,
target_stores=target_stores,
region=region,
)
else:
future = executor.submit(
IngestionManagerPandas._ingest_single_batch,
data_frame=data_frame,
feature_group_name=feature_group_name,
feature_definitions=feature_definitions,
start_index=start_index,
end_index=end_index,
target_stores=target_stores,
region=region,
)
futures[future] = (start_index + row_offset, end_index + row_offset)
# Writes still running after a timeout are not audited (see write_audit module docs).
with _write_audit(feature_group_name, write_audit_config, region):
futures = {}
for i in range(max_workers):
start_index = min(i * batch_size, data_frame.shape[0])
end_index = min(i * batch_size + batch_size, data_frame.shape[0])
if use_batch_write_record:
future = executor.submit(
IngestionManagerPandas._ingest_batch_write,
data_frame=data_frame,
feature_group_name=feature_group_name,
feature_definitions=feature_definitions,
start_index=start_index,
end_index=end_index,
target_stores=target_stores,
region=region,
)
else:
future = executor.submit(
IngestionManagerPandas._ingest_single_batch,
data_frame=data_frame,
feature_group_name=feature_group_name,
feature_definitions=feature_definitions,
start_index=start_index,
end_index=end_index,
target_stores=target_stores,
region=region,
)
futures[future] = (start_index + row_offset, end_index + row_offset)

failed_indices = []
for future in as_completed(futures, timeout=timeout):
start, end = futures[future]
failed_rows = future.result()
if not failed_rows:
logger.info("Successfully ingested row %d to %d", start, end)
failed_indices.extend(failed_rows)
failed_indices = []
for future in as_completed(futures, timeout=timeout):
start, end = futures[future]
failed_rows = future.result()
if not failed_rows:
logger.info("Successfully ingested row %d to %d", start, end)
failed_indices.extend(failed_rows)

executor.shutdown(wait=False)
return failed_indices
Expand Down Expand Up @@ -358,7 +389,7 @@ def _ingest_row(
)

except Exception as e:
logger.error("Failed to ingest row %d: %s", row[0], e)
logger.error("Failed to ingest row %d%s: %s", row[0], _request_id_suffix(e), e)
failed_rows.append(row[0])

@staticmethod
Expand Down Expand Up @@ -553,8 +584,9 @@ def _ingest_batch_write(

except Exception as e:
logger.error(
"BatchWriteRecord call failed for batch starting at row %d: %s",
"BatchWriteRecord call failed for batch starting at row %d%s: %s",
row_indices[0] if row_indices else start_index,
_request_id_suffix(e),
e,
)
failed_rows.extend(row_indices)
Expand Down
Loading
Loading