Skip to content
Open
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
6 changes: 6 additions & 0 deletions cloud_export_to_parquet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

This is an example workflow to convert exported file from proto to parquet file. The workflow is an hourly schedule.

The sample reads both `ExportedExecutions` and legacy `WorkflowExecutions` files. Each
input file produces one Parquet file with one row per workflow history event and one
row per standalone activity execution. Standalone activity rows include `ActivityId`,
`RunId`, and flattened activity details in `activity_` columns. When present,
`activity_callbacks` contains a JSON string for the callback list.

Please make sure your python version is 3.10 or above. For this sample, run:

uv sync --group=cloud-export-to-parquet
Expand Down
86 changes: 45 additions & 41 deletions cloud_export_to_parquet/data_trans_activities.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import boto3
import pandas as pd
import temporalio.api.export.v1 as export
from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import MessageToDict
from temporalio import activity


Expand Down Expand Up @@ -57,53 +57,57 @@ def data_trans_and_land(activity_input: DataTransAndLandActivityInput) -> str:

def get_data_from_object_key(
bucket_name: str, object_key: str
) -> export.WorkflowExecutions:
) -> export.ExportedExecutions:
"""Function that get object by key."""
v = export.WorkflowExecutions()

s3 = boto3.client("s3")
try:
data = s3.get_object(Bucket=bucket_name, Key=object_key)["Body"].read()
except Exception as e:
activity.logger.error(f"Error reading object: {e}")
raise e
v.ParseFromString(data)
return v


def convert_proto_to_parquet_flatten(wfs: export.WorkflowExecutions) -> pd.DataFrame:
"""Function that convert flatten proto data to parquet."""
dfs = []
for wf in wfs.items:
start_attributes = wf.history.events[
0
].workflow_execution_started_event_attributes
histories = wf.history
json_str = MessageToJson(histories)
row = {
"WorkflowID": start_attributes.workflow_id,
"RunID": start_attributes.original_execution_run_id,
"Histories": json.loads(json_str),
}
dfs.append(pd.DataFrame([row]))
df = pd.concat(dfs, ignore_index=True)
rows_flatten = []
for _, row in df.iterrows():
wf_histories_raw = row["Histories"]["events"]
worfkow_id = row["WorkflowID"]
run_id = row["RunID"]
for history_event in wf_histories_raw:
row_flatten = pd.json_normalize(history_event, sep="_")
skip_name = ["payloads", "."]
columns_to_drop = [
col for col in row_flatten.columns for skip in skip_name if skip in col
]
row_flatten.drop(columns_to_drop, axis=1, inplace=True)
row_flatten.insert(0, "WorkflowId", worfkow_id)
row_flatten.insert(1, "RunId", run_id)
rows_flatten.append(row_flatten)
df_flatten = pd.concat(rows_flatten, ignore_index=True)
return df_flatten
# Legacy WorkflowExecutions.items uses the same protobuf field as workflows.
return export.ExportedExecutions.FromString(data)


def convert_proto_to_parquet_flatten(
executions: export.ExportedExecutions,
) -> pd.DataFrame:
"""Flatten one row per workflow history event or standalone activity execution."""
rows = []
for workflow in executions.workflows:
events = workflow.history.events
start_attributes = events[0].workflow_execution_started_event_attributes
for event in events:
rows.append(
{
"WorkflowId": start_attributes.workflow_id,
"RunId": start_attributes.original_execution_run_id,
**MessageToDict(event),
}
)

for activity_execution in executions.activities:
response = activity_execution.activity
details = MessageToDict(response)
if "callbacks" in details:
# Callback triggers can contain empty protobuf messages that Parquet cannot store as structs.
details["callbacks"] = json.dumps(details["callbacks"])
rows.append(
{
"ActivityId": response.info.activity_id,
"RunId": response.info.run_id or response.run_id,
"activity": details,
}
)

if not rows:
raise ValueError("Export contains no workflow history events or activities")

flattened = pd.json_normalize(rows, sep="_")
columns_to_drop = [
column for column in flattened.columns if "payloads" in column or "." in column
]
return flattened.drop(columns=columns_to_drop)


def save_to_sink(data: pd.DataFrame, s3_bucket: str, write_path: str) -> str:
Expand Down
Loading