Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[core][state][no_early_kickoff] Add "humanify" feature to StateSchema #35059

Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
24158f2
add new module
ProjectsByJackHe Feb 27, 2023
b323ff8
create human readable class
ProjectsByJackHe Feb 27, 2023
6dd01e2
lint
ProjectsByJackHe Feb 27, 2023
135d804
add humanify()
ProjectsByJackHe Apr 3, 2023
310e0ab
remove human readable subclass
ProjectsByJackHe Apr 3, 2023
676d4e9
remove human readable subclass in state_cli
ProjectsByJackHe Apr 3, 2023
a2284e5
move humanify logic into base class
ProjectsByJackHe Apr 17, 2023
86f67ab
merge upstream
ProjectsByJackHe Apr 30, 2023
f8f82a5
resolve merge conflicts
ProjectsByJackHe Apr 30, 2023
b3c5488
lint state_cli
ProjectsByJackHe Apr 30, 2023
0b8c88e
add more default format functions and refactor state_column()
ProjectsByJackHe Apr 30, 2023
f7b25fb
run unit tests, add event humanifier
ProjectsByJackHe May 1, 2023
d21cba6
merge common.py
ProjectsByJackHe May 1, 2023
a05f225
revert buggy changes
ProjectsByJackHe May 1, 2023
e93dd82
add unit testing
ProjectsByJackHe May 3, 2023
226bde0
add memory function
ProjectsByJackHe May 4, 2023
049ea07
remove complex regex unit test
ProjectsByJackHe May 4, 2023
f810bbb
revert rename of local variable
ProjectsByJackHe May 4, 2023
21c3290
remove requiring all details
ProjectsByJackHe May 6, 2023
31246b9
add more default converter functions for node resource
ProjectsByJackHe May 6, 2023
75a06f6
add more default format_fn
ProjectsByJackHe May 6, 2023
1b678b4
remove is_valid_state
ProjectsByJackHe May 6, 2023
54cd9a5
Merge remote-tracking branch 'upstream/master' into jackhe/readable-s…
ProjectsByJackHe May 6, 2023
0c4b566
avoid unspecified behavior
ProjectsByJackHe May 6, 2023
3c5a2ee
remove dead code
ProjectsByJackHe May 6, 2023
8ae3ff9
ensure inputs are not none
ProjectsByJackHe May 7, 2023
92269b9
use format_fn=
ProjectsByJackHe May 8, 2023
7a185fc
lint
ProjectsByJackHe May 8, 2023
8b8eb35
remove unused code
ProjectsByJackHe May 8, 2023
b629102
remove unused code
ProjectsByJackHe May 8, 2023
f58d757
Merge branch 'jackhe/readable-state-api_schema-try3' of https://githu…
ProjectsByJackHe May 8, 2023
ff592dc
add try except, truncate memory
ProjectsByJackHe May 9, 2023
3ba5046
update unit tests, add non-null checks
ProjectsByJackHe May 13, 2023
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
84 changes: 79 additions & 5 deletions python/ray/experimental/state/common.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import dataclasses
import datetime
import json
import logging
import sys
Expand Down Expand Up @@ -156,14 +158,15 @@ def state_column(*, filterable: bool, detail: bool = False, **kwargs):
kwargs: The same kwargs for the `dataclasses.field` function.
"""
m = {"detail": detail, "filterable": filterable}

# Default for detail field is None since it could be missing.
if detail and "default" not in kwargs:
kwargs["default"] = None

if "metadata" in kwargs:
# Metadata explicitly specified, so add detail and filterable if missing.
kwargs["metadata"].update(m)
else:
# Metadata not explicitly specified, so add it.
kwargs["metadata"] = m
return field(**kwargs)

Expand Down Expand Up @@ -193,8 +196,36 @@ class State(StateSchema):
# Returns {"column_a", "column_b"}
s.columns()
```

In addition, the schema also provides a humanify abstract method to
convert the state object into something human readable, ready for printing.

Subclasses should override this method, providing logic to convert its own fields
to something human readable, packaged and returned in a dict.

Each field that wants to be humanified should include a 'format_fn' key in its
metadata dictionary.
"""

@classmethod
def humanify(cls, state: dict) -> dict:
"""Convert the given state object into something human readable."""
if not cls.is_valid_state(state):
ProjectsByJackHe marked this conversation as resolved.
Show resolved Hide resolved
return state # return the original state
for f in fields(cls):
if f.metadata.get("format_fn") is not None and state[f.name] is not None:
state[f.name] = f.metadata["format_fn"](state[f.name])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: let' also add a try...except around this and logger errors instead of failing:

                try:
                    state[f.name] = f.metadata["format_fn"](state[f.name])
                except Exception as e:
                    logger.error(f"Failed to format {f.name}:{state[f.name]} with {e}")

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i found out an issue which raised error due to some of the data not correct, I think let's do best effort here instead of disallowing users to see the outputs.

#35130

Copy link
Contributor Author

@ProjectsByJackHe ProjectsByJackHe May 9, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added the try-except.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just confirming, the issue doesn't have anything to do with this PR? I tried running without the Humanify logic, but still get the incorrect data (year 584556019 for worker_launch_time)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i found out an issue which raised error due to some of the data not correct, I think let's do best effort here instead of disallowing users to see the outputs.

#35130

I am new to this;
By "best effort," what did you have in mind? If there is an error in the format_fn, we just leave the data as is. Where do we disallow users to see the outputs?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: let' also add a try...except around this and logger errors instead of failing:

                try:
                    state[f.name] = f.metadata["format_fn"](state[f.name])
                except Exception as e:
                    logger.error(f"Failed to format {f.name}:{state[f.name]} with {e}")

Also, added a null check to pass state_log unit test.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just confirming, the issue doesn't have anything to do with this PR? I tried running without the Humanify logic, but still get the incorrect data (year 584556019 for worker_launch_time)

Yes, it's not caused by this PR.

return state

@classmethod
def is_valid_state(cls, state: dict) -> bool:
ProjectsByJackHe marked this conversation as resolved.
Show resolved Hide resolved
"""Checks to make sure state has all keys in the current schema class."""
cols = cls.list_columns(detail=True)
for col in cols:
if col not in state:
return False
return True

@classmethod
def list_columns(cls, detail: bool = True) -> List[str]:
"""Return a list of columns."""
Expand Down Expand Up @@ -516,6 +547,35 @@ class ClusterEventState(StateSchema):
custom_fields: Optional[dict] = state_column(filterable=False, detail=True)


class Humanify:
"""A class containing default methods to convert units into a human readable string."""

def timestamp(x: float):
"""Converts miliseconds to a datetime object."""
return str(datetime.datetime.fromtimestamp(x / 1000))

def memory(x: int):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

Copy link
Contributor Author

@ProjectsByJackHe ProjectsByJackHe May 6, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

btw, thanks for reviewing! I got 20/20 for my school's open source assessment :)

"""Converts raw bytes to a human readable memory size."""
if x >= 2**30:
return str(x / (2**30)) + " GiB"
elif x >= 2**20:
return str(x / (2**20)) + " MiB"
elif x >= 2**10:
return str(x / (2**10)) + " KiB"
return str(x) + " B"

def duration(x: int):
"""Converts miliseconds to a human readable duration."""
return str(datetime.timedelta(milliseconds=x))

def events(events: List[dict]):
"""Converts a list of task events into a human readable format."""
for event in events:
rickyyx marked this conversation as resolved.
Show resolved Hide resolved
if "created_ms" in event:
event["created_ms"] = Humanify.timestamp(event["created_ms"])
return events


@dataclass(init=True)
class TaskState(StateSchema):
"""Task State"""
Expand Down Expand Up @@ -571,15 +631,29 @@ class TaskState(StateSchema):
#: The list of events of the given task.
#: Refer to src/ray/protobuf/common.proto for a detailed explanation of the state
#: breakdowns and typical state transition flow.
events: Optional[List[dict]] = state_column(detail=True, filterable=False)
events: Optional[List[dict]] = state_column(
detail=True, filterable=False, metadata={"format_fn": Humanify.events}
)
#: The list of profile events of the given task.
profiling_data: Optional[dict] = state_column(detail=True, filterable=False)
#: The time when the task is created. A Unix timestamp in ms.
creation_time_ms: Optional[int] = state_column(detail=True, filterable=False)
creation_time_ms: Optional[int] = state_column(
detail=True,
filterable=False,
metadata={"format_fn": Humanify.timestamp},
)
#: The time when the task starts to run. A Unix timestamp in ms.
start_time_ms: Optional[int] = state_column(detail=True, filterable=False)
start_time_ms: Optional[int] = state_column(
detail=True,
filterable=False,
metadata={"format_fn": Humanify.timestamp},
)
#: The time when the task is finished or failed. A Unix timestamp in ms.
end_time_ms: Optional[int] = state_column(detail=True, filterable=False)
end_time_ms: Optional[int] = state_column(
detail=True,
filterable=False,
metadata={"format_fn": Humanify.timestamp},
)
#: The task logs info, e.g. offset into the worker log file when the task
#: starts/finishes.
task_log_info: Optional[dict] = state_column(detail=True, filterable=False)
Expand Down
5 changes: 5 additions & 0 deletions python/ray/experimental/state/state_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,9 @@ def output_with_format(
format: AvailableFormat = AvailableFormat.DEFAULT,
detail: bool = False,
) -> str:
# humanify all input state data
state_data = [schema.humanify(state) for state in state_data]

if format == AvailableFormat.DEFAULT:
return get_table_output(state_data, schema, detail)
if format == AvailableFormat.YAML:
Expand Down Expand Up @@ -292,8 +295,10 @@ def format_get_api_output(
) -> str:
if not state_data or isinstance(state_data, list) and len(state_data) == 0:
return f"Resource with id={id} not found in the cluster."

if not isinstance(state_data, list):
state_data = [state_data]

state_data = [dataclasses.asdict(state) for state in state_data]
return output_with_format(state_data, schema=schema, format=format, detail=True)

Expand Down
15 changes: 15 additions & 0 deletions python/ray/tests/test_state_api.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import datetime
import os
import re
import time
import json
import sys
Expand All @@ -8,6 +10,7 @@
from unittest.mock import MagicMock

import pytest
from ray.experimental.state.common import Humanify
from ray._private.gcs_utils import GcsAioClient
import yaml
from click.testing import CliRunner
Expand Down Expand Up @@ -1696,6 +1699,18 @@ def ready(self):
assert result.total == 6


def test_humanify():
raw_bytes = 1024
assert Humanify.memory(raw_bytes) == "1.0 KiB"
raw_bytes *= 1024
assert Humanify.memory(raw_bytes) == "1.0 MiB"
raw_bytes *= 1024
assert Humanify.memory(raw_bytes) == "1.0 GiB"
timestamp = 1610000000
assert Humanify.timestamp(timestamp) == "1970-01-19 07:13:20"
assert Humanify.duration(timestamp) == "18 days, 15:13:20"


@pytest.mark.asyncio
async def test_state_data_source_client_limit_distributed_sources(ray_start_cluster):
cluster = ray_start_cluster
Expand Down