HyukjinKwon opened a new pull request, #854:
URL: https://github.com/apache/spark-connect-rust/pull/854
### What changes were proposed in this pull request?
A follow-up of #820 (SPARK-61952), #822 (SPARK-61958) and #844
(SPARK-61992), from a review of the drop-in's Rust protobuf runtime
(`pyspark.sql.connect.proto`, `crates/pyspark-rs/src/pbmsg`) against upb
(protobuf 7.36.2), the implementation that pyspark-client 4.3.0 uses. Each item
was probed on both clients.
**1. `MergeFrom` and `update` of a map take their arguments as upb's do**
(`containers.rs`: `MapContainer::merge_from`, `set_message_of_key`, `update`).
- A map of the runtime of other key or value types was copied as it was,
without conversion. So a map held keys and values of other types:
- `sql.args.MergeFrom(sql.named_arguments)` put an `Expression` into the
map of `Literal`s, which serialized as a `Literal` of other fields;
- `options.MergeFrom(sql.args)` put a message into a map of strings;
- a map of int32 keys merged from one of uint32 keys held two entries of
the key 4.
- Any other argument but a dict was iterated as (key, value) pairs. upb
takes a mapping by its items, so the map of a message of `protobuf`'s class of
the type, which a plugin's module that keeps `protobuf`'s classes gives (Delta
Lake's `base_pb2`), merged `{"ab": "zz"}` as `{"a": "b"}`. So did a
`MappingProxyType` or a `UserDict`.
- upb's `MergeFrom` of a map refuses a dict, then takes its argument as its
`InitMapAttributes` takes the value of a map field of a constructor. #844 made
the runtime's constructor do that (`MapContainer::update_from`), and
`MergeFrom` now calls it after its dict check:
- a map of scalars goes through `MutableMapping.update`, called as upb
calls it, which spreads a tuple into the arguments (`MergeFrom(({"a": "b"},))`
merges, and `MergeFrom((("a", "b"),))` raises upb's `ValueError`). Each key and
value is converted with upb's errors;
- a map of messages takes the keys that the argument iterates. It copies
each value into the message of its key, which it makes if the map has none, or
sets that message's fields from a dict. An argument that is not iterable raises
`Argument for field spark.connect.SQL.args is not iterable`.
- The message of a key that the map already has keeps its identity. upb
copies the value into it (`CopyFrom`), so a message read before the `MergeFrom`
(`x = map[key]`) has the new fields after it. The fast path of a map of the
same types, and #844's insert of a copy of a message of the type, replaced the
entry, which left `x` with the old fields. `set_message_of_key` now copies into
the message that the map has, and inserts a copy only when it has none, which
is the only case for a constructor's new map.
- `update` takes `MutableMapping.update`'s one positional argument. So
`update(None)` is the `TypeError` of its iteration, which it took for no
argument before. A second argument raises upb's `MutableMapping.update() takes
from 1 to 2 positional arguments but 3 were given`.
**2. A map changed during its iteration fails the iteration**
(`MapIterator`, and the version of `MapContainer`).
- upb's map takes a new version at the start of each method that may change
its keys, even one that then fails or changes nothing. A set of a key that the
map already has is the exception. The next step of an iteration in progress
then raises `RuntimeError: Map modified during iteration.`.
- The runtime iterated a copy of the keys. So `items()` and `values()` read
the value of a key that the loop had removed, which inserted the key again,
with the default value, and the message serialized it.
- Iterating a map now gives a `MapIterator` (registered in the module as
`ProtoMapIterator`, so its C name is its bare name, as for the other classes).
It reads the entries as they are at each step, by their positions, and fails
once the version changes. The methods take a new version where upb's do:
- set, delete (also of a missing or a bad key), and the read of a missing
key;
- `clear`, `pop`, `popitem`, `setdefault`, `get_or_create` of a new key,
and `MergeFrom` (also of an argument that it refuses);
- `ClearField` of the map field.
- Like upb's iterator, it does not fail for any of these:
- `Clear`, `CopyFrom` and `ParseFromString` of the message, after which it
reads the entries that the map keeps;
- `MergeFrom` and `MergeFromString` of the message, whose new keys it
reads;
- `get`, `in`, `len`, `==`, `str`, and a change of a message in the map.
- `setdefault` also sets an unset message in its parent, as upb's does, also
for a key that it refuses.
**3. upb's order of integer keys** (`text.rs`, `upb_text_key_order`).
- upb orders the keys of a map of a signed integer type as unsigned numbers,
so a negative key comes after the others: `0, 1, 3, 100, -5, -1` in `str()`,
and the reverse in `SerializeToString(deterministic=True)`.
- The runtime ordered them as signed numbers, so its bytes and `str()`
differed for negative keys.
- The protos of Spark Connect have maps of string keys only, so this affects
the maps of plugins' protos.
**4. Docs** (`docs/compatibility.md`).
- upb's limit of 100 nested messages applies wherever upb parses a message:
- the parse, the load of a pickle and `Any.Unpack`;
- where upb copies a message by its bytes: `MergeFrom`, `copy.copy`, the
`append`, `extend` and `insert` of a repeated field, and a constructor given a
message for a message field or a repeated field.
The runtime does all of these at any depth. Before, the doc said only that
upb "refuses to parse" such messages.
- Map order:
- the runtime serializes a map's entries in the key order of upb's
deterministic serialization, with `deterministic` or without it;
- upb's default serialization uses the order of its hash table, which
changes from one process to the next;
- `str()` follows upb's order, which takes signed keys as unsigned.
- A truncated varint fails the parse with a `DecodeError` on both. upb keeps
a value of the bytes that it read past the varint, and the earlier values of a
packed field. The runtime keeps neither.
- `MergeFrom` of the runtime's maps takes the items of `protobuf`'s maps.
- Two lines that the review of the docs found stale:
- Garbage collection: not every message that the runtime makes is
untracked. The messages that a parse or a copy makes inside the message, those
of `copy.deepcopy`, and that of a read of an unset field are not tracked
(`gc.is_tracked`). The message of a constructor or of `FromString`, and the one
that `ParseFromString` or `CopyFrom` fills, are tracked.
- The server's limit of the depth of a plan is 1,024 nested messages
(`spark.connect.grpc.marshallerRecursionLimit`), not 100. From about 510 nested
expressions, the server fails the request with `[Unknown error] Application
error processing RPC`. Probed against a Spark 4.3.0 server: 505 nested
expressions run, 509 fail.
### Why are the changes needed?
Until now:
- a map's `MergeFrom` could corrupt the message silently: a message of
another type, a key of another type, or the characters of the keys of
`protobuf`'s map taken as pairs;
- a loop that changed a map brought deleted keys back into the message,
where pyspark-client raises;
- the bytes of a plugin's map of negative integer keys differed from
PySpark's.
### Does this PR introduce _any_ user-facing change?
Yes, as upb behaves:
| | pyspark-client 4.3.0, and now | before |
|---|---|---|
| `sql.args.MergeFrom(sql.named_arguments)` | `TypeError: Parameter to
CopyFrom() must be instance of same class: expected <class
'...Expression.Literal'> got <class '...Expression'>.` | merged; the `Literal`
holds the `Expression`'s bytes |
| `d.options.MergeFrom(types.MappingProxyType({"ab": "zz"}))` | `{'ab':
'zz'}` | `{'a': 'b'}` |
| `scan.table.options.MergeFrom(base_pb2.Table(options={"ab":
"zz"}).options)` | `{'ab': 'zz'}` | `{'a': 'b'}` |
| `sql.args.MergeFrom(5)` | `TypeError: Argument for field
spark.connect.SQL.args is not iterable` | `TypeError: 'int' object is not
iterable` |
| `for k, v in d.options.items(): del d.options["k1"]` | `RuntimeError: Map
modified during iteration.`; `k1` stays deleted | completes; `k1` is back, as
`""` |
| `str()` of a plugin's map of int32 keys `{3, -5, 1}` | keys `1, 3, -5` |
keys `-5, 1, 3` |
### How was this patch tested?
- **New tests in `python/tests/test_proto_rust_offline.py`.** They compare
against upb, and all of them fail on master.
- `test_merge_from_of_a_map_takes_its_argument_as_upbs`: `MergeFrom` of 23
arguments of a map of scalars and 19 of a map of messages:
- the runtime's maps of the same and of other types, and `protobuf`'s
map of the type;
- `MappingProxyType`, `UserDict`, an object with `keys`, pairs, a
generator, a str, an int and None;
- tuples, which upb spreads into the arguments of `update`;
- dict values, values that cannot be read, and values that are neither
messages nor dicts.
Each case compares the outcome, the bytes and the text. The test also
checks the identity of the message of a key the map has, after `MergeFrom` of a
map of the type, of a mapping of a message or of a dict, and of the map itself.
A `MergeFrom` of the message replaces that message, on both clients.
- `test_update_of_a_map_takes_its_arguments_as_upbs`: `update` of None, of
nothing, of two arguments, of a keyword named `other`, of a mapping and
keywords, of pairs and of an int.
- `test_maps_changed_during_their_iteration_fail_it_as_upbs`: 43
operations between two steps of an iteration, of maps of scalars and of
messages and of their message. It also covers `items()` and `values()` of a
loop that deletes keys, and a change before the first step and after the last.
- `test_maps_of_integer_keys_merge_serialize_and_print_as_upbs`:
`MergeFrom` of maps of other key types (uint32, int64, bool and string keys
into int32 keys). Also the bytes, `str()`, `repr()` and `text_format` of maps
of int32, int64, sint32, sfixed64, uint32, uint64 and bool keys. It uses a
plugin-like file of a map of each key type, built as protoc's modules build
theirs. It comes at the end of the file, as the file adds its classes to those
of the runtime, which earlier tests compare with upb's one by one.
- A new case of `test_unset_children_set_in_their_parents_as_upbs`:
`setdefault` of a key that the map cannot hold.
- **Rust:** the unit test of `Entries` now also iterates the entries by
their positions, as `MapIterator` does.
- **Probes of both clients:**
- about 150 cases of `MergeFrom` arguments, of operations during an
iteration, and of key orders;
- the KD review's map-order and truncated-varint probes, for the doc lines;
- the Delta-shaped plugin protos of the tests.
- the 16 cases of the KD review's `map_methods.py` (the `update` and
`MergeFrom` of maps of the values that `InitMapAttributes` takes): all give
upb's results.
Apart from the documented differences (upb's hash order, the names of the
types), they give upb's results. The other remaining difference is the text of
an argument error of `MergeFrom` itself, such as a keyword argument: PyO3's,
where upb's names `ScalarMapContainer.MergeFrom()`.
- **Rust gates:**
- `cargo fmt --all --check`;
- `cargo +1.100.0 clippy -p apache-spark-connect-core -p
apache-spark-connect -p pyspark-rs --all-targets -- -D warnings`;
- `RUSTDOCFLAGS="-D warnings" cargo doc --no-deps -p apache-spark-connect
-p apache-spark-connect-core`;
- `cargo test -p pyspark-rs --lib`, linked as `rust.yml` links it: 13
passed.
- **Python gates:**
- ruff 0.14.0 `check` and `format --check`, `test_ruff_excludes.py` and
`scripts/audit_no_stubs.sh`;
- `gen_type_stubs.py --check` and `gen_fn_dispatch.py --check` against the
v4.3.0 source, and the guards of the offline, e2e and live Rust test lists;
- `test_type_stubs_offline.py` with mypy 2.4.1: 7 passed.
- **The offline suite of `coverage.yml`:** 6371 passed and 77 skipped, the
skips of master.
- **`test_dropin_e2e.py` against a Spark 4.3.0 server:** 319 passed.
### Was this patch authored or co-authored using generative AI tooling?
Generated-by: Claude Opus 5.5
This pull request and its description were written by Isaac.
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]