YongGoose commented on code in PR #945:
URL: https://github.com/apache/burr/pull/945#discussion_r4718611401
##########
burr/integrations/serde/pandas.py:
##########
@@ -16,39 +16,90 @@
# under the License.
# try to import to serialize Pandas Objects
+#
+# DataFrames are stored as parquet files under a configured directory
+# (``pandas_kwargs["path"]``). The persisted state records the file name
+# relative to that directory; on load the name is resolved against the
+# configured directory and must land inside it.
import hashlib
import os
-from typing import Optional
+from typing import Optional, Union
import pandas as pd
from burr.core import serde
+def _pandas_kwargs_with_path(pandas_kwargs: Optional[dict], operation: str) ->
dict:
+ """Returns a copy of ``pandas_kwargs``, requiring it to carry a ``path``
entry."""
+ if not isinstance(pandas_kwargs, dict) or "path" not in pandas_kwargs:
+ raise ValueError(
+ f"{operation} a pandas DataFrame requires a `path` entry in
`pandas_kwargs` -- "
+ "this is the directory where the dataframe is stored as a parquet
file. "
+ "Pass it through whatever triggers serialization, e.g. "
+ '`LocalTrackingClient(..., serde_kwargs={"pandas_kwargs": {"path":
"/some/dir"}})` '
+ 'or `state.serialize(pandas_kwargs={"path": "/some/dir"})`. '
+ f"Got pandas_kwargs={pandas_kwargs!r}."
+ )
+ return pandas_kwargs.copy()
+
+
+def _resolve_within_base(base_path: Union[str, os.PathLike], stored_path:
object) -> str:
+ """Resolves a persisted parquet path against the configured directory.
+
+ Serialization records the parquet file name relative to the configured
directory.
+ Earlier versions recorded the joined path instead, so an absolute value is
still
+ accepted as long as it resolves to a location inside the configured
directory.
+ URL-style values and anything resolving outside the directory are rejected.
+
+ :param base_path: the configured directory (``pandas_kwargs["path"]``).
+ :param stored_path: the ``path`` value read from persisted state.
+ :return: the resolved absolute path of the parquet file.
+ """
+ if not isinstance(stored_path, str) or not stored_path:
+ raise ValueError(f"Persisted parquet path must be a non-empty string,
got {stored_path!r}.")
+ if "://" in stored_path:
+ raise ValueError(
+ f"Persisted parquet path {stored_path!r} must be a file name
relative to the "
+ "configured directory, not a URL."
+ )
+ real_base = os.path.realpath(os.fspath(base_path))
Review Comment:
Question: is a remote (fsspec) `path` meant to be supported? `realpath()`
turns a URL base into a local path. I ran a round trip with
`pandas_kwargs={"path": "memory://bucket/dir"}`, with fsspec installed:
```
main: stored "memory://bucket/dir/df_<hash>.parquet"; deserialize loads
it
this PR: stored "df_<hash>.parquet"; deserialize -> FileNotFoundError:
<cwd>/memory:/bucket/dir/df_<hash>.parquet
```
`serialize_pandas_df` still writes to the remote store, so the failure only
shows up on load, for new state too. I couldn't find anything in the docs about
`pandas_kwargs` either way.
- If URL bases aren't supported, rejecting them in `serialize_pandas_df`
would make this fail at write time instead.
- If they are, the base is trusted config, so it could get a URL-aware join
here. The stored value can still be required to be a bare name.
##########
burr/integrations/serde/pandas.py:
##########
@@ -16,39 +16,90 @@
# under the License.
# try to import to serialize Pandas Objects
+#
+# DataFrames are stored as parquet files under a configured directory
+# (``pandas_kwargs["path"]``). The persisted state records the file name
+# relative to that directory; on load the name is resolved against the
+# configured directory and must land inside it.
import hashlib
import os
-from typing import Optional
+from typing import Optional, Union
import pandas as pd
from burr.core import serde
+def _pandas_kwargs_with_path(pandas_kwargs: Optional[dict], operation: str) ->
dict:
+ """Returns a copy of ``pandas_kwargs``, requiring it to carry a ``path``
entry."""
+ if not isinstance(pandas_kwargs, dict) or "path" not in pandas_kwargs:
+ raise ValueError(
+ f"{operation} a pandas DataFrame requires a `path` entry in
`pandas_kwargs` -- "
+ "this is the directory where the dataframe is stored as a parquet
file. "
+ "Pass it through whatever triggers serialization, e.g. "
+ '`LocalTrackingClient(..., serde_kwargs={"pandas_kwargs": {"path":
"/some/dir"}})` '
+ 'or `state.serialize(pandas_kwargs={"path": "/some/dir"})`. '
+ f"Got pandas_kwargs={pandas_kwargs!r}."
+ )
+ return pandas_kwargs.copy()
+
+
+def _resolve_within_base(base_path: Union[str, os.PathLike], stored_path:
object) -> str:
+ """Resolves a persisted parquet path against the configured directory.
+
+ Serialization records the parquet file name relative to the configured
directory.
+ Earlier versions recorded the joined path instead, so an absolute value is
still
+ accepted as long as it resolves to a location inside the configured
directory.
+ URL-style values and anything resolving outside the directory are rejected.
+
+ :param base_path: the configured directory (``pandas_kwargs["path"]``).
+ :param stored_path: the ``path`` value read from persisted state.
+ :return: the resolved absolute path of the parquet file.
+ """
+ if not isinstance(stored_path, str) or not stored_path:
+ raise ValueError(f"Persisted parquet path must be a non-empty string,
got {stored_path!r}.")
+ if "://" in stored_path:
+ raise ValueError(
+ f"Persisted parquet path {stored_path!r} must be a file name
relative to the "
+ "configured directory, not a URL."
+ )
+ real_base = os.path.realpath(os.fspath(base_path))
+ candidate = stored_path if os.path.isabs(stored_path) else
os.path.join(real_base, stored_path)
Review Comment:
**This one should block:** legacy state written with a *relative* `path` no
longer loads.
On `main`, `serialize_pandas_df` stores `os.path.join(base_path,
file_name)`. With `pandas_kwargs={"path": "data"}` that persists
`data/df_<hash>.parquet`, which is still relative. Here that value isn't
absolute, so it gets joined onto the base a second time:
```
legacy stored "data/df_legacy.parquet", same cwd, pandas_kwargs={"path":
"data"}
main: loads
this PR: ValueError: Failed to deserialize state field 'df':
/tmp/.../data/data/df_legacy.parquet (root: FileNotFoundError)
```
`"./data"` fails the same way. The error doesn't point at the cause, and
`test_serde_of_pandas_dataframe_with_relative_base_path` only covers state
written by the new code.
The serializer has only ever written `<base>/df_<hash>.parquet`, so keeping
just the file name covers every legacy shape. I ran exactly this change on top
of the PR:
```suggestion
# Earlier versions stored the joined path `<base>/<file name>`; only the
name is needed.
stored_path = os.path.basename(stored_path)
real_base = os.path.realpath(os.fspath(base_path))
candidate = stored_path if os.path.isabs(stored_path) else
os.path.join(real_base, stored_path)
```
With it, these all load:
- legacy relative state, from the same cwd and from a different one
- legacy absolute state after the directory was moved (the PR currently
rejects that as "outside")
- symlinked base, in both directions
`../outside.parquet` and an absolute path outside the base both resolve to
`<base>/outside.parquet`, so the outside file is never read.
The trade-off is that 3 existing tests fail with this change, so they'd need
adjusting:
- `test_deserialize_pandas_df_accepts_nested_relative_path_inside_base`:
nested names aren't resolved any more, but the serializer never writes them.
- `test_deserialize_pandas_df_rejects_parent_directory_path` and
`test_deserialize_pandas_df_rejects_absolute_path_outside_base`: they now get a
`FileNotFoundError` for a path inside the base instead of the "resolves
outside" message.
##########
tests/integrations/serde/test_pandas.py:
##########
@@ -62,14 +89,104 @@ def
test_serialize_pandas_df_without_path_raises_informative_error():
assert "path" in str(exc_info.value)
-def test_deserialize_pandas_df_without_pandas_kwargs(tmp_path):
+def test_deserialize_pandas_df_without_path_raises_informative_error(tmp_path):
Review Comment:
Nit / release note: this replaces `main`'s
`test_deserialize_pandas_df_without_pandas_kwargs` with a test that expects the
opposite. On `main`, `State.deserialize(serialized)` with no `pandas_kwargs`
loads the DataFrame. With this PR it raises the new `path` error. I ran both.
That follows from the fix, and the built-in callers are unaffected. I
grepped them, and they pass the same `serde_kwargs` in both directions:
- `persistence.py` L531/L582
- `b_aiosqlite`, `b_psycopg2`, `b_asyncpg`, `b_redis` (both classes),
`b_pymongo` and `b_aerospike`
- `tracking/client.py` L479/L664
Could the release notes mention it for people who call `State.deserialize`
directly?
--
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]