Skip to content

[refactor, perf] Simplify SimpleStorage result mapping - #244

Merged
ji-huazhong merged 3 commits into
Ascend:mainfrom
ji-huazhong:refactor/simplify-storage-result-mapping
Nov 30, 2026
Merged

ji-huazhong merged 3 commits into
Ascend:mainfrom
ji-huazhong:refactor/simplify-storage-result-mapping

Conversation

@ji-huazhong

@ji-huazhong ji-huazhong commented Nov 30, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

SimpleStorage GET keeps source rows, parser arguments, and output destinations in separate dictionaries. After grouping by storage unit, result assembly follows another position lookup through those dictionaries. Keeping these structures aligned makes reordered requests, repeated keys, and linked fields harder to trace.

UPDATE already knows each unit's positions in the original batch, but builds a global-index dictionary for every field and then reconstructs the requested shape order. This adds temporary allocations and repeated lookups.

Implementation

  • Keep each GET source row, its parser argument, and its output positions together in _ReadMapping. Build read tasks while routing, reusing each unit's indexes, and carry the mappings through to result assembly.
  • Place UPDATE shapes directly into their batch positions. Build a last-occurrence mapping only for repeated indexes in the native metadata API, preserving the existing last-write description at every repeated position.
  • Reject incomplete tensor shape descriptions before notifying the controller, and check returned row counts during GET result assembly.
  • Preserve public APIs, return ordering, linked-field sharing, parser grouping, and finalization behavior.

Tests

Extend existing real-storage tests to cover mixed own and linked fields, reordered and repeated GET keys with per-key parser arguments, and reordered multi-field updates across storage units. Both own and linked values have enough elements to make incorrectly aligned slicing arguments observable.

Add one native metadata-update regression that checks both the returned schema and stored values when a row occurs more than once. It covers both a column that remains ragged and one that becomes uniform after the final write. This covers different behavior from the existing KV tests that reject duplicate update keys.

Remove two private-helper tests for shape ordering and uniform-column schemas: their assertions are now covered through real updates and returned metadata. The number of test functions decreases by one.

  • Focused manager, update, link, and KV interface tests: 187 passed, 2 skipped.
  • Link and KV interface end-to-end tests with the Rust Controller: 136 passed, 2 skipped.
  • python -m compileall -q transfer_queue tutorial tests: passed.
  • Pre-commit checks, including formatting and type checking: passed.

The full local suite reports 1004 passed, 16 skipped, 1 failed, and 6 setup errors. The remaining failures match the previously recorded order-sensitive test_opt_out_keeps_the_process_alive_for_inspection failure and six Yuanrong fixture setup errors without the optional datasystem SDK. The worker-exit test previously passed in isolation. All modified tests pass in the full suite and the focused runs above.

Performance

Compared with main at 5f9fb8b, local CPU measurements of UPDATE schema assembly for 4,096 samples across four units gave:

Fields Before After Time reduction Peak Python allocation before / after
1 0.304 ms 0.233 ms 23.3% 218 / 160 KiB
8 2.554 ms 1.451 ms 43.2% 1,416 / 261 KiB

Times are medians of seven alternating blocks of 100 calls per implementation; allocation peaks were measured separately with tracemalloc.

A separate 12-block alternating comparison of complete requests through two local SimpleStorage units over real ZMQ used 4,096 samples, eight fields, and three calls per block. Median GET latency was 520.55 -> 555.61 ms (+6.7%); UPDATE was 185.61 -> 175.66 ms (-5.4%). These results support a local schema-assembly improvement; they do not establish a training-throughput gain.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-30T03:13:31.185150Z bfc3d9e PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@0oshowero0 0oshowero0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Clean refactor overall — _ReadRow makes get_data much easier to follow, and direct batch-position indexing in _build_update_field_schema is a nice local speedup. Left one fail-fast guard suggestion and a few optional cleanup/test notes inline.

Comment on lines +154 to 157
ordered = shapes[field_name]
if repeated_positions is not None:
ordered = [ordered[pos] for pos in repeated_positions]
is_nested = len(set(ordered)) > 1

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Pre-allocating [None] * len(global_indexes) silently loses the previous fail-fast KeyError if any routed storage unit omits a field (or returns an empty stored_shapes dict via reply.meta.get("stored_shapes", {})).

With the current code, unfilled slots stay None, causing len(set(ordered)) > 1 to treat None as a shape and publish is_nested=True, per_sample_shapes=[..., None, ...] to the controller instead of failing fast.

Checking that every position was populated before computing is_nested restores the fail-fast invariant at negligible cost (and narrows tuple | None to tuple):

        ordered = shapes[field_name]
        if None in ordered:
            raise ValueError(f"Missing stored shape for field {field_name!r}")
        if repeated_positions is not None:
            ordered = [ordered[pos] for pos in repeated_positions]

Comment on lines 787 to 802
requests = []
for fields, rows in rows_by_fields.items():
routing = self._group_by_hash([row.global_index for row in rows])
for su_id, group in routing.items():
requests.append((su_id, fields, [rows[p] for p in group.batch_positions]))

tasks = [
self._get_from_single_storage_unit(
group.global_indexes,
[row.global_index for row in rows],
list(fields),
target_storage_unit=su_id,
data_parser=data_parser,
parser_args=None if parser_args is None else [args_by_fields[fields][p] for p in group.batch_positions],
parser_args=None if parser_args is None else [row.parser_arg for row in rows],
)
for su_id, fields, group in requests
for su_id, fields, rows in requests
]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Minor cleanup: _group_by_hash already computes group.global_indexes, which gets discarded when building requests and immediately rebuilt via [row.global_index for row in rows] when building tasks.

Building tasks directly in the routing loop lets us reuse group.global_indexes and keep only (fields, unit_rows) for result assembly, avoiding the redundant list comprehension and carrying one fewer element in requests:

        requests = []
        tasks = []
        for fields, rows in rows_by_fields.items():
            routing = self._group_by_hash([row.global_index for row in rows])
            for su_id, group in routing.items():
                unit_rows = [rows[p] for p in group.batch_positions]
                requests.append((fields, unit_rows))
                tasks.append(
                    self._get_from_single_storage_unit(
                        group.global_indexes,
                        list(fields),
                        target_storage_unit=su_id,
                        data_parser=data_parser,
                        parser_args=None if parser_args is None else [row.parser_arg for row in unit_rows],
                    )
                )

(Then result assembly below can unpack for (fields, rows), (_, su_data) in zip(requests, results, strict=True):.)

Comment on lines 821 to 824
for i, row in enumerate(rows):
value = su_data[field][i]
for pos in destinations[fields][row]:
for pos in row.output_positions:
ordered_data[field][pos] = value

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Optional nit: using zip(..., strict=True) here is slightly cleaner and also catches any unexpected length mismatch between rows and su_data[field]:

                for row, value in zip(rows, su_data[field], strict=True):
                    for pos in row.output_positions:
                        ordered_data[field][pos] = value

Comment on lines +1557 to +1570
values = [torch.tensor([20]), torch.tensor([30, 31]), torch.tensor([40, 41, 42])]
scores = torch.tensor([[20, 21], [30, 31], [40, 41]])

updated = client.update(
metadata,
TensorDict(
{"tokens": torch.nested.as_nested_tensor(values, layout=torch.jagged), "score": scores}, batch_size=3
),
lambda old, new: new,
plan,
)

assert updated.field_schema["tokens"]["per_sample_shapes"] == [(3,), (2,), (3,)]
assert updated.field_schema["tokens"]["shape"] is None

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Optional test suggestion: here tokens has shapes [(1,), (2,), (3,)] -> [(3,), (2,), (3,)], which stays is_nested=True both before and after remapping repeated_positions.

It would be nice to also cover the case where an earlier occurrence of a repeated row has a different shape, while the last write makes the stored column uniform (e.g., [(1,), (2,), (2,)] -> [(2,), (2,), (2,)] yielding is_nested=False, shape=(2,)), which specifically exercises applying repeated_positions before computing is_nested.

Comment thread tests/e2e/test_kv_link_e2e.py Outdated
Comment on lines +354 to +357
tq.kv_batch_put(
keys, PARTITION, fields=TensorDict({"response": torch.arange(len(keys)).unsqueeze(1)}, batch_size=len(keys))
)
tq.kv_put("own", PARTITION, fields={"prompt": _prompt(20), "response": torch.tensor([len(keys)])})

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Optional test suggestion: because each response tensor currently has length 1 while lengths are in {1, 2, 3}, slicing value[:length] always returns the entire tensor regardless of which parser_arg an own row receives (and "own" itself only appears once in order).

Making response length >= 3 (e.g., matching _prompt's 3-element layout) and asserting the sliced response values would verify per-occurrence parser_args alignment on repeated own rows (such as key index 4 appearing with lengths 1 and 3) as well.

Signed-off-by: ji-huazhong <hzji210@gmail.com>
Signed-off-by: ji-huazhong <hzji210@gmail.com>
@ji-huazhong
ji-huazhong merged commit eb39cc4 into Ascend:main Nov 30, 2026
16 checks passed
@ji-huazhong
ji-huazhong deleted the refactor/simplify-storage-result-mapping branch November 30, 2026 05:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants