YongGoose commented on code in PR #1046:
URL: https://github.com/apache/burr/pull/1046#discussion_r4718554574


##########
burr/tracking/client.py:
##########
@@ -254,13 +328,14 @@ def _log_child_relationships(
                     ),
                 )
             )
-        for parent_id, child_of in parent_relationships:
-            parent_path = os.path.join(self.storage_dir, parent_id)
+        for parent_id, parent_partition_key, child_of in parent_relationships:
+            parent_root = join_path(self.storage_dir, parent_id)
+            parent_path = application_directory(parent_root, 
parent_partition_key)

Review Comment:
   **Forking from a run written before this change loses the child link in the 
UI.** This line has the same write/read mismatch as `_ensure_dir_structure`, 
but for `children.jsonl`. When the parent was written by an earlier version, 
the child pointer goes to `<parent>/partitions/p-<sha>/children.jsonl`. The 
parent has no nested log, so `_resolve_app_directory` in the backend keeps 
resolving it to the app root and reads the root's `children.jsonl`.
   
   To check, I wrote a parent `old-run`/`tenant-A` with `main`, then forked 
`child` from it with this PR (`fork_from_app_id="old-run", 
fork_from_partition_key="tenant-A"`):
   
   - `main`: `GET /api/v0/proj/old-run/tenant-A/apps` → `children: ['child']`
   - this PR: `children: []`
   
   The fix suggested for `_ensure_dir_structure` would cover this as well: pick 
the same directory the readers resolve.



##########
burr/tracking/client.py:
##########
@@ -370,14 +465,19 @@ def load_state(
         prior_state["__SEQUENCE_ID"] = line_seq  # add the sequence id back
         return prior_state, entry_point
 
-    def _ensure_dir_structure(self, app_id: str):
+    def _ensure_dir_structure(self, app_id: str, partition_key: Optional[str] 
= None) -> str:
         if not os.path.exists(self.storage_dir):
             logger.info(f"Creating storage directory: {self.storage_dir}")
             os.makedirs(self.storage_dir)
-        application_path = os.path.join(self.storage_dir, app_id)
+        app_root = join_path(self.storage_dir, app_id)
+        if not os.path.exists(app_root):
+            logger.info(f"Creating application directory: {app_root}")
+            os.makedirs(app_root)
+        application_path = application_directory(app_root, partition_key)

Review Comment:
   **Resuming a run written before this change splits it across two 
directories.** This line always sends a non-`None` partition to 
`partitions/p-<sha>/`. When a run was written by an earlier version, it lives 
at the app root, and the read path (`_resolve_existing_app_dir`) still loads 
its state from there. So reads and writes for the same (app_id, partition) use 
different directories.
   
   To check, I wrote `old-run`/`tenant-A` (3 steps) with `main`, then resumed 
it with this PR (`initialize_from(..., resume_at_next_action=True)`, same 
`app_id` and `partition_key`) and ran 2 more steps:
   
   | | `get_application_logs(old-run, tenant-A)` sequence ids | `list_apps` 
`num_steps` |
   |---|---|---|
   | `main` | `[0, 1, 2, 3, 4]` | 5 |
   | this PR | `[3, 4]` | 5 |
   
   Steps 0–2 are still on disk but are no longer reachable from the UI. One 
fix: when the app root's log exists and its metadata confirms `partition_key`, 
return the app root here, so the resumed run keeps appending to the same log. 
The nested layout would then only be used for runs that start after the 
upgrade. It would also remove the "old readers load stale S1" hazard that the 
description warns about.



##########
burr/tracking/server/backend.py:
##########
@@ -464,34 +545,64 @@ async def list_apps(
         limit: int = 100,
         offset: int = 0,
     ) -> Tuple[Sequence[ApplicationSummary], int]:
-        project_filepath = os.path.join(self.path, project_id)
+        project_filepath = join_path(self.path, project_id)
         if not os.path.exists(project_filepath):
             return [], 0
-            # raise fastapi.HTTPException(status_code=404, detail=f"Project: 
{project_id} not found")
         out = []
         for entry in await aiofilesos.listdir(project_filepath):
             if entry.startswith("."):
                 # skip hidden files/directories
                 continue
-            full_path = os.path.join(project_filepath, entry)
-            metadata_path = os.path.join(full_path, "metadata.json")
-            log_path = os.path.join(full_path, "log.jsonl")
-            if os.path.isdir(full_path):
-                metadata = await self._load_metadata(metadata_path)
-                app_partition_key = metadata.partition_key
-                # quick, hacky way to do it -- we should really have this be 
part of the path
-                # But we load it up anyway. TODO -- add partition key to the 
path
-                # If this is slow you'll want to use the s3-based storage 
system
-                # Which has an actual index
+            app_root = join_path(project_filepath, entry)
+            if not os.path.isdir(app_root):
+                continue
+
+            # A run is either the legacy root files or one partition 
subdirectory.
+            runs = []
+            legacy_log = join_path(app_root, "log.jsonl")
+            if os.path.exists(legacy_log):
+                legacy_metadata = _metadata_at(app_root)
+                runs.append(
+                    (
+                        app_root,
+                        metadata_partition_key(legacy_metadata),
+                        entry,
+                        log_has_end_entry(legacy_log),
+                    )
+                )
+            for partition_dir in partition_directories(app_root):
+                log_path = join_path(partition_dir, "log.jsonl")
+                if not os.path.exists(log_path):
+                    continue
+                metadata = _metadata_at(partition_dir)
+                run_partition = metadata_partition_key(metadata)
+                if run_partition is None or partition_segment(run_partition) 
!= os.path.basename(
+                    partition_dir
+                ):
+                    logger.warning(
+                        "Skipping %s: partition metadata does not match its 
directory",
+                        partition_dir,
+                    )
+                    continue
+                has_data = log_has_end_entry(log_path)
+                if not has_data and any(run[1] == run_partition and run[3] for 
run in runs):
+                    # An empty partitioned log must not hide completed legacy 
data during resume.
+                    continue
+                if has_data:
+                    runs = [run for run in runs if run[1] != run_partition]

Review Comment:
   **This is the read side of the resume split.** Once the nested log has an 
`end_entry`, the legacy run for the same partition is dropped from the listing, 
and `_resolve_app_directory` returns only the nested directory. When a run 
written by an earlier version is resumed, the UI therefore shows only the 
post-upgrade steps: `[3, 4]` instead of `[0, 1, 2, 3, 4]` in my run (details on 
`client.py` `_ensure_dir_structure`). `num_steps` still reads 5, because it 
comes from the last `sequence_id`.
   
   `test_resume_from_legacy_then_continue_in_new_partition_directory` only 
asserts that every returned step's marker starts with `LEGACY_A`, which still 
holds when steps are missing. Asserting the returned sequence ids would catch 
this.



##########
burr/tracking/client.py:
##########
@@ -108,6 +117,69 @@ def _filter_inputs(d: dict) -> dict:
     return {k: v for k, v in d.items() if k not in INPUT_FILTERLIST}
 
 
+def _resolve_existing_app_dir(
+    app_root: str,
+    partition_key: Optional[str],
+    *,
+    log_filename: str,
+    metadata_filename: str,
+    context: str,
+) -> Optional[str]:
+    """Resolve an existing application directory for a partition, or None if 
absent.
+
+    Legacy data at ``app_root`` is only accepted when its metadata confirms 
the requested
+    partition. Missing or mismatched metadata is an explicit error rather than 
a guess.
+    """
+    legacy_log = join_path(app_root, log_filename)
+    if partition_key is not None:
+        nested_dir = application_directory(app_root, partition_key)
+        nested_log = join_path(nested_dir, log_filename)
+        if log_has_end_entry(nested_log):
+            metadata = read_metadata(join_path(nested_dir, metadata_filename))
+            if not partition_matches(metadata, partition_key):
+                raise ValueError(
+                    f"Local tracking data for {context} is corrupt: partition 
directory metadata "
+                    f"does not confirm partition {partition_key!r}."
+                )
+            return nested_dir
+        if os.path.exists(legacy_log):
+            metadata = read_metadata(join_path(app_root, metadata_filename))
+            if partition_matches(metadata, partition_key):
+                return app_root
+            raise ValueError(
+                f"Local tracking data for {context} exists at the legacy path 
but belongs to "
+                f"partition {metadata_partition_key(metadata)!r} (or has no 
partition metadata). "
+                f"Refusing to load it as partition {partition_key!r}. 
Move/archive the legacy "
+                "directory explicitly if this is intended."
+            )

Review Comment:
   **Reusing an app_id that belongs to another partition now fails at 
`build()`.** For example: `initialize_from(...)` with `app_id="old-run", 
partition_key="tenant-B"`, where the root data was written by `main` for 
`tenant-A`. On `main`, this silently resumed A's state, which is the #319 bug. 
With this PR it raises this `ValueError` instead of starting B from 
`default_state`.
   
   A legacy log can hold interleaved writes from both partitions, so refusing 
is defensible. But metadata that names a different partition could also mean 
"nothing is stored for B" (return `None`). That is how new-layout data already 
behaves. Either way, users with existing data will see this as a behavior 
change, so a maintainer should decide which it is.



##########
burr/tracking/client.py:
##########
@@ -108,6 +117,69 @@ def _filter_inputs(d: dict) -> dict:
     return {k: v for k, v in d.items() if k not in INPUT_FILTERLIST}
 
 
+def _resolve_existing_app_dir(
+    app_root: str,
+    partition_key: Optional[str],
+    *,
+    log_filename: str,
+    metadata_filename: str,
+    context: str,
+) -> Optional[str]:
+    """Resolve an existing application directory for a partition, or None if 
absent.
+
+    Legacy data at ``app_root`` is only accepted when its metadata confirms 
the requested
+    partition. Missing or mismatched metadata is an explicit error rather than 
a guess.
+    """
+    legacy_log = join_path(app_root, log_filename)
+    if partition_key is not None:
+        nested_dir = application_directory(app_root, partition_key)
+        nested_log = join_path(nested_dir, log_filename)
+        if log_has_end_entry(nested_log):
+            metadata = read_metadata(join_path(nested_dir, metadata_filename))
+            if not partition_matches(metadata, partition_key):
+                raise ValueError(
+                    f"Local tracking data for {context} is corrupt: partition 
directory metadata "
+                    f"does not confirm partition {partition_key!r}."
+                )
+            return nested_dir
+        if os.path.exists(legacy_log):
+            metadata = read_metadata(join_path(app_root, metadata_filename))
+            if partition_matches(metadata, partition_key):
+                return app_root
+            raise ValueError(
+                f"Local tracking data for {context} exists at the legacy path 
but belongs to "
+                f"partition {metadata_partition_key(metadata)!r} (or has no 
partition metadata). "
+                f"Refusing to load it as partition {partition_key!r}. 
Move/archive the legacy "
+                "directory explicitly if this is intended."
+            )
+        if os.path.exists(nested_log):
+            metadata = read_metadata(join_path(nested_dir, metadata_filename))
+            if not partition_matches(metadata, partition_key):
+                raise ValueError(
+                    f"Local tracking data for {context} is corrupt: partition 
directory metadata "
+                    f"does not confirm partition {partition_key!r}."
+                )
+            return nested_dir
+        return None
+
+    if os.path.exists(legacy_log):
+        metadata = read_metadata(join_path(app_root, metadata_filename))
+        if partition_matches(metadata, None):
+            return app_root
+        raise ValueError(
+            f"Local tracking data for {context} belongs to partition "
+            f"{metadata_partition_key(metadata)!r}. Refusing to load it 
without a partition_key."
+        )

Review Comment:
   **Forking without a partition key now raises on data that loads today.** 
With `fork_from_partition_key=None` against a partitioned run written by 
`main`, the two versions behave differently:
   
   - `main` loads the run (count=3).
   - This PR raises `ValueError: Local tracking data for proj/old-run belongs 
to partition 'tenant-A'. Refusing to load it without a partition_key.`
   
   The fork template in `docs/ui/getting-started.rst` passes 
`fork_from_partition_key=None`, so users following the docs would hit this. If 
the strictness is intended, it needs a release note and a docs change. 
Otherwise, a fallback could load the run when exactly one partition owns that 
app_id.



##########
burr/tracking/common/partition_paths.py:
##########
@@ -0,0 +1,136 @@
+# 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.
+
+"""Filesystem layout for partition-aware local tracking.
+
+Legacy layout (still read, never rewritten or migrated)::
+
+    
<storage>/<project>/<app_id>/{graph.json,metadata.json,log.jsonl,children.jsonl}
+
+New layout used for any non-``None`` partition key::
+
+    
<storage>/<project>/<app_id>/partitions/p-<sha256>/{graph.json,metadata.json,log.jsonl,children.jsonl}
+
+The partition key itself is never used as a path segment. Its UTF-8 bytes are 
hashed, so
+every separator, control character, Unicode string and empty string maps to 
one safe
+directory name, and no new path-validation rules are needed. The original 
value remains in
+``metadata.json`` and is verified before any legacy or partitioned data is 
loaded.
+"""
+
+import hashlib
+import json
+import os
+from typing import Optional
+
+try:  # #946/#948 add the shared path-containment helper; use it when 
available.
+    from burr.tracking.common.identifiers import join_within as join_path
+except ImportError:  # pragma: no cover - exercised only before those PRs land
+
+    def join_path(base: str, *parts: str) -> str:
+        return os.path.join(base, *parts)
+
+
+PARTITIONS_DIRNAME = "partitions"
+PARTITION_PREFIX = "p-"
+
+
+def partition_segment(partition_key: str) -> str:
+    """Return the directory name for a non-None partition key."""
+    if not isinstance(partition_key, str):
+        raise TypeError(
+            f"partition_key must be a string or None, got 
{type(partition_key).__name__}"
+        )
+    if partition_key == "":
+        # Keep the empty string distinct from None without relying on a 
special directory name.
+        return PARTITION_PREFIX + "e"

Review Comment:
   **This special case isn't needed.** `sha256("")` already maps the empty key 
to its own directory, distinct from every other key and from `None` (the app 
root). Without the branch, `partition_segment` would have a single rule.
   
   Related: `burr/tracking/s3client.py:126` maps both `""` and `None` to 
`__none__` (`partition_key or "__none__"`). After this change, the local and S3 
trackers disagree on whether the empty key is its own partition. S3 already has 
the partition in its key path, so nothing else in S3 needs to change for #319.



##########
burr/tracking/server/backend.py:
##########
@@ -293,6 +306,74 @@ def get_uri(project_id: str) -> str:
 DEFAULT_PATH = os.path.expanduser("~/.burr")
 
 
+def _metadata_at(app_dir: str) -> Optional[dict]:
+    return read_metadata(join_path(app_dir, "metadata.json"))
+
+
+def _resolve_app_directory(

Review Comment:
   **The same resolution logic is written twice.** `_resolve_existing_app_dir` 
in `burr/tracking/client.py` implements the same legacy/nested/metadata policy 
as this function, about 60 lines each, with different exception types. A fix to 
one (for example, the resume split) has to be repeated in the other.
   
   One function in `partition_paths` that returns the directory or raises a 
typed error would keep them from drifting. The backend would then only map that 
error to 400/404.



##########
burr/tracking/common/partition_paths.py:
##########
@@ -0,0 +1,136 @@
+# 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.
+
+"""Filesystem layout for partition-aware local tracking.
+
+Legacy layout (still read, never rewritten or migrated)::
+
+    
<storage>/<project>/<app_id>/{graph.json,metadata.json,log.jsonl,children.jsonl}
+
+New layout used for any non-``None`` partition key::
+
+    
<storage>/<project>/<app_id>/partitions/p-<sha256>/{graph.json,metadata.json,log.jsonl,children.jsonl}
+
+The partition key itself is never used as a path segment. Its UTF-8 bytes are 
hashed, so
+every separator, control character, Unicode string and empty string maps to 
one safe
+directory name, and no new path-validation rules are needed. The original 
value remains in
+``metadata.json`` and is verified before any legacy or partitioned data is 
loaded.
+"""
+
+import hashlib
+import json
+import os
+from typing import Optional
+
+try:  # #946/#948 add the shared path-containment helper; use it when 
available.
+    from burr.tracking.common.identifiers import join_within as join_path
+except ImportError:  # pragma: no cover - exercised only before those PRs land
+
+    def join_path(base: str, *parts: str) -> str:
+        return os.path.join(base, *parts)

Review Comment:
   **This imports a module that only exists in two unmerged PRs.** 
`burr.tracking.common.identifiers` comes from #946/#948. The `pragma: no cover 
- exercised only before those PRs land` comment marks the fallback, but the 
fallback is the branch that runs on `main` today, so the other branch is the 
one CI never covers.
   
   I checked the other branch by dropping #948's `identifiers.py` into this 
tree: `join_path` resolves to `identifiers.join_within`, and `tests/tracking` 
still passes (39 passed). So the shim works. However, `git merge-tree` reports 
textual conflicts with both PRs: #946 in `burr/tracking/client.py` and #948 in 
`burr/tracking/server/backend.py`. A rebase is needed whichever lands first. 
I'd drop the shim and use `os.path.join` (or `join_within` once it exists on 
`main`) 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]

Reply via email to