diff --git a/documentation/components/core/aggregations.md b/documentation/components/core/aggregations.md
index 5786f5608..d03662e24 100644
--- a/documentation/components/core/aggregations.md
+++ b/documentation/components/core/aggregations.md
@@ -18,6 +18,7 @@ You can aggregate each group of the `groupBy` function with one of the aggregati
- [`FIRST()`](/src/core/etl/src/Flow/ETL/Functions/First.php)
- [`LAST()`](/src/core/etl/src/Flow/ETL/Functions/Last.php)
- [`STRING_AGG()`](/src/core/etl/src/Flow/ETL/Functions/StringAggregate.php)
+- [`MULTISET_HASH()`](/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php)
All aggregation functions implement [`AggregatingFunction`](/src/core/etl/src/Flow/ETL/Functions/AggregatingFunction.php).
`aggregate(Rows $rows, array $indices, Backend $backend)` folds the rows of one group into the state.
@@ -107,6 +108,11 @@ df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'))])
df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'), exact: true)])->fetch(); // 0.3
```
+## Hashing rows
+
+`multiset_hash()` hashes the rows of each group. The order of the rows does not change it. See
+[Hashing](/documentation/components/core/hashing.md).
+
## Example
```php
diff --git a/documentation/components/core/core.md b/documentation/components/core/core.md
index 4382d8214..4d8c469b0 100644
--- a/documentation/components/core/core.md
+++ b/documentation/components/core/core.md
@@ -214,7 +214,7 @@ Physical plan
Statistics: rows exact 1 · size unknown
```
-`Memory: 1024 MiB` is the default limit under `memory_limit = -1`: the memory the join may add after it starts.
+`Memory: 1024 MiB` is the default limit under `memory_limit = -1`: the memory the join can add after it starts.
[Memory limit](/documentation/components/core/sort.md#memory-limit) lists the other defaults and the process cap.
The planner plans a joined frame separately, so its pipelines have their own numbers. `Right side:` tells which
@@ -338,6 +338,7 @@ For more information about each DataFrame operation, see this component document
- [Column Backend](/documentation/components/core/column-backend.md): where batch columns live: PHP arrays or the flow_php extension
- [Batch Processing](/documentation/components/core/batch-processing.md): controlling batch sizes and memory collection
- [Partitioning](/documentation/components/core/partitioning.md): data partitioning for efficient processing
+- [Hashing](/documentation/components/core/hashing.md): row, group, run and partition hashes to detect changed data
- [Caching](/documentation/components/core/caching.md): performance optimization through caching
- [Floe File Format](/documentation/components/core/floe.md): flow's native self-describing columnar binary format
- [Source Statistics](/documentation/components/core/statistics.md): what a source declares about its rows and bytes before it is read
diff --git a/documentation/components/core/hashing.md b/documentation/components/core/hashing.md
new file mode 100644
index 000000000..39d54b8c3
--- /dev/null
+++ b/documentation/components/core/hashing.md
@@ -0,0 +1,240 @@
+# Hashing
+
+[DOC_LINK:/documentation/components/core/core.md]
+
+[TOC]
+
+A hash is 32 hex characters. Equal rows give equal hashes, in any row order and any column order.
+
+| You want the hash of | Use |
+|----------------------|--------------------------------------------|
+| each row | `row_hash()` |
+| each group of rows | `multiset_hash()` |
+| the output of a run | `analyze()->withDatasetHash()` |
+| each partition | `analyze()->withDatasetHash([ref('...')])` |
+
+## Hash of each row
+
+```php
+ 1, 'email' => 'anna@example.com'],
+ ['id' => 2, 'email' => 'ben@example.com'],
+];
+
+data_frame()
+ ->read(from_array($users))
+ ->withColumn('row_id', row_hash(ref('id'), ref('email')))
+ ->fetch();
+
+// id | email | row_id
+// 1 | anna@example.com | 2744464bb197527041dacd2b68271cb1
+// 2 | ben@example.com | c54423327bcec58acac7706cdbc4272f
+```
+
+### Find the rows that changed
+
+A row that changed has a new `row_id`. An anti join keeps the rows of today that have no equal row yesterday:
+
+```php
+ 1, 'email' => 'anna@example.com'],
+ ['id' => 2, 'email' => 'ben@example.com'],
+ ['id' => 3, 'email' => 'cleo@example.com'],
+];
+$today = [
+ ['id' => 1, 'email' => 'anna@example.com'],
+ ['id' => 2, 'email' => 'ben@flow-php.com'],
+ ['id' => 4, 'email' => 'dan@example.com'],
+];
+
+$before = data_frame()
+ ->read(from_array($yesterday))
+ ->withColumn('row_id', row_hash(ref('id'), ref('email')));
+
+$after = data_frame()
+ ->read(from_array($today))
+ ->withColumn('row_id', row_hash(ref('id'), ref('email')));
+
+$after->join($before, join_on(['row_id' => 'row_id']), JoinType::left_anti)->fetch();
+
+// id | email | row_id
+// 2 | ben@flow-php.com | f5b67f844cd96344dd9b52ad0c62b296 changed
+// 4 | dan@example.com | e82fadddb3641857a4537cc9227a44cd new
+```
+
+The same join on `id`, from `$before` to `$after`, gives the deleted rows: `id` 3.
+
+## Hash of each group
+
+```php
+ 1, 'country' => 'PL'],
+ ['id' => 2, 'country' => 'DE'],
+ ['id' => 3, 'country' => 'PL'],
+];
+$target = [
+ ['id' => 3, 'country' => 'PL'],
+ ['id' => 1, 'country' => 'PL'],
+ ['id' => 5, 'country' => 'DE'],
+];
+
+data_frame()->read(from_array($source))->groupBy('country')->aggregate(multiset_hash())->fetch();
+
+// country | _multiset_hash
+// PL | 2fe815e0c8f7f41d4485efeb669f1a76
+// DE | 01d6077fd12ee579f3a83a381ebfa16f
+
+data_frame()->read(from_array($target))->groupBy('country')->aggregate(multiset_hash())->fetch();
+
+// country | _multiset_hash
+// PL | 2fe815e0c8f7f41d4485efeb669f1a76 equal: same rows, other order
+// DE | bf27be873349d150690543b879826d53 different
+```
+
+`multiset_hash()` hashes every column. `multiset_hash(ref('id'))` hashes only `id`.
+
+## Hash of the output of a run
+
+```php
+read(from_csv('orders.csv')->withSchema($orders))
+ ->write(to_parquet('orders.parquet'))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash();
+
+$stored = data_frame()
+ ->read(from_parquet('orders.parquet'))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash();
+
+$written->algorithm; // MultisetHashAlgorithm::xxh128
+$written->total->rows; // 3
+$written->total->value; // 'f2920d3f120d5130873032ec79839580'
+$stored->total->value; // 'f2920d3f120d5130873032ec79839580', the copy is complete
+```
+
+### Choose the algorithm
+
+The default is `xxh128`. A run can use `md5` or `sha256` instead:
+
+```php
+read(from_array([
+ ['id' => 1, 'country' => 'PL'],
+ ['id' => 2, 'country' => 'DE'],
+ ['id' => 3, 'country' => 'PL'],
+ ]))
+ ->run(analyze: analyze()->withDatasetHash(algorithm: MultisetHashAlgorithm::sha256))
+ ->datasetHash();
+
+$hash->algorithm; // MultisetHashAlgorithm::sha256
+$hash->total->value; // 'cb6fbf9a3db645ba28221bc5cc601940'
+```
+
+| Algorithm | Hash of the same three rows |
+|-----------|------------------------------------|
+| `xxh128` | `31be1d609a26d996382e2a23855ebbe5` |
+| `md5` | `d3534278fef52e032aa2fe1e55c44c1b` |
+| `sha256` | `cb6fbf9a3db645ba28221bc5cc601940` |
+
+Every hash is 32 hex characters. Flow adds the first 128 bits of the digest of each row, so a `sha256` hash is not
+the SHA-256 of a file. The flow_php extension gives the same hash for each algorithm. `row_hash()` and
+`multiset_hash()` always use `xxh128`.
+
+## Hash of each partition
+
+```php
+read(from_csv('orders.csv')->withSchema($orders))
+ ->write(to_parquet('orders/orders.parquet')->partitionBy(partition_by('date')))
+ ->run(analyze: analyze()->withDatasetHash([ref('date')]));
+
+$current = [];
+
+foreach ($report->datasetHash()->partitions as $partition) {
+ $current[$partition->partitions->get('date')->segment()] = $partition->hash->value;
+}
+
+// [
+// 'date=2026-11-20' => '91793f2efee71fbc2caf6b0a8a21a8ff',
+// 'date=2026-11-21' => '6118ce10132631745a80c7e1ef61ec81',
+// ]
+```
+
+`$report->datasetHash()->total` is still the hash of all rows.
+
+### Find the partitions that changed
+
+Store `$current` after each run. In the next run it is `$previous`:
+
+```php
+datasetHash()->normalize()));
+
+// {"algorithm":"xxh128","total":{"rows":1,"value":"61d8d2f77533f36e5f23e4e587fa5e41"},"partitions":[]}
+
+$stored = json_decode(file_get_contents('monday.json'), true);
+$week = DatasetHash::fromArray($stored)->plus($tuesday->datasetHash());
+
+$week->total->rows; // 3
+$week->total->value; // '31be1d609a26d996382e2a23855ebbe5', equal to one run over both days
+```
+
+`plus()` also adds the partitions with the same values. If the two hashes have different algorithms, `plus()` throws.
+
+## Rules
+
+- Duplicate rows count: two equal rows give another hash than one.
+- Declare the schema. The same value with another type gives another hash.
+- A float, list, map, structure, json, xml or html column cannot be a partition column.
+- The hash finds accidental differences. It does not protect against tampering.
diff --git a/documentation/components/core/partitioning.md b/documentation/components/core/partitioning.md
index befdc7a5d..1248fbf26 100644
--- a/documentation/components/core/partitioning.md
+++ b/documentation/components/core/partitioning.md
@@ -141,6 +141,48 @@ Flow writes each value in full. A typed read gets the value back without changes
| `datetime` | `2026-10-02 13:00:00.123456 UTC` | `date=2026-10-02T13%3A00%3A00.123456%2B00%3A00` |
| `date` | `2026-10-02` | `date=2026-10-02` |
| `float` | `1.0E-9` | `x=1.0e-9` |
+| `string` | `null` | `country=__HIVE_DEFAULT_PARTITION__` |
+| `string` | `''` | `country=` |
+
+### Null and Empty Values
+
+A null value goes to the directory `__HIVE_DEFAULT_PARTITION__`, the name that Hive, Spark and DuckDB use. An empty
+string goes to a directory with no value. A read gives both back:
+
+```php
+read(from_array([
+ ['id' => 1, 'country' => 'PL'],
+ ['id' => 2, 'country' => null],
+ ['id' => 3, 'country' => ''],
+ ])->withSchema($users))
+ ->write(to_parquet(__DIR__ . '/users/users.parquet')
+ ->partitionBy(partition_by('country'))
+ ->saveMode(overwrite()))
+ ->run();
+
+// users/country=PL
+// users/country=__HIVE_DEFAULT_PARTITION__
+// users/country=
+
+data_frame()->read(from_parquet(__DIR__ . '/users/**/*.parquet'))->fetch();
+
+// id | country
+// 1 | PL
+// 2 | null
+// 3 | ''
+```
+
+A string value `__HIVE_DEFAULT_PARTITION__` reads back as null.
+
+### Datetime Values
A `datetime` column makes one directory for each distinct value. For one directory for each day, partition by a `date`:
diff --git a/documentation/components/extensions/flow-php-ext.md b/documentation/components/extensions/flow-php-ext.md
index fa6281591..bd164d943 100644
--- a/documentation/components/extensions/flow-php-ext.md
+++ b/documentation/components/extensions/flow-php-ext.md
@@ -80,10 +80,10 @@ Each contract with a Rust and a PHP implementation follows one pattern:
| `Flow\ETL\Adapter\Parquet\IO\Extractor\ParquetOpenSource` | `RustParquetOpenSource` | `PhpParquetOpenSource` | `ParquetSourceFile::open()` |
| `Flow\ETL\IO\Loader\File\FileWriter` | `RustParquetFileWriter` | `ParquetFileWriter` | `ParquetFileWriterFactory::writer()` |
-The extension also registers `Flow\ETL\Values\Column\{Column, ColumnBuilder, GroupedTotals, GroupedCounts}` (`RustColumn`,
-`RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`), `Flow\ETL\Values\Grouping\GroupTable`
-(`RustGroupTable`), the last three returned by `RustBackend`, and `Flow\ETL\Values\RustIterator`, the iterator its
-sources return.
+The extension also registers `Flow\ETL\Values\Column\{Column, ColumnBuilder, GroupedTotals, GroupedCounts,
+GroupedMultisetHashes}` (`RustColumn`, `RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`,
+`RustGroupedMultisetHashes`). It also registers `Flow\ETL\Values\Grouping\GroupTable` (`RustGroupTable`).
+`RustBackend` returns the last four. Its sources return the iterator `Flow\ETL\Values\RustIterator`.
## CSV and JSON writers
diff --git a/documentation/upgrading.md b/documentation/upgrading.md
index 3af04e966..181d52349 100644
--- a/documentation/upgrading.md
+++ b/documentation/upgrading.md
@@ -49,6 +49,54 @@ with(cte('tree', $query))->recursive()->select(star())->from(table('tree'));
Applies to the delete, update, insert and merge builders.
+### 4) `flow-php/etl` - a detached xml element is stored by its canonical markup
+
+| Before | After |
+|----------------------------------------------------------------|--------------------------------------|
+| a detached xml element is stored as `saveXML()`, `` | stored as its C14N markup, `` |
+| an xml element with no owner document throws in `toPhysical()` | stored as its C14N markup |
+
+Floe files and caches written by 0.45 to 0.48 keep the raw form of a detached xml element. Flow compares, hashes and
+writes such a value in that raw form. Write the file again with this version to store the C14N markup.
+
+### 5) `flow-php/etl` - `NativePHPHash` is renamed to `PhpAlgorithm`, and `hash()` takes an algorithm name
+
+| Before | After |
+|--------------------------------------------------------------------------|-----------------------------------------------------------------------|
+| `Flow\ETL\Kernels\Hash\NativePHPHash` | `Flow\ETL\Kernels\Hash\PhpAlgorithm` |
+| `hash(ref('email'), new NativePHPHash('sha256'))` | `hash(ref('email'), 'sha256')` |
+| `ref('email')->hash(new NativePHPHash('xxh64', options: ['seed' => 7]))` | `ref('email')->hash(hash_algorithm('xxh64', options: ['seed' => 7]))` |
+
+Catch `Flow\ETL\Foundation\Exception\InvalidArgumentException` instead of `\InvalidArgumentException` for an unknown algorithm name.
+
+### 6) `flow-php/etl` - `Backend` has two new methods, and the flow_php ABI is 4
+
+| Before | After |
+|------------------|-------------------------------------------------------------------------------------------|
+| - | `Backend::rowHashes(array $columns, int $count): Column` |
+| - | `Backend::groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes` |
+| `FLOW_PHP_ABI` 3 | `FLOW_PHP_ABI` 4 |
+
+A custom `Backend` must implement the two methods. Update or rebuild the flow_php extension together with the library.
+
+### 7) `flow-php/etl` - group, join, distinct and bucket keys have the declared type of their column
+
+| Before | After |
+|--------------------------------------------------------------------|--------------------------------------------------------------------|
+| a datetime batch under a date key column groups by instant | it is cast to the date first and groups by day |
+| an xml value under a string key column keys by its stored document | it keys by the text that the string cast gives |
+| int `1` and float `1.0` under a float key column are two keys | one key |
+| a join with an undeclared left schema buckets the right side first | it reads the first left batch first, so both sides key in one type |
+
+### 8) `flow-php/filesystem` - an empty string is a valid partition value
+
+| Before | After |
+|----------------------------------------------|---------------------------------------------------|
+| `new Partition('country', '')` throws | it is the partition `country` with the value `''` |
+| `Partition::fromSegment('country=')` is null | it is the partition `country` with the value `''` |
+| a partitioned write refuses an empty value | it writes the folder `country=` |
+| a read ignores a folder `country=` | it reads it as the partition column `country` |
+
---
## Upgrading from 0.47.x to 0.48.x
diff --git a/src/core/etl/src/Flow/ETL/DSL/functions.php b/src/core/etl/src/Flow/ETL/DSL/functions.php
index 346452f0d..1155be89d 100644
--- a/src/core/etl/src/Flow/ETL/DSL/functions.php
+++ b/src/core/etl/src/Flow/ETL/DSL/functions.php
@@ -128,6 +128,7 @@
use Flow\ETL\Functions\MatchCases\MatchCondition;
use Flow\ETL\Functions\Max;
use Flow\ETL\Functions\Min;
+use Flow\ETL\Functions\MultisetHash;
use Flow\ETL\Functions\Not;
use Flow\ETL\Functions\Now;
use Flow\ETL\Functions\NumberFormat;
@@ -143,6 +144,7 @@
use Flow\ETL\Functions\RegexMatchAll;
use Flow\ETL\Functions\RegexReplace;
use Flow\ETL\Functions\Round;
+use Flow\ETL\Functions\RowHash;
use Flow\ETL\Functions\RowNumber;
use Flow\ETL\Functions\Sanitize;
use Flow\ETL\Functions\ScalarFunction;
@@ -196,7 +198,7 @@
use Flow\ETL\IO\Loader\StreamLoader;
use Flow\ETL\IO\Loader\StreamLoader\Output;
use Flow\ETL\Kernels\Hash\Algorithm;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Operators\Constraint;
use Flow\ETL\Operators\Constraint\SortedByConstraint;
use Flow\ETL\Operators\Constraint\UniqueConstraint;
@@ -278,6 +280,7 @@
use Psr\Clock\ClockInterface;
use function array_is_list;
+use function array_values;
use function class_exists;
use function enum_exists;
use function Flow\Filesystem\DSL\path;
@@ -1170,12 +1173,30 @@ function concat_ws(ScalarFunction|string $separator, ScalarFunction|string ...$f
return new ConcatWithSeparator($separator, ...$functions);
}
+/**
+ * @param Algorithm|string $algorithm a hash_algos() name, or an Algorithm such as hash_algorithm('xxh64', options: [...])
+ */
#[DocumentationDSL(module: Module::CORE, type: DSLType::SCALAR_FUNCTION)]
-function hash(mixed $value, Algorithm $algorithm = new NativePHPHash()): Hash
+function hash(mixed $value, Algorithm|string $algorithm = 'xxh128'): Hash
{
return new Hash($value, $algorithm);
}
+/**
+ * @param array $options the options of PHP's hash(), for example ['seed' => 7]
+ */
+#[DocumentationDSL(module: Module::CORE, type: DSLType::HELPER)]
+function hash_algorithm(string $name = 'xxh128', bool $binary = false, array $options = []): Algorithm
+{
+ return new PhpAlgorithm($name, $binary, $options);
+}
+
+#[DocumentationDSL(module: Module::CORE, type: DSLType::SCALAR_FUNCTION)]
+function row_hash(Reference $ref, Reference ...$refs): RowHash
+{
+ return new RowHash([$ref, ...array_values($refs)]);
+}
+
/**
* @param \Flow\Types\Type|string $type
*/
@@ -1209,6 +1230,12 @@ function count(?Reference $function = null): Count
return new Count($function);
}
+#[DocumentationDSL(module: Module::CORE, type: DSLType::AGGREGATING_FUNCTION)]
+function multiset_hash(Reference ...$refs): MultisetHash
+{
+ return new MultisetHash(array_values($refs));
+}
+
/**
* Calls a user-defined function with the given parameters.
*
diff --git a/src/core/etl/src/Flow/ETL/Foundation/FlowPhpExtension.php b/src/core/etl/src/Flow/ETL/Foundation/FlowPhpExtension.php
index 41ef46492..c1a002a3d 100644
--- a/src/core/etl/src/Flow/ETL/Foundation/FlowPhpExtension.php
+++ b/src/core/etl/src/Flow/ETL/Foundation/FlowPhpExtension.php
@@ -17,7 +17,7 @@
/**
* Equals the extension's FLOW_PHP_ABI; both change together.
*/
- public const int ABI = 3;
+ public const int ABI = 4;
public function __construct(
public bool $loaded,
diff --git a/src/core/etl/src/Flow/ETL/Functions/Hash.php b/src/core/etl/src/Flow/ETL/Functions/Hash.php
index deb28cd69..c66776ad7 100644
--- a/src/core/etl/src/Flow/ETL/Functions/Hash.php
+++ b/src/core/etl/src/Flow/ETL/Functions/Hash.php
@@ -11,7 +11,7 @@
use Flow\ETL\Foundation\Exception\EvaluationException;
use Flow\ETL\Functions\Evaluation\ResultColumn;
use Flow\ETL\Kernels\Hash\Algorithm;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Values\Column\Backend;
use Flow\ETL\Values\Column\Column;
use Flow\ETL\Values\Rows;
@@ -23,19 +23,21 @@
use function Flow\Types\DSL\type_string;
use function gettype;
use function is_scalar;
+use function is_string;
use function serialize;
final class Hash implements ScalarFunction
{
use ScalarFunctionChain;
+ private readonly Algorithm $algorithm;
+
private readonly ScalarFunction $value;
- public function __construct(
- mixed $value,
- private readonly Algorithm $algorithm = new NativePHPHash(),
- ) {
+ public function __construct(mixed $value, Algorithm|string $algorithm = 'xxh128')
+ {
$this->value = $value instanceof ScalarFunction ? $value : new Literal($value);
+ $this->algorithm = is_string($algorithm) ? new PhpAlgorithm($algorithm) : $algorithm;
}
public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static
diff --git a/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php
new file mode 100644
index 000000000..f9d28de7b
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php
@@ -0,0 +1,176 @@
+ $refs [] hashes every column
+ */
+ public function __construct(
+ private readonly array $refs = [],
+ ) {
+ $this->absorbed = MultisetDigest::empty();
+ }
+
+ public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static
+ {
+ return new self(array_values($rebuild->all($data['refs'] ?? [], Reference::class)));
+ }
+
+ public function describe(): ?Description
+ {
+ return Description::compose(self::class, ['refs' => $this->refs]);
+ }
+
+ public function aggregate(Rows $rows, array $indices, Backend $backend): void
+ {
+ if ($indices === []) {
+ return;
+ }
+
+ $names = $this->names();
+ $columns = $names === [] ? $rows->columns() : $rows->select(...$names)->columns();
+ ($this->hash ??= $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128))->add(
+ count($indices) === $rows->count()
+ ? $columns
+ : array_map(static fn(Column $column): Column => $column->take($indices), $columns),
+ $backend->constant(Definitions::of('group', type_integer()), 0, count($indices)),
+ );
+ }
+
+ public function merge(array $partial, Backend $backend): void
+ {
+ $this->absorbed = $this->absorbed->plus(MultisetDigest::fromHex(type_string()->assert(
+ $partial['hash'] ?? null,
+ )));
+ }
+
+ public function partial(): array
+ {
+ return ['hash' => $this->value()];
+ }
+
+ public function partialType(): StructureType
+ {
+ return type_structure(['hash' => type_string()]);
+ }
+
+ public function grouped(Backend $backend): GroupedAggregation
+ {
+ return new MultisetHashesByGroup(
+ $this->names(),
+ $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128),
+ );
+ }
+
+ /**
+ * @return list
+ */
+ public function children(): array
+ {
+ return $this->refs;
+ }
+
+ public function deterministic(): bool
+ {
+ foreach ($this->refs as $ref) {
+ if (!$ref->deterministic()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ public function resolved(): bool
+ {
+ foreach ($this->refs as $ref) {
+ if (!$ref->resolved()) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * @param list $children
+ */
+ public function withChildren(array $children): static
+ {
+ if (count($children) !== count($this->refs)) {
+ throw InvalidLogicException::because(
+ 'multiset_hash() has %d reference children; withChildren() must receive them back.',
+ count($this->refs),
+ );
+ }
+
+ /** @var list $children */
+ return new self($children);
+ }
+
+ public function outputName(): string
+ {
+ return '_multiset_hash';
+ }
+
+ /**
+ * @return null|list null keeps every column, because a multiset_hash() without references hashes them all
+ */
+ public function references(): ?array
+ {
+ return $this->refs === [] ? null : $this->refs;
+ }
+
+ /**
+ * @return Type
+ */
+ public function returns(): Type
+ {
+ return type_string();
+ }
+
+ public function value(): string
+ {
+ return MultisetDigest::fromHex(type_string()->assert(
+ $this->hash?->hashes()->physicals()[0] ?? MultisetDigest::empty()->hex(),
+ ))->plus($this->absorbed)->hex();
+ }
+
+ /**
+ * @return list
+ */
+ private function names(): array
+ {
+ return array_map(static fn(Reference $ref): string => $ref->base(), $this->refs);
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php b/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php
new file mode 100644
index 000000000..636b65ce2
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php
@@ -0,0 +1,56 @@
+ $columns [] takes every column of each batch
+ */
+ public function __construct(
+ private array $columns,
+ private GroupedMultisetHashes $hashes,
+ ) {}
+
+ public function aggregateGroups(Rows $rows, GroupIds $ids, Backend $backend): void
+ {
+ if ($rows->isEmpty()) {
+ return;
+ }
+
+ $this->hashes->add(
+ $this->columns === [] ? $rows->columns() : $rows->select(...$this->columns)->columns(),
+ $ids->ids,
+ );
+ }
+
+ public function groupValues(int $groups, Backend $backend): Column
+ {
+ return $this->hashes->hashes();
+ }
+
+ public function partials(int $groups): array
+ {
+ return array_map(static fn(mixed $hash): array => ['hash' => $hash], $this->hashes->hashes()->physicals());
+ }
+
+ public function absorbEarlier(GroupedAggregation $earlier, array $into, Backend $backend): void
+ {
+ if (!$earlier instanceof self) {
+ throw new InvalidArgumentException('Grouped multiset hashes absorb only other grouped multiset hashes');
+ }
+
+ $this->hashes->absorbEarlier($earlier->hashes, $into);
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Functions/RowHash.php b/src/core/etl/src/Flow/ETL/Functions/RowHash.php
new file mode 100644
index 000000000..f53d9ff44
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Functions/RowHash.php
@@ -0,0 +1,93 @@
+
+ */
+ private readonly array $refs;
+
+ /**
+ * @param list $refs
+ *
+ * @throws InvalidArgumentException
+ */
+ public function __construct(array $refs)
+ {
+ if ($refs === []) {
+ throw new InvalidArgumentException(
+ 'row_hash() needs at least one column reference, for example row_hash(ref("id")).',
+ );
+ }
+
+ $this->refs = $refs;
+ }
+
+ public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static
+ {
+ return new self(array_values($rebuild->all($data['refs'] ?? null, Reference::class)));
+ }
+
+ public function describe(): ?Description
+ {
+ return Description::compose(self::class, ['refs' => $this->refs]);
+ }
+
+ /**
+ * @return non-empty-list
+ */
+ public function children(): array
+ {
+ return $this->refs;
+ }
+
+ /**
+ * @param list $children
+ */
+ public function withChildren(array $children): static
+ {
+ /** @var list $children */
+ return new self($children);
+ }
+
+ /**
+ * @return Type
+ */
+ public function returns(): Type
+ {
+ return type_string();
+ }
+
+ public function eval(Rows $rows, Backend $backend): Column
+ {
+ return $backend->rowHashes(
+ $rows->isEmpty()
+ ? []
+ : $rows->select(...array_map(
+ static fn(Reference $ref): string => $ref->base(),
+ $this->refs,
+ ))->columns(),
+ $rows->count(),
+ );
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Functions/ScalarFunctionChain.php b/src/core/etl/src/Flow/ETL/Functions/ScalarFunctionChain.php
index 2951f16eb..94e0f46f6 100644
--- a/src/core/etl/src/Flow/ETL/Functions/ScalarFunctionChain.php
+++ b/src/core/etl/src/Flow/ETL/Functions/ScalarFunctionChain.php
@@ -14,7 +14,6 @@
use Flow\ETL\Functions\Between\Boundary;
use Flow\ETL\Functions\String\StringStyles;
use Flow\ETL\Kernels\Hash\Algorithm;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
use Flow\ETL\Values\Schema;
use Flow\Types\Type;
use Flow\Types\Type\Comparison\Operator;
@@ -376,7 +375,7 @@ public function greaterThanEqual(mixed $ref): Comparison
return new Comparison($this, Operator::GREATER_THAN_EQUAL, $ref);
}
- public function hash(Algorithm $algorithm = new NativePHPHash()): Hash
+ public function hash(Algorithm|string $algorithm = 'xxh128'): Hash
{
return new Hash($this, $algorithm);
}
diff --git a/src/core/etl/src/Flow/ETL/Kernels/Hash/NativePHPHash.php b/src/core/etl/src/Flow/ETL/Kernels/Hash/PhpAlgorithm.php
similarity index 93%
rename from src/core/etl/src/Flow/ETL/Kernels/Hash/NativePHPHash.php
rename to src/core/etl/src/Flow/ETL/Kernels/Hash/PhpAlgorithm.php
index 8ff179d51..efbb32ae8 100644
--- a/src/core/etl/src/Flow/ETL/Kernels/Hash/NativePHPHash.php
+++ b/src/core/etl/src/Flow/ETL/Kernels/Hash/PhpAlgorithm.php
@@ -7,7 +7,7 @@
use Flow\ETL\Foundation\Describe\Describable;
use Flow\ETL\Foundation\Describe\Description;
use Flow\ETL\Foundation\Describe\Rebuild;
-use InvalidArgumentException;
+use Flow\ETL\Foundation\Exception\InvalidArgumentException;
use SensitiveParameter;
use function Flow\Types\DSL\type_array;
@@ -18,7 +18,7 @@
use function in_array;
use function sprintf;
-final class NativePHPHash implements Algorithm, Describable
+final class PhpAlgorithm implements Algorithm, Describable
{
private static ?array $algorithms = null;
diff --git a/src/core/etl/src/Flow/ETL/Operators/Join/HashJoin.php b/src/core/etl/src/Flow/ETL/Operators/Join/HashJoin.php
index 6f8827c22..f0bf52d28 100644
--- a/src/core/etl/src/Flow/ETL/Operators/Join/HashJoin.php
+++ b/src/core/etl/src/Flow/ETL/Operators/Join/HashJoin.php
@@ -229,13 +229,6 @@ public function join(Generator $left, Generator $right, Backend $backend): Gener
}
}
- // the bounded read has seen the first right batch, so an undescribable right side has its schema now
- [$leftKeys, $rightKeys] = $equalityKeys?->encoders($leftSchema, $rightSchema) ?? [null, null];
-
- if ($held === null) {
- $this->bucketize($rightRows, $rightBuckets, $resident ? null : $rightKeys, 'join-right', $backend);
- }
-
$leftRows = $this->tap($left, $leftSchema);
// left rows with a null join key can never match, they only surface in left/left_anti output
@@ -243,6 +236,18 @@ public function join(Generator $left, Generator $right, Backend $backend): Gener
$leftRows = (new NullKeyFilter($equalityKeys->left))->rows($leftRows);
}
+ // the right buckets key in the type both sides compare in, so an undeclared left side shows its first batch
+ if ($equalityKeys !== null && !$resident && $held === null && $leftSchema === null && !$leftRows->valid()) {
+ $leftRows = self::noRows();
+ }
+
+ // the bounded read has seen the first right batch, so an undescribable right side has its schema now
+ [$leftKeys, $rightKeys] = $equalityKeys?->encoders($leftSchema, $rightSchema) ?? [null, null];
+
+ if ($held === null) {
+ $this->bucketize($rightRows, $rightBuckets, $resident ? null : $rightKeys, 'join-right', $backend);
+ }
+
if ($resident || $held !== null) {
$rightBucket = $rightBuckets->all()[0] ?? null;
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php
index 045af4271..0f60d8f05 100644
--- a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php
+++ b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php
@@ -4,6 +4,13 @@
namespace Flow\ETL\Runtime;
+use Flow\ETL\Functions\Reference\Reference;
+use Flow\ETL\Functions\Reference\References;
+use Flow\ETL\Runtime\Executor\OutputHasher;
+use Flow\ETL\Runtime\Executor\PartitionedOutputHasher;
+use Flow\ETL\Runtime\Executor\WholeOutputHasher;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
+
final class Analyze
{
private bool $collectColumnStatistics = false;
@@ -12,6 +19,10 @@ final class Analyze
private bool $collectSourceStatistics = false;
+ private ?References $datasetHashBy = null;
+
+ private MultisetHashAlgorithm $datasetHashAlgorithm;
+
public function __construct() {}
public function collectColumnStatistics(): bool
@@ -36,6 +47,28 @@ public function withColumnStatistics(): self
return $this;
}
+ public function newOutputHasher(): ?OutputHasher
+ {
+ return match (true) {
+ $this->datasetHashBy === null => null,
+ $this->datasetHashBy->count() === 0 => new WholeOutputHasher($this->datasetHashAlgorithm),
+ default => new PartitionedOutputHasher($this->datasetHashBy, $this->datasetHashAlgorithm),
+ };
+ }
+
+ /**
+ * @param array $partitions
+ */
+ public function withDatasetHash(
+ array $partitions = [],
+ MultisetHashAlgorithm $algorithm = MultisetHashAlgorithm::xxh128,
+ ): self {
+ $this->datasetHashBy = new References(...$partitions);
+ $this->datasetHashAlgorithm = $algorithm;
+
+ return $this;
+ }
+
public function withSchema(): self
{
$this->collectSchema = true;
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/OutputHasher.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/OutputHasher.php
new file mode 100644
index 000000000..62c80e03a
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/OutputHasher.php
@@ -0,0 +1,19 @@
+ by group id
+ */
+ private array $partitions = [];
+
+ private DatasetHash $absorbed;
+
+ public function __construct(
+ private readonly References $by,
+ private readonly MultisetHashAlgorithm $algorithm,
+ ) {
+ $this->absorbed = new DatasetHash(Hash::empty(), [], $algorithm);
+ $this->declared = new Schema();
+ $this->rowPartitions = new RowPartitions($by);
+ }
+
+ public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static
+ {
+ return new self(
+ $rebuild->of($data['by'] ?? null, References::class),
+ MultisetHashAlgorithm::named(type_string()->assert($data['algorithm'] ?? null)),
+ );
+ }
+
+ public function describe(): ?Description
+ {
+ return Description::compose(self::class, ['by' => $this->by, 'algorithm' => $this->algorithm->value]);
+ }
+
+ public function add(Rows $rows, Backend $backend): void
+ {
+ if ($rows->isEmpty()) {
+ return;
+ }
+
+ if ($this->table === null) {
+ $this->assertPartitionable($rows);
+ $this->declared = $rows->schema()->keep(...array_unique([
+ ...array_map(static fn(Reference $ref): string => $ref->base(), $this->by->all()),
+ ...$this->by->names(),
+ ]));
+ $this->table = $backend->groupTable($this->by->names(), $rows->schema());
+ }
+
+ foreach ($this->by as $ref) {
+ if (
+ $rows->schema()->findDefinition($ref->base()) === null
+ && !$this->declared->get($ref->base())->isNullable()
+ ) {
+ throw self::missing($ref->base());
+ }
+ }
+
+ $ids = $this->table->assign($rows);
+ ($this->digests ??= $backend->groupedMultisetHashes($this->algorithm))->add($rows->columns(), $ids->ids);
+ ($this->rows ??= $backend->groupedCounts())->add($ids->ids, $ids->ids);
+
+ if ($ids->firstRows === []) {
+ return;
+ }
+
+ $firsts = $rows->gather($ids->firstRows)->castTo($this->declared, $backend);
+
+ for ($index = 0; $index < $firsts->count(); $index++) {
+ $this->partitions[] = $this->rowPartitions->of($firsts, $index);
+ }
+ }
+
+ public function absorb(DatasetHash $partial): void
+ {
+ $this->absorbed = $this->absorbed->plus($partial);
+ }
+
+ public function hash(): DatasetHash
+ {
+ $hashes = $this->digests?->hashes()->physicals() ?? [];
+ $counts = $this->rows?->partials() ?? [];
+ $local = [];
+ $total = Hash::empty();
+
+ foreach ($this->partitions as $id => $partitions) {
+ $local[] = new PartitionHash($partitions, new Hash($counts[$id], type_string()->assert($hashes[$id])));
+ $total = $total->plus($local[$id]->hash);
+ }
+
+ return $this->absorbed->plus(new DatasetHash($total, $local, $this->algorithm));
+ }
+
+ private static function missing(string $column): InvalidArgumentException
+ {
+ return new InvalidArgumentException(sprintf(
+ 'analyze()->withDatasetHash() groups by "%s", but a batch has no column "%s". Name only columns that '
+ . 'every row of the output has.',
+ $column,
+ $column,
+ ));
+ }
+
+ private function assertPartitionable(Rows $rows): void
+ {
+ foreach ($this->by as $ref) {
+ $definition = $rows->schema()->findDefinition($ref->base()) ?? throw self::missing($ref->base());
+
+ if ($definition->type() instanceof FloatType) {
+ throw new InvalidArgumentException(sprintf(
+ 'analyze()->withDatasetHash() cannot group by the float column "%s": 0.0 and -0.0 are one value '
+ . 'but two partition names. Cast it to a decimal string or an integer first.',
+ $ref->base(),
+ ));
+ }
+
+ Partition::assertPartitionable($ref->base(), $definition->type());
+ }
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php
index d810fee51..0c0127c6b 100644
--- a/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php
+++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php
@@ -8,10 +8,13 @@
use Flow\ETL\IO\Extractor;
use Flow\ETL\IO\Extractor\Signal;
use Flow\ETL\IO\Extractor\Statistics;
+use Flow\ETL\Runtime\Metrics\DatasetHash;
use Flow\ETL\Runtime\Metrics\Processes;
use Flow\ETL\Runtime\Metrics\SourceStatistics;
+use Flow\ETL\Values\Column\Backend;
use Flow\ETL\Values\Memory\Unit;
use Flow\ETL\Values\Rows;
+use Flow\ETL\Values\Schema;
use Flow\Telemetry\ObjectExtractor;
use Generator;
use SplObjectStorage;
@@ -19,6 +22,7 @@
use function array_map;
use function array_values;
use function max;
+use function min;
final class RunCounts
{
@@ -40,8 +44,11 @@ final class RunCounts
*/
private array $workers = [];
- public function __construct()
- {
+ private int $rowsCoveredByAbsorbedHashes = 0;
+
+ public function __construct(
+ private readonly ?OutputHasher $outputHasher = null,
+ ) {
/** @var SplObjectStorage $reads */
$reads = new SplObjectStorage();
$this->reads = $reads;
@@ -113,6 +120,39 @@ public function absorbWorkers(self $other): void
}
}
+ public function outputHasher(): ?OutputHasher
+ {
+ return $this->outputHasher;
+ }
+
+ public function hashOutput(Rows $rows, Backend $backend): void
+ {
+ if ($this->outputHasher === null) {
+ return;
+ }
+
+ if ($rows->schema()->count() === 0) {
+ $covered = min($rows->count(), $this->rowsCoveredByAbsorbedHashes);
+ $this->rowsCoveredByAbsorbedHashes -= $covered;
+ $this->outputHasher->add(Rows::fromColumns(new Schema(), [], $rows->count() - $covered), $backend);
+
+ return;
+ }
+
+ $this->outputHasher->add($rows, $backend);
+ }
+
+ public function absorbOutputHash(DatasetHash $partial): void
+ {
+ $this->outputHasher?->absorb($partial);
+ $this->rowsCoveredByAbsorbedHashes += $partial->total->rows;
+ }
+
+ public function outputHash(): ?DatasetHash
+ {
+ return $this->outputHasher?->hash();
+ }
+
public function worker(int $pid, int $peakBytes): void
{
$this->workers[$pid] = max($this->workers[$pid] ?? 0, $peakBytes);
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/StatisticsCollector.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/StatisticsCollector.php
index 8d059988a..189b6634e 100644
--- a/src/core/etl/src/Flow/ETL/Runtime/Executor/StatisticsCollector.php
+++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/StatisticsCollector.php
@@ -57,7 +57,7 @@ public function __construct(
$this->schema = $this->analyze->collectSchema() ? new Schema() : null;
}
- $this->counts = new RunCounts();
+ $this->counts = new RunCounts($this->analyze?->newOutputHasher());
if ($this->readsColumns() && $this->context->config->launcher() !== null) {
$this->context
@@ -92,6 +92,8 @@ public function capture(Rows $rows): void
$this->columnStatistics->add($definition, $rows->column($name));
}
}
+
+ $this->counts->hashOutput($rows, $this->context->backend());
}
/**
@@ -134,6 +136,7 @@ public function report(): ?Report
$this->counts->processes(Unit::processPeak()),
),
$this->analyze->collectSourceStatistics() ? $this->counts->statistics() : null,
+ $this->counts->outputHash(),
);
}
}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php
new file mode 100644
index 000000000..c8885153f
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php
@@ -0,0 +1,72 @@
+absorbed = new DatasetHash(Hash::empty(), [], $algorithm);
+ }
+
+ public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static
+ {
+ return new self(MultisetHashAlgorithm::named(type_string()->assert($data['algorithm'] ?? null)));
+ }
+
+ public function describe(): ?Description
+ {
+ return new Description(self::class, ['algorithm' => $this->algorithm->value]);
+ }
+
+ public function add(Rows $rows, Backend $backend): void
+ {
+ $this->rows += $rows->count();
+ ($this->hasher ??= $backend->groupedMultisetHashes($this->algorithm))->add($rows->columns(), $backend->constant(
+ Definitions::of('group', type_integer()),
+ 0,
+ $rows->count(),
+ ));
+ }
+
+ public function absorb(DatasetHash $partial): void
+ {
+ $this->absorbed = $this->absorbed->plus(new DatasetHash($partial->total, [], $partial->algorithm));
+ }
+
+ public function hash(): DatasetHash
+ {
+ return (new DatasetHash(
+ new Hash(
+ $this->rows,
+ type_string()->assert($this->hasher?->hashes()->physicals()[0] ?? MultisetDigest::empty()->hex()),
+ ),
+ [],
+ $this->algorithm,
+ ))->plus($this->absorbed);
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php
new file mode 100644
index 000000000..891610f43
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php
@@ -0,0 +1,111 @@
+ $partitions
+ */
+ public function __construct(
+ public Hash $total,
+ public array $partitions,
+ public MultisetHashAlgorithm $algorithm,
+ ) {}
+
+ /**
+ * @param array $data
+ *
+ * @throws InvalidArgumentException
+ */
+ public static function fromArray(array $data): self
+ {
+ foreach ([
+ 'algorithm' => type_string(),
+ 'total' => type_array(),
+ 'partitions' => type_list(type_array()),
+ ] as $key => $type) {
+ if (!array_key_exists($key, $data) || !$type->isValid($data[$key])) {
+ throw new InvalidArgumentException(sprintf(
+ 'A dataset hash needs "%s" of type %s',
+ $key,
+ $type->toString(),
+ ));
+ }
+ }
+
+ /** @var array{algorithm: string, total: array, partitions: list>} $data */
+ return new self(
+ Hash::fromArray($data['total']),
+ array_map(PartitionHash::fromArray(...), $data['partitions']),
+ MultisetHashAlgorithm::named($data['algorithm']),
+ );
+ }
+
+ /**
+ * @throws InvalidArgumentException
+ */
+ public function plus(self $other): self
+ {
+ if ($this->algorithm !== $other->algorithm) {
+ throw new InvalidArgumentException(sprintf(
+ 'A %s dataset hash cannot be added to a %s dataset hash, hash both datasets with the same algorithm',
+ $other->algorithm->value,
+ $this->algorithm->value,
+ ));
+ }
+
+ $partitions = [];
+
+ foreach ([...$this->partitions, ...$other->partitions] as $partition) {
+ // one entry is one folder: null and its folder name are one partition
+ $folder = json_encode(
+ array_map(
+ static fn(Partition $value): string => $value->value ?? Partition::NULL_VALUE,
+ $partition->partitions->toArray(),
+ ),
+ JSON_THROW_ON_ERROR,
+ );
+ $partitions[$folder] = array_key_exists($folder, $partitions)
+ ? new PartitionHash(
+ $partitions[$folder]->partitions,
+ $partitions[$folder]->hash->plus($partition->hash),
+ )
+ : $partition;
+ }
+
+ return new self($this->total->plus($other->total), array_values($partitions), $this->algorithm);
+ }
+
+ /**
+ * @return array{algorithm: string, total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>}
+ */
+ public function normalize(): array
+ {
+ return [
+ 'algorithm' => $this->algorithm->value,
+ 'total' => $this->total->normalize(),
+ 'partitions' => array_map(
+ static fn(PartitionHash $partition): array => $partition->normalize(),
+ $this->partitions,
+ ),
+ ];
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Hash.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Hash.php
new file mode 100644
index 000000000..4e94095d0
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Hash.php
@@ -0,0 +1,59 @@
+hex());
+ }
+
+ /**
+ * @param array $data
+ *
+ * @throws InvalidArgumentException
+ */
+ public static function fromArray(array $data): self
+ {
+ foreach (['rows' => type_integer(), 'value' => type_string()] as $key => $type) {
+ if (!array_key_exists($key, $data) || !$type->isValid($data[$key])) {
+ throw new InvalidArgumentException(sprintf('A hash needs "%s" of type %s', $key, $type->toString()));
+ }
+ }
+
+ /** @var array{rows: int, value: string} $data */
+ return new self($data['rows'], $data['value']);
+ }
+
+ /**
+ * @return array{rows: int, value: string}
+ */
+ public function normalize(): array
+ {
+ return ['rows' => $this->rows, 'value' => $this->value];
+ }
+
+ public function plus(self $other): self
+ {
+ return new self(
+ $this->rows + $other->rows,
+ MultisetDigest::fromHex($this->value)->plus(MultisetDigest::fromHex($other->value))->hex(),
+ );
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Metrics/PartitionHash.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/PartitionHash.php
new file mode 100644
index 000000000..5eebc118c
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/PartitionHash.php
@@ -0,0 +1,62 @@
+ $data
+ *
+ * @throws InvalidArgumentException
+ */
+ public static function fromArray(array $data): self
+ {
+ foreach ([
+ 'partitions' => type_map(type_string(), type_optional(type_string())),
+ 'hash' => type_array(),
+ ] as $key => $type) {
+ if (!array_key_exists($key, $data) || !$type->isValid($data[$key])) {
+ throw new InvalidArgumentException(sprintf(
+ 'A partition hash needs "%s" of type %s',
+ $key,
+ $type->toString(),
+ ));
+ }
+ }
+
+ /** @var array{partitions: array, hash: array} $data */
+ return new self(new Partitions(...Partition::fromArray($data['partitions'])), Hash::fromArray($data['hash']));
+ }
+
+ /**
+ * @return array{partitions: array, hash: array{rows: int, value: string}}
+ */
+ public function normalize(): array
+ {
+ $partitions = [];
+
+ foreach ($this->partitions->toArray() as $partition) {
+ $partitions[$partition->name] = $partition->value;
+ }
+
+ return ['partitions' => $partitions, 'hash' => $this->hash->normalize()];
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php
index c2ec4cfd8..aaf8c5c27 100644
--- a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php
+++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php
@@ -17,12 +17,13 @@ public function __construct(
private ?Schema $schema,
private Statistics $statistics,
private ?array $sources,
+ private ?DatasetHash $datasetHash = null,
) {}
/**
* The JSON form for CI: the same values as the typed getters, memory in bytes.
*
- * @return array{schema: null|array, statistics: array, sources: null|list>}
+ * @return array{schema: null|array, statistics: array, sources: null|list>, dataset_hash: null|array{algorithm: string, total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>}}
*/
public function normalize(): array
{
@@ -32,9 +33,15 @@ public function normalize(): array
'sources' => $this->sources === null
? null
: array_map(static fn(SourceStatistics $source): array => $source->normalize(), $this->sources),
+ 'dataset_hash' => $this->datasetHash?->normalize(),
];
}
+ public function datasetHash(): ?DatasetHash
+ {
+ return $this->datasetHash;
+ }
+
/**
* @return null|list
*/
diff --git a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Statistics/Column.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Statistics/Column.php
index 1147480e7..05933478b 100644
--- a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Statistics/Column.php
+++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Statistics/Column.php
@@ -8,6 +8,7 @@
use Flow\ETL\Functions\Reference\Reference;
use Flow\ETL\Functions\Reference\UnresolvedReference;
use Flow\ETL\Kernels\Bucketing\SeenKeys;
+use Flow\ETL\Values\Column\CanonicalEncoding;
use Flow\ETL\Values\Column\Column as ColumnData;
use Flow\ETL\Values\Grouping\KeyEncoder;
use Flow\ETL\Values\Rows;
@@ -100,7 +101,9 @@ public function add(Definition $definition, ColumnData $column): void
[$definition->name() => $column],
$column->count(),
));
- $this->seen->add($column->nullCount() === 0 ? $keys : array_values(array_diff($keys, ["\0n"])));
+ $this->seen->add(
+ $column->nullCount() === 0 ? $keys : array_values(array_diff($keys, [CanonicalEncoding::NULL])),
+ );
}
public function distinctCount(): int
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php b/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php
index 9acf71143..0651b89cf 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php
@@ -139,6 +139,16 @@ public function groupedCounts(): GroupedCounts
return $this->backend->groupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return $this->backend->rowHashes($columns, $count);
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ return $this->backend->groupedMultisetHashes($algorithm);
+ }
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Backend.php b/src/core/etl/src/Flow/ETL/Values/Column/Backend.php
index 92e1964c7..045a66be1 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/Backend.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/Backend.php
@@ -127,6 +127,15 @@ public function groupedTotals(): GroupedTotals;
public function groupedCounts(): GroupedCounts;
+ /**
+ * @param array $columns
+ *
+ * @return Column string, never null
+ */
+ public function rowHashes(array $columns, int $count): Column;
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes;
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/CanonicalEncoding.php b/src/core/etl/src/Flow/ETL/Values/Column/CanonicalEncoding.php
new file mode 100644
index 000000000..ab84f3680
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Values/Column/CanonicalEncoding.php
@@ -0,0 +1,429 @@
+ $columns
+ *
+ * @throws InvalidArgumentException
+ *
+ * @return list
+ */
+ public function ordered(array $columns, int $count): array
+ {
+ $encoded = array_fill(0, max(0, $count), '');
+
+ foreach ($columns as $column) {
+ $this->append($encoded, $column, '', self::NULL);
+ }
+
+ return $encoded;
+ }
+
+ /**
+ * @param array $columns
+ *
+ * @throws InvalidArgumentException
+ *
+ * @return list
+ */
+ public function named(array $columns, int $count): array
+ {
+ $encoded = array_fill(0, max(0, $count), '');
+ ksort($columns, SORT_STRING);
+
+ foreach ($columns as $name => $column) {
+ $this->append($encoded, $column, pack('P', strlen((string) $name)) . $name, '');
+ }
+
+ return $encoded;
+ }
+
+ /**
+ * @param list $encoded
+ * @param string $part written before each non-null value
+ * @param string $null written for each null value
+ *
+ * @throws InvalidArgumentException
+ */
+ private function append(array &$encoded, Column $column, string $part, string $null): void
+ {
+ $type = $column->type();
+ $base = $type instanceof OptionalType ? $type->base() : $type;
+ $physicals = $column->physicals();
+
+ if ($base instanceof IntegerType || $base instanceof PositiveIntegerType) {
+ $this->fixedWidth($encoded, $physicals, $part . self::INTEGER, $null, 'P', 8);
+ } elseif ($base instanceof DateTimeType) {
+ $this->fixedWidth($encoded, $physicals, $part . self::DATETIME, $null, 'P', 8);
+ } elseif ($base instanceof TimeType) {
+ $this->fixedWidth($encoded, $physicals, $part . self::TIME, $null, 'P', 8);
+ } elseif ($base instanceof DateType) {
+ $this->fixedWidth($encoded, $physicals, $part . self::DATE, $null, 'V', 4);
+ } elseif ($base instanceof FloatType) {
+ $this->floats($encoded, $physicals, $part . self::FLOAT, $null);
+ } elseif ($base instanceof BooleanType) {
+ $this->booleans($encoded, $physicals, $part, $null);
+ } elseif (
+ $base instanceof StringType
+ || $base instanceof NonEmptyStringType
+ || $base instanceof NumericStringType
+ || $base instanceof ClassStringType
+ ) {
+ $this->texts($encoded, $physicals, $part . self::STRING, $null);
+ } elseif ($base instanceof JsonType) {
+ $this->texts($encoded, $physicals, $part . self::JSON, $null);
+ } elseif ($base instanceof EnumType) {
+ $this->texts($encoded, $physicals, $part . self::ENUM, $null);
+ } elseif ($base instanceof XMLType) {
+ $this->texts($encoded, $physicals, $part . self::XML, $null);
+ } elseif ($base instanceof HTMLType) {
+ $this->texts($encoded, $physicals, $part . self::HTML, $null);
+ } elseif ($base instanceof TimeZoneType) {
+ $this->texts($encoded, $physicals, $part . self::TIMEZONE, $null);
+ } else {
+ $write = $this->writer($type);
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physicals as $i => $physical) {
+ $encoded[$i] .= $physical === null ? $null : $part . $write($physical);
+ }
+ }
+ }
+
+ /**
+ * @param list $encoded
+ * @param list $physicals ints or nulls
+ * @param positive-int $width
+ */
+ private function fixedWidth(
+ array &$encoded,
+ array $physicals,
+ string $prefix,
+ string $null,
+ string $format,
+ int $width,
+ ): void {
+ // one pack() per column: a pack() per value costs more than splitting the packed string
+ $packed = str_split(
+ pack($format . '*', ...in_array(null, $physicals, true) ? array_map(intval(...), $physicals) : $physicals),
+ $width,
+ );
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physicals as $i => $physical) {
+ $encoded[$i] .= $physical === null ? $null : $prefix . $packed[$i];
+ }
+ }
+
+ /**
+ * @param list $encoded
+ * @param list $physicals floats or nulls
+ */
+ private function floats(array &$encoded, array $physicals, string $prefix, string $null): void
+ {
+ $packed = str_split(
+ pack('e*', ...in_array(null, $physicals, true) ? array_map(floatval(...), $physicals) : $physicals),
+ 8,
+ );
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physicals as $i => $physical) {
+ $encoded[$i] .= match (true) {
+ $physical === null => $null,
+ $physical === 0.0 => $prefix . self::ZERO,
+ is_float($physical) && is_nan($physical) => $prefix . self::NAN,
+ default => $prefix . $packed[$i],
+ };
+ }
+ }
+
+ /**
+ * @param list $encoded
+ * @param list $physicals booleans or nulls
+ */
+ private function booleans(array &$encoded, array $physicals, string $part, string $null): void
+ {
+ $true = $part . self::BOOLEAN . "\x01";
+ $false = $part . self::BOOLEAN . "\x00";
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physicals as $i => $physical) {
+ $encoded[$i] .= match ($physical) {
+ null => $null,
+ true => $true,
+ default => $false,
+ };
+ }
+ }
+
+ /**
+ * @param list $encoded
+ * @param list $physicals strings or nulls
+ */
+ private function texts(array &$encoded, array $physicals, string $prefix, string $null): void
+ {
+ $lengths = [];
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physicals as $i => $physical) {
+ $encoded[$i] .= is_string($physical)
+ ? $prefix . ($lengths[strlen($physical)] ??= pack('P', strlen($physical))) . $physical
+ : $null;
+ }
+ }
+
+ /**
+ * @param Type $type
+ *
+ * @throws InvalidArgumentException
+ *
+ * @return Closure(mixed): string takes a non-null physical of $type
+ */
+ private function writer(Type $type): Closure
+ {
+ $base = $type instanceof OptionalType ? $type->base() : $type;
+
+ return match (true) {
+ $base instanceof BooleanType => static fn(bool $physical): string => $physical
+ ? self::BOOLEAN . "\x01"
+ : self::BOOLEAN . "\x00",
+ $base instanceof IntegerType,
+ $base instanceof PositiveIntegerType,
+ => static fn(int $physical): string => self::INTEGER . pack('P', $physical),
+ $base instanceof FloatType => static fn(float $physical): string => (
+ self::FLOAT . (is_nan($physical) ? self::NAN : pack('e', $physical === 0.0 ? 0.0 : $physical))
+ ),
+ $base instanceof StringType,
+ $base instanceof NonEmptyStringType,
+ $base instanceof NumericStringType,
+ $base instanceof ClassStringType,
+ => $this->text(self::STRING),
+ $base instanceof JsonType => $this->text(self::JSON),
+ $base instanceof EnumType => $this->text(self::ENUM),
+ $base instanceof XMLType => $this->text(self::XML),
+ $base instanceof HTMLType => $this->text(self::HTML),
+ $base instanceof XMLElementType => $this->element(
+ self::XML_ELEMENT,
+ (new XmlElementPhysical())->markup(...),
+ ),
+ $base instanceof HTMLElementType => $this->element(
+ self::HTML_ELEMENT,
+ (new HtmlElementPhysical())->markup(...),
+ ),
+ $base instanceof TimeZoneType => $this->text(self::TIMEZONE),
+ $base instanceof UuidType => static fn(string $physical): string => self::UUID . $physical,
+ $base instanceof DateType => static fn(int $physical): string => self::DATE . pack('V', $physical),
+ $base instanceof DateTimeType => static fn(int $physical): string => self::DATETIME . pack('P', $physical),
+ $base instanceof TimeType => static fn(int $physical): string => self::TIME . pack('P', $physical),
+ $base instanceof ListType => $this->list($this->writer($base->element())),
+ $base instanceof MapType => $this->map(
+ $this->writer($base->key()),
+ $this->writer($base->value()),
+ $base->key() instanceof IntegerType,
+ ),
+ $base instanceof StructureType => $this->structure($base),
+ $base instanceof NullType => static fn(mixed $physical): string => self::NULL,
+ default => throw new InvalidArgumentException(sprintf(
+ 'type %s has no canonical encoding, declare the type of the column',
+ $base->toString(),
+ )),
+ };
+ }
+
+ /**
+ * @return Closure(string): string
+ */
+ private function text(string $tag): Closure
+ {
+ return static fn(string $physical): string => $tag . pack('P', strlen($physical)) . $physical;
+ }
+
+ /**
+ * @param Closure(string): string $markup
+ *
+ * @return Closure(string): string
+ */
+ private function element(string $tag, Closure $markup): Closure
+ {
+ return static function (string $physical) use ($tag, $markup): string {
+ $text = $markup($physical);
+
+ return $tag . pack('P', strlen($text)) . $text;
+ };
+ }
+
+ /**
+ * @param Closure(mixed): string $element
+ *
+ * @return Closure(list): string
+ */
+ private function list(Closure $element): Closure
+ {
+ return static function (array $physical) use ($element): string {
+ $encoded = self::LIST . pack('P', count($physical));
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physical as $value) {
+ $encoded .= $value === null ? self::NULL : $element($value);
+ }
+
+ return $encoded;
+ };
+ }
+
+ /**
+ * @param Closure(mixed): string $key
+ * @param Closure(mixed): string $value
+ *
+ * @return Closure(array): string
+ */
+ private function map(Closure $key, Closure $value, bool $integerKeys): Closure
+ {
+ return static function (array $physical) use ($key, $value, $integerKeys): string {
+ $entries = [];
+
+ // @mago-ignore analysis:mixed-assignment
+ foreach ($physical as $name => $element) {
+ $entries[] =
+ $key($integerKeys ? $name : (string) $name) . ($element === null ? self::NULL : $value($element));
+ }
+
+ sort($entries, SORT_STRING);
+
+ return self::MAP . pack('P', count($entries)) . implode('', $entries);
+ };
+ }
+
+ /**
+ * @param StructureType> $type
+ *
+ * @throws InvalidArgumentException
+ *
+ * @return Closure(array): string
+ */
+ private function structure(StructureType $type): Closure
+ {
+ $elements = [];
+ $parts = [];
+
+ foreach ($type->elements() as $element) {
+ $name = (string) $element->name;
+ $elements[$name] = $this->writer($element->type);
+ $parts[$name] = pack('P', strlen($name)) . $name;
+ }
+
+ ksort($elements, SORT_STRING);
+
+ return static function (array $physical) use ($elements, $parts): string {
+ $encoded = '';
+ $present = 0;
+
+ foreach ($elements as $name => $element) {
+ if (array_key_exists($name, $physical) && $physical[$name] !== null) {
+ $encoded .= $parts[$name] . $element($physical[$name]);
+ $present++;
+ }
+ }
+
+ return self::STRUCTURE . pack('P', $present) . $encoded;
+ };
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php b/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php
new file mode 100644
index 000000000..df7bcf7b5
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php
@@ -0,0 +1,26 @@
+ $columns
+ */
+ public function add(array $columns, Column $ids): void;
+
+ public function hashes(): Column;
+
+ /**
+ * @param array $into earlier group id => this group id
+ */
+ public function absorbEarlier(self $earlier, array $into): void;
+}
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php b/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php
new file mode 100644
index 000000000..0cccf8dce
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php
@@ -0,0 +1,69 @@
+ $lowLow
+ * @param int<0, max> $lowHigh
+ * @param int<0, max> $highLow
+ * @param int<0, max> $highHigh
+ */
+ public static function ofHalfSums(int $lowLow, int $lowHigh, int $highLow, int $highHigh): self
+ {
+ return (new self($lowLow, $highLow))->plus(new self($lowHigh << 32, $highHigh << 32));
+ }
+
+ public function plus(self $other): self
+ {
+ return new self(self::wrappingAdd($this->low, $other->low), self::wrappingAdd($this->high, $other->high));
+ }
+
+ public function hex(): string
+ {
+ return sprintf('%016x%016x', $this->high, $this->low);
+ }
+
+ private static function wrappingAdd(int $a, int $b): int
+ {
+ $low = ($a & 0xFFFFFFFF) + ($b & 0xFFFFFFFF);
+ $high = (($a >> 32) & 0xFFFFFFFF) + (($b >> 32) & 0xFFFFFFFF) + ($low >> 32);
+
+ return (($high & 0xFFFFFFFF) << 32) | ($low & 0xFFFFFFFF);
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/MultisetHashAlgorithm.php b/src/core/etl/src/Flow/ETL/Values/Column/MultisetHashAlgorithm.php
new file mode 100644
index 000000000..84705afab
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Values/Column/MultisetHashAlgorithm.php
@@ -0,0 +1,32 @@
+ $algorithm->value, self::cases())),
+ ))
+ );
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php
new file mode 100644
index 000000000..14c77e637
--- /dev/null
+++ b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php
@@ -0,0 +1,106 @@
+
+ */
+ private array $digests = [];
+
+ public function __construct(
+ private readonly MultisetHashAlgorithm $algorithm,
+ private readonly CanonicalEncoding $encoding = new CanonicalEncoding(),
+ ) {}
+
+ public function add(array $columns, Column $ids): void
+ {
+ /** @var list $groups */
+ $groups = $ids->physicals();
+
+ if ($groups === []) {
+ return;
+ }
+
+ $this->grow(max($groups));
+ /** @var array> $lowLow */
+ $lowLow = [];
+ /** @var array> $lowHigh */
+ $lowHigh = [];
+ /** @var array> $highLow */
+ $highLow = [];
+ /** @var array> $highHigh */
+ $highHigh = [];
+
+ foreach ($this->encoding->named($columns, count($groups)) as $row => $bytes) {
+ /** @var array{1: int<0, max>, 2: int<0, max>, 3: int<0, max>, 4: int<0, max>} $hash */
+ $hash = unpack('N4', hash($this->algorithm->value, $bytes, true));
+ $id = $groups[$row];
+ $highHigh[$id] = ($highHigh[$id] ?? 0) + $hash[1];
+ $highLow[$id] = ($highLow[$id] ?? 0) + $hash[2];
+ $lowHigh[$id] = ($lowHigh[$id] ?? 0) + $hash[3];
+ $lowLow[$id] = ($lowLow[$id] ?? 0) + $hash[4];
+ }
+
+ foreach ($lowLow as $id => $sum) {
+ $this->digests[$id] = $this->digests[$id]->plus(MultisetDigest::ofHalfSums(
+ $sum,
+ $lowHigh[$id],
+ $highLow[$id],
+ $highHigh[$id],
+ ));
+ }
+ }
+
+ public function hashes(): Column
+ {
+ return new ScalarColumn(
+ type_string(),
+ (new PhysicalFor())->physical(type_string()),
+ array_map(static fn(MultisetDigest $digest): string => $digest->hex(), $this->digests),
+ 0,
+ );
+ }
+
+ public function absorbEarlier(GroupedMultisetHashes $earlier, array $into): void
+ {
+ $digests = $earlier instanceof self
+ ? $earlier->digests
+ : array_map(static fn(mixed $hex): MultisetDigest => MultisetDigest::fromHex(type_string()->assert(
+ $hex,
+ )), $earlier->hashes()->physicals());
+
+ foreach ($into as $from => $to) {
+ $this->grow($to);
+ $this->digests[$to] = $this->digests[$to]->plus(
+ $digests[$from] ?? throw new InvalidArgumentException(sprintf('Earlier group %d has no hash', $from)),
+ );
+ }
+ }
+
+ private function grow(int $id): void
+ {
+ while (count($this->digests) <= $id) {
+ $this->digests[] = MultisetDigest::empty();
+ }
+ }
+}
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php b/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php
index eb6af292b..24d2a28e5 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php
@@ -24,6 +24,7 @@
use Flow\ETL\Values\Column\Php\ListColumn;
use Flow\ETL\Values\Column\Php\MapColumn;
use Flow\ETL\Values\Column\Php\PhpGroupedCounts;
+use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes;
use Flow\ETL\Values\Column\Php\PhpGroupedTotals;
use Flow\ETL\Values\Column\Php\ScalarColumn;
use Flow\ETL\Values\Column\Php\StructColumn;
@@ -52,6 +53,8 @@
use function Flow\Types\DSL\type_boolean;
use function Flow\Types\DSL\type_float;
use function Flow\Types\DSL\type_integer;
+use function Flow\Types\DSL\type_string;
+use function hash;
use function intdiv;
use function is_float;
use function is_int;
@@ -667,6 +670,24 @@ public function groupedCounts(): GroupedCounts
return new PhpGroupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return new ScalarColumn(
+ type_string(),
+ (new PhysicalFor())->physical(type_string()),
+ array_map(
+ static fn(string $bytes): string => hash('xxh128', $bytes),
+ (new CanonicalEncoding())->named($columns, $count),
+ ),
+ 0,
+ );
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ return new PhpGroupedMultisetHashes($algorithm);
+ }
+
public function groupTable(array $columns, Schema $declared): GroupTable
{
return new PhpGroupTable($columns, $declared);
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Physical/ElementPosition.php b/src/core/etl/src/Flow/ETL/Values/Column/Physical/ElementPosition.php
index 19192471b..5d52dc2f9 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/Physical/ElementPosition.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/Physical/ElementPosition.php
@@ -17,7 +17,7 @@
use const XML_ELEMENT_NODE;
/**
- * Format: "\x01\0\0"; older builds wrote legacy forms.
+ * Format: "\x01\0\0".
*/
final readonly class ElementPosition
{
@@ -60,9 +60,7 @@ public function physical(string $path, string $markup, string $document): string
*/
public function pathOf(string $physical): ?string
{
- return str_starts_with($physical, "\x01") || str_starts_with($physical, "\0")
- ? substr($physical, 1, (int) strpos($physical, "\0", 1) - 1)
- : null;
+ return str_starts_with($physical, "\x01") ? substr($physical, 1, (int) strpos($physical, "\0", 1) - 1) : null;
}
/**
@@ -83,11 +81,6 @@ public function markupOf(string $physical): ?string
public function documentOf(string $physical): string
{
$pathEnd = (int) strpos($physical, "\0", 1);
-
- if (!str_starts_with($physical, "\x01")) {
- return substr($physical, $pathEnd + 1);
- }
-
$lengthEnd = (int) strpos($physical, "\0", $pathEnd + 1);
return substr($physical, $lengthEnd + 1 + (int) substr($physical, $pathEnd + 1, $lengthEnd - $pathEnd - 1));
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Physical/HtmlElementPhysical.php b/src/core/etl/src/Flow/ETL/Values/Column/Physical/HtmlElementPhysical.php
index 3a2feec47..ff1a01e13 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/Physical/HtmlElementPhysical.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/Physical/HtmlElementPhysical.php
@@ -83,24 +83,7 @@ public function fromPhysical(mixed $physical): mixed
public function markup(string $physical): string
{
- $markup = $this->position->markupOf($physical);
-
- if ($markup !== null) {
- return $markup;
- }
-
- if ($this->position->pathOf($physical) === null) {
- return $physical;
- }
-
- /** @var \Dom\HTMLElement $element */
- $element = $this->fromPhysical($physical);
- // @mago-ignore analysis:non-existent-method
- // @mago-ignore analysis:mixed-assignment
- $html = $element->ownerDocument?->saveHtml($element);
- assert(is_string($html));
-
- return $html;
+ return $this->position->markupOf($physical) ?? $physical;
}
public function fromPhysicalAll(array $physicals): array
diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Physical/XmlElementPhysical.php b/src/core/etl/src/Flow/ETL/Values/Column/Physical/XmlElementPhysical.php
index 545a19f1d..e7ea111a6 100644
--- a/src/core/etl/src/Flow/ETL/Values/Column/Physical/XmlElementPhysical.php
+++ b/src/core/etl/src/Flow/ETL/Values/Column/Physical/XmlElementPhysical.php
@@ -4,6 +4,8 @@
namespace Flow\ETL\Values\Column\Physical;
+use Dom\Element;
+use Dom\XMLDocument;
use DOMDocument;
use DOMElement;
use Flow\ETL\Foundation\Exception\InvalidArgumentException;
@@ -26,28 +28,37 @@ public function __construct(
public function toPhysical(mixed $value): mixed
{
+ /** @var DOMElement|\Dom\Element $value */
+ $path = $this->position->path($value);
+
+ if ($path === null) {
+ return $this->canonical($this->rooted($value));
+ }
+
if ($value instanceof DOMElement) {
- $path = $this->position->path($value);
- $xml = $value->ownerDocument?->saveXML($path === null ? $value : null);
+ $xml = $value->ownerDocument?->saveXML();
if ($xml === null || $xml === false) {
throw new InvalidArgumentException('Floe failed to convert DOMElement to XML string');
}
- $xml = (new XmlCharacterReferences())->decoded($xml);
-
- return $path === null ? $xml : $this->position->physical($path, $this->canonical($value), $xml);
+ return $this->position->physical(
+ $path,
+ $this->canonical($value),
+ (new XmlCharacterReferences())->decoded($xml),
+ );
}
- /** @var \Dom\Element $value */
- $path = $this->position->path($value);
// @mago-ignore analysis:non-existent-method
// @mago-ignore analysis:mixed-assignment
- $markup = $value->ownerDocument?->saveXml($path === null ? $value : null);
+ $markup = $value->ownerDocument?->saveXml();
assert(is_string($markup));
- $markup = (new XmlCharacterReferences())->decoded($markup);
- return $path === null ? $markup : $this->position->physical($path, $this->canonical($value), $markup);
+ return $this->position->physical(
+ $path,
+ $this->canonical($value),
+ (new XmlCharacterReferences())->decoded($markup),
+ );
}
public function fromPhysical(mixed $physical): mixed
@@ -69,11 +80,7 @@ public function fromPhysical(mixed $physical): mixed
public function markup(string $physical): string
{
- return (
- $this->position->markupOf($physical) ?? $this->canonical(type_instance_of(
- DOMElement::class,
- )->assert($this->fromPhysical($physical)))
- );
+ return $this->position->markupOf($physical) ?? $physical;
}
/**
@@ -90,6 +97,28 @@ public function canonical(object $element): string
return $markup;
}
+ /**
+ * @param DOMElement|\Dom\Element $element
+ *
+ * @return DOMElement|\Dom\Element
+ */
+ private function rooted(object $element): object
+ {
+ // C14N() of a node outside any document tree returns ''
+ if ($element instanceof DOMElement) {
+ $document = new DOMDocument();
+
+ return type_instance_of(DOMElement::class)->assert($document->appendChild(type_instance_of(
+ DOMElement::class,
+ )->assert($document->importNode($element, true))));
+ }
+
+ // @mago-ignore analysis:unavailable-method
+ $document = XMLDocument::createEmpty();
+
+ return type_instance_of(Element::class)->assert($document->appendChild($document->importNode($element, true)));
+ }
+
public function fromPhysicalAll(array $physicals): array
{
$values = [];
diff --git a/src/core/etl/src/Flow/ETL/Values/Grouping/KeyEncoder.php b/src/core/etl/src/Flow/ETL/Values/Grouping/KeyEncoder.php
index 2a03ed1b1..74bbfdab7 100644
--- a/src/core/etl/src/Flow/ETL/Values/Grouping/KeyEncoder.php
+++ b/src/core/etl/src/Flow/ETL/Values/Grouping/KeyEncoder.php
@@ -5,34 +5,24 @@
namespace Flow\ETL\Values\Grouping;
use Flow\ETL\Values\Column\Backend;
+use Flow\ETL\Values\Column\CanonicalEncoding;
use Flow\ETL\Values\Column\Column;
-use Flow\ETL\Values\Column\ComparableValues;
+use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Column\ValueEquality;
use Flow\ETL\Values\Rows;
use Flow\ETL\Values\Schema;
use Flow\Types\Type;
-use function array_fill;
-use function array_key_exists;
-use function count;
use function hash;
use function hexdec;
-use function is_bool;
-use function is_float;
-use function is_int;
-use function is_string;
-use function serialize;
-use function strlen;
use function substr;
-/**
- * Equal keys exactly when ComparableValues::equality() holds; every value is type-tagged.
- */
final readonly class KeyEncoder
{
/**
* @param list $columns
- * @param array> $types by position: the type a column is cast to before it is tagged
+ * @param array> $types by position: the type a column is cast to before it is encoded; the
+ * declared type when a position has none
* @param null|Schema $declared the bound schema of the batches, when the caller has one
*/
public function __construct(
@@ -58,9 +48,9 @@ public function columns(Rows $rows, Backend $backend): array
continue;
}
- $columns[] = array_key_exists($position, $this->types)
- ? $equality->cast($rows->column($name), $this->types[$position], $name)
- : $rows->column($name);
+ $type = $this->types[$position] ?? $declared?->type();
+ // Rows::column() refuses a column the batch lacks, naming it
+ $columns[] = $type === null ? $rows->column($name) : $equality->cast($rows->column($name), $type, $name);
}
return $columns;
@@ -71,36 +61,11 @@ public function columns(Rows $rows, Backend $backend): array
*/
public function of(Rows $rows): array
{
- if ($rows->isEmpty()) {
- return [];
- }
-
- $count = count($rows);
- $keys = array_fill(0, $count, '');
- $equality = new ValueEquality();
-
- foreach ($this->columns as $position => $name) {
- if (
- $rows->schema()->findDefinition($name) === null
- && $this->declared?->findDefinition($name)?->isNullable() === true
- ) {
- for ($i = 0; $i < $count; $i++) {
- $keys[$i] .= "\0n";
- }
-
- continue;
- }
-
- // Rows::column() refuses a column the batch lacks, naming it
- self::tag(
- $keys,
- array_key_exists($position, $this->types)
- ? $equality->cast($rows->column($name), $this->types[$position], $name)
- : $rows->column($name),
- );
- }
-
- return $keys;
+ return (
+ $rows->isEmpty()
+ ? []
+ : (new CanonicalEncoding())->ordered($this->columns($rows, new PhpBackend()), $rows->count())
+ );
}
/**
@@ -110,46 +75,11 @@ public function of(Rows $rows): array
*/
public static function ofColumns(array $columns, int $count): array
{
- if ($count < 1) {
- return [];
- }
-
- $keys = array_fill(0, $count, '');
-
- foreach ($columns as $column) {
- self::tag($keys, $column);
- }
-
- return $keys;
+ return $count < 1 ? [] : (new CanonicalEncoding())->ordered($columns, $count);
}
public static function bucketOf(string $key, int $buckets, int $hashOffset): int
{
return (int) hexdec(substr(hash('xxh128', $key), $hashOffset, 8)) % $buckets;
}
-
- /**
- * @param list $keys
- */
- private static function tag(array &$keys, Column $column): void
- {
- // tagged inline, not through a call per value: this runs once per value on the groupBy and dropDuplicates path
- // @mago-ignore analysis:mixed-assignment
- foreach ((new ComparableValues())->equality($column) as $i => $value) {
- if ($value === null) {
- $keys[$i] .= "\0n";
- } elseif (is_int($value)) {
- $keys[$i] .= "\0i" . $value;
- } elseif (is_string($value)) {
- $keys[$i] .= "\0s" . strlen($value) . ':' . $value;
- } elseif (is_float($value)) {
- // -0.0 === 0.0 but serializes as "-0"; serialize(), unlike a cast, keeps every digit
- $keys[$i] .= "\0d" . ($value === 0.0 ? '0' : serialize($value));
- } elseif (is_bool($value)) {
- $keys[$i] .= $value ? "\0t" : "\0f";
- } else {
- $keys[$i] .= "\0z" . serialize($value);
- }
- }
- }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Context/AggregatorFixtures.php b/src/core/etl/tests/Flow/ETL/Tests/Context/AggregatorFixtures.php
index 27d5f2941..cc1dab602 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Context/AggregatorFixtures.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Context/AggregatorFixtures.php
@@ -15,6 +15,7 @@
use Flow\ETL\Functions\Last;
use Flow\ETL\Functions\Max;
use Flow\ETL\Functions\Min;
+use Flow\ETL\Functions\MultisetHash;
use Flow\ETL\Functions\ReferenceResolver;
use Flow\ETL\Functions\StringAggregate;
use Flow\ETL\Functions\Sum;
@@ -33,6 +34,7 @@
use function Flow\ETL\DSL\last;
use function Flow\ETL\DSL\max;
use function Flow\ETL\DSL\min;
+use function Flow\ETL\DSL\multiset_hash;
use function Flow\ETL\DSL\ref;
use function Flow\ETL\DSL\schema;
use function Flow\ETL\DSL\str_schema;
@@ -60,6 +62,7 @@ public static function classes(): array
Last::class,
Max::class,
Min::class,
+ MultisetHash::class,
StringAggregate::class,
Sum::class,
];
@@ -79,6 +82,7 @@ public static function instance(string $class): AggregatingFunction
Last::class => last(ref('v')),
Max::class => max(ref('v')),
Min::class => min(ref('v')),
+ MultisetHash::class => multiset_hash(ref('v'), ref('s')),
StringAggregate::class => string_agg(ref('s'), '|', SortOrder::DESC),
Sum::class => sum(ref('v'), exact: true)->over(window()->partitionBy(ref('s'))),
default => throw InvalidArgumentException::because('%s has no fixture', $class),
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php b/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php
index b75535663..456bf5a43 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php
@@ -46,7 +46,7 @@
use Flow\ETL\IO\Loader\StreamLoader;
use Flow\ETL\IO\Loader\StreamLoader\Output;
use Flow\ETL\IO\Loader\StreamLoader\Type;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Kernels\Hash\PlainText;
use Flow\ETL\Kernels\Sort\ExternalSortConfig;
use Flow\ETL\Kernels\Sort\MemorySortConfig;
@@ -99,6 +99,8 @@
use Flow\ETL\Runtime\ErrorHandler\SkipRows;
use Flow\ETL\Runtime\ErrorHandler\ThrowError;
use Flow\ETL\Runtime\Executor\OfferedFailure;
+use Flow\ETL\Runtime\Executor\PartitionedOutputHasher;
+use Flow\ETL\Runtime\Executor\WholeOutputHasher;
use Flow\ETL\Runtime\Heartbeat\HeartbeatStage;
use Flow\ETL\Runtime\Heartbeat\ScheduledHeartbeat;
use Flow\ETL\Storage\BucketingConfig;
@@ -113,6 +115,7 @@
use Flow\ETL\Values\BatchSize;
use Flow\ETL\Values\Column\AdaptiveBackend;
use Flow\ETL\Values\Column\Frame\NoopCodec;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Join\JoinType;
use Flow\ETL\Values\Memory\Unit;
@@ -338,7 +341,7 @@ public static function others(): array
MemoryLoader::class => static fn(): Describable => new MemoryLoader(new ArrayMemory()),
MemorySortConfig::class => static fn(): Describable => new MemorySortConfig(),
MergedAggregate::class => static fn(): Describable => new MergedAggregate(sum(ref('amount'))),
- NativePHPHash::class => static fn(): Describable => new NativePHPHash('sha256', true, ['seed' => 3]),
+ PhpAlgorithm::class => static fn(): Describable => new PhpAlgorithm('sha256', true, ['seed' => 3]),
NativePHPRandomValueGenerator::class => static fn(): Describable => new NativePHPRandomValueGenerator(),
PartialAggregate::class => static fn(): Describable => new PartialAggregate(sum(ref('amount'))),
PeerFrame::class => static fn(): Describable => new PeerFrame([ref('id')->desc()]),
@@ -390,6 +393,13 @@ public static function others(): array
config()->serializer(),
),
OfferedFailure::class => static fn(): Describable => new OfferedFailure(new SkipRows()),
+ PartitionedOutputHasher::class => static fn(): Describable => new PartitionedOutputHasher(
+ refs('date', 'country'),
+ MultisetHashAlgorithm::xxh128,
+ ),
+ WholeOutputHasher::class => static fn(): Describable => new WholeOutputHasher(
+ MultisetHashAlgorithm::xxh128,
+ ),
SkipRows::class => static fn(): Describable => new SkipRows(),
SortColumn::class => static fn(): Describable => new SortColumn('id', SortOrder::DESC, NullsOrder::FIRST),
StreamLoader::class => static fn(): Describable => new StreamLoader(
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Context/ScalarFunctionFixtures.php b/src/core/etl/tests/Flow/ETL/Tests/Context/ScalarFunctionFixtures.php
index 7f245f4ee..5ab69f1fb 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Context/ScalarFunctionFixtures.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Context/ScalarFunctionFixtures.php
@@ -106,6 +106,7 @@
use Flow\ETL\Functions\Repeat;
use Flow\ETL\Functions\Reverse;
use Flow\ETL\Functions\Round;
+use Flow\ETL\Functions\RowHash;
use Flow\ETL\Functions\Sanitize;
use Flow\ETL\Functions\ScalarFunction;
use Flow\ETL\Functions\Size;
@@ -145,7 +146,7 @@
use Flow\ETL\Functions\When;
use Flow\ETL\Functions\Wordwrap;
use Flow\ETL\Functions\XPath;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Tests\Fixtures\Enum\BackedStringEnum;
use Flow\ETL\Values\Column\Backend;
use Flow\ETL\Values\Rows;
@@ -571,11 +572,15 @@ public static function all(): array
'returns' => type_optional(type_integer()),
],
Hash::class => [
- 'factory' => static fn(): ScalarFunction => new Hash(ref('string'), new NativePHPHash('sha256', true, [
+ 'factory' => static fn(): ScalarFunction => new Hash(ref('string'), new PhpAlgorithm('sha256', true, [
'seed' => 3,
])),
'returns' => type_optional(type_string()),
],
+ RowHash::class => [
+ 'factory' => static fn(): ScalarFunction => new RowHash([ref('integer'), ref('string')]),
+ 'returns' => type_string(),
+ ],
HTMLQuerySelector::class => [
'factory' => static fn(): ScalarFunction => new HTMLQuerySelector(ref('html'), lit('div')),
'returns' => type_optional(type_html_element()),
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php
index 8693a13b2..559e9bb5b 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php
@@ -9,7 +9,9 @@
use Flow\ETL\Values\Column\ColumnBuilder;
use Flow\ETL\Values\Column\Frame\Codec;
use Flow\ETL\Values\Column\GroupedCounts;
+use Flow\ETL\Values\Column\GroupedMultisetHashes;
use Flow\ETL\Values\Column\GroupedTotals;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Grouping\GroupTable;
use Flow\ETL\Values\Rows;
@@ -109,6 +111,16 @@ public function groupedCounts(): GroupedCounts
return (new PhpBackend())->groupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return (new PhpBackend())->rowHashes($columns, $count);
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ return (new PhpBackend())->groupedMultisetHashes($algorithm);
+ }
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php
index c682a160c..e8dd4539a 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php
@@ -9,7 +9,9 @@
use Flow\ETL\Values\Column\ColumnBuilder;
use Flow\ETL\Values\Column\Frame\Codec;
use Flow\ETL\Values\Column\GroupedCounts;
+use Flow\ETL\Values\Column\GroupedMultisetHashes;
use Flow\ETL\Values\Column\GroupedTotals;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Grouping\GroupTable;
use Flow\ETL\Values\Rows;
@@ -138,6 +140,16 @@ public function groupedCounts(): GroupedCounts
return $this->php->groupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return $this->php->rowHashes($columns, $count);
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ return $this->php->groupedMultisetHashes($algorithm);
+ }
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Double/MistypedColumnStub.php b/src/core/etl/tests/Flow/ETL/Tests/Double/MistypedColumnStub.php
new file mode 100644
index 000000000..62cbf1f90
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Double/MistypedColumnStub.php
@@ -0,0 +1,84 @@
+ $type
+ */
+ public function __construct(
+ private Column $column,
+ private Type $type,
+ ) {}
+
+ public function at(int $i): mixed
+ {
+ return $this->column->at($i);
+ }
+
+ public function concat(Column ...$others): Column
+ {
+ return $this->column->concat(...$others);
+ }
+
+ public function count(): int
+ {
+ return $this->column->count();
+ }
+
+ public function encode(): array
+ {
+ return $this->column->encode();
+ }
+
+ public function isNull(int $i): bool
+ {
+ return $this->column->isNull($i);
+ }
+
+ public function nullCount(): int
+ {
+ return $this->column->nullCount();
+ }
+
+ public function physicals(): array
+ {
+ return $this->column->physicals();
+ }
+
+ public function slice(int $offset, int $length): Column
+ {
+ return new self($this->column->slice($offset, $length), $this->type);
+ }
+
+ public function take(array $indices): Column
+ {
+ return $this->column->take($indices);
+ }
+
+ public function type(): Type
+ {
+ return $this->type;
+ }
+
+ public function value(int $i): mixed
+ {
+ return $this->column->value($i);
+ }
+
+ public function values(): array
+ {
+ return $this->column->values();
+ }
+
+ public function withType(Type $type): Column
+ {
+ return $this->column->withType($type);
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php
index 125a066fa..8baff3c82 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php
@@ -9,7 +9,9 @@
use Flow\ETL\Values\Column\ColumnBuilder;
use Flow\ETL\Values\Column\Frame\Codec;
use Flow\ETL\Values\Column\GroupedCounts;
+use Flow\ETL\Values\Column\GroupedMultisetHashes;
use Flow\ETL\Values\Column\GroupedTotals;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Grouping\GroupTable;
use Flow\ETL\Values\Rows;
@@ -145,6 +147,16 @@ public function groupedCounts(): GroupedCounts
return $this->php->groupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return $this->php->rowHashes($columns, $count);
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ return $this->php->groupedMultisetHashes($algorithm);
+ }
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php
index 052422170..73c93ce0b 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php
@@ -9,7 +9,9 @@
use Flow\ETL\Values\Column\ColumnBuilder;
use Flow\ETL\Values\Column\Frame\Codec;
use Flow\ETL\Values\Column\GroupedCounts;
+use Flow\ETL\Values\Column\GroupedMultisetHashes;
use Flow\ETL\Values\Column\GroupedTotals;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Grouping\GroupTable;
use Flow\ETL\Values\Rows;
@@ -32,6 +34,8 @@ final class SpyBackend implements Backend
private int $groupedTotals = 0;
+ private int $groupedMultisetHashes = 0;
+
private readonly PhpBackend $php;
private int $releases = 0;
@@ -195,11 +199,28 @@ public function groupedCounts(): GroupedCounts
return $this->php->groupedCounts();
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ return $this->php->rowHashes($columns, $count);
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ $this->groupedMultisetHashes++;
+
+ return $this->php->groupedMultisetHashes($algorithm);
+ }
+
public function groupedCountsCreated(): int
{
return $this->groupedCounts;
}
+ public function groupedMultisetHashesCreated(): int
+ {
+ return $this->groupedMultisetHashes;
+ }
+
/**
* @param list $columns
*/
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php
new file mode 100644
index 000000000..001b2062f
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php
@@ -0,0 +1,179 @@
+ 1, 'price' => 1, 'payload' => '{"a":1}'],
+ ['id' => 2, 'price' => 1.5, 'payload' => '{"a": 2}'],
+ ['id' => 3, 'price' => 2, 'payload' => '[]'],
+ ];
+
+ public function test_the_dataset_hash_does_not_depend_on_the_batch_size(): void
+ {
+ static::assertSame(
+ '72c000bf6397e932faa3a3f30eeaa6db',
+ df()
+ ->read(from_array(self::ROWS)->withBatchSize(1))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash()
+ ?->total
+ ->value,
+ );
+ static::assertSame(
+ '72c000bf6397e932faa3a3f30eeaa6db',
+ df()
+ ->read(from_array(self::ROWS))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash()
+ ?->total
+ ->value,
+ );
+ }
+
+ public function test_the_dataset_hash_equals_the_multiset_hash_aggregate(): void
+ {
+ static::assertSame(
+ [['_multiset_hash' => '72c000bf6397e932faa3a3f30eeaa6db']],
+ df()->read(from_array(self::ROWS))->aggregate([multiset_hash()])->fetch()->toArray(),
+ );
+ }
+
+ public function test_the_report_names_the_chosen_algorithm(): void
+ {
+ $hash = df()
+ ->read(from_array([
+ ['id' => 1, 'country' => 'PL'],
+ ['id' => 2, 'country' => 'DE'],
+ ['id' => 3, 'country' => 'PL'],
+ ]))
+ ->run(analyze: analyze()->withDatasetHash(algorithm: MultisetHashAlgorithm::sha256))
+ ->datasetHash();
+
+ static::assertSame(MultisetHashAlgorithm::sha256, $hash?->algorithm);
+ static::assertSame('cb6fbf9a3db645ba28221bc5cc601940', $hash->total->value);
+ }
+
+ public function test_rows_without_columns_hash_as_empty_rows(): void
+ {
+ /** @var array{1: int, 2: int} $lanes */
+ $lanes = unpack('J2', hash('xxh128', '', true));
+ $empty = new MultisetDigest($lanes[2], $lanes[1]);
+
+ static::assertSame(
+ $empty->plus($empty)->plus($empty)->hex(),
+ df()
+ ->read(from_array(self::ROWS))
+ ->drop('id', 'price', 'payload')
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash()
+ ?->total
+ ->value,
+ );
+ }
+
+ public function test_an_empty_dataset_hashes_to_zero(): void
+ {
+ static::assertSame(
+ '00000000000000000000000000000000',
+ df()
+ ->read(from_array([])->withSchema(schema(int_schema('id'))))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash()
+ ?->total
+ ->value,
+ );
+ }
+
+ #[TestWith([1])]
+ #[TestWith([100])]
+ public function test_a_partitioned_write_gets_one_partition_hash_per_folder(int $batchSize): void
+ {
+ $output = $this->cacheDir->suffix('/orders');
+ $schema = schema(date_schema('date'), str_schema('country'), int_schema('id'));
+ $orders = [
+ ['date' => new DateTimeImmutable('2026-11-20'), 'country' => 'PL', 'id' => 1],
+ ['date' => new DateTimeImmutable('2026-11-20'), 'country' => 'DE', 'id' => 2],
+ ['date' => new DateTimeImmutable('2026-11-21'), 'country' => 'PL', 'id' => 3],
+ ['date' => new DateTimeImmutable('2026-11-20'), 'country' => 'PL', 'id' => 4],
+ ];
+
+ $hash = df()
+ ->read(from_array($orders)->withSchema($schema)->withBatchSize($batchSize))
+ ->write(
+ to_floe($output->suffix('/orders.floe')->path())
+ ->saveMode(overwrite())
+ ->partitionBy(partition_by('date', 'country')),
+ )
+ ->run(analyze: analyze()->withDatasetHash([ref('date'), ref('country')]))
+ ->datasetHash();
+ $folders = [];
+
+ foreach (glob($output->path() . '/*/*', GLOB_ONLYDIR) ?: [] as $folder) {
+ $folders[] = substr($folder, strlen($output->path()) + 1);
+ }
+
+ $rows = [];
+
+ foreach ($hash->partitions ?? [] as $partition) {
+ $rows[implode('/', array_map(
+ static fn(Partition $value): string => $value->segment(),
+ $partition->partitions->toArray(),
+ ))] = $partition->hash->rows;
+ }
+
+ sort($folders);
+ ksort($rows);
+
+ static::assertSame(
+ ['date=2026-11-20/country=DE', 'date=2026-11-20/country=PL', 'date=2026-11-21/country=PL'],
+ $folders,
+ );
+ static::assertSame(
+ ['date=2026-11-20/country=DE' => 1, 'date=2026-11-20/country=PL' => 2, 'date=2026-11-21/country=PL' => 1],
+ $rows,
+ );
+ static::assertEquals(
+ df()
+ ->read(from_array($orders)->withSchema($schema))
+ ->run(analyze: analyze()->withDatasetHash())
+ ->datasetHash()
+ ?->total,
+ $hash?->total,
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/HashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/HashTest.php
index ed75dc9c9..610b6733e 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/HashTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/HashTest.php
@@ -4,7 +4,7 @@
namespace Flow\ETL\Tests\Integration\Functions;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Storage\Memory\ArrayMemory;
use Flow\ETL\Tests\FlowTestCase;
use Generator;
@@ -48,7 +48,7 @@ public function test_hash_with_different_algorithm(): void
->read(from_array([
['key' => 'value'],
]))
- ->withColumn('hash', ref('key')->hash(new NativePHPHash('sha512')))
+ ->withColumn('hash', ref('key')->hash(new PhpAlgorithm('sha512')))
->write(to_memory($memory = new ArrayMemory()))
->run();
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/MultisetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/MultisetHashTest.php
new file mode 100644
index 000000000..86130e862
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/MultisetHashTest.php
@@ -0,0 +1,30 @@
+ 'a', '_multiset_hash' => '1a61bf177bb5a2b671c0494779768cc9'],
+ ['g' => 'b', '_multiset_hash' => '5df1c2802504f984036241b9f1e54ea0'],
+ ],
+ df()
+ ->read(from_array([['g' => 'a', 'v' => 1], ['g' => 'b', 'v' => 1], ['g' => 'a', 'v' => 2]]))
+ ->groupBy('g')
+ ->aggregate(multiset_hash())
+ ->fetch()
+ ->toArray(),
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Integration/IO/Loader/PartitionedWriteTest.php b/src/core/etl/tests/Flow/ETL/Tests/Integration/IO/Loader/PartitionedWriteTest.php
index 00569177e..f13e5b33e 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Integration/IO/Loader/PartitionedWriteTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/IO/Loader/PartitionedWriteTest.php
@@ -132,6 +132,31 @@ public function test_a_null_partition_value_writes_the_hive_default_directory():
static::assertFileExists($output->suffix('/region=__HIVE_DEFAULT_PARTITION__/out.floe')->path());
}
+ public function test_an_empty_partition_value_writes_an_empty_directory_value_and_reads_back_apart_from_null(): void
+ {
+ $output = $this->cacheDir->suffix('/empty');
+
+ df()
+ ->read(from_array([['region' => '', 'text' => 'a'], ['region' => null, 'text' => 'b']]))
+ ->write(
+ to_floe($output->suffix('/out.floe')->path())
+ ->saveMode(overwrite())
+ ->partitionBy(partition_by('region')),
+ )
+ ->run();
+
+ static::assertFileExists($output->suffix('/region=/out.floe')->path());
+ static::assertFileExists($output->suffix('/region=__HIVE_DEFAULT_PARTITION__/out.floe')->path());
+ static::assertSame(
+ [['text' => 'a', 'region' => ''], ['text' => 'b', 'region' => null]],
+ df()
+ ->read(from_floe($output->suffix('/**/*.floe')->path()))
+ ->sortBy(ref('text'))
+ ->fetch()
+ ->toArray(),
+ );
+ }
+
public function test_a_partition_value_carrying_a_reserved_character_is_encoded(): void
{
$output = $this->cacheDir->suffix('/encoded');
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php b/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php
index 92cc67ab8..ed126380e 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php
@@ -6,6 +6,7 @@
use DateTimeImmutable;
use Flow\ETL\Foundation\Clock\HighResolutionTime;
+use Flow\ETL\Runtime\Metrics\DatasetHash;
use Flow\ETL\Runtime\Metrics\Processes;
use Flow\ETL\Runtime\Metrics\Report;
use Flow\ETL\Runtime\Metrics\SourceStatistics;
@@ -29,6 +30,7 @@ public static function of(
?Schema $schema = null,
?array $sources = null,
?Columns $columns = null,
+ ?DatasetHash $datasetHash = null,
): Report {
return new Report(
$schema,
@@ -44,6 +46,7 @@ public static function of(
$processes,
),
$sources,
+ $datasetHash,
);
}
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllAggregatesDeclareTheirTypeTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllAggregatesDeclareTheirTypeTest.php
index b6d1b103d..8369e6a46 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllAggregatesDeclareTheirTypeTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllAggregatesDeclareTheirTypeTest.php
@@ -15,6 +15,7 @@
use Flow\ETL\Functions\Last;
use Flow\ETL\Functions\Max;
use Flow\ETL\Functions\Min;
+use Flow\ETL\Functions\MultisetHash;
use Flow\ETL\Functions\Rank;
use Flow\ETL\Functions\ReferenceResolver;
use Flow\ETL\Functions\RowNumber;
@@ -42,6 +43,7 @@
use function Flow\ETL\DSL\last;
use function Flow\ETL\DSL\max;
use function Flow\ETL\DSL\min;
+use function Flow\ETL\DSL\multiset_hash;
use function Flow\ETL\DSL\rank;
use function Flow\ETL\DSL\ref;
use function Flow\ETL\DSL\row_number;
@@ -98,7 +100,7 @@ public function test_every_producer_declares_and_round_trips(): void
}
static::assertSame(10, $nullable);
- static::assertSame(5, $bare);
+ static::assertSame(6, $bare);
}
public function test_with_children_round_trips_in_both_directions(): void
@@ -145,6 +147,7 @@ public static function factories(): array
Last::class => static fn(): Last => last(ref('v')),
Max::class => static fn(): Max => max(ref('v')),
Min::class => static fn(): Min => min(ref('v')),
+ MultisetHash::class => static fn(): MultisetHash => multiset_hash(ref('v')),
Rank::class => static fn(): Rank => rank(),
RowNumber::class => static fn(): RowNumber => row_number(),
StringAggregate::class => static fn(): StringAggregate => string_agg(ref('v')),
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllFunctionsDeclareTheirTypeTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllFunctionsDeclareTheirTypeTest.php
index 1e4564ee8..7a310272b 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllFunctionsDeclareTheirTypeTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/AllFunctionsDeclareTheirTypeTest.php
@@ -205,18 +205,18 @@ public function test_with_children_round_trips(string $class): void
ScalarFunctionContract::withChildrenRoundTrips($fn);
}
- public function test_exactly_49_of_the_127_declare_themselves_nullable(): void
+ public function test_exactly_49_of_the_128_declare_themselves_nullable(): void
{
[$nullable, $notNull, $unavailable] = ScalarFunctionFixtures::nullabilitySplit();
- static::assertCount(127, ScalarFunctionClasses::declaring(ExtractorClasses::root('core/etl')));
+ static::assertCount(128, ScalarFunctionClasses::declaring(ExtractorClasses::root('core/etl')));
static::assertCount(49, self::declared_nullable_classes());
static::assertCount(
49,
[...$nullable, ...array_intersect($unavailable, self::declared_nullable_classes())],
'nullable set drifted: ' . implode(', ', array_diff($nullable, self::declared_nullable_classes())),
);
- static::assertCount(78, [...$notNull, ...array_diff($unavailable, self::declared_nullable_classes())]);
+ static::assertCount(79, [...$notNull, ...array_diff($unavailable, self::declared_nullable_classes())]);
}
/**
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/HashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/HashTest.php
index 206f8f2c1..a24fea5ad 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/HashTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/HashTest.php
@@ -5,8 +5,9 @@
namespace Flow\ETL\Tests\Unit\Functions;
use DateTimeImmutable;
+use Flow\ETL\Foundation\Exception\InvalidArgumentException;
use Flow\ETL\Functions\Hash;
-use Flow\ETL\Kernels\Hash\NativePHPHash;
+use Flow\ETL\Kernels\Hash\PhpAlgorithm;
use Flow\ETL\Tests\Context\DescribeRoundTrip;
use Flow\ETL\Tests\Context\FunctionContext;
use Flow\ETL\Tests\Context\ScalarFunctionFixtures;
@@ -17,6 +18,7 @@
use function Flow\ETL\DSL\datetime_schema;
use function Flow\ETL\DSL\flow_context;
use function Flow\ETL\DSL\hash;
+use function Flow\ETL\DSL\hash_algorithm;
use function Flow\ETL\DSL\list_schema;
use function Flow\ETL\DSL\lit;
use function Flow\ETL\DSL\ref;
@@ -41,9 +43,9 @@ public function test_hashing_array_value(): void
public function test_hashing_concat(): void
{
static::assertSame(
- (new NativePHPHash())->hash('test_test'),
+ (new PhpAlgorithm())->hash('test_test'),
(new FunctionContext(flow_context()))->eval(
- hash(concat(ref('value'), lit('_'), ref('value')), new NativePHPHash('xxh128')),
+ hash(concat(ref('value'), lit('_'), ref('value')), 'xxh128'),
[
'value' => 'test',
],
@@ -84,11 +86,48 @@ public function test_hashing_string_value(): void
public function test_describe_round_trips(): void
{
$context = new FunctionContext();
- $function = new Hash(ref('string'), new NativePHPHash('sha256'));
+ $function = new Hash(ref('string'), hash_algorithm('sha256'));
$rebuilt = DescribeRoundTrip::rebuilt($function);
$rows = ScalarFunctionFixtures::rows(new PhpBackend());
$schema = ScalarFunctionFixtures::schema();
static::assertSame($context->exported($function, $rows, $schema), $context->exported($rebuilt, $rows, $schema));
}
+
+ public function test_the_default_the_name_and_hash_algorithm_give_todays_hash(): void
+ {
+ $context = new FunctionContext(flow_context());
+ $schema = schema(str_schema('a'));
+
+ static::assertSame([
+ '6c78e0e3bd51d358d01e758642b85fb8',
+ '6c78e0e3bd51d358d01e758642b85fb8',
+ '6c78e0e3bd51d358d01e758642b85fb8',
+ '6c78e0e3bd51d358d01e758642b85fb8',
+ ], [
+ $context->eval(hash(ref('a')), ['a' => 'test'], $schema),
+ $context->eval(hash(ref('a'), 'xxh128'), ['a' => 'test'], $schema),
+ $context->eval(hash(ref('a'), hash_algorithm()), ['a' => 'test'], $schema),
+ $context->eval(ref('a')->hash('xxh128'), ['a' => 'test'], $schema),
+ ]);
+ }
+
+ public function test_a_name_and_the_same_algorithm_object_hash_alike(): void
+ {
+ $context = new FunctionContext(flow_context());
+ $schema = schema(str_schema('a'));
+
+ static::assertSame(
+ $context->eval(hash(ref('a'), new PhpAlgorithm('sha256')), ['a' => 'test'], $schema),
+ $context->eval(ref('a')->hash('sha256'), ['a' => 'test'], $schema),
+ );
+ }
+
+ public function test_an_unknown_name_is_refused_when_the_pipeline_is_built(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Hashing algorithm "unknown" is not supported');
+
+ hash(ref('a'), 'unknown');
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php
new file mode 100644
index 000000000..97b35755a
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php
@@ -0,0 +1,186 @@
+ 1, 'b' => 'x'], ['a' => 2, 'b' => 'y']],
+ schema(int_schema('a'), str_schema('b')),
+ );
+ $rowHashes = type_list(type_string())->assert(row_hash(ref('a'), ref('b'))->eval($rows, $backend)->values());
+ $aggregate = multiset_hash();
+ $aggregate->aggregate($rows, [0, 1], $backend);
+ $summed = multiset_hash();
+
+ foreach ($rowHashes as $rowHash) {
+ $summed->merge(['hash' => $rowHash], $backend);
+ }
+
+ static::assertSame(['bdea5ee4847f3df6cb724988fb66ecd4', 'ba7c3390ce5fcedfea5c7d697dbe1ac9'], $rowHashes);
+ static::assertSame('7866927552df0cd5b5cec6f27925079d', $aggregate->value());
+ static::assertSame($aggregate->value(), $summed->value());
+ }
+
+ public function test_the_row_order_and_the_batches_do_not_count(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(int_schema('a'), str_schema('b'));
+ $forward = multiset_hash();
+ $forward->aggregate(array_to_rows([['a' => 1, 'b' => 'x'], ['a' => 2, 'b' => 'y']], $schema), [0, 1], $backend);
+ $split = multiset_hash();
+ $split->aggregate(array_to_rows([['a' => 2, 'b' => 'y']], $schema), [0], $backend);
+ $split->aggregate(array_to_rows([['a' => 1, 'b' => 'x']], $schema), [0], $backend);
+
+ static::assertSame('7866927552df0cd5b5cec6f27925079d', $split->value());
+ static::assertSame($forward->value(), $split->value());
+ }
+
+ public function test_a_duplicate_row_counts(): void
+ {
+ $aggregate = multiset_hash();
+ $aggregate->aggregate(
+ array_to_rows([['a' => 1, 'b' => 'x'], ['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b'))),
+ [0, 1],
+ new PhpBackend(),
+ );
+
+ static::assertSame('7bd4bdc908fe7bec96e49311f6cdd9a8', $aggregate->value());
+ }
+
+ public function test_only_the_indexed_rows_are_hashed(): void
+ {
+ $aggregate = multiset_hash();
+ $aggregate->aggregate(
+ array_to_rows(
+ [['a' => 1, 'b' => 'x'], ['a' => 9, 'b' => 'z'], ['a' => 2, 'b' => 'y']],
+ schema(int_schema('a'), str_schema('b')),
+ ),
+ [0, 2],
+ new PhpBackend(),
+ );
+
+ static::assertSame('7866927552df0cd5b5cec6f27925079d', $aggregate->value());
+ }
+
+ public function test_references_name_the_hashed_columns(): void
+ {
+ $aggregate = multiset_hash(ref('a'));
+ $aggregate->aggregate(
+ array_to_rows([['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b'))),
+ [0],
+ new PhpBackend(),
+ );
+
+ static::assertSame('8e18789eac90baf2a1f6bc7cceafa11a', $aggregate->value());
+ static::assertEquals([ref('a')], $aggregate->references());
+ static::assertNull(multiset_hash()->references());
+ }
+
+ public function test_merging_two_partials_equals_one_pass(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(int_schema('a'), str_schema('b'));
+ $first = multiset_hash();
+ $first->aggregate(array_to_rows([['a' => 1, 'b' => 'x']], $schema), [0], $backend);
+ $second = multiset_hash();
+ $second->aggregate(array_to_rows([['a' => 2, 'b' => 'y']], $schema), [0], $backend);
+ $merged = multiset_hash();
+ $merged->merge($first->partial(), $backend);
+ $merged->merge($second->partial(), $backend);
+
+ static::assertSame('7866927552df0cd5b5cec6f27925079d', $merged->value());
+ static::assertSame(['hash' => '7866927552df0cd5b5cec6f27925079d'], $merged->partial());
+ }
+
+ public function test_an_aggregate_that_saw_no_row_is_zero(): void
+ {
+ static::assertSame('00000000000000000000000000000000', multiset_hash()->value());
+ static::assertSame(['hash' => '00000000000000000000000000000000'], multiset_hash()->partial());
+ }
+
+ public function test_it_declares_its_output_and_partial(): void
+ {
+ static::assertSame('_multiset_hash', multiset_hash()->outputName());
+ static::assertEquals(type_string(), multiset_hash()->returns());
+ static::assertEquals(type_structure(['hash' => type_string()]), multiset_hash()->partialType());
+ }
+
+ public function test_a_rebuilt_aggregate_keeps_its_references(): void
+ {
+ static::assertEquals(
+ [ref('a'), ref('b')],
+ DescribeRoundTrip::rebuilt(multiset_hash(ref('a'), ref('b')))->references(),
+ );
+ static::assertNull(DescribeRoundTrip::rebuilt(multiset_hash())->references());
+ static::assertEquals([ref('b')], multiset_hash(ref('a'))->withChildren([ref('b')])->children());
+ static::assertTrue(multiset_hash(ref('a'))->deterministic());
+ static::assertEquals([], multiset_hash()->withChildren([])->children());
+ static::assertTrue(multiset_hash()->resolved());
+ }
+
+ public function test_with_children_refuses_another_number_of_children(): void
+ {
+ $this->expectException(InvalidLogicException::class);
+ $this->expectExceptionMessage(
+ 'multiset_hash() has 1 reference children; withChildren() must receive them back.',
+ );
+
+ multiset_hash(ref('a'))->withChildren([]);
+ }
+
+ public function test_a_named_column_the_batch_lacks_is_refused_with_a_suggestion(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Schema definition for column "emal" not found. Did you mean one of: [email]?');
+
+ multiset_hash(ref('emal'))
+ ->aggregate(array_to_rows([['email' => 'x']], schema(str_schema('email'))), [0], new PhpBackend());
+ }
+
+ public function test_a_batch_without_rows_needs_no_named_column(): void
+ {
+ $aggregate = multiset_hash(ref('missing'));
+ $aggregate->aggregate(array_to_rows([], schema(int_schema('a'))), [], new PhpBackend());
+
+ static::assertSame(MultisetDigest::empty()->hex(), $aggregate->value());
+ }
+
+ public function test_without_references_a_null_column_hashes_like_a_batch_without_that_column(): void
+ {
+ $withNulls = multiset_hash();
+ $withNulls->aggregate(
+ array_to_rows([['a' => 1, 'b' => null]], schema(int_schema('a'), str_schema('b', true))),
+ [0],
+ new PhpBackend(),
+ );
+ $without = multiset_hash();
+ $without->aggregate(array_to_rows([['a' => 1]], schema(int_schema('a'))), [0], new PhpBackend());
+
+ static::assertSame('8e18789eac90baf2a1f6bc7cceafa11a', $withNulls->value());
+ static::assertSame($without->value(), $withNulls->value());
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php
new file mode 100644
index 000000000..78adffe41
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php
@@ -0,0 +1,125 @@
+ 'a', 'v' => 1], ['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema);
+ $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+
+ $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend);
+
+ static::assertSame(
+ ['1a61bf177bb5a2b671c0494779768cc9', '5df1c2802504f984036241b9f1e54ea0'],
+ $hashes->groupValues(2, $backend)->values(),
+ );
+ }
+
+ public function test_the_row_order_and_the_batches_do_not_count(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(str_schema('g'), int_schema('v'));
+ $table = $backend->groupTable(['g'], $schema);
+ $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+ $first = array_to_rows([['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema);
+ $second = array_to_rows([['g' => 'a', 'v' => 1]], $schema);
+
+ $hashes->aggregateGroups($first, $table->assign($first), $backend);
+ $hashes->aggregateGroups($second, $table->assign($second), $backend);
+
+ static::assertSame(
+ ['1a61bf177bb5a2b671c0494779768cc9', '5df1c2802504f984036241b9f1e54ea0'],
+ $hashes->groupValues(2, $backend)->values(),
+ );
+ }
+
+ public function test_named_columns_hash_only_those_columns(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(str_schema('g'), int_schema('v'));
+ $rows = array_to_rows([['g' => 'a', 'v' => 1], ['g' => 'a', 'v' => 1]], $schema);
+ $hashes = new MultisetHashesByGroup(['v'], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+
+ $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend);
+
+ static::assertSame(['e0191505b9cce3349c6f8093cab56dec'], $hashes->groupValues(1, $backend)->values());
+ static::assertSame([['hash' => 'e0191505b9cce3349c6f8093cab56dec']], $hashes->partials(1));
+ }
+
+ public function test_earlier_groups_are_absorbed_into_the_groups_they_map_to(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(str_schema('g'), int_schema('v'));
+ $earlierRows = array_to_rows([['g' => 'a', 'v' => 1], ['g' => 'b', 'v' => 1]], $schema);
+ $laterRows = array_to_rows([['g' => 'b', 'v' => 9], ['g' => 'a', 'v' => 2]], $schema);
+ $earlier = new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+ $later = new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+
+ $earlier->aggregateGroups($earlierRows, $backend->groupTable(['g'], $schema)->assign($earlierRows), $backend);
+ $later->aggregateGroups($laterRows, $backend->groupTable(['g'], $schema)->assign($laterRows), $backend);
+ $later->absorbEarlier($earlier, [0 => 1, 1 => 0], $backend);
+ $later->absorbEarlier($earlier, [], $backend);
+
+ static::assertSame('1a61bf177bb5a2b671c0494779768cc9', $later->groupValues(2, $backend)->values()[1]);
+ }
+
+ public function test_it_absorbs_only_grouped_multiset_hashes(): void
+ {
+ $backend = new PhpBackend();
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Grouped multiset hashes absorb only other grouped multiset hashes');
+
+ (new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)))->absorbEarlier(
+ new CountsByGroup(null, $backend->groupedCounts()),
+ [0 => 0],
+ $backend,
+ );
+ }
+
+ public function test_a_named_column_the_batch_lacks_is_refused_with_a_suggestion(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(str_schema('g'), int_schema('value'));
+ $rows = array_to_rows([['g' => 'a', 'value' => 1]], $schema);
+ $hashes = new MultisetHashesByGroup(['valu'], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128));
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Schema definition for column "valu" not found. Did you mean one of: [value]?');
+
+ $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend);
+ }
+
+ public function test_a_batch_without_rows_needs_no_named_column(): void
+ {
+ $backend = new PhpBackend();
+ $schema = schema(str_schema('g'));
+ $rows = array_to_rows([], $schema);
+ $hashes = new MultisetHashesByGroup(
+ ['missing'],
+ $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128),
+ );
+
+ $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend);
+
+ static::assertSame([], $hashes->groupValues(0, $backend)->values());
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php
new file mode 100644
index 000000000..bc21cd24d
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php
@@ -0,0 +1,147 @@
+column(
+ row_hash(ref('a'), ref('b')),
+ [['a' => 1, 'b' => 'x'], ['a' => 2, 'b' => 'y']],
+ schema(int_schema('a'), str_schema('b')),
+ )
+ ->values(),
+ );
+ }
+
+ public function test_it_equals_the_row_hashes_of_the_backend(): void
+ {
+ $rows = array_to_rows(
+ [['a' => 1, 'b' => 'x'], ['a' => 2, 'b' => 'y']],
+ schema(int_schema('a'), str_schema('b')),
+ );
+
+ static::assertSame(
+ (new PhpBackend())
+ ->rowHashes($rows->columns(), 2)
+ ->values(),
+ row_hash(ref('a'), ref('b'))->eval($rows, new PhpBackend())->values(),
+ );
+ }
+
+ public function test_the_order_of_the_references_does_not_count(): void
+ {
+ $rows = array_to_rows([['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b')));
+
+ static::assertSame(
+ row_hash(ref('a'), ref('b'))->eval($rows, new PhpBackend())->values(),
+ row_hash(ref('b'), ref('a'))->eval($rows, new PhpBackend())->values(),
+ );
+ }
+
+ public function test_a_renamed_column_gives_another_hash(): void
+ {
+ $original = array_to_rows([['a' => 1]], schema(int_schema('a')));
+ $renamed = array_to_rows([['c' => 1]], schema(int_schema('c')));
+
+ static::assertSame(
+ ['8e18789eac90baf2a1f6bc7cceafa11a'],
+ row_hash(ref('a'))->eval($original, new PhpBackend())->values(),
+ );
+ static::assertNotSame(
+ row_hash(ref('a'))->eval($original, new PhpBackend())->values(),
+ row_hash(ref('c'))->eval($renamed, new PhpBackend())->values(),
+ );
+ }
+
+ public function test_a_reference_the_batch_lacks_is_refused_with_a_suggestion(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Schema definition for column "emal" not found. Did you mean one of: [email]?');
+
+ row_hash(ref('a'), ref('emal'))->eval(
+ array_to_rows([['a' => 1, 'email' => 'x']], schema(int_schema('a'), str_schema('email'))),
+ new PhpBackend(),
+ );
+ }
+
+ public function test_a_batch_without_rows_needs_no_referenced_column(): void
+ {
+ static::assertSame(
+ [],
+ row_hash(ref('missing'))->eval(Rows::fromColumns(schema(), [], 0), new PhpBackend())->values(),
+ );
+ }
+
+ public function test_a_null_value_hashes_like_a_row_without_that_column(): void
+ {
+ static::assertSame(
+ ['8e18789eac90baf2a1f6bc7cceafa11a'],
+ row_hash(ref('a'), ref('b'))
+ ->eval(
+ array_to_rows([['a' => 1, 'b' => null]], schema(int_schema('a'), str_schema('b', true))),
+ new PhpBackend(),
+ )
+ ->values(),
+ );
+ static::assertSame(
+ ['8e18789eac90baf2a1f6bc7cceafa11a'],
+ row_hash(ref('a'))->eval(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend())->values(),
+ );
+ }
+
+ public function test_it_returns_a_not_null_string(): void
+ {
+ static::assertEquals(type_string(), row_hash(ref('a'))->returns());
+ }
+
+ public function test_it_needs_at_least_one_reference(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('row_hash() needs at least one column reference');
+
+ new RowHash([]);
+ }
+
+ public function test_its_children_are_its_references_and_a_rebuilt_one_hashes_alike(): void
+ {
+ $function = row_hash(ref('a'), ref('b'));
+ $rows = array_to_rows([['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b')));
+
+ static::assertEquals([ref('a'), ref('b')], $function->children());
+ static::assertSame(
+ $function->eval($rows, new PhpBackend())->values(),
+ $function
+ ->withChildren([ref('b'), ref('a')])
+ ->eval($rows, new PhpBackend())
+ ->values(),
+ );
+ static::assertSame(
+ $function->eval($rows, new PhpBackend())->values(),
+ DescribeRoundTrip::rebuilt($function)->eval($rows, new PhpBackend())->values(),
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/IO/Loader/RowPartitionsTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/IO/Loader/RowPartitionsTest.php
index 0959e35b0..6160cc4be 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/IO/Loader/RowPartitionsTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/IO/Loader/RowPartitionsTest.php
@@ -5,6 +5,7 @@
namespace Flow\ETL\Tests\Unit\IO\Loader;
use DateTimeImmutable;
+use Flow\ETL\Foundation\Exception\SchemaDefinitionNotFoundException;
use Flow\ETL\IO\Loader\RowPartitions;
use Flow\ETL\Tests\FlowTestCase;
use Flow\ETL\Values\Schema\Definition;
@@ -101,4 +102,14 @@ public function test_a_structure_column_is_refused(): void
'a' => 'x',
])]], schema(structure_schema('v', $structure))), 0);
}
+
+ public function test_an_aliased_reference_needs_a_column_of_the_alias_name(): void
+ {
+ $this->expectException(SchemaDefinitionNotFoundException::class);
+ $this->expectExceptionMessage('Schema definition for column "day" not found.');
+
+ (new RowPartitions(refs(ref('date')->as('day'))))->of(array_to_rows([[
+ 'date' => '2026-11-20',
+ ]], schema(str_schema('date'))), 0);
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Bucketing/HashBucketingTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Bucketing/HashBucketingTest.php
index e5ab84564..7f16e74ca 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Bucketing/HashBucketingTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Bucketing/HashBucketingTest.php
@@ -21,6 +21,7 @@
use function hexdec;
use function iterator_to_array;
use function ksort;
+use function pack;
use function range;
use function sort;
use function substr;
@@ -29,16 +30,18 @@ final class HashBucketingTest extends FlowTestCase
{
public function test_a_hash_offset_reads_other_digits_of_the_key_hash(): void
{
- $hash = hash('xxh128', "\0i1");
+ $hash = hash('xxh128', "\x02\x01\x00\x00\x00\x00\x00\x00\x00");
static::assertSame(
(int) hexdec(substr($hash, 0, 8)) % 16,
- (new HashBucketing(new KeyEncoder(['id']), 16, new NativePHPRandomValueGenerator()))->indexOf("\0i1"),
+ (new HashBucketing(new KeyEncoder(['id']), 16, new NativePHPRandomValueGenerator()))->indexOf(
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00",
+ ),
);
static::assertSame(
(int) hexdec(substr($hash, 8, 8)) % 16,
(new HashBucketing(new KeyEncoder(['id']), 16, new NativePHPRandomValueGenerator(), 'bucket', 8))->indexOf(
- "\0i1",
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00",
),
);
}
@@ -47,7 +50,9 @@ public function test_one_bucket_takes_every_key(): void
{
static::assertSame(
0,
- (new HashBucketing(new KeyEncoder(['id']), 1, new NativePHPRandomValueGenerator()))->indexOf("\0i1"),
+ (new HashBucketing(new KeyEncoder(['id']), 1, new NativePHPRandomValueGenerator()))->indexOf(
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00",
+ ),
);
}
@@ -272,7 +277,7 @@ public function test_every_row_of_a_unique_key_lands_in_its_key_bucket_in_row_or
$expected = [];
foreach (range(0, 99) as $id) {
- $expected[$strategy->indexOf("\0i{$id}")][] = $id;
+ $expected[$strategy->indexOf("\x02" . pack('P', $id))][] = $id;
}
$actual = [];
@@ -322,7 +327,7 @@ public function test_a_batch_without_a_nullable_declared_key_column_lands_with_t
}
static::assertCount(1, $buckets);
- static::assertSame($strategy->indexOf("\0n"), $buckets[0]->index);
+ static::assertSame($strategy->indexOf("\x00"), $buckets[0]->index);
static::assertSame([1, 2, 3], $values);
}
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/NativePHPHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/NativePHPHashTest.php
deleted file mode 100644
index 37dcbc088..000000000
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/NativePHPHashTest.php
+++ /dev/null
@@ -1,32 +0,0 @@
-hash('test'));
- }
-
- public function test_support_sha512_hash(): void
- {
- static::assertSame(
- 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff',
- (new NativePHPHash('sha512'))->hash('test'),
- );
- }
-
- public function test_hashing_unknown_algorithm(): void
- {
- static::expectException(InvalidArgumentException::class);
-
- new NativePHPHash('unknown');
- }
-}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/PhpAlgorithmTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/PhpAlgorithmTest.php
new file mode 100644
index 000000000..a9d4f24c6
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/PhpAlgorithmTest.php
@@ -0,0 +1,47 @@
+hash('test'));
+ static::assertSame('6c78e0e3bd51d358d01e758642b85fb8', hash_algorithm()->hash('test'));
+ }
+
+ public function test_support_sha512_hash(): void
+ {
+ static::assertSame(
+ 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff',
+ (new PhpAlgorithm('sha512'))->hash('test'),
+ );
+ static::assertSame(
+ 'ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff',
+ hash_algorithm('sha512')->hash('test'),
+ );
+ }
+
+ public function test_hash_algorithm_passes_the_binary_flag_and_the_options(): void
+ {
+ static::assertEquals(new PhpAlgorithm('xxh64', true, ['seed' => 7]), hash_algorithm('xxh64', true, [
+ 'seed' => 7,
+ ]));
+ }
+
+ public function test_hashing_unknown_algorithm(): void
+ {
+ static::expectException(InvalidArgumentException::class);
+ static::expectExceptionMessage('Hashing algorithm "unknown" is not supported');
+
+ hash_algorithm('unknown');
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Sort/ExternalSortTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Sort/ExternalSortTest.php
index 0a8594e54..a055c1a67 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Sort/ExternalSortTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Sort/ExternalSortTest.php
@@ -145,13 +145,14 @@ public function test_the_last_run_spilled_after_the_input_ends_returns_freed_mem
public function test_data_over_the_limit_spills_and_merges(): void
{
$storage = new SpyRowsStorage(new MemoryRowsStorage());
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with([ref('id')->asc()], $storage);
static::assertSame(
[0, 1, 2, 3, 10, 11, 12, 13],
IdRows::ids($sort->sort(
- IdRows::batches([10, 0], [11, 1], [2, 12], [13, 3]),
+ IdRows::reportedFrames($backend, $yields, [10, 0], [11, 1], [2, 12], [13, 3]),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
)),
@@ -309,13 +310,14 @@ public function test_a_spill_whose_sort_would_cross_the_cap_writes_runs_that_fit
public function test_a_spilled_run_is_written_in_frames_of_at_most_the_batch_size(): void
{
$storage = new RecordingRowsStorage(new MemoryRowsStorage());
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with([ref('id')->asc()], $storage, batchSize: 2);
static::assertSame(
[0, 1, 2, 3, 4, 10, 11, 12, 13, 14],
IdRows::ids($sort->sort(
- IdRows::batches([14, 10, 12, 11, 13], [4, 0, 2, 1, 3]),
+ IdRows::reportedFrames($backend, $yields, [14, 10, 12, 11, 13], [4, 0, 2, 1, 3]),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
)),
@@ -402,7 +404,8 @@ public function test_an_in_memory_sort_counts_every_row_it_takes_once(): void
public function test_a_spilling_sort_counts_every_row_it_takes_once_and_is_busy_while_it_merges(): void
{
$progress = new ProgressSpy();
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with(
[ref('id')->asc()],
mergeFanIn: 2,
@@ -410,10 +413,11 @@ public function test_a_spilling_sort_counts_every_row_it_takes_once_and_is_busy_
);
IdRows::ids($sort->sort(
- $sort->counted(IdRows::batches(...array_map(
- static fn(int $i): array => [($i * 2) + 1, $i * 2],
- range(9, 0),
- ))),
+ $sort->counted(IdRows::reportedFrames(
+ $backend,
+ $yields,
+ ...array_map(static fn(int $i): array => [($i * 2) + 1, $i * 2], range(9, 0)),
+ )),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
));
@@ -426,13 +430,18 @@ public function test_a_spilling_sort_counts_every_row_it_takes_once_and_is_busy_
public function test_runs_past_the_fan_in_are_reduced_to_merged_runs_first(): void
{
$storage = new RecordingRowsStorage(new MemoryRowsStorage());
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with([ref('id')->asc()], $storage, mergeFanIn: 2);
static::assertSame(
range(0, 19),
IdRows::ids($sort->sort(
- IdRows::batches(...array_map(static fn(int $i): array => [($i * 2) + 1, $i * 2], range(9, 0))),
+ IdRows::reportedFrames(
+ $backend,
+ $yields,
+ ...array_map(static fn(int $i): array => [($i * 2) + 1, $i * 2], range(9, 0)),
+ ),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
)),
@@ -448,11 +457,12 @@ public function test_merged_runs_go_to_the_merge_storage(): void
$spill = new RecordingRowsStorage(new MemoryRowsStorage());
$merge = new RecordingRowsStorage(new MemoryRowsStorage());
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with([ref('id')->asc()], $spill, 2, mergeStorage: $merge);
IdRows::ids($sort->sort(
- IdRows::batches([3], [2], [1]),
+ IdRows::reportedFrames($backend, $yields, [3], [2], [1]),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
));
@@ -483,13 +493,18 @@ public function test_a_limit_under_the_memory_limit_keeps_the_first_rows(): void
public function test_a_limit_over_the_memory_limit_stops_every_merge_at_the_limit(): void
{
$storage = new SpyRowsStorage(new MemoryRowsStorage());
- $backend = config()->backend();
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
$sort = ExternalSortMother::with([ref('id')->asc()], $storage, mergeFanIn: 2);
static::assertSame(
[0, 1, 2],
IdRows::ids($sort->sort(
- IdRows::batches(...array_map(static fn(int $i): array => [$i + 10, $i], range(9, 0))),
+ IdRows::reportedFrames(
+ $backend,
+ $yields,
+ ...array_map(static fn(int $i): array => [$i + 10, $i], range(9, 0)),
+ ),
$backend,
new MemoryBudget($backend, Unit::fromBytes(1), null),
3,
@@ -516,14 +531,16 @@ public function test_a_limit_over_the_memory_limit_stops_every_merge_at_the_limi
public function test_spilled_sort_equals_one_in_memory_sort(int $seed): void
{
$dataset = SortDatasetMother::random($seed);
- $input = (static function () use ($dataset): Generator {
+ $backend = new ReportedMemoryBackend();
+ $input = (static function () use ($dataset, $backend): Generator {
foreach ($dataset['runs'] as $rows) {
+ $backend->reported += 1_000_000;
+
yield array_to_rows($rows, $dataset['schema']);
}
})();
$sorted = rows($dataset['schema']);
- $backend = config()->backend();
$sort = ExternalSortMother::with($dataset['columns'], mergeFanIn: 2, batchSize: $dataset['mergeBatchSize']);
foreach ($sort->sort($input, $backend, new MemoryBudget($backend, Unit::fromBytes(1), null)) as $batch) {
@@ -559,16 +576,20 @@ public function test_both_storages_are_cleared_when_the_first_clear_throws(): vo
$mergeStorage->append('pre-existing', array_to_rows([['id' => 1]], schema(int_schema('id'))));
$merge->add(new Bucket('pre-existing', 1, 0));
+ $backend = new ReportedMemoryBackend();
+
try {
iterator_to_array(
(new ExternalSort([ref('id')->asc()], $spill, $merge, new NativePHPRandomValueGenerator(), 2))->sort(
- (static function (): Generator {
- yield from IdRows::batches([9, 8], [7, 6]);
+ (static function () use ($backend): Generator {
+ $yields = 0;
+
+ yield from IdRows::reportedFrames($backend, $yields, [9, 8], [7, 6]);
throw new RuntimeException('upstream failed');
})(),
- config()->backend(),
- new MemoryBudget(config()->backend(), Unit::fromBytes(1), null),
+ $backend,
+ new MemoryBudget($backend, Unit::fromBytes(1), null),
),
false,
);
@@ -597,6 +618,8 @@ public function test_throws_when_merge_fan_in_below_one(): void
public function test_of_merges_into_the_spill_storage_without_a_merge_storage(): void
{
$spill = new RecordingRowsStorage(new MemoryRowsStorage());
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
iterator_to_array(
ExternalSort::of(
@@ -605,12 +628,16 @@ public function test_of_merges_into_the_spill_storage_without_a_merge_storage():
->storage($spill)
->memoryLimit(Unit::fromBytes(1))
->bucketsCount(2)
- ->build(path('memory://spill'), new PhpBackend()),
+ ->build(path('memory://spill'), $backend),
new NativePHPRandomValueGenerator(),
)->sort(
- IdRows::batches(...array_map(static fn(int $id): array => [$id], range(9, 0))),
- new PhpBackend(),
- new MemoryBudget(new PhpBackend(), Unit::fromBytes(1), null),
+ IdRows::reportedFrames(
+ $backend,
+ $yields,
+ ...array_map(static fn(int $id): array => [$id], range(9, 0)),
+ ),
+ $backend,
+ new MemoryBudget($backend, Unit::fromBytes(1), null),
),
false,
);
@@ -625,6 +652,8 @@ public function test_of_merges_into_the_merge_storage_when_set(): void
{
$spill = new RecordingRowsStorage(new MemoryRowsStorage());
$merge = new RecordingRowsStorage(new MemoryRowsStorage());
+ $backend = new ReportedMemoryBackend();
+ $yields = 0;
iterator_to_array(
ExternalSort::of(
@@ -634,12 +663,16 @@ public function test_of_merges_into_the_merge_storage_when_set(): void
->mergeStorage($merge)
->memoryLimit(Unit::fromBytes(1))
->bucketsCount(2)
- ->build(path('memory://spill'), new PhpBackend()),
+ ->build(path('memory://spill'), $backend),
new NativePHPRandomValueGenerator(),
)->sort(
- IdRows::batches(...array_map(static fn(int $id): array => [$id], range(9, 0))),
- new PhpBackend(),
- new MemoryBudget(new PhpBackend(), Unit::fromBytes(1), null),
+ IdRows::reportedFrames(
+ $backend,
+ $yields,
+ ...array_map(static fn(int $id): array => [$id], range(9, 0)),
+ ),
+ $backend,
+ new MemoryBudget($backend, Unit::fromBytes(1), null),
),
false,
);
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Operators/Join/HashJoinTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Operators/Join/HashJoinTest.php
index 535362f42..03ce67586 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Operators/Join/HashJoinTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Operators/Join/HashJoinTest.php
@@ -5,6 +5,7 @@
namespace Flow\ETL\Tests\Unit\Operators\Join;
use ArrayObject;
+use DateTimeImmutable;
use Flow\ETL\Foundation\Describe\Rebuild;
use Flow\ETL\Foundation\Exception\JoinException;
use Flow\ETL\Foundation\ProgressUnit;
@@ -34,6 +35,8 @@
use function Flow\ETL\DSL\array_to_rows;
use function Flow\ETL\DSL\config_builder;
+use function Flow\ETL\DSL\date_schema;
+use function Flow\ETL\DSL\datetime_schema;
use function Flow\ETL\DSL\flow_context;
use function Flow\ETL\DSL\int_schema;
use function Flow\ETL\DSL\rows;
@@ -1125,4 +1128,65 @@ public function test_a_spilling_join_ends_its_stage_once_after_its_last_bucket_p
static::assertSame(1, $stage->doneCalls(StageName::join));
}
+
+ public function test_an_undeclared_left_side_buckets_both_sides_in_the_type_they_compare_in(): void
+ {
+ $joined = [];
+
+ foreach (HashJoinMother::grace(Expression::on(['day' => 'at']), JoinType::inner)->join(
+ (static function () {
+ yield array_to_rows([['day' => new DateTimeImmutable('2024-01-01')]], schema(date_schema('day')));
+ })(),
+ (static function () {
+ yield array_to_rows(
+ [['at' => new DateTimeImmutable('2024-01-01 00:00:00 UTC'), 'name' => 'Alice']],
+ schema(datetime_schema('at'), str_schema('name')),
+ );
+ })(),
+ flow_context()->backend(),
+ ) as $batch) {
+ foreach ($batch->toArray() as $row) {
+ $joined[] = $row['name'];
+ }
+ }
+
+ static::assertSame(['Alice'], $joined);
+ }
+
+ public function test_only_an_undeclared_left_side_is_read_before_the_right_side_is_bucketized(): void
+ {
+ /** @var ArrayObject $order */
+ $order = new ArrayObject();
+ $left = static function () use ($order) {
+ $order->append('left read');
+
+ yield array_to_rows([['id' => 1]], schema(int_schema('id')));
+ };
+ $right = static function (ReportedMemoryBackend $backend) use ($order) {
+ yield array_to_rows([['user_id' => 1]], schema(int_schema('user_id')));
+ // the build side outgrows the memory limit, so it is bucketized
+ $backend->reported = 2_000_000_000;
+ yield array_to_rows([['user_id' => 2]], schema(int_schema('user_id')));
+
+ $order->append('right read');
+ };
+ $spilling = static fn(): HashJoin => HashJoinMother::with(
+ Expression::on(['id' => 'user_id']),
+ JoinType::inner,
+ new SpyRowsStorage(new MemoryRowsStorage()),
+ memoryLimit: Unit::fromGb(1),
+ );
+ $declared = type_instance_of(HashJoin::class)->assert($spilling()->bind(
+ schema(int_schema('id')),
+ schema(int_schema('user_id')),
+ )->step);
+
+ iterator_to_array($declared->join($left(), $right($backend = new ReportedMemoryBackend()), $backend), false);
+ $declaredOrder = $order->getArrayCopy();
+ $order->exchangeArray([]);
+ iterator_to_array($spilling()->join($left(), $right($backend = new ReportedMemoryBackend()), $backend), false);
+
+ static::assertSame(['right read', 'left read'], $declaredOrder);
+ static::assertSame(['left read', 'right read'], $order->getArrayCopy());
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php
new file mode 100644
index 000000000..f82a76d51
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php
@@ -0,0 +1,54 @@
+newOutputHasher());
+ static::assertSame($analyze, $analyze->withDatasetHash());
+ static::assertEquals(new WholeOutputHasher(MultisetHashAlgorithm::xxh128), $analyze->newOutputHasher());
+ static::assertFalse($analyze->collectSchema());
+ }
+
+ public function test_named_columns_give_a_partitioned_hasher(): void
+ {
+ static::assertEquals(
+ new PartitionedOutputHasher(refs(ref('date'), ref('country')), MultisetHashAlgorithm::xxh128),
+ analyze()->withDatasetHash([ref('date'), ref('country')])->newOutputHasher(),
+ );
+ }
+
+ public function test_the_algorithm_reaches_the_hasher(): void
+ {
+ static::assertEquals(
+ new WholeOutputHasher(MultisetHashAlgorithm::sha256),
+ analyze()->withDatasetHash(algorithm: MultisetHashAlgorithm::sha256)->newOutputHasher(),
+ );
+ static::assertEquals(
+ new PartitionedOutputHasher(refs(ref('date')), MultisetHashAlgorithm::md5),
+ analyze()->withDatasetHash([ref('date')], MultisetHashAlgorithm::md5)->newOutputHasher(),
+ );
+ }
+
+ public function test_each_call_builds_a_new_hasher(): void
+ {
+ $analyze = analyze()->withDatasetHash();
+
+ static::assertNotSame($analyze->newOutputHasher(), $analyze->newOutputHasher());
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/PartitionedOutputHasherTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/PartitionedOutputHasherTest.php
new file mode 100644
index 000000000..07dba8309
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/PartitionedOutputHasherTest.php
@@ -0,0 +1,347 @@
+add(array_to_rows([
+ ['country' => 'PL', 'id' => 1],
+ ['country' => 'PL', 'id' => 3],
+ ], $schema), new PhpBackend());
+ $de = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $de->add(array_to_rows([['country' => 'DE', 'id' => 2]], $schema), new PhpBackend());
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([
+ ['country' => 'PL', 'id' => 1],
+ ['country' => 'DE', 'id' => 2],
+ ], $schema), new PhpBackend());
+ $hasher->add(array_to_rows([['country' => 'PL', 'id' => 3]], $schema), new PhpBackend());
+
+ static::assertEquals(
+ [
+ new PartitionHash(new Partitions(new Partition('country', 'PL')), $pl->hash()->total),
+ new PartitionHash(new Partitions(new Partition('country', 'DE')), $de->hash()->total),
+ ],
+ $hasher->hash()->partitions,
+ );
+ }
+
+ public function test_the_total_equals_the_hash_of_the_whole_output(): void
+ {
+ $schema = schema(str_schema('country'), int_schema('id'));
+ $rows = array_to_rows([
+ ['country' => 'PL', 'id' => 1],
+ ['country' => 'DE', 'id' => 2],
+ ['country' => 'PL', 'id' => 3],
+ ], $schema);
+ $whole = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $whole->add($rows, new PhpBackend());
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add($rows, new PhpBackend());
+
+ static::assertEquals($whole->hash()->total, $hasher->hash()->total);
+ }
+
+ public function test_a_null_partition_value_is_one_partition_with_the_rows_of_the_null_folder(): void
+ {
+ $schema = schema(str_schema('country', nullable: true), int_schema('id'));
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([
+ ['country' => null, 'id' => 1],
+ ['country' => null, 'id' => 2],
+ ], $schema), new PhpBackend());
+
+ static::assertEquals(
+ [new Partitions(new Partition('country', null))],
+ array_map(static fn(PartitionHash $hash): Partitions => $hash->partitions, $hasher->hash()->partitions),
+ );
+ static::assertSame(2, $hasher->hash()->partitions[0]->hash->rows);
+ }
+
+ public function test_null_and_the_null_folder_name_are_one_partition(): void
+ {
+ $schema = schema(str_schema('country', nullable: true), int_schema('id'));
+ $whole = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $rows = array_to_rows([
+ ['country' => null, 'id' => 1],
+ ['country' => Partition::NULL_VALUE, 'id' => 2],
+ ], $schema);
+ $whole->add($rows, new PhpBackend());
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add($rows, new PhpBackend());
+
+ static::assertCount(1, $hasher->hash()->partitions);
+ static::assertSame(2, $hasher->hash()->partitions[0]->hash->rows);
+ static::assertEquals($whole->hash()->total, $hasher->hash()->partitions[0]->hash);
+ }
+
+ public function test_an_empty_string_and_null_are_two_partitions(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(
+ array_to_rows(
+ [
+ ['country' => '', 'id' => 1],
+ ['country' => null, 'id' => 2],
+ ],
+ schema(str_schema('country', nullable: true), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+
+ static::assertSame(
+ ['', null],
+ array_map(
+ static fn(PartitionHash $hash): ?string => $hash->partitions->toArray()[0]->value,
+ $hasher->hash()->partitions,
+ ),
+ );
+ }
+
+ public function test_values_that_print_one_joined_partition_id_stay_apart(): void
+ {
+ $schema = schema(str_schema('a'), str_schema('b'));
+ $hasher = new PartitionedOutputHasher(refs('a', 'b'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([
+ ['a' => 'x/b|y', 'b' => 'z'],
+ ['a' => 'x', 'b' => 'y/b|z'],
+ ['a' => 'x|b|y', 'b' => 'z'],
+ ['a' => 'x', 'b' => 'y|b|z'],
+ ], $schema), new PhpBackend());
+
+ static::assertCount(4, $hasher->hash()->partitions);
+ }
+
+ public function test_one_datetime_instant_gives_one_partition_in_either_batch_order(): void
+ {
+ $schema = schema(datetime_schema('at'), int_schema('id'));
+ $utc = array_to_rows([['at' => new DateTimeImmutable('2026-11-20T10:00:00+00:00'), 'id' => 1]], $schema);
+ $warsaw = array_to_rows([['at' => new DateTimeImmutable('2026-11-20T12:00:00+02:00'), 'id' => 2]], $schema);
+ $forward = new PartitionedOutputHasher(refs('at'), MultisetHashAlgorithm::xxh128);
+ $forward->add($utc, new PhpBackend());
+ $forward->add($warsaw, new PhpBackend());
+ $backward = new PartitionedOutputHasher(refs('at'), MultisetHashAlgorithm::xxh128);
+ $backward->add($warsaw, new PhpBackend());
+ $backward->add($utc, new PhpBackend());
+
+ static::assertCount(1, $forward->hash()->partitions);
+ static::assertEquals($forward->hash(), $backward->hash());
+ }
+
+ public function test_a_later_batch_of_another_type_names_its_partition_in_the_declared_type(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('day'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(
+ array_to_rows(
+ [['day' => new DateTimeImmutable('2026-11-19'), 'id' => 1]],
+ schema(date_schema('day'), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+ $hasher->add(
+ array_to_rows(
+ [['day' => new DateTimeImmutable('2026-11-20 10:00:00'), 'id' => 2]],
+ schema(datetime_schema('day'), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+
+ static::assertSame(
+ ['2026-11-19', '2026-11-20'],
+ array_map(
+ static fn(PartitionHash $hash): ?string => $hash->partitions->toArray()[0]->value,
+ $hasher->hash()->partitions,
+ ),
+ );
+ }
+
+ public function test_a_float_partition_column_is_refused(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() cannot group by the float column "price": 0.0 and -0.0 are one value but two '
+ . 'partition names. Cast it to a decimal string or an integer first.',
+ );
+
+ (new PartitionedOutputHasher(refs('price'), MultisetHashAlgorithm::xxh128))->add(array_to_rows([[
+ 'price' => 1.5,
+ ]], schema(float_schema('price'))), new PhpBackend());
+ }
+
+ public function test_a_json_partition_column_is_refused(): void
+ {
+ $this->expectException(PartitionException::class);
+ $this->expectExceptionMessage('Column "payload" of type json can\'t be used as a partition');
+
+ (new PartitionedOutputHasher(refs('payload'), MultisetHashAlgorithm::xxh128))->add(array_to_rows([[
+ 'payload' => '{"a":1}',
+ ]], schema(json_schema('payload'))), new PhpBackend());
+ }
+
+ public function test_a_first_batch_without_a_named_column_is_refused(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() groups by "country", but a batch has no column "country". Name only columns '
+ . 'that every row of the output has.',
+ );
+
+ (new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128))->add(array_to_rows([[
+ 'id' => 1,
+ ]], schema(int_schema('id'))), new PhpBackend());
+ }
+
+ public function test_a_later_batch_without_a_nullable_named_column_hashes_into_the_null_partition(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(
+ array_to_rows(
+ [['country' => null, 'id' => 1]],
+ schema(str_schema('country', nullable: true), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+ $hasher->add(array_to_rows([['id' => 2]], schema(int_schema('id'))), new PhpBackend());
+
+ static::assertCount(1, $hasher->hash()->partitions);
+ static::assertSame(2, $hasher->hash()->partitions[0]->hash->rows);
+ }
+
+ public function test_a_later_batch_without_a_non_nullable_named_column_is_refused(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() groups by "country", but a batch has no column "country".',
+ );
+
+ $hasher->add(array_to_rows([['id' => 2]], schema(int_schema('id'))), new PhpBackend());
+ }
+
+ public function test_an_empty_batch_first_does_not_fix_the_columns(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([], schema(int_schema('id'))), new PhpBackend());
+ $hasher->add(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+
+ static::assertCount(1, $hasher->hash()->partitions);
+ }
+
+ public function test_absorb_merges_a_partial_into_the_partition_with_the_same_values(): void
+ {
+ $schema = schema(str_schema('country'), int_schema('id'));
+ $all = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $all->add(array_to_rows([
+ ['country' => 'PL', 'id' => 1],
+ ['country' => 'PL', 'id' => 2],
+ ], $schema), new PhpBackend());
+ $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend());
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([['country' => 'PL', 'id' => 1]], $schema), new PhpBackend());
+ $hasher->absorb($worker->hash());
+
+ static::assertEquals($all->hash(), $hasher->hash());
+ }
+
+ public function test_absorb_into_an_empty_hasher_gives_the_partial_with_its_total(): void
+ {
+ $schema = schema(str_schema('country'), int_schema('id'));
+ $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend());
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->absorb($worker->hash());
+
+ static::assertEquals($worker->hash(), $hasher->hash());
+ }
+
+ public function test_describe_writes_no_state(): void
+ {
+ $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $hasher->add(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+
+ static::assertEquals(
+ new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ DescribeRoundTrip::rebuilt($hasher)->hash(),
+ );
+ }
+
+ public function test_a_rebuilt_hasher_keeps_its_algorithm(): void
+ {
+ $rebuilt = DescribeRoundTrip::rebuilt(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::md5));
+ $rebuilt->add(
+ array_to_rows([['country' => 'DE', 'id' => 2]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+
+ static::assertEquals(
+ new DatasetHash(
+ new Hash(1, '5e61d7a340ce02e52ce8b6900a2c5b18'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'DE')),
+ new Hash(1, '5e61d7a340ce02e52ce8b6900a2c5b18'),
+ ),
+ ],
+ MultisetHashAlgorithm::md5,
+ ),
+ $rebuilt->hash(),
+ );
+ }
+
+ public function test_an_aliased_partition_reference_fails_as_the_partitioned_loader_fails(): void
+ {
+ $this->expectException(SchemaDefinitionNotFoundException::class);
+ $this->expectExceptionMessage('Schema definition for column "day" not found.');
+
+ (new PartitionedOutputHasher(refs(ref('date')->as('day')), MultisetHashAlgorithm::xxh128))->add(
+ array_to_rows([['date' => '2026-11-20', 'id' => 1]], schema(str_schema('date'), int_schema('id'))),
+ new PhpBackend(),
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/RunCountsTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/RunCountsTest.php
index 5ec2d6ad0..72de7ab90 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/RunCountsTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/RunCountsTest.php
@@ -4,24 +4,39 @@
namespace Flow\ETL\Tests\Unit\Runtime\Executor;
+use Flow\ETL\Foundation\Exception\InvalidArgumentException;
use Flow\ETL\IO\Extractor\Criteria;
use Flow\ETL\IO\Extractor\Signal;
use Flow\ETL\IO\Extractor\Statistics;
+use Flow\ETL\Runtime\Executor\PartitionedOutputHasher;
use Flow\ETL\Runtime\Executor\RunCounts;
+use Flow\ETL\Runtime\Executor\WholeOutputHasher;
+use Flow\ETL\Runtime\Metrics\DatasetHash;
+use Flow\ETL\Runtime\Metrics\Hash;
+use Flow\ETL\Runtime\Metrics\PartitionHash;
use Flow\ETL\Runtime\Metrics\Processes;
use Flow\ETL\Runtime\Metrics\SourceStatistics;
use Flow\ETL\Tests\Double\CountingExtractor;
use Flow\ETL\Tests\FlowTestCase;
use Flow\ETL\Values\Cardinality;
+use Flow\ETL\Values\Column\MultisetDigest;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
+use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Memory\Unit;
use Flow\ETL\Values\Rows;
+use Flow\Filesystem\Partition;
+use Flow\Filesystem\Partitions;
use function Flow\ETL\DSL\array_to_rows;
use function Flow\ETL\DSL\flow_context;
use function Flow\ETL\DSL\from_array;
use function Flow\ETL\DSL\int_schema;
+use function Flow\ETL\DSL\refs;
use function Flow\ETL\DSL\schema;
+use function Flow\ETL\DSL\str_schema;
+use function hash;
use function iterator_to_array;
+use function unpack;
final class RunCountsTest extends FlowTestCase
{
@@ -330,4 +345,196 @@ public function test_open_returns_the_same_read_per_extractor(): void
static::assertSame(5, $sources->statistics()[0]->rows);
static::assertFalse($sources->statistics()[0]->complete);
}
+
+ public function test_absorb_leaves_the_output_hash_alone(): void
+ {
+ $counts = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128));
+ $other = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128));
+ $other->absorbOutputHash(
+ new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [], MultisetHashAlgorithm::xxh128),
+ );
+
+ $counts->absorb($other);
+ $counts->absorbWorkers($other);
+
+ static::assertEquals(
+ new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ $counts->outputHash(),
+ );
+ }
+
+ public function test_without_a_hasher_nothing_is_hashed_and_no_hash_is_given(): void
+ {
+ $counts = new RunCounts();
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend());
+ $counts->absorbOutputHash(
+ new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [], MultisetHashAlgorithm::xxh128),
+ );
+
+ static::assertNull($counts->outputHasher());
+ static::assertNull($counts->outputHash());
+ }
+
+ public function test_rows_with_columns_are_hashed(): void
+ {
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $counts = new RunCounts($hasher);
+ $counts->hashOutput(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend());
+ $counts->hashOutput(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend());
+
+ static::assertSame($hasher, $counts->outputHasher());
+ static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()?->total->value);
+ }
+
+ public function test_rows_without_columns_hash_as_empty_rows(): void
+ {
+ /** @var array{1: int, 2: int} $lanes */
+ $lanes = unpack('J2', hash('xxh128', '', true));
+ $empty = new MultisetDigest($lanes[2], $lanes[1]);
+ $counts = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128));
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend());
+
+ static::assertSame($empty->plus($empty)->plus($empty)->hex(), $counts->outputHash()?->total->value);
+ }
+
+ public function test_rows_without_columns_that_absorbed_digests_cover_are_hashed_only_by_those_digests(): void
+ {
+ $first = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $first->add(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend());
+ $second = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $second->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend());
+ $counts = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128));
+ $counts->absorbOutputHash($first->hash());
+ $counts->absorbOutputHash($second->hash());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+
+ static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()?->total->value);
+ }
+
+ public function test_rows_without_columns_beyond_the_covered_rows_hash_as_empty_rows(): void
+ {
+ /** @var array{1: int, 2: int} $lanes */
+ $lanes = unpack('J2', hash('xxh128', '', true));
+ $empty = new MultisetDigest($lanes[2], $lanes[1]);
+ $worker = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $worker->add(array_to_rows([['a' => 1], ['a' => 2], ['a' => 3]], schema(int_schema('a'))), new PhpBackend());
+ $counts = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128));
+ $counts->absorbOutputHash($worker->hash());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 2), new PhpBackend());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 2), new PhpBackend());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+
+ static::assertSame(
+ MultisetDigest::fromHex($worker->hash()->total->value)->plus($empty)->plus($empty)->hex(),
+ $counts->outputHash()?->total->value,
+ );
+ }
+
+ public function test_a_partitioned_hash_takes_the_partitions_of_the_covered_rows_from_the_partial(): void
+ {
+ $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $worker->add(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+ $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128));
+ $counts->absorbOutputHash($worker->hash());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+
+ static::assertEquals($worker->hash(), $counts->outputHash());
+ }
+
+ public function test_a_partitioned_hash_refuses_rows_without_columns_that_no_partial_covers(): void
+ {
+ $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128));
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() groups by "country", but a batch has no column "country".',
+ );
+
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+ }
+
+ public function test_a_partitioned_hash_refuses_the_uncovered_part_of_partly_covered_rows_before_a_first_batch(): void
+ {
+ $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $worker->add(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+ $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128));
+ $counts->absorbOutputHash($worker->hash());
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() groups by "country", but a batch has no column "country".',
+ );
+
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 2), new PhpBackend());
+ }
+
+ public function test_a_partitioned_hash_puts_uncovered_rows_without_columns_into_the_null_partition_after_a_nullable_first_batch(): void
+ {
+ /** @var array{1: int, 2: int} $lanes */
+ $lanes = unpack('J2', hash('xxh128', '', true));
+ $empty = new MultisetDigest($lanes[2], $lanes[1]);
+ $nulls = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $nulls->add(
+ array_to_rows(
+ [['country' => null, 'id' => 1]],
+ schema(str_schema('country', nullable: true), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+ $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128);
+ $worker->add(
+ array_to_rows(
+ [['country' => 'PL', 'id' => 2]],
+ schema(str_schema('country', nullable: true), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+ $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128));
+ $counts->hashOutput(
+ array_to_rows(
+ [['country' => null, 'id' => 1]],
+ schema(str_schema('country', nullable: true), int_schema('id')),
+ ),
+ new PhpBackend(),
+ );
+ $counts->absorbOutputHash($worker->hash());
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend());
+
+ static::assertEquals(
+ [
+ new PartitionHash(new Partitions(new Partition('country', 'PL')), $worker->hash()->total),
+ new PartitionHash(
+ new Partitions(new Partition('country', null)),
+ new Hash(
+ 3,
+ MultisetDigest::fromHex($nulls->hash()->total->value)->plus($empty)->plus($empty)->hex(),
+ ),
+ ),
+ ],
+ $counts->outputHash()?->partitions,
+ );
+ }
+
+ public function test_a_partitioned_hash_refuses_uncovered_rows_without_columns_after_a_not_null_first_batch(): void
+ {
+ $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128));
+ $counts->hashOutput(
+ array_to_rows([['country' => 'PL', 'id' => 1]], schema(str_schema('country'), int_schema('id'))),
+ new PhpBackend(),
+ );
+
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'analyze()->withDatasetHash() groups by "country", but a batch has no column "country".',
+ );
+
+ $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend());
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/StatisticsCollectorTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/StatisticsCollectorTest.php
index d964e5bf7..8f51f6ecd 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/StatisticsCollectorTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/StatisticsCollectorTest.php
@@ -11,14 +11,20 @@
use Flow\ETL\IO\Extractor\Criteria;
use Flow\ETL\IO\Extractor\Statistics;
use Flow\ETL\Runtime\Executor\StatisticsCollector;
+use Flow\ETL\Runtime\Executor\WholeOutputHasher;
+use Flow\ETL\Runtime\Metrics\Hash;
+use Flow\ETL\Runtime\Metrics\PartitionHash;
use Flow\ETL\Runtime\Metrics\Report;
use Flow\ETL\Runtime\Metrics\SourceStatistics;
use Flow\ETL\Runtime\Metrics\Statistics\Columns;
use Flow\ETL\Tests\Context\MemoryTelemetryContext;
+use Flow\ETL\Tests\Double\SpyBackend;
use Flow\ETL\Tests\Double\StubLauncher;
use Flow\ETL\Tests\FlowTestCase;
use Flow\ETL\Values\Cardinality;
use Flow\ETL\Values\Memory\Unit;
+use Flow\Filesystem\Partition;
+use Flow\Filesystem\Partitions;
use Flow\Telemetry\Logger\LogEntry;
use Flow\Telemetry\Logger\Severity;
@@ -29,6 +35,7 @@
use function Flow\ETL\DSL\flow_context;
use function Flow\ETL\DSL\from_array;
use function Flow\ETL\DSL\int_schema;
+use function Flow\ETL\DSL\ref;
use function Flow\ETL\DSL\schema;
use function Flow\ETL\DSL\str_schema;
use function iterator_to_array;
@@ -312,4 +319,118 @@ public function test_nothing_is_warned_without_a_launcher_or_without_reading_col
static::assertSame([], $telemetry->logs->entriesWithSeverity(Severity::WARN));
}
+
+ public function test_the_dataset_hash_is_the_multiset_hash_of_every_captured_row(): void
+ {
+ $collector = new StatisticsCollector(analyze()->withDatasetHash(), flow_context());
+
+ $collector->capture(array_to_rows([['a' => 2]], schema(int_schema('a'))));
+ $collector->capture(array_to_rows([], schema(int_schema('a'))));
+ $collector->capture(array_to_rows([['a' => 1]], schema(int_schema('a'))));
+
+ static::assertEquals(
+ new Hash(2, '721f4650154ebb88ac4ec50a605901df'),
+ $collector->report()->datasetHash()?->total,
+ );
+ static::assertSame([], $collector->report()->datasetHash()?->partitions);
+ static::assertFalse($collector->readsColumns());
+ }
+
+ public function test_a_dataset_hash_of_no_rows_is_zero(): void
+ {
+ static::assertEquals(
+ new Hash(0, '00000000000000000000000000000000'),
+ (new StatisticsCollector(analyze()->withDatasetHash(), flow_context()))->report()->datasetHash()?->total,
+ );
+ }
+
+ public function test_without_the_dataset_hash_no_accumulator_is_created_and_none_is_reported(): void
+ {
+ $backend = new SpyBackend();
+ $collector = new StatisticsCollector(
+ analyze()->withSchema()->withColumnStatistics()->withSourceStatistics(),
+ flow_context(config_builder()->backend($backend)->build()),
+ );
+
+ $collector->capture(array_to_rows([['a' => 1]], schema(int_schema('a')), $backend));
+
+ static::assertNull($collector->report()->datasetHash());
+ static::assertSame(0, $backend->groupedMultisetHashesCreated());
+ static::assertFalse(
+ (new StatisticsCollector(
+ analyze()->withSourceStatistics(),
+ flow_context(config_builder()->backend($backend)->build()),
+ ))->readsColumns(),
+ );
+ }
+
+ public function test_the_dataset_hash_takes_its_accumulator_from_the_context_backend(): void
+ {
+ $backend = new SpyBackend();
+
+ $collector = new StatisticsCollector(
+ analyze()->withDatasetHash(),
+ flow_context(config_builder()->backend($backend)->build()),
+ );
+ $collector->capture(array_to_rows([['a' => 1]], schema(int_schema('a')), $backend));
+
+ static::assertSame(1, $backend->groupedMultisetHashesCreated());
+ }
+
+ public function test_the_dataset_hash_under_a_launcher_is_not_named_in_the_warning(): void
+ {
+ $telemetry = new MemoryTelemetryContext();
+
+ new StatisticsCollector(
+ analyze()->withSchema()->withDatasetHash(),
+ flow_context(config_builder()->withTelemetry($telemetry->telemetry)->launcher(new StubLauncher())->build()),
+ );
+
+ static::assertSame(
+ 'analyze()->withSchema() sends every row to the parent process, so the writes do not '
+ . 'run in parallel. Drop it to keep parallel writes.',
+ $telemetry->logs->entriesWithSeverity(Severity::WARN)[0]->record->body,
+ );
+ }
+
+ public function test_the_dataset_hash_alone_under_a_launcher_keeps_the_writes_parallel(): void
+ {
+ $telemetry = new MemoryTelemetryContext();
+ $collector = new StatisticsCollector(
+ analyze()->withDatasetHash(),
+ flow_context(config_builder()->withTelemetry($telemetry->telemetry)->launcher(new StubLauncher())->build()),
+ );
+
+ static::assertFalse($collector->readsColumns());
+ static::assertInstanceOf(WholeOutputHasher::class, $collector->counts()?->outputHasher());
+ static::assertSame([], $telemetry->logs->entriesWithSeverity(Severity::WARN));
+ }
+
+ public function test_a_partitioned_dataset_hash_reports_one_hash_per_partition_and_their_total(): void
+ {
+ $schema = schema(str_schema('country'), int_schema('id'));
+ $whole = new StatisticsCollector(analyze()->withDatasetHash(), flow_context());
+ $collector = new StatisticsCollector(analyze()->withDatasetHash([ref('country')]), flow_context());
+
+ foreach ([$whole, $collector] as $each) {
+ $each->capture(array_to_rows([['country' => 'PL', 'id' => 1], ['country' => 'DE', 'id' => 2]], $schema));
+ $each->capture(array_to_rows([['country' => 'PL', 'id' => 3]], $schema));
+ }
+
+ static::assertEquals($whole->report()->datasetHash()?->total, $collector->report()->datasetHash()?->total);
+ static::assertEquals(
+ [new Partitions(new Partition('country', 'PL')), new Partitions(new Partition('country', 'DE'))],
+ array_map(
+ static fn(PartitionHash $hash): Partitions => $hash->partitions,
+ $collector->report()->datasetHash()->partitions ?? [],
+ ),
+ );
+ static::assertSame(
+ [2, 1],
+ array_map(
+ static fn(PartitionHash $hash): int => $hash->hash->rows,
+ $collector->report()->datasetHash()->partitions ?? [],
+ ),
+ );
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/WholeOutputHasherTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/WholeOutputHasherTest.php
new file mode 100644
index 000000000..ee0b55a9d
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/WholeOutputHasherTest.php
@@ -0,0 +1,116 @@
+ 1], ['a' => 2]], schema(int_schema('a')));
+ $kernel = (new PhpBackend())->groupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $kernel->add($rows->columns(), ColumnMother::of(int_schema('id'), [0, 0]));
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend());
+ $hasher->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend());
+
+ static::assertEquals(
+ new DatasetHash(new Hash(2, '721f4650154ebb88ac4ec50a605901df'), [], MultisetHashAlgorithm::xxh128),
+ $hasher->hash(),
+ );
+ static::assertSame([$hasher->hash()->total->value], $kernel->hashes()->physicals());
+ }
+
+ public function test_another_algorithm_is_hashed_reported_and_described(): void
+ {
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::sha256);
+ $hasher->add(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend());
+
+ static::assertEquals(
+ new DatasetHash(new Hash(1, '7c396438b2b1506bc82ea94d4ad238cd'), [], MultisetHashAlgorithm::sha256),
+ $hasher->hash(),
+ );
+ static::assertSame(['algorithm' => 'sha256'], $hasher->describe()?->data);
+ }
+
+ public function test_absorb_refuses_a_partial_of_another_algorithm(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A md5 dataset hash cannot be added to a xxh128 dataset hash');
+
+ (new WholeOutputHasher(MultisetHashAlgorithm::xxh128))->absorb(
+ new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::md5),
+ );
+ }
+
+ public function test_absorb_reads_only_the_total_of_a_partial(): void
+ {
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend());
+ $hasher->absorb(
+ new DatasetHash(
+ new Hash(1, 'e406cdb168be00960a58088d91a960c5'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('a', '2')),
+ new Hash(5, '00000000000000000000000000000001'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ),
+ );
+
+ static::assertEquals(
+ new DatasetHash(new Hash(2, '721f4650154ebb88ac4ec50a605901df'), [], MultisetHashAlgorithm::xxh128),
+ $hasher->hash(),
+ );
+ }
+
+ public function test_a_hasher_that_saw_nothing_gives_the_empty_digest(): void
+ {
+ static::assertEquals(
+ new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ (new WholeOutputHasher(MultisetHashAlgorithm::xxh128))->hash(),
+ );
+ }
+
+ public function test_a_hasher_whose_kernel_saw_no_row_gives_the_empty_digest(): void
+ {
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([], schema(int_schema('a'))), new PhpBackend());
+
+ static::assertEquals(
+ new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ $hasher->hash(),
+ );
+ }
+
+ public function test_describe_writes_no_state(): void
+ {
+ $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128);
+ $hasher->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend());
+
+ static::assertEquals(
+ new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ DescribeRoundTrip::rebuilt($hasher)->hash(),
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/DatasetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/DatasetHashTest.php
new file mode 100644
index 000000000..f0116bfb3
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/DatasetHashTest.php
@@ -0,0 +1,316 @@
+total);
+ static::assertSame([$partition], $hash->partitions);
+ }
+
+ public function test_plus_adds_the_totals_and_the_hashes_of_equal_partitions(): void
+ {
+ static::assertEquals(
+ new DatasetHash(
+ new Hash(3, '00000000000000000000000000000003'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(3, '00000000000000000000000000000003'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ),
+ (new DatasetHash(
+ new Hash(1, '00000000000000000000000000000001'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(1, '00000000000000000000000000000001'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ))->plus(
+ new DatasetHash(
+ new Hash(2, '00000000000000000000000000000002'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(2, '00000000000000000000000000000002'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ),
+ ),
+ );
+ }
+
+ public function test_plus_keeps_different_partitions_in_order_of_first_appearance(): void
+ {
+ $pl = new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(1, '00000000000000000000000000000001'),
+ );
+ $de = new PartitionHash(
+ new Partitions(new Partition('country', 'DE')),
+ new Hash(1, '00000000000000000000000000000002'),
+ );
+ $us = new PartitionHash(
+ new Partitions(new Partition('country', 'US')),
+ new Hash(1, '00000000000000000000000000000004'),
+ );
+
+ static::assertEquals(
+ [$pl, $de, $us],
+ (new DatasetHash(
+ new Hash(2, '00000000000000000000000000000003'),
+ [$pl, $de],
+ MultisetHashAlgorithm::xxh128,
+ ))->plus(
+ new DatasetHash(new Hash(1, '00000000000000000000000000000004'), [$us], MultisetHashAlgorithm::xxh128),
+ )->partitions,
+ );
+ }
+
+ public function test_plus_merges_equal_partitions_of_one_operand(): void
+ {
+ static::assertEquals(
+ [new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(2, '00000000000000000000000000000003'),
+ )],
+ (new DatasetHash(
+ new Hash(2, '00000000000000000000000000000003'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(1, '00000000000000000000000000000001'),
+ ),
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(1, '00000000000000000000000000000002'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ))->plus(new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::xxh128))->partitions,
+ );
+ }
+
+ public function test_plus_takes_null_and_the_null_folder_name_as_one_partition(): void
+ {
+ static::assertEquals(
+ [new PartitionHash(
+ new Partitions(new Partition('country', null)),
+ new Hash(2, '00000000000000000000000000000003'),
+ )],
+ (new DatasetHash(
+ new Hash(1, '00000000000000000000000000000001'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', null)),
+ new Hash(1, '00000000000000000000000000000001'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ))->plus(
+ new DatasetHash(
+ new Hash(1, '00000000000000000000000000000002'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', Partition::NULL_VALUE)),
+ new Hash(1, '00000000000000000000000000000002'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ),
+ )->partitions,
+ );
+ }
+
+ public function test_plus_with_the_empty_hash_is_the_identity(): void
+ {
+ $hash = new DatasetHash(
+ new Hash(1, '00000000000000000000000000000001'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(1, '00000000000000000000000000000001'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ );
+
+ static::assertEquals($hash, $hash->plus(new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::xxh128)));
+ static::assertEquals($hash, (new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::xxh128))->plus($hash));
+ }
+
+ public function test_plus_of_two_whole_hashes_adds_the_totals_and_has_no_partitions(): void
+ {
+ static::assertEquals(
+ new DatasetHash(new Hash(5, 'ffffffffffffffff0000000000000000'), [], MultisetHashAlgorithm::xxh128),
+ (new DatasetHash(new Hash(2, 'ffffffffffffffffffffffffffffffff'), [], MultisetHashAlgorithm::xxh128))->plus(
+ new DatasetHash(new Hash(3, '00000000000000000000000000000001'), [], MultisetHashAlgorithm::xxh128),
+ ),
+ );
+ }
+
+ public function test_normalize_writes_the_total_and_each_partition(): void
+ {
+ static::assertSame(
+ [
+ 'algorithm' => 'xxh128',
+ 'total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'],
+ 'partitions' => [
+ [
+ 'partitions' => ['country' => 'PL'],
+ 'hash' => ['rows' => 2, 'value' => 'ab8476f29c95212a306bffff897d7afb'],
+ ],
+ [
+ 'partitions' => ['country' => null],
+ 'hash' => ['rows' => 1, 'value' => 'f3aebd664d56cdeceed04ea04775ad52'],
+ ],
+ ],
+ ],
+ (new DatasetHash(
+ new Hash(3, '31be1d609a26d996382e2a23855ebbe5'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('country', 'PL')),
+ new Hash(2, 'ab8476f29c95212a306bffff897d7afb'),
+ ),
+ new PartitionHash(
+ new Partitions(new Partition('country', null)),
+ new Hash(1, 'f3aebd664d56cdeceed04ea04775ad52'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ ))->normalize(),
+ );
+ }
+
+ public function test_from_array_reads_back_what_normalize_wrote_with_a_null_partition_value(): void
+ {
+ $hash = new DatasetHash(
+ new Hash(2, '31be1d609a26d996382e2a23855ebbe5'),
+ [
+ new PartitionHash(
+ new Partitions(new Partition('date', '2026-11-20'), new Partition('country', null)),
+ new Hash(2, 'ab8476f29c95212a306bffff897d7afb'),
+ ),
+ ],
+ MultisetHashAlgorithm::xxh128,
+ );
+
+ static::assertEquals($hash, DatasetHash::fromArray($hash->normalize()));
+ }
+
+ public function test_a_hash_without_partitions_reads_back_without_partitions(): void
+ {
+ $hash = new DatasetHash(new Hash(3, '31be1d609a26d996382e2a23855ebbe5'), [], MultisetHashAlgorithm::xxh128);
+
+ static::assertSame(
+ [
+ 'algorithm' => 'xxh128',
+ 'total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'],
+ 'partitions' => [],
+ ],
+ $hash->normalize(),
+ );
+ static::assertEquals($hash, DatasetHash::fromArray($hash->normalize()));
+ }
+
+ public function test_a_stored_hash_keeps_its_algorithm(): void
+ {
+ $stored = DatasetHash::fromArray([
+ 'algorithm' => 'sha256',
+ 'total' => ['rows' => 1, 'value' => '00000000000000000000000000000001'],
+ 'partitions' => [],
+ ]);
+
+ static::assertSame(MultisetHashAlgorithm::sha256, $stored->algorithm);
+ static::assertSame(MultisetHashAlgorithm::sha256, $stored->plus($stored)->algorithm);
+ }
+
+ public function test_from_array_needs_the_algorithm(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A dataset hash needs "algorithm" of type string');
+
+ DatasetHash::fromArray(['total' => ['rows' => 0, 'value' => ''], 'partitions' => []]);
+ }
+
+ public function test_from_array_refuses_an_unknown_algorithm(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Unknown multiset hash algorithm "crc32", use one of: md5, sha256, xxh128');
+
+ DatasetHash::fromArray([
+ 'algorithm' => 'crc32',
+ 'total' => ['rows' => 0, 'value' => '00000000000000000000000000000000'],
+ 'partitions' => [],
+ ]);
+ }
+
+ public function test_plus_refuses_a_hash_of_another_algorithm(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'A sha256 dataset hash cannot be added to a xxh128 dataset hash, hash both datasets with the same algorithm',
+ );
+
+ (new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::xxh128))->plus(
+ new DatasetHash(Hash::empty(), [], MultisetHashAlgorithm::sha256),
+ );
+ }
+
+ public function test_from_array_names_a_missing_key(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A dataset hash needs "total" of type array');
+
+ DatasetHash::fromArray(['algorithm' => 'xxh128', 'partitions' => []]);
+ }
+
+ public function test_from_array_names_a_key_of_another_type(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A dataset hash needs "partitions" of type list>');
+
+ DatasetHash::fromArray([
+ 'algorithm' => 'xxh128',
+ 'total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'],
+ 'partitions' => 'none',
+ ]);
+ }
+
+ public function test_from_array_names_a_missing_key_of_the_total(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A hash needs "value" of type string');
+
+ DatasetHash::fromArray(['algorithm' => 'xxh128', 'total' => ['rows' => 3], 'partitions' => []]);
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/HashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/HashTest.php
new file mode 100644
index 000000000..114c0d695
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/HashTest.php
@@ -0,0 +1,59 @@
+ 120, 'value' => 'ab8476f29c95212a306bffff897d7afb'],
+ (new Hash(120, 'ab8476f29c95212a306bffff897d7afb'))->normalize(),
+ );
+ }
+
+ public function test_plus_adds_the_rows_and_each_lane_of_the_value_with_wrapping(): void
+ {
+ static::assertEquals(
+ new Hash(5, 'ffffffffffffffff0000000000000000'),
+ (new Hash(2, 'ffffffffffffffffffffffffffffffff'))->plus(new Hash(3, '00000000000000000000000000000001')),
+ );
+ }
+
+ public function test_empty_is_the_identity_of_plus(): void
+ {
+ $hash = new Hash(120, 'ab8476f29c95212a306bffff897d7afb');
+
+ static::assertEquals($hash, Hash::empty()->plus($hash));
+ static::assertEquals(new Hash(0, '00000000000000000000000000000000'), Hash::empty());
+ }
+
+ public function test_from_array_reads_back_what_normalize_wrote(): void
+ {
+ $hash = new Hash(120, 'ab8476f29c95212a306bffff897d7afb');
+
+ static::assertEquals($hash, Hash::fromArray($hash->normalize()));
+ }
+
+ public function test_from_array_names_a_missing_key(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A hash needs "rows" of type integer');
+
+ Hash::fromArray(['value' => 'ab8476f29c95212a306bffff897d7afb']);
+ }
+
+ public function test_from_array_names_a_key_of_another_type(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A hash needs "value" of type string');
+
+ Hash::fromArray(['rows' => 120, 'value' => 7]);
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/PartitionHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/PartitionHashTest.php
new file mode 100644
index 000000000..3f2cf1595
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/PartitionHashTest.php
@@ -0,0 +1,63 @@
+ ['date' => '2026-11-20', 'country' => null],
+ 'hash' => ['rows' => 120, 'value' => 'ab8476f29c95212a306bffff897d7afb'],
+ ],
+ (new PartitionHash(
+ new Partitions(new Partition('date', '2026-11-20'), new Partition('country', null)),
+ new Hash(120, 'ab8476f29c95212a306bffff897d7afb'),
+ ))->normalize(),
+ );
+ }
+
+ public function test_from_array_reads_back_what_normalize_wrote(): void
+ {
+ $hash = new PartitionHash(
+ new Partitions(new Partition('date', '2026-11-20'), new Partition('country', null)),
+ new Hash(120, 'ab8476f29c95212a306bffff897d7afb'),
+ );
+
+ static::assertEquals($hash, PartitionHash::fromArray($hash->normalize()));
+ }
+
+ public function test_from_array_names_a_missing_key(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A partition hash needs "hash" of type array');
+
+ PartitionHash::fromArray(['partitions' => ['date' => '2026-11-20']]);
+ }
+
+ public function test_from_array_names_a_key_of_another_type(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A partition hash needs "partitions" of type map');
+
+ PartitionHash::fromArray(['partitions' => ['date' => 1], 'hash' => ['rows' => 1, 'value' => 'ab']]);
+ }
+
+ public function test_from_array_names_a_missing_key_of_the_hash(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('A hash needs "rows" of type integer');
+
+ PartitionHash::fromArray(['partitions' => ['date' => '2026-11-20'], 'hash' => ['value' => 'ab']]);
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/ReportTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/ReportTest.php
index bed4e2171..a1eb119fd 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/ReportTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/ReportTest.php
@@ -5,6 +5,9 @@
namespace Flow\ETL\Tests\Unit\Runtime\Metrics;
use Flow\ETL\IO\Extractor\Statistics;
+use Flow\ETL\Runtime\Metrics\DatasetHash;
+use Flow\ETL\Runtime\Metrics\Hash;
+use Flow\ETL\Runtime\Metrics\PartitionHash;
use Flow\ETL\Runtime\Metrics\Processes;
use Flow\ETL\Runtime\Metrics\SourceStatistics;
use Flow\ETL\Runtime\Metrics\Statistics\Columns;
@@ -12,7 +15,10 @@
use Flow\ETL\Tests\Mother\ColumnMother;
use Flow\ETL\Tests\Mother\ReportMother;
use Flow\ETL\Values\Cardinality;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Memory\Unit;
+use Flow\Filesystem\Partition;
+use Flow\Filesystem\Partitions;
use function Flow\ETL\DSL\float_schema;
use function Flow\ETL\DSL\int_schema;
@@ -31,7 +37,12 @@ public function test_normalize_holds_what_the_typed_getters_hold_and_survives_js
$source = new SourceStatistics('ArrayExtractor', new Statistics(Cardinality::exact(2)), 2, true);
$report = ReportMother::of(new Processes(Unit::fromBytes(25), [Unit::fromBytes(
40,
- )]), 2, schema(int_schema('id')), [$source]);
+ )]), 2, schema(int_schema('id')), [$source], datasetHash: new DatasetHash(new Hash(2, '721f4650154ebb88ac4ec50a605901df'), [
+ new PartitionHash(
+ new Partitions(new Partition('country', null)),
+ new Hash(2, '721f4650154ebb88ac4ec50a605901df'),
+ ),
+ ], MultisetHashAlgorithm::xxh128));
$normalized = $report->normalize();
@@ -46,9 +57,20 @@ public function test_normalize_holds_what_the_typed_getters_hold_and_survives_js
'columns' => null,
],
'sources' => [$source->normalize()],
+ 'dataset_hash' => [
+ 'algorithm' => 'xxh128',
+ 'total' => ['rows' => 2, 'value' => '721f4650154ebb88ac4ec50a605901df'],
+ 'partitions' => [
+ [
+ 'partitions' => ['country' => null],
+ 'hash' => ['rows' => 2, 'value' => '721f4650154ebb88ac4ec50a605901df'],
+ ],
+ ],
+ ],
],
$normalized,
);
+ static::assertSame('721f4650154ebb88ac4ec50a605901df', $report->datasetHash()?->total->value);
// JSON keeps the values, not a float's ".0"
static::assertEquals($normalized, json_decode(
json_encode($normalized, JSON_THROW_ON_ERROR),
@@ -63,6 +85,7 @@ public function test_a_report_without_schema_or_sources_normalizes_them_to_null(
static::assertNull($normalized['schema']);
static::assertNull($normalized['sources']);
+ static::assertNull($normalized['dataset_hash']);
}
public function test_a_report_holding_infinite_and_nan_values_encodes_as_json(): void
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/AdaptiveBackendTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/AdaptiveBackendTest.php
index 92c84860a..d130982a7 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/AdaptiveBackendTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/AdaptiveBackendTest.php
@@ -13,7 +13,9 @@
use Flow\ETL\Tests\Mother\RowsMother;
use Flow\ETL\Values\Column\AdaptiveBackend;
use Flow\ETL\Values\Column\Frame\NoopCodec;
+use Flow\ETL\Values\Column\MultisetHashAlgorithm;
use Flow\ETL\Values\Column\Php\PhpGroupedCounts;
+use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes;
use Flow\ETL\Values\Column\Php\PhpGroupedTotals;
use Flow\ETL\Values\Column\PhpBackend;
use Flow\ETL\Values\Column\ValueColumn;
@@ -288,4 +290,22 @@ public function test_a_flow_php_of_another_abi_is_refused(): void
new AdaptiveBackend(new FlowPhpExtension(true, FlowPhpExtension::ABI + 1, '0.46.0'));
}
+
+ public function test_row_hashes_and_multiset_hashes_are_the_php_backends(): void
+ {
+ $rows = array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')));
+
+ static::assertSame(
+ (new PhpBackend())
+ ->rowHashes($rows->columns(), 2)
+ ->physicals(),
+ (new AdaptiveBackend())
+ ->rowHashes($rows->columns(), 2)
+ ->physicals(),
+ );
+ static::assertInstanceOf(
+ PhpGroupedMultisetHashes::class,
+ (new AdaptiveBackend())->groupedMultisetHashes(MultisetHashAlgorithm::xxh128),
+ );
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/CanonicalEncodingTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/CanonicalEncodingTest.php
new file mode 100644
index 000000000..5d7fd414a
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/CanonicalEncodingTest.php
@@ -0,0 +1,466 @@
+ [null_schema('v'), [null], ['00']];
+ yield 'boolean' => [bool_schema('v', true), [true, false, null], ['0101', '0100', '00']];
+ yield 'integer' => [int_schema('v'), [1, -1], ['020100000000000000', '02ffffffffffffffff']];
+ yield 'float' => [float_schema('v'), [1.0, 1.5], ['03000000000000f03f', '03000000000000f83f']];
+ yield 'string' => [str_schema('v'), ['1', ''], ['04010000000000000031', '040000000000000000']];
+ yield 'json' => [json_schema('v'), ['{"a":1}'], ['0507000000000000007b2261223a317d']];
+ yield 'enum' => [
+ enum_schema('v', BackedStringEnum::class),
+ [BackedStringEnum::one],
+ ['0603000000000000006f6e65'],
+ ];
+ yield 'xml' => [
+ xml_schema('v'),
+ [''],
+ ['071b000000000000003c3f786d6c2076657273696f6e3d22312e30223f3e0a3c612f3e0a'],
+ ];
+ yield 'timezone' => [time_zone_schema('v'), [new DateTimeZone('UTC')], ['090300000000000000555443']];
+ yield 'uuid' => [
+ uuid_schema('v'),
+ ['00000000-0000-0000-0000-000000000001'],
+ ['0a00000000000000000000000000000001'],
+ ];
+ yield 'date' => [date_schema('v'), [new DateTimeImmutable('1970-01-02')], ['0b01000000']];
+ yield 'datetime' => [
+ datetime_schema('v'),
+ [new DateTimeImmutable('1970-01-01 00:00:01.000002 UTC')],
+ ['0c42420f0000000000'],
+ ];
+ yield 'time' => [
+ time_schema('v'),
+ [new DateInterval('PT1S'), DateIntervalMother::of('PT1S', 0.0, 1)],
+ ['0d40420f0000000000', '0dc0bdf0ffffffffff'],
+ ];
+ yield 'list with a null element' => [
+ list_schema('v', type_list(type_optional(type_integer()))),
+ [[1, null]],
+ ['0e020000000000000002010000000000000000'],
+ ];
+ yield 'map' => [
+ map_schema('v', type_map(type_string(), type_integer())),
+ [['b' => 2, 'a' => 1]],
+ ['0f02000000000000000401000000000000006102010000000000000004010000000000000062020200000000000000'],
+ ];
+ yield 'nested structure' => [
+ structure_schema('v', type_structure([
+ 'b' => type_integer(),
+ 'a' => type_optional(type_structure(['x' => type_string()])),
+ ])),
+ [['b' => 1, 'a' => ['x' => 'y']], ['b' => 1, 'a' => null]],
+ [
+ '10020000000000000001000000000000006110010000000000000001000000000000007804010000000000000079010000000000000062020100000000000000',
+ '100100000000000000010000000000000062020100000000000000',
+ ],
+ ];
+ }
+
+ /**
+ * @param Definition $definition
+ * @param list $values
+ * @param list $expected
+ */
+ #[DataProvider('provide_encodings')]
+ public function test_ordered_writes_the_tag_and_payload_of_each_type(
+ Definition $definition,
+ array $values,
+ array $expected,
+ ): void {
+ $rows = array_to_rows(array_map(static fn(mixed $value): array => [
+ 'v' => $value,
+ ], $values), schema($definition));
+
+ static::assertSame($expected, array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column(
+ 'v',
+ )], $rows->count())));
+ }
+
+ #[RequiresPhp('>= 8.4.0')]
+ public function test_html_takes_tag_08(): void
+ {
+ $rows = array_to_rows([[
+ 'v' => 'a
',
+ ]], schema(html_schema('v')));
+
+ static::assertSame(
+ [
+ '083e000000000000003c21444f43545950452068746d6c3e3c68746d6c3e3c686561643e3c2f686561643e3c626f64793e3c703e613c2f703e3c2f626f64793e3c2f68746d6c3e',
+ ],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 1)),
+ );
+ }
+
+ public function test_xml_element_is_encoded_by_its_markup_wherever_it_lives(): void
+ {
+ $rows = array_to_rows([
+ ['v' => type_xml_element()->cast('')->firstElementChild],
+ ['v' => type_xml_element()->cast('')->lastElementChild],
+ ['v' => type_xml_element()->cast('')->firstElementChild],
+ ['v' => (new DOMDocument())->createElement('a')],
+ ], schema(xml_element_schema('v')));
+
+ static::assertSame(
+ [
+ '110d000000000000003c6120783d2231223e3c2f613e',
+ '110d000000000000003c6120783d2231223e3c2f613e',
+ '1107000000000000003c613e3c2f613e',
+ '1107000000000000003c613e3c2f613e',
+ ],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 4)),
+ );
+ }
+
+ public function test_xml_element_differs_from_xml_document_with_the_same_markup(): void
+ {
+ $rows = array_to_rows(
+ [['d' => '', 'e' => type_xml_element()->cast('')]],
+ schema(xml_schema('d'), xml_element_schema('e')),
+ );
+
+ static::assertNotSame(
+ (new CanonicalEncoding())->ordered([$rows->column('d')], 1),
+ (new CanonicalEncoding())->ordered([$rows->column('e')], 1),
+ );
+ }
+
+ #[RequiresPhp('>= 8.4.0')]
+ public function test_html_element_is_encoded_by_its_markup_wherever_it_lives(): void
+ {
+ $rows = array_to_rows([
+ ['v' => type_html_element()->cast('')->firstElementChild],
+ ['v' => type_html_element()->cast('')->lastElementChild],
+ ], schema(html_element_schema('v')));
+
+ static::assertSame(
+ ['1208000000000000003c703e613c2f703e', '1208000000000000003c703e613c2f703e'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 2)),
+ );
+ }
+
+ public function test_ordered_concatenates_the_columns_in_list_order(): void
+ {
+ $rows = array_to_rows([['a' => 1, 'b' => true]], schema(int_schema('a'), bool_schema('b')));
+
+ static::assertSame(['0201000000000000000101'], array_map(bin2hex(...), (new CanonicalEncoding())->ordered([
+ $rows->column('a'),
+ $rows->column('b'),
+ ], 1)));
+ static::assertSame(['0101020100000000000000'], array_map(bin2hex(...), (new CanonicalEncoding())->ordered([
+ $rows->column('b'),
+ $rows->column('a'),
+ ], 1)));
+ }
+
+ public function test_same_text_of_different_types_differs(): void
+ {
+ $rows = array_to_rows(
+ [['i' => 1, 'f' => 1.0, 's' => '1', 'j' => '[1]', 'e' => BackedStringEnum::one]],
+ schema(
+ int_schema('i'),
+ float_schema('f'),
+ str_schema('s'),
+ json_schema('j'),
+ enum_schema('e', BackedStringEnum::class),
+ ),
+ );
+
+ static::assertCount(
+ 5,
+ array_unique(array_map(
+ static fn($column): string => (new CanonicalEncoding())->ordered([$column], 1)[0],
+ array_values($rows->columns()),
+ )),
+ );
+ }
+
+ public function test_null_differs_from_empty_string(): void
+ {
+ $rows = array_to_rows([['v' => null], ['v' => '']], schema(str_schema('v', true)));
+
+ static::assertSame(['00', '040000000000000000'], array_map(bin2hex(...), (new CanonicalEncoding())->ordered(
+ [$rows->column('v')],
+ 2,
+ )));
+ }
+
+ public function test_negative_zero_equals_zero_and_every_nan_is_one_value(): void
+ {
+ $rows = array_to_rows([['v' => -0.0], ['v' => 0.0], ['v' => NAN], ['v' => -NAN]], schema(float_schema('v')));
+
+ static::assertSame(
+ ['030000000000000000', '030000000000000000', '03000000000000f87f', '03000000000000f87f'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 4)),
+ );
+ }
+
+ public function test_float_nan_differs_from_string_nan(): void
+ {
+ $rows = array_to_rows([['f' => NAN, 's' => 'NaN']], schema(float_schema('f'), str_schema('s')));
+
+ static::assertNotSame(
+ (new CanonicalEncoding())->ordered([$rows->column('f')], 1),
+ (new CanonicalEncoding())->ordered([$rows->column('s')], 1),
+ );
+ }
+
+ public function test_same_instant_in_two_zones_is_equal(): void
+ {
+ $rows = array_to_rows([
+ ['v' => new DateTimeImmutable('2026-01-01 01:00:00', new DateTimeZone('Europe/Warsaw'))],
+ ['v' => new DateTimeImmutable('2026-01-01 00:00:00', new DateTimeZone('UTC'))],
+ ], schema(datetime_schema('v')));
+
+ static::assertSame(
+ ['0c0040204648470600', '0c0040204648470600'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 2)),
+ );
+ }
+
+ public function test_date_differs_from_datetime_at_midnight(): void
+ {
+ $rows = array_to_rows(
+ [['d' => new DateTimeImmutable('1970-01-02'), 't' => new DateTimeImmutable('1970-01-02 00:00:00 UTC')]],
+ schema(date_schema('d'), datetime_schema('t')),
+ );
+
+ static::assertSame(['0b01000000', '0c0060d71d14000000'], [
+ bin2hex((new CanonicalEncoding())->ordered([$rows->column('d')], 1)[0]),
+ bin2hex((new CanonicalEncoding())->ordered([$rows->column('t')], 1)[0]),
+ ]);
+ }
+
+ public function test_map_entry_order_does_not_count(): void
+ {
+ $rows = array_to_rows([
+ ['v' => ['a' => 1, 'b' => 2]],
+ ['v' => ['b' => 2, 'a' => 1]],
+ ], schema(map_schema('v', type_map(type_string(), type_integer()))));
+ $encoded = (new CanonicalEncoding())->ordered([$rows->column('v')], 2);
+
+ static::assertSame($encoded[0], $encoded[1]);
+ }
+
+ public function test_map_with_integer_keys_takes_tag_02_for_the_keys(): void
+ {
+ $rows = array_to_rows([['v' => [1 => 'a']]], schema(map_schema('v', type_map(type_integer(), type_string()))));
+
+ static::assertSame(
+ ['0f010000000000000002010000000000000004010000000000000061'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 1)),
+ );
+ }
+
+ public function test_map_string_key_that_php_turned_into_an_integer_takes_tag_04(): void
+ {
+ $column = new MapColumn(
+ type_map(type_string(), type_integer()),
+ [0, 1],
+ ColumnMother::of(str_schema('k'), ['1']),
+ ColumnMother::of(int_schema('v'), [1]),
+ [],
+ );
+
+ static::assertSame(
+ ['0f010000000000000004010000000000000031020100000000000000'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$column], 1)),
+ );
+ }
+
+ public function test_list_order_counts(): void
+ {
+ $rows = array_to_rows([['v' => [1, 2]], ['v' => [2, 1]]], schema(list_schema('v', type_list(type_integer()))));
+ $encoded = (new CanonicalEncoding())->ordered([$rows->column('v')], 2);
+
+ static::assertNotSame($encoded[0], $encoded[1]);
+ }
+
+ public function test_structure_element_order_does_not_count(): void
+ {
+ $rows = array_to_rows(
+ [['l' => ['a' => 1, 'b' => 'x'], 'r' => ['b' => 'x', 'a' => 1]]],
+ schema(
+ structure_schema('l', type_structure(['a' => type_integer(), 'b' => type_string()])),
+ structure_schema('r', type_structure(['b' => type_string(), 'a' => type_integer()])),
+ ),
+ );
+
+ static::assertSame(
+ (new CanonicalEncoding())->ordered([$rows->column('l')], 1),
+ (new CanonicalEncoding())->ordered([$rows->column('r')], 1),
+ );
+ }
+
+ public function test_renamed_nested_element_differs(): void
+ {
+ $rows = array_to_rows(
+ [['l' => ['s' => ['a' => 1]], 'r' => ['s' => ['b' => 1]]]],
+ schema(
+ structure_schema('l', type_structure(['s' => type_structure(['a' => type_integer()])])),
+ structure_schema('r', type_structure(['s' => type_structure(['b' => type_integer()])])),
+ ),
+ );
+
+ static::assertNotSame(
+ (new CanonicalEncoding())->ordered([$rows->column('l')], 1),
+ (new CanonicalEncoding())->ordered([$rows->column('r')], 1),
+ );
+ }
+
+ public function test_null_structure_element_equals_missing_optional_element(): void
+ {
+ $rows = array_to_rows([
+ ['v' => ['a' => 1, 'b' => null]],
+ ['v' => ['a' => 1]],
+ ], schema(structure_schema('v', type_structure([
+ 'a' => type_integer(),
+ 'b' => structure_element('b', type_optional(type_string()), true),
+ ]))));
+
+ static::assertSame(
+ [
+ '100100000000000000010000000000000061020100000000000000',
+ '100100000000000000010000000000000061020100000000000000',
+ ],
+ array_map(bin2hex(...), (new CanonicalEncoding())->ordered([$rows->column('v')], 2)),
+ );
+ }
+
+ public function test_json_whitespace_counts(): void
+ {
+ $rows = array_to_rows([['v' => '{"a":1}'], ['v' => '{"a": 1}']], schema(json_schema('v')));
+ $encoded = (new CanonicalEncoding())->ordered([$rows->column('v')], 2);
+
+ static::assertNotSame($encoded[0], $encoded[1]);
+ }
+
+ public function test_named_writes_name_parts_sorted_by_name(): void
+ {
+ $rows = array_to_rows([['b' => true, 'a' => 1]], schema(bool_schema('b'), int_schema('a')));
+
+ static::assertSame(
+ ['0100000000000000610201000000000000000100000000000000620101'],
+ array_map(bin2hex(...), (new CanonicalEncoding())->named($rows->columns(), 1)),
+ );
+ }
+
+ public function test_named_ignores_the_column_order(): void
+ {
+ $rows = array_to_rows([['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b')));
+
+ static::assertSame(
+ (new CanonicalEncoding())->named(['a' => $rows->column('a'), 'b' => $rows->column('b')], 1),
+ (new CanonicalEncoding())->named(['b' => $rows->column('b'), 'a' => $rows->column('a')], 1),
+ );
+ }
+
+ public function test_named_renamed_column_differs(): void
+ {
+ $rows = array_to_rows([['a' => 1]], schema(int_schema('a')));
+
+ static::assertNotSame(
+ (new CanonicalEncoding())->named(['a' => $rows->column('a')], 1),
+ (new CanonicalEncoding())->named(['c' => $rows->column('a')], 1),
+ );
+ }
+
+ public function test_named_null_column_equals_missing_column(): void
+ {
+ $with = array_to_rows([['a' => 1, 'b' => null]], schema(int_schema('a'), str_schema('b', true)));
+ $without = array_to_rows([['a' => 1]], schema(int_schema('a')));
+
+ static::assertSame(
+ (new CanonicalEncoding())->named($with->columns(), 1),
+ (new CanonicalEncoding())->named($without->columns(), 1),
+ );
+ }
+
+ public function test_named_of_only_nulls_is_empty(): void
+ {
+ $rows = array_to_rows([['a' => null, 'b' => null]], schema(int_schema('a', true), null_schema('b')));
+
+ static::assertSame([''], (new CanonicalEncoding())->named($rows->columns(), 1));
+ }
+
+ public function test_type_outside_the_table_is_refused(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('type mixed has no canonical encoding, declare the type of the column');
+
+ (new CanonicalEncoding())->ordered([new MistypedColumnStub(
+ ColumnMother::of(int_schema('a'), [1]),
+ type_mixed(),
+ )], 1);
+ }
+
+ public function test_no_rows_encode_to_no_values(): void
+ {
+ $rows = array_to_rows([], schema(int_schema('a')));
+
+ static::assertSame([], (new CanonicalEncoding())->named($rows->columns(), 0));
+ static::assertSame([], (new CanonicalEncoding())->ordered([$rows->column('a')], 0));
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetDigestTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetDigestTest.php
new file mode 100644
index 000000000..9bb080ea8
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetDigestTest.php
@@ -0,0 +1,80 @@
+hex());
+ }
+
+ public function test_a_lane_carries_into_its_upper_half_and_wraps(): void
+ {
+ static::assertEquals(
+ new MultisetDigest(0x1FFFFFFFE, PHP_INT_MIN),
+ (new MultisetDigest(0xFFFFFFFF, PHP_INT_MAX))->plus(new MultisetDigest(0xFFFFFFFF, 1)),
+ );
+ }
+
+ public function test_half_sums_carry_the_low_halves_into_the_high_halves_and_wrap(): void
+ {
+ static::assertEquals(
+ new MultisetDigest(0x0000000300000001, 0x0000000100000000),
+ MultisetDigest::ofHalfSums(0x200000001, 1, 0xFFFFFFFF + 0xFFFFFFFF + 2, 0xFFFFFFFF),
+ );
+ }
+
+ public function test_from_hex_reads_back_both_lanes_at_the_limits(): void
+ {
+ static::assertEquals(
+ new MultisetDigest(PHP_INT_MIN, PHP_INT_MAX),
+ MultisetDigest::fromHex((new MultisetDigest(PHP_INT_MIN, PHP_INT_MAX))->hex()),
+ );
+ static::assertEquals(
+ new MultisetDigest(PHP_INT_MAX, PHP_INT_MIN),
+ MultisetDigest::fromHex((new MultisetDigest(PHP_INT_MAX, PHP_INT_MIN))->hex()),
+ );
+ }
+
+ public function test_from_hex_refuses_a_string_that_is_not_32_lowercase_hex_characters(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage(
+ 'A multiset digest is 32 lowercase hex characters, high lane first, given: "0000000000000000000000000000000"',
+ );
+
+ MultisetDigest::fromHex('0000000000000000000000000000000');
+ }
+
+ public function test_from_hex_refuses_uppercase_hex(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+
+ MultisetDigest::fromHex('0000000000000000000000000000000A');
+ }
+
+ public function test_both_lanes_wrap_past_minus_one(): void
+ {
+ static::assertEquals(
+ new MultisetDigest(-2, 0),
+ (new MultisetDigest(-1, PHP_INT_MIN))->plus(new MultisetDigest(-1, PHP_INT_MIN)),
+ );
+ }
+
+ public function test_hex_is_the_high_lane_then_the_low_lane_in_two_complement(): void
+ {
+ static::assertSame('800000000000000000000001fffffffe', (new MultisetDigest(0x1FFFFFFFE, PHP_INT_MIN))->hex());
+ static::assertSame('0000000000000002ffffffffffffffff', (new MultisetDigest(-1, 2))->hex());
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetHashAlgorithmTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetHashAlgorithmTest.php
new file mode 100644
index 000000000..240823864
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetHashAlgorithmTest.php
@@ -0,0 +1,25 @@
+expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Unknown multiset hash algorithm "sha1", use one of: md5, sha256, xxh128');
+
+ MultisetHashAlgorithm::named('sha1');
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpGroupedMultisetHashesTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpGroupedMultisetHashesTest.php
new file mode 100644
index 000000000..3969f04a6
--- /dev/null
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpGroupedMultisetHashesTest.php
@@ -0,0 +1,182 @@
+add(
+ array_to_rows([['a' => 1], ['a' => 2], ['a' => 1]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0, 1, 0]),
+ );
+
+ static::assertSame(
+ ['1c30f13d592175e443ed78f99d5f4234', 'e406cdb168be00960a58088d91a960c5'],
+ $hashes->hashes()->physicals(),
+ );
+ }
+
+ #[TestWith([MultisetHashAlgorithm::md5, '53b117ed69552c4ee4c638e6c72a526a', '8c589f902ff9330489f46e8138ef3fff'])]
+ #[TestWith([MultisetHashAlgorithm::sha256, '8f55cd2c66338b181c9f478cff77d05c', '7c396438b2b1506bc82ea94d4ad238cd'])]
+ public function test_another_algorithm_sums_the_first_128_bits_of_its_digest(
+ MultisetHashAlgorithm $algorithm,
+ string $first,
+ string $second,
+ ): void {
+ $hashes = new PhpGroupedMultisetHashes($algorithm);
+ $hashes->add(
+ array_to_rows([['a' => 1], ['a' => 2], ['a' => 1]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0, 1, 0]),
+ );
+
+ static::assertSame([$first, $second], $hashes->hashes()->physicals());
+ }
+
+ public function test_a_group_below_the_highest_seen_one_is_zero(): void
+ {
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add(
+ array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [1]),
+ );
+
+ static::assertSame(
+ ['00000000000000000000000000000000', '8e18789eac90baf2a1f6bc7cceafa11a'],
+ $hashes->hashes()->physicals(),
+ );
+ }
+
+ public function test_no_rows_give_no_groups(): void
+ {
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add([], ColumnMother::of(int_schema('id'), []));
+
+ static::assertSame([], $hashes->hashes()->physicals());
+ }
+
+ public function test_hashes_are_the_digests_by_group(): void
+ {
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add(
+ array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0, 1]),
+ );
+
+ static::assertSame(
+ ['8e18789eac90baf2a1f6bc7cceafa11a', 'e406cdb168be00960a58088d91a960c5'],
+ $hashes->hashes()->physicals(),
+ );
+ }
+
+ public function test_earlier_groups_are_added_to_the_groups_they_map_to(): void
+ {
+ $earlier = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $earlier->add(
+ array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0, 1]),
+ );
+ $later = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $later->add(
+ array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0]),
+ );
+ $later->absorbEarlier($earlier, [1 => 0, 0 => 2]);
+
+ static::assertSame(
+ [
+ '721f4650154ebb88ac4ec50a605901df',
+ '00000000000000000000000000000000',
+ '8e18789eac90baf2a1f6bc7cceafa11a',
+ ],
+ $later->hashes()->physicals(),
+ );
+ }
+
+ public function test_a_batch_without_columns_hashes_each_row_as_the_empty_row(): void
+ {
+ /** @var array{1: int, 2: int} $lanes */
+ $lanes = unpack('J2', hash('xxh128', '', true));
+ $empty = new MultisetDigest($lanes[2], $lanes[1]);
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add([], ColumnMother::of(int_schema('id'), [1, 0, 1]));
+
+ static::assertSame([$empty->hex(), $empty->plus($empty)->hex()], $hashes->hashes()->physicals());
+ }
+
+ public function test_one_row_in_one_group_equals_its_row_hash(): void
+ {
+ $rows = array_to_rows([['a' => 1]], schema(int_schema('a')));
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add($rows->columns(), ColumnMother::of(int_schema('id'), [0]));
+
+ static::assertSame(['8e18789eac90baf2a1f6bc7cceafa11a'], $hashes->hashes()->physicals());
+ static::assertSame(
+ (new PhpBackend())
+ ->rowHashes($rows->columns(), 1)
+ ->physicals(),
+ $hashes->hashes()->physicals(),
+ );
+ }
+
+ public function test_row_order_over_batches_does_not_count(): void
+ {
+ $forward = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $forward->add(
+ array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0, 0]),
+ );
+ $backward = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $backward->add(
+ array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0]),
+ );
+ $backward->add(
+ array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(),
+ ColumnMother::of(int_schema('id'), [0]),
+ );
+
+ static::assertSame(['721f4650154ebb88ac4ec50a605901df'], $forward->hashes()->physicals());
+ static::assertSame($forward->hashes()->physicals(), $backward->hashes()->physicals());
+ }
+
+ public function test_a_row_of_only_nulls_counts_as_a_row(): void
+ {
+ $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128);
+ $hashes->add(
+ array_to_rows([['a' => null]], schema(int_schema('a', true)))->columns(),
+ ColumnMother::of(int_schema('id'), [0]),
+ );
+
+ static::assertSame(['99aa06d3014798d86001c324468d497f'], $hashes->hashes()->physicals());
+ }
+
+ public function test_an_earlier_group_it_lacks_is_refused(): void
+ {
+ $this->expectException(InvalidArgumentException::class);
+ $this->expectExceptionMessage('Earlier group 3 has no hash');
+
+ (new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128))->absorbEarlier(
+ new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128),
+ [3 => 0],
+ );
+ }
+}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/PhpBackendTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/PhpBackendTest.php
index 6c6d908d0..41aa5a174 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/PhpBackendTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/PhpBackendTest.php
@@ -1407,7 +1407,13 @@ public static function partitions(): Generator
],
schema(int_schema('k'), str_schema('v')),
['k'],
- ["\0i1", "\0i2", "\0i1", "\0i3", "\0i2"],
+ [
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00",
+ "\x02\x02\x00\x00\x00\x00\x00\x00\x00",
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00",
+ "\x02\x03\x00\x00\x00\x00\x00\x00\x00",
+ "\x02\x02\x00\x00\x00\x00\x00\x00\x00",
+ ],
4,
0,
];
@@ -1419,7 +1425,11 @@ public static function partitions(): Generator
],
schema(int_schema('k'), str_schema('s'), str_schema('v')),
['k', 's'],
- ["\0i1\0s1:a", "\0i1\0s1:b", "\0i1\0s1:a"],
+ [
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00\x04\x01\x00\x00\x00\x00\x00\x00\x00a",
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00\x04\x01\x00\x00\x00\x00\x00\x00\x00b",
+ "\x02\x01\x00\x00\x00\x00\x00\x00\x00\x04\x01\x00\x00\x00\x00\x00\x00\x00a",
+ ],
16,
8,
];
@@ -1427,7 +1437,7 @@ public static function partitions(): Generator
[['k' => null, 'v' => 'a'], ['k' => 7, 'v' => 'b'], ['k' => null, 'v' => 'c']],
schema(int_schema('k', nullable: true), str_schema('v')),
['k'],
- ["\0n", "\0i7", "\0n"],
+ ["\x00", "\x02\x07\x00\x00\x00\x00\x00\x00\x00", "\x00"],
4,
24,
];
@@ -1509,4 +1519,39 @@ public function test_partition_refuses_a_hash_offset_outside_zero_to_twenty_four
// @mago-ignore analysis:invalid-argument
(new PhpBackend())->partition($rows, [$rows->column('k')], 4, 25);
}
+
+ public function test_row_hashes_are_the_xxh128_of_the_row_form(): void
+ {
+ $rows = array_to_rows(
+ [['a' => 1, 'b' => null], ['a' => 2, 'b' => null]],
+ schema(int_schema('a'), str_schema('b', true)),
+ );
+
+ static::assertSame(
+ ['8e18789eac90baf2a1f6bc7cceafa11a', 'e406cdb168be00960a58088d91a960c5'],
+ (new PhpBackend())
+ ->rowHashes($rows->columns(), 2)
+ ->physicals(),
+ );
+ static::assertSame(
+ ['99aa06d3014798d86001c324468d497f'],
+ (new PhpBackend())
+ ->rowHashes([], 1)
+ ->physicals(),
+ );
+ }
+
+ public function test_row_hashes_ignore_the_column_order(): void
+ {
+ $rows = array_to_rows([['a' => 1, 'b' => 'x']], schema(int_schema('a'), str_schema('b')));
+
+ static::assertSame(
+ (new PhpBackend())
+ ->rowHashes(['a' => $rows->column('a'), 'b' => $rows->column('b')], 1)
+ ->physicals(),
+ (new PhpBackend())
+ ->rowHashes(['b' => $rows->column('b'), 'a' => $rows->column('a')], 1)
+ ->physicals(),
+ );
+ }
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/ElementPositionTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/ElementPositionTest.php
index cdf531379..02d1fb1cc 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/ElementPositionTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/ElementPositionTest.php
@@ -50,15 +50,6 @@ public function test_the_physical_splits_into_the_path_the_markup_and_the_docume
static::assertSame("\0", $position->documentOf($physical));
}
- public function test_the_document_without_the_markup_splits_into_the_path_and_the_document(): void
- {
- $position = new ElementPosition();
-
- static::assertSame('0/2', $position->pathOf("\x000/2\x00"));
- static::assertNull($position->markupOf("\x000/2\x00"));
- static::assertSame('', $position->documentOf("\x000/2\x00"));
- }
-
public function test_bare_markup_has_no_position(): void
{
static::assertNull((new ElementPosition())->pathOf(''));
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/HtmlElementPhysicalTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/HtmlElementPhysicalTest.php
index 795736eb2..967cc6145 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/HtmlElementPhysicalTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/HtmlElementPhysicalTest.php
@@ -58,18 +58,6 @@ public function test_bare_element_markup_of_earlier_builds_still_loads(): void
static::assertSame('BODY', $element->parentElement?->tagName);
}
- #[RequiresPhp('>= 8.4.0')]
- public function test_the_document_without_the_element_markup_still_loads(): void
- {
- $physical = new HtmlElementPhysical();
- $bytes = "\x000\x0001";
- $element = type_html_element()->assert($physical->fromPhysical($bytes));
-
- static::assertSame('SECTION', $element->tagName);
- static::assertSame('ARTICLE', $element->parentElement?->tagName);
- static::assertSame('', $physical->markup($bytes));
- }
-
#[RequiresPhp('>= 8.4.0')]
public function test_a_detached_element_is_stored_as_its_markup(): void
{
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/XmlElementPhysicalTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/XmlElementPhysicalTest.php
index 76e430acb..ddd76e84f 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/XmlElementPhysicalTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Physical/XmlElementPhysicalTest.php
@@ -64,16 +64,12 @@ public function test_bare_element_markup_of_earlier_builds_still_loads(): void
);
}
- public function test_the_document_without_the_element_markup_still_loads(): void
+ public function test_bare_markup_is_its_own_markup(): void
{
- $physical = new XmlElementPhysical();
- $bytes = "\x000\x00Name01";
- $element = type_instance_of(DOMElement::class)->assert($physical->fromPhysical($bytes));
-
- static::assertSame('user', $element->tagName);
- static::assertSame('root', $element->parentElement?->tagName);
- static::assertSame('Name', $physical->markup($bytes));
- static::assertSame('- value
', $physical->markup('- value
'));
+ static::assertSame(
+ '- value
',
+ (new XmlElementPhysical())->markup('- value
'),
+ );
}
public function test_a_path_outside_the_document_is_refused(): void
@@ -112,11 +108,41 @@ public function test_restoring_xml_element_from_string(): void
);
}
- public function test_a_detached_dom_element_is_refused(): void
+ public function test_an_element_without_an_owner_document_is_stored_by_its_canonical_markup(): void
{
- $this->expectException(InvalidArgumentException::class);
- $this->expectExceptionMessage('failed to convert DOMElement to XML string');
+ static::assertSame('', (new XmlElementPhysical())->toPhysical(new DOMElement('detached')));
+ }
+
+ public function test_a_detached_element_is_stored_by_its_canonical_markup_and_returned_as_stored(): void
+ {
+ $document = new DOMDocument();
+ $element = type_instance_of(DOMElement::class)->assert($document->createElement('a'));
+ $element->setAttribute('x', '1');
+ $element->appendChild(type_instance_of(DOMElement::class)->assert($document->createElement('b')));
+ $physical = new XmlElementPhysical();
+ $bytes = type_string()->assert($physical->toPhysical($element));
+
+ static::assertSame('', $bytes);
+ static::assertSame('', $physical->markup($bytes));
+ static::assertSame(
+ 'b',
+ type_instance_of(DOMElement::class)->assert($physical->fromPhysical($bytes))->firstElementChild?->tagName,
+ );
+ }
+
+ #[RequiresPhp('>= 8.4.0')]
+ public function test_a_detached_dom_element_of_the_new_api_is_stored_by_its_canonical_markup(): void
+ {
+ // @mago-ignore analysis:unavailable-method
+ $document = XMLDocument::createEmpty();
+ $element = $document->createElement('a');
+ $element->appendChild($document->createElement('b'));
- (new XmlElementPhysical())->toPhysical(new DOMElement('detached'));
+ static::assertSame('', (new XmlElementPhysical())->toPhysical($element));
+ }
+
+ public function test_a_raw_markup_of_earlier_builds_is_returned_as_stored(): void
+ {
+ static::assertSame('', (new XmlElementPhysical())->markup(''));
}
}
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/TextValuesTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/TextValuesTest.php
index 390e5fadf..3fa48d7f8 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/TextValuesTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/TextValuesTest.php
@@ -93,7 +93,7 @@ public static function plain_values(): Generator
],
['
', '', null],
];
- yield 'xml_element' => [type_xml_element(), ['', null], ['', null]];
+ yield 'xml_element' => [type_xml_element(), ['', null], ['', null]];
yield 'html' => [type_html(), ['x', null], ['x', null]];
yield 'html_element' => [type_html_element(), ['x
', null], ['x
', null]];
yield 'null' => [type_null(), [null, null], [null, null]];
@@ -226,7 +226,7 @@ public static function scalar_texts(): Generator
['' . "\n" . '1' . "\n", null],
['1', null],
];
- yield 'xml_element' => [type_xml_element(), [''], ['']];
+ yield 'xml_element' => [type_xml_element(), [''], ['']];
yield 'html' => [
type_html(),
['x'],
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/GroupTableTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/GroupTableTest.php
index c7f676536..365fedf53 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/GroupTableTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/GroupTableTest.php
@@ -222,7 +222,7 @@ public function test_batches_built_by_either_backend_share_ids(Backend $backend)
#[DataProviderExternal(BackendsContext::class, 'backends')]
public function test_a_date_and_a_datetime_at_the_same_instant_share_an_id(Backend $backend): void
{
- $table = $backend->groupTable(['k'], schema(date_schema('k')));
+ $table = $backend->groupTable(['k'], schema(date_schema('k')->merge(datetime_schema('k'))));
$table->assign(array_to_rows([['k' => new DateTimeImmutable('2024-01-01')]], schema(date_schema('k'))));
static::assertSame(
@@ -236,6 +236,23 @@ public function test_a_date_and_a_datetime_at_the_same_instant_share_an_id(Backe
);
}
+ #[DataProviderExternal(BackendsContext::class, 'backends')]
+ public function test_a_key_has_the_declared_type_so_datetimes_under_a_date_key_group_by_day(Backend $backend): void
+ {
+ $table = $backend->groupTable(['k'], schema(date_schema('k')));
+ $table->assign(array_to_rows([['k' => new DateTimeImmutable('2024-01-01')]], schema(date_schema('k'))));
+
+ static::assertSame(
+ [0, 0],
+ $table
+ ->assign(array_to_rows([
+ ['k' => new DateTimeImmutable('2024-01-01 00:00:00', new DateTimeZone('UTC'))],
+ ['k' => new DateTimeImmutable('2024-01-01 00:00:01', new DateTimeZone('UTC'))],
+ ], schema(datetime_schema('k'))))
+ ->ids->values(),
+ );
+ }
+
#[DataProviderExternal(BackendsContext::class, 'backends')]
public function test_a_column_the_batch_lacks_under_a_required_declaration_is_refused(Backend $backend): void
{
@@ -270,7 +287,7 @@ public function test_an_xml_key_and_a_string_key_of_the_same_text_are_one_group(
$document->loadXML('x');
$table = $backend->groupTable(['k'], schema(str_schema('k')->merge(xml_schema('k'))));
$table->assign(array_to_rows(
- [['k' => "\nx\n"]],
+ [['k' => 'x'], ['k' => "\nx\n"]],
schema(str_schema('k')),
$backend,
));
@@ -279,7 +296,7 @@ public function test_an_xml_key_and_a_string_key_of_the_same_text_are_one_group(
[0],
$table->assign(array_to_rows([['k' => $document]], schema(xml_schema('k')), $backend))->ids->values(),
);
- static::assertSame(1, $table->count());
+ static::assertSame(2, $table->count());
}
#[DataProviderExternal(BackendsContext::class, 'backends')]
diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/KeyEncoderTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/KeyEncoderTest.php
index d613230a7..82041a0c4 100644
--- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/KeyEncoderTest.php
+++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Grouping/KeyEncoderTest.php
@@ -7,11 +7,19 @@
use DateTimeImmutable;
use Flow\ETL\Foundation\Exception\InvalidArgumentException;
use Flow\ETL\Tests\FlowTestCase;
+use Flow\ETL\Tests\Mother\ColumnMother;
use Flow\ETL\Values\Grouping\KeyEncoder;
+use Flow\ETL\Values\Schema\Definitions;
+use Flow\Filesystem\Partition;
+use Flow\Types\Type;
+use Generator;
+use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestWith;
+use function array_map;
use function array_merge;
use function array_unique;
+use function count;
use function Flow\ETL\DSL\array_to_rows;
use function Flow\ETL\DSL\bool_schema;
use function Flow\ETL\DSL\date_schema;
@@ -21,6 +29,8 @@
use function Flow\ETL\DSL\rows;
use function Flow\ETL\DSL\schema;
use function Flow\ETL\DSL\str_schema;
+use function Flow\Types\DSL\type_date;
+use function Flow\Types\DSL\type_datetime;
use function Flow\Types\DSL\type_float;
use function Flow\Types\DSL\type_integer;
use function Flow\Types\DSL\type_list;
@@ -29,6 +39,52 @@
final class KeyEncoderTest extends FlowTestCase
{
+ public static function sharedKeys(): Generator
+ {
+ yield 'two nan payloads' => [type_float(), [NAN, -NAN]];
+ yield 'a date' => [type_date(), [new DateTimeImmutable('2026-11-20'), new DateTimeImmutable('2026-11-20')]];
+ yield 'one instant in utc and in +02:00' => [
+ type_datetime(),
+ [new DateTimeImmutable('2026-11-20T10:00:00+00:00'), new DateTimeImmutable('2026-11-20T12:00:00+02:00')],
+ ];
+ }
+
+ /**
+ * @param Type $type
+ * @param list $values
+ */
+ #[DataProvider('sharedKeys')]
+ public function test_one_key_gives_one_partition_value(Type $type, array $values): void
+ {
+ static::assertCount(
+ 1,
+ array_unique(KeyEncoder::ofColumns([ColumnMother::of(
+ Definitions::of('k', $type),
+ $values,
+ )], count($values))),
+ );
+ static::assertCount(
+ 1,
+ array_unique(array_map(static fn(mixed $value): string => Partition::fromValue(
+ 'k',
+ $type,
+ $value,
+ ), $values)),
+ );
+ }
+
+ public function test_zero_and_negative_zero_are_one_key_but_two_partition_values(): void
+ {
+ static::assertCount(
+ 1,
+ array_unique(KeyEncoder::ofColumns([ColumnMother::of(Definitions::of('k', type_float()), [0.0, -0.0])], 2)),
+ );
+ static::assertSame(['0.0', '-0.0'], [
+ Partition::fromValue('k', type_float(), 0.0),
+ Partition::fromValue('k', type_float(), -0.0),
+ ]);
+ }
+
public function test_an_empty_batch_has_no_keys(): void
{
static::assertSame([], (new KeyEncoder(['k']))->of(rows(schema(int_schema('k')))));
@@ -175,4 +231,29 @@ public function test_the_bucket_of_a_key_is_eight_hex_digits_of_its_xxh128_at_th
): void {
static::assertSame($bucket, KeyEncoder::bucketOf($key, $buckets, $hashOffset));
}
+
+ public function test_an_int_and_a_float_of_one_value_are_one_key_under_a_float_key_type(): void
+ {
+ $declared = schema(float_schema('k'));
+
+ static::assertSame(
+ ["\x03\x00\x00\x00\x00\x00\x00\xF0\x3F"],
+ (new KeyEncoder(['k'], declared: $declared))->of(array_to_rows([['k' => 1]], schema(int_schema('k')))),
+ );
+ static::assertSame(
+ ["\x03\x00\x00\x00\x00\x00\x00\xF0\x3F"],
+ (new KeyEncoder(['k'], declared: $declared))->of(array_to_rows([['k' => 1.0]], $declared)),
+ );
+ }
+
+ public function test_a_column_the_batch_lacks_under_a_nullable_declaration_keys_as_null(): void
+ {
+ static::assertSame(
+ ["\x00\x02\x01\x00\x00\x00\x00\x00\x00\x00"],
+ (new KeyEncoder(
+ ['k', 'id'],
+ declared: schema(int_schema('k', nullable: true), int_schema('id')),
+ ))->of(array_to_rows([['id' => 1]], schema(int_schema('id')))),
+ );
+ }
}
diff --git a/src/extension/flow-php-ext/Cargo.lock b/src/extension/flow-php-ext/Cargo.lock
index 0f756819e..41c03cb98 100644
--- a/src/extension/flow-php-ext/Cargo.lock
+++ b/src/extension/flow-php-ext/Cargo.lock
@@ -16,7 +16,7 @@ checksum = "f1fc76eaeac4c9164506c466d4ffdd8ec9d0c5bf57ee97177c4d8eceb3a0e138"
dependencies = [
"cipher",
"cpubits",
- "cpufeatures",
+ "cpufeatures 0.3.0",
"zeroize",
]
@@ -244,6 +244,15 @@ version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
[[package]]
name = "block-buffer"
version = "0.12.1"
@@ -384,7 +393,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
- "crypto-common",
+ "crypto-common 0.2.2",
"inout",
]
@@ -471,6 +480,15 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "cpufeatures"
version = "0.3.0"
@@ -495,6 +513,16 @@ version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
[[package]]
name = "crypto-common"
version = "0.2.2"
@@ -569,15 +597,25 @@ version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
+]
+
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
- "block-buffer",
+ "block-buffer 0.12.1",
"const-oid",
- "crypto-common",
+ "crypto-common 0.2.2",
"ctutils",
"zeroize",
]
@@ -711,7 +749,10 @@ dependencies = [
"arrow-buffer",
"arrow-ord",
"arrow-schema",
+ "flow-batch-frame",
+ "md-5",
"memchr",
+ "sha2 0.10.9",
"xxhash-rust",
]
@@ -799,6 +840,16 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
[[package]]
name = "getrandom"
version = "0.2.17"
@@ -865,7 +916,7 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f"
dependencies = [
- "digest",
+ "digest 0.11.3",
]
[[package]]
@@ -1050,7 +1101,17 @@ version = "0.23.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1c46f3fcd2e888afdb01a07efc071cb21300e07c68d32c3e8b01b5c8cb1fcaa"
dependencies = [
- "sha2",
+ "sha2 0.11.0",
+]
+
+[[package]]
+name = "md-5"
+version = "0.10.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
+dependencies = [
+ "cfg-if",
+ "digest 0.10.7",
]
[[package]]
@@ -1267,7 +1328,7 @@ version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"
dependencies = [
- "digest",
+ "digest 0.11.3",
"hmac",
]
@@ -1539,8 +1600,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
- "cpufeatures",
- "digest",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
]
[[package]]
@@ -1550,8 +1622,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
dependencies = [
"cfg-if",
- "cpufeatures",
- "digest",
+ "cpufeatures 0.3.0",
+ "digest 0.11.3",
]
[[package]]
diff --git a/src/extension/flow-php-ext/Cargo.toml b/src/extension/flow-php-ext/Cargo.toml
index 0c488ea5f..78254e771 100644
--- a/src/extension/flow-php-ext/Cargo.toml
+++ b/src/extension/flow-php-ext/Cargo.toml
@@ -44,7 +44,9 @@ arrow-array = { version = "60", features = ["ffi"] }
arrow-buffer = "60"
arrow-data = "60"
arrow-schema = { version = "60", features = ["canonical_extension_types"] }
+md-5 = "0.10"
memchr = "2"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "unbounded_depth"] }
+sha2 = "0.10"
xxhash-rust = { version = "0.8", features = ["xxh3"] }
diff --git a/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml b/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml
index f7536e9ed..9e1260e84 100644
--- a/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml
+++ b/src/extension/flow-php-ext/crates/flow-column-kernels/Cargo.toml
@@ -12,5 +12,8 @@ arrow-buffer.workspace = true
arrow-arith = "60"
arrow-ord = "60"
arrow-schema.workspace = true
+flow-batch-frame = { path = "../flow-batch-frame" }
+md-5.workspace = true
memchr.workspace = true
+sha2.workspace = true
xxhash-rust.workspace = true
diff --git a/src/extension/flow-php-ext/crates/flow-column-kernels/src/canonical.rs b/src/extension/flow-php-ext/crates/flow-column-kernels/src/canonical.rs
new file mode 100644
index 000000000..48d42a31e
--- /dev/null
+++ b/src/extension/flow-php-ext/crates/flow-column-kernels/src/canonical.rs
@@ -0,0 +1,879 @@
+//! The canonical, type-tagged bytes of values and rows, byte for byte those of PHP's `CanonicalEncoding`.
+
+use arrow_array::cast::AsArray;
+use arrow_array::types::{Date32Type, DurationMicrosecondType, Float64Type, Int64Type, TimestampMicrosecondType};
+use arrow_array::Array;
+use arrow_schema::DataType;
+use flow_batch_frame::error::Part;
+use flow_batch_frame::kind::TypeJson;
+use flow_batch_frame::Error;
+use md5::Md5;
+use sha2::{Digest, Sha256};
+use xxhash_rust::xxh3::xxh3_128;
+
+pub const NULL: u8 = 0x00;
+pub const BOOLEAN: u8 = 0x01;
+pub const INTEGER: u8 = 0x02;
+pub const FLOAT: u8 = 0x03;
+pub const STRING: u8 = 0x04;
+pub const JSON: u8 = 0x05;
+pub const ENUM: u8 = 0x06;
+pub const XML: u8 = 0x07;
+pub const HTML: u8 = 0x08;
+pub const TIMEZONE: u8 = 0x09;
+pub const UUID: u8 = 0x0A;
+pub const DATE: u8 = 0x0B;
+pub const DATETIME: u8 = 0x0C;
+pub const TIME: u8 = 0x0D;
+const LIST: u8 = 0x0E;
+const MAP: u8 = 0x0F;
+const STRUCTURE: u8 = 0x10;
+pub const XML_ELEMENT: u8 = 0x11;
+pub const HTML_ELEMENT: u8 = 0x12;
+
+const NAN_BITS: u64 = 0x7FF8_0000_0000_0000;
+
+/// Arrow `LargeBinary` cannot tell string, json, enum, xml, html and timezone apart, so the tag comes from the type.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Encoding {
+ Scalar(u8),
+ List(Box),
+ Map(Box, Box),
+ /// (child index in the Arrow struct, its encoding), sorted by the element name bytes.
+ Struct(Vec<(usize, Encoding)>),
+}
+
+/// The encoding of a column of `parsed`, by the type JSON name; an optional type is encoded as its base.
+pub fn encoding_of(parsed: &TypeJson) -> Result {
+ let missing = |part: Part| Error::MissingPart {
+ type_name: parsed.type_.clone(),
+ part,
+ };
+
+ Ok(match parsed.type_.as_str() {
+ "null" => Encoding::Scalar(NULL),
+ "boolean" => Encoding::Scalar(BOOLEAN),
+ "integer" | "positive_integer" => Encoding::Scalar(INTEGER),
+ "float" => Encoding::Scalar(FLOAT),
+ "string" | "non_empty_string" | "numeric-string" | "class_string" => Encoding::Scalar(STRING),
+ "json" => Encoding::Scalar(JSON),
+ "enum" => Encoding::Scalar(ENUM),
+ "xml" => Encoding::Scalar(XML),
+ "html" => Encoding::Scalar(HTML),
+ "timezone" => Encoding::Scalar(TIMEZONE),
+ "uuid" => Encoding::Scalar(UUID),
+ "date" => Encoding::Scalar(DATE),
+ "datetime" => Encoding::Scalar(DATETIME),
+ "time" => Encoding::Scalar(TIME),
+ "xml_element" => Encoding::Scalar(XML_ELEMENT),
+ "html_element" => Encoding::Scalar(HTML_ELEMENT),
+ "list" => Encoding::List(Box::new(encoding_of(
+ parsed.element().ok_or_else(|| missing(Part::Element))?,
+ )?)),
+ "map" => Encoding::Map(
+ Box::new(encoding_of(parsed.key().ok_or_else(|| missing(Part::Key))?)?),
+ Box::new(encoding_of(parsed.value().ok_or_else(|| missing(Part::Value))?)?),
+ ),
+ "structure_v2" => {
+ let mut elements = parsed.fields().iter().enumerate().collect::>();
+
+ elements.sort_by(|(_, left), (_, right)| left.name.as_bytes().cmp(right.name.as_bytes()));
+
+ Encoding::Struct(
+ elements
+ .into_iter()
+ .map(|(child, element)| Ok((child, encoding_of(&element.type_)?)))
+ .collect::>()?,
+ )
+ }
+ "optional" => encoding_of(parsed.base().ok_or_else(|| missing(Part::Base))?)?,
+ other => {
+ return Err(Error::UnknownType {
+ type_name: other.to_owned(),
+ })
+ }
+ })
+}
+
+/// `entries` is the reused pool of map entry buffers.
+pub fn append_value(out: &mut Vec, entries: &mut Vec>, encoding: &Encoding, array: &dyn Array, row: usize) {
+ write(out, entries, 0, encoding, array, row);
+}
+
+/// The caller passes the pairs sorted by name bytes.
+pub fn append_pair(
+ out: &mut Vec,
+ entries: &mut Vec>,
+ name: &[u8],
+ encoding: &Encoding,
+ array: &dyn Array,
+ row: usize,
+) {
+ if is_null(array, row) {
+ return;
+ }
+
+ append_name(out, name);
+ write(out, entries, 0, encoding, array, row);
+}
+
+pub fn append_name(out: &mut Vec, name: &[u8]) {
+ out.extend_from_slice(&(name.len() as u64).to_le_bytes());
+ out.extend_from_slice(name);
+}
+
+/// [low, high] of `xxh3_128(encoded)`.
+pub fn row_lanes(encoded: &[u8]) -> [u64; 2] {
+ let hash = xxh3_128(encoded);
+
+ [hash as u64, (hash >> 64) as u64]
+}
+
+/// [low, high] of the first 128 bits of `md5(encoded)`.
+pub fn md5_row_lanes(encoded: &[u8]) -> [u64; 2] {
+ first_128_bits(&Md5::digest(encoded))
+}
+
+/// [low, high] of the first 128 bits of `sha256(encoded)`.
+pub fn sha256_row_lanes(encoded: &[u8]) -> [u64; 2] {
+ first_128_bits(&Sha256::digest(encoded))
+}
+
+fn first_128_bits(digest: &[u8]) -> [u64; 2] {
+ let mut first = [0_u8; 16];
+ first.copy_from_slice(&digest[..16]);
+ let hash = u128::from_be_bytes(first);
+
+ [hash as u64, (hash >> 64) as u64]
+}
+
+fn write(
+ out: &mut Vec,
+ entries: &mut Vec>,
+ base: usize,
+ encoding: &Encoding,
+ array: &dyn Array,
+ row: usize,
+) {
+ if is_null(array, row) {
+ return out.push(NULL);
+ }
+
+ match encoding {
+ Encoding::Scalar(tag) => write_scalar(out, *tag, array, row),
+ Encoding::List(element) => {
+ let list = array.as_list::();
+ let values = list.value(row);
+
+ out.push(LIST);
+ out.extend_from_slice(&(values.len() as u64).to_le_bytes());
+
+ for index in 0..values.len() {
+ write(out, entries, base, element, values.as_ref(), index);
+ }
+ }
+ Encoding::Map(key, value) => {
+ let map = array.as_map();
+ let start = map.value_offsets()[row] as usize;
+ let count = map.value_offsets()[row + 1] as usize - start;
+
+ while entries.len() < base + count {
+ entries.push(Vec::new());
+ }
+
+ for index in 0..count {
+ let mut entry = std::mem::take(&mut entries[base + index]);
+
+ entry.clear();
+ write(
+ &mut entry,
+ entries,
+ base + count,
+ key,
+ map.keys().as_ref(),
+ start + index,
+ );
+ write(
+ &mut entry,
+ entries,
+ base + count,
+ value,
+ map.values().as_ref(),
+ start + index,
+ );
+ entries[base + index] = entry;
+ }
+
+ entries[base..base + count].sort_unstable();
+ out.push(MAP);
+ out.extend_from_slice(&(count as u64).to_le_bytes());
+
+ for entry in &entries[base..base + count] {
+ out.extend_from_slice(entry);
+ }
+ }
+ Encoding::Struct(elements) => {
+ let structure = array.as_struct();
+
+ out.push(STRUCTURE);
+ let count_at = out.len();
+ out.extend_from_slice(&0_u64.to_le_bytes());
+ let mut present = 0_u64;
+
+ for (child, element) in elements {
+ let column = structure.column(*child);
+
+ if is_null(column.as_ref(), row) {
+ continue;
+ }
+
+ append_name(out, structure.fields()[*child].name().as_bytes());
+ write(out, entries, base, element, column.as_ref(), row);
+ present += 1;
+ }
+
+ out[count_at..count_at + 8].copy_from_slice(&present.to_le_bytes());
+ }
+ }
+}
+
+// a NullArray has no validity buffer, so is_null() is false for its rows
+fn is_null(array: &dyn Array, row: usize) -> bool {
+ array.data_type() == &DataType::Null || array.is_null(row)
+}
+
+fn write_scalar(out: &mut Vec, tag: u8, array: &dyn Array, row: usize) {
+ out.push(tag);
+
+ match tag {
+ NULL => {}
+ BOOLEAN => out.push(u8::from(array.as_boolean().value(row))),
+ INTEGER => out.extend_from_slice(&array.as_primitive::().value(row).to_le_bytes()),
+ FLOAT => {
+ let value = array.as_primitive::().value(row);
+ let bits = if value.is_nan() {
+ NAN_BITS
+ } else if value == 0.0 {
+ 0.0_f64.to_bits()
+ } else {
+ value.to_bits()
+ };
+
+ out.extend_from_slice(&bits.to_le_bytes());
+ }
+ UUID => out.extend_from_slice(array.as_fixed_size_binary().value(row)),
+ DATE => out.extend_from_slice(&array.as_primitive::().value(row).to_le_bytes()),
+ DATETIME => out.extend_from_slice(
+ &array
+ .as_primitive::()
+ .value(row)
+ .to_le_bytes(),
+ ),
+ TIME => out.extend_from_slice(&array.as_primitive::().value(row).to_le_bytes()),
+ XML_ELEMENT | HTML_ELEMENT => append_text(out, element_markup(array.as_binary::().value(row))),
+ _ => append_text(out, array.as_binary::().value(row)),
+ }
+}
+
+fn append_text(out: &mut Vec, text: &[u8]) {
+ out.extend_from_slice(&(text.len() as u64).to_le_bytes());
+ out.extend_from_slice(text);
+}
+
+/// `ElementPosition::markupOf()`: `\x01 path \0 length \0 markup document`; bare markup is its own markup.
+fn element_markup(physical: &[u8]) -> &[u8] {
+ positioned_markup(physical).unwrap_or(physical)
+}
+
+fn positioned_markup(physical: &[u8]) -> Option<&[u8]> {
+ let rest = physical.strip_prefix(b"\x01")?;
+ let path_end = rest.iter().position(|&byte| byte == 0)?;
+ let rest = &rest[path_end + 1..];
+ let length_end = rest.iter().position(|&byte| byte == 0)?;
+ let length: usize = std::str::from_utf8(&rest[..length_end]).ok()?.parse().ok()?;
+
+ rest.get(length_end + 1..length_end + 1 + length)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use arrow_array::builder::{Int64Builder, LargeBinaryBuilder, MapBuilder};
+ use arrow_array::{
+ ArrayRef, BooleanArray, Date32Array, DurationMicrosecondArray, FixedSizeBinaryArray, Float64Array, Int64Array,
+ LargeBinaryArray, ListArray, NullArray, StructArray, TimestampMicrosecondArray,
+ };
+ use arrow_buffer::NullBuffer;
+ use arrow_schema::{Field, Fields};
+ use flow_batch_frame::kind::parse_type;
+ use std::sync::Arc;
+
+ fn encoded(type_json: &str, array: &ArrayRef) -> Vec {
+ let encoding = encoding_of(&parse_type(type_json.as_bytes()).unwrap()).unwrap();
+ let mut entries = Vec::new();
+
+ (0..array.len())
+ .map(|row| {
+ let mut out = Vec::new();
+ append_value(&mut out, &mut entries, &encoding, array.as_ref(), row);
+ hex(&out)
+ })
+ .collect()
+ }
+
+ fn hex(bytes: &[u8]) -> String {
+ bytes.iter().map(|byte| format!("{byte:02x}")).collect()
+ }
+
+ fn binary(values: &[&[u8]]) -> ArrayRef {
+ Arc::new(LargeBinaryArray::from_vec(values.to_vec()))
+ }
+
+ fn strings(values: &[Option<&str>]) -> ArrayRef {
+ Arc::new(LargeBinaryArray::from_opt_vec(
+ values.iter().map(|value| value.map(str::as_bytes)).collect(),
+ ))
+ }
+
+ fn ints(values: &[Option]) -> ArrayRef {
+ Arc::new(Int64Array::from(values.to_vec()))
+ }
+
+ fn structure(fields: Vec<(&str, ArrayRef)>, nulls: Option) -> ArrayRef {
+ let (fields, columns): (Vec<_>, Vec<_>) = fields
+ .into_iter()
+ .map(|(name, column)| (Field::new(name, column.data_type().clone(), true), column))
+ .unzip();
+
+ Arc::new(StructArray::try_new(Fields::from(fields), columns, nulls).unwrap())
+ }
+
+ fn string_map(entries: &[&[(&str, i64)]]) -> ArrayRef {
+ let mut builder = MapBuilder::new(None, LargeBinaryBuilder::new(), Int64Builder::new());
+
+ for entry in entries {
+ for (key, value) in *entry {
+ builder.keys().append_value(key.as_bytes());
+ builder.values().append_value(*value);
+ }
+ builder.append(true).unwrap();
+ }
+
+ Arc::new(builder.finish())
+ }
+
+ fn positioned(path: &str, markup: &str, document: &str) -> Vec {
+ [
+ b"\x01".as_slice(),
+ path.as_bytes(),
+ b"\0",
+ markup.len().to_string().as_bytes(),
+ b"\0",
+ markup.as_bytes(),
+ document.as_bytes(),
+ ]
+ .concat()
+ }
+
+ const INTEGER_JSON: &str = r#"{"type":"integer"}"#;
+
+ #[test]
+ fn null_in_the_columns_form_is_tag_00() {
+ assert_eq!(
+ encoded(r#"{"type":"null"}"#, &(Arc::new(NullArray::new(1)) as ArrayRef)),
+ ["00"]
+ );
+ }
+
+ #[test]
+ fn boolean_is_tag_01() {
+ let array: ArrayRef = Arc::new(BooleanArray::from(vec![Some(true), Some(false), None]));
+
+ assert_eq!(
+ encoded(r#"{"type":"optional","base":{"type":"boolean"}}"#, &array),
+ ["0101", "0100", "00"]
+ );
+ }
+
+ #[test]
+ fn integer_is_tag_02() {
+ assert_eq!(
+ encoded(INTEGER_JSON, &ints(&[Some(1), Some(-1)])),
+ ["020100000000000000", "02ffffffffffffffff"]
+ );
+ }
+
+ #[test]
+ fn float_is_tag_03() {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![1.0, 1.5]));
+
+ assert_eq!(
+ encoded(r#"{"type":"float"}"#, &array),
+ ["03000000000000f03f", "03000000000000f83f"]
+ );
+ }
+
+ #[test]
+ fn string_is_tag_04() {
+ assert_eq!(
+ encoded(r#"{"type":"string"}"#, &strings(&[Some("1"), Some("")])),
+ ["04010000000000000031", "040000000000000000"]
+ );
+ }
+
+ #[test]
+ fn json_is_tag_05() {
+ assert_eq!(
+ encoded(r#"{"type":"json"}"#, &strings(&[Some(r#"{"a":1}"#)])),
+ ["0507000000000000007b2261223a317d"]
+ );
+ }
+
+ #[test]
+ fn enum_is_tag_06() {
+ assert_eq!(
+ encoded(r#"{"type":"enum","class":"E"}"#, &strings(&[Some("one")])),
+ ["0603000000000000006f6e65"]
+ );
+ }
+
+ #[test]
+ fn xml_is_tag_07() {
+ assert_eq!(
+ encoded(
+ r#"{"type":"xml"}"#,
+ &strings(&[Some("\n\n")])
+ ),
+ ["071b000000000000003c3f786d6c2076657273696f6e3d22312e30223f3e0a3c612f3e0a"]
+ );
+ }
+
+ #[test]
+ fn html_is_tag_08() {
+ assert_eq!(
+ encoded(
+ r#"{"type":"html"}"#,
+ &strings(&[Some("a
")])
+ ),
+ ["083e000000000000003c21444f43545950452068746d6c3e3c68746d6c3e3c686561643e3c2f686561643e3c626f64793e3c703e613c2f703e3c2f626f64793e3c2f68746d6c3e"]
+ );
+ }
+
+ #[test]
+ fn timezone_is_tag_09() {
+ assert_eq!(
+ encoded(r#"{"type":"timezone"}"#, &strings(&[Some("UTC")])),
+ ["090300000000000000555443"]
+ );
+ }
+
+ #[test]
+ fn uuid_is_tag_0a() {
+ let mut bytes = [0_u8; 16];
+ bytes[15] = 1;
+ let array: ArrayRef = Arc::new(FixedSizeBinaryArray::try_from_iter([bytes].into_iter()).unwrap());
+
+ assert_eq!(
+ encoded(r#"{"type":"uuid"}"#, &array),
+ ["0a00000000000000000000000000000001"]
+ );
+ }
+
+ #[test]
+ fn date_is_tag_0b() {
+ let array: ArrayRef = Arc::new(Date32Array::from(vec![1]));
+
+ assert_eq!(encoded(r#"{"type":"date"}"#, &array), ["0b01000000"]);
+ }
+
+ #[test]
+ fn datetime_is_tag_0c() {
+ let array: ArrayRef = Arc::new(TimestampMicrosecondArray::from(vec![1_000_002]).with_timezone("UTC"));
+
+ assert_eq!(
+ encoded(r#"{"type":"datetime","zone":"UTC"}"#, &array),
+ ["0c42420f0000000000"]
+ );
+ }
+
+ #[test]
+ fn time_is_tag_0d() {
+ let array: ArrayRef = Arc::new(DurationMicrosecondArray::from(vec![1_000_000, -1_000_000]));
+
+ assert_eq!(
+ encoded(r#"{"type":"time"}"#, &array),
+ ["0d40420f0000000000", "0dc0bdf0ffffffffff"]
+ );
+ }
+
+ #[test]
+ fn list_with_a_null_element_is_tag_0e() {
+ let array: ArrayRef = Arc::new(ListArray::from_iter_primitive::(vec![Some(vec![
+ Some(1),
+ None,
+ ])]));
+
+ assert_eq!(
+ encoded(
+ r#"{"type":"list","element":{"type":"optional","base":{"type":"integer"}}}"#,
+ &array
+ ),
+ ["0e020000000000000002010000000000000000"]
+ );
+ }
+
+ const STRING_INTEGER_MAP: &str = r#"{"type":"map","key":{"type":"string"},"value":{"type":"integer"}}"#;
+
+ #[test]
+ fn map_is_tag_0f_with_entries_sorted_by_bytes() {
+ assert_eq!(
+ encoded(
+ STRING_INTEGER_MAP,
+ &string_map(&[&[("b", 2), ("a", 1)], &[("a", 1), ("b", 2)]])
+ ),
+ [
+ "0f02000000000000000401000000000000006102010000000000000004010000000000000062020200000000000000",
+ "0f02000000000000000401000000000000006102010000000000000004010000000000000062020200000000000000"
+ ]
+ );
+ }
+
+ #[test]
+ fn map_string_key_one_takes_tag_04() {
+ assert_eq!(
+ encoded(STRING_INTEGER_MAP, &string_map(&[&[("1", 1)]])),
+ ["0f010000000000000004010000000000000031020100000000000000"]
+ );
+ }
+
+ #[test]
+ fn map_with_integer_keys_takes_tag_02_for_the_keys() {
+ let mut builder = MapBuilder::new(None, Int64Builder::new(), LargeBinaryBuilder::new());
+ builder.keys().append_value(1);
+ builder.values().append_value(b"a");
+ builder.append(true).unwrap();
+ let array: ArrayRef = Arc::new(builder.finish());
+
+ assert_eq!(
+ encoded(
+ r#"{"type":"map","key":{"type":"integer"},"value":{"type":"string"}}"#,
+ &array
+ ),
+ ["0f010000000000000002010000000000000004010000000000000061"]
+ );
+ }
+
+ #[test]
+ fn nested_structure_is_tag_10_with_elements_by_name() {
+ let inner = structure(
+ vec![("x", strings(&[Some("y"), Some("y")]))],
+ Some(NullBuffer::from(vec![true, false])),
+ );
+ let array = structure(vec![("b", ints(&[Some(1), Some(1)])), ("a", inner)], None);
+
+ assert_eq!(
+ encoded(
+ r#"{"type":"structure_v2","fields":[
+ {"name":"b","type":{"type":"integer"}},
+ {"name":"a","type":{"type":"optional","base":{"type":"structure_v2","fields":[{"name":"x","type":{"type":"string"}}]}}}
+ ]}"#,
+ &array
+ ),
+ [
+ "10020000000000000001000000000000006110010000000000000001000000000000007804010000000000000079010000000000000062020100000000000000",
+ "100100000000000000010000000000000062020100000000000000"
+ ]
+ );
+ }
+
+ #[test]
+ fn null_structure_element_equals_missing_optional_element() {
+ let array = structure(vec![("a", ints(&[Some(1)])), ("b", strings(&[None]))], None);
+
+ assert_eq!(
+ encoded(
+ r#"{"type":"structure_v2","fields":[
+ {"name":"a","type":{"type":"integer"}},
+ {"name":"b","type":{"type":"optional","base":{"type":"string"}},"optional":true}
+ ]}"#,
+ &array
+ ),
+ ["100100000000000000010000000000000061020100000000000000"]
+ );
+ }
+
+ #[test]
+ fn structure_element_order_does_not_count() {
+ let left = structure(vec![("a", ints(&[Some(1)])), ("b", strings(&[Some("x")]))], None);
+ let right = structure(vec![("b", strings(&[Some("x")])), ("a", ints(&[Some(1)]))], None);
+
+ assert_eq!(
+ encoded(
+ r#"{"type":"structure_v2","fields":[{"name":"a","type":{"type":"integer"}},{"name":"b","type":{"type":"string"}}]}"#,
+ &left
+ ),
+ encoded(
+ r#"{"type":"structure_v2","fields":[{"name":"b","type":{"type":"string"}},{"name":"a","type":{"type":"integer"}}]}"#,
+ &right
+ )
+ );
+ }
+
+ #[test]
+ fn renamed_nested_element_differs() {
+ let left = structure(vec![("s", structure(vec![("a", ints(&[Some(1)]))], None))], None);
+ let right = structure(vec![("s", structure(vec![("b", ints(&[Some(1)]))], None))], None);
+
+ assert_ne!(
+ encoded(
+ r#"{"type":"structure_v2","fields":[{"name":"s","type":{"type":"structure_v2","fields":[{"name":"a","type":{"type":"integer"}}]}}]}"#,
+ &left
+ ),
+ encoded(
+ r#"{"type":"structure_v2","fields":[{"name":"s","type":{"type":"structure_v2","fields":[{"name":"b","type":{"type":"integer"}}]}}]}"#,
+ &right
+ )
+ );
+ }
+
+ #[test]
+ fn xml_element_is_tag_11_with_its_markup_wherever_it_lives() {
+ let array = binary(&[
+ &positioned(
+ "0",
+ "",
+ "\n\n",
+ ),
+ &positioned(
+ "1",
+ "",
+ "\n\n",
+ ),
+ &positioned("0", "", "\n\n"),
+ b"",
+ ]);
+
+ assert_eq!(
+ encoded(r#"{"type":"xml_element"}"#, &array),
+ [
+ "110d000000000000003c6120783d2231223e3c2f613e",
+ "110d000000000000003c6120783d2231223e3c2f613e",
+ "1107000000000000003c613e3c2f613e",
+ "1107000000000000003c613e3c2f613e"
+ ]
+ );
+ }
+
+ #[test]
+ fn xml_element_differs_from_xml_document_with_the_same_markup() {
+ let array = strings(&[Some("")]);
+
+ assert_ne!(
+ encoded(r#"{"type":"xml"}"#, &array),
+ encoded(r#"{"type":"xml_element"}"#, &array)
+ );
+ }
+
+ #[test]
+ fn html_element_is_tag_12_with_its_markup_wherever_it_lives() {
+ let array = binary(&[
+ &positioned("0", "a
", ""),
+ &positioned("1", "a
", ""),
+ b"a
",
+ ]);
+
+ assert_eq!(
+ encoded(r#"{"type":"html_element"}"#, &array),
+ [
+ "1208000000000000003c703e613c2f703e",
+ "1208000000000000003c703e613c2f703e",
+ "1208000000000000003c703e613c2f703e"
+ ]
+ );
+ }
+
+ #[test]
+ fn same_text_of_different_types_differs() {
+ let mut all = vec![
+ encoded(INTEGER_JSON, &ints(&[Some(1)])),
+ encoded(
+ r#"{"type":"float"}"#,
+ &(Arc::new(Float64Array::from(vec![1.0])) as ArrayRef),
+ ),
+ encoded(r#"{"type":"string"}"#, &strings(&[Some("1")])),
+ encoded(r#"{"type":"json"}"#, &strings(&[Some("[1]")])),
+ encoded(r#"{"type":"enum","class":"E"}"#, &strings(&[Some("one")])),
+ ];
+ all.sort();
+ all.dedup();
+
+ assert_eq!(all.len(), 5);
+ }
+
+ #[test]
+ fn null_differs_from_empty_string() {
+ assert_eq!(
+ encoded(
+ r#"{"type":"optional","base":{"type":"string"}}"#,
+ &strings(&[None, Some("")])
+ ),
+ ["00", "040000000000000000"]
+ );
+ }
+
+ #[test]
+ fn negative_zero_equals_zero_and_every_nan_is_one_value() {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![-0.0, 0.0, f64::NAN, -f64::NAN]));
+
+ assert_eq!(
+ encoded(r#"{"type":"float"}"#, &array),
+ [
+ "030000000000000000",
+ "030000000000000000",
+ "03000000000000f87f",
+ "03000000000000f87f"
+ ]
+ );
+ }
+
+ #[test]
+ fn float_nan_differs_from_string_nan() {
+ let array: ArrayRef = Arc::new(Float64Array::from(vec![f64::NAN]));
+
+ assert_ne!(
+ encoded(r#"{"type":"float"}"#, &array),
+ encoded(r#"{"type":"string"}"#, &strings(&[Some("NaN")]))
+ );
+ }
+
+ #[test]
+ fn the_same_instant_is_one_value_whatever_the_zone_of_the_type() {
+ let array: ArrayRef =
+ Arc::new(TimestampMicrosecondArray::from(vec![1_767_225_600_000_000]).with_timezone("UTC"));
+
+ assert_eq!(
+ encoded(r#"{"type":"datetime","zone":"Europe/Warsaw"}"#, &array),
+ encoded(r#"{"type":"datetime","zone":"UTC"}"#, &array)
+ );
+ assert_eq!(
+ encoded(r#"{"type":"datetime","zone":"UTC"}"#, &array),
+ ["0c0040204648470600"]
+ );
+ }
+
+ #[test]
+ fn date_differs_from_datetime_at_midnight() {
+ let date: ArrayRef = Arc::new(Date32Array::from(vec![1]));
+ let datetime: ArrayRef = Arc::new(TimestampMicrosecondArray::from(vec![86_400_000_000]).with_timezone("UTC"));
+
+ assert_eq!(encoded(r#"{"type":"date"}"#, &date), ["0b01000000"]);
+ assert_eq!(
+ encoded(r#"{"type":"datetime","zone":"UTC"}"#, &datetime),
+ ["0c0060d71d14000000"]
+ );
+ }
+
+ #[test]
+ fn list_order_counts() {
+ let array: ArrayRef = Arc::new(ListArray::from_iter_primitive::(vec![
+ Some(vec![Some(1), Some(2)]),
+ Some(vec![Some(2), Some(1)]),
+ ]));
+ let encoded = encoded(r#"{"type":"list","element":{"type":"integer"}}"#, &array);
+
+ assert_ne!(encoded[0], encoded[1]);
+ }
+
+ #[test]
+ fn json_whitespace_counts() {
+ let encoded = encoded(
+ r#"{"type":"json"}"#,
+ &strings(&[Some(r#"{"a":1}"#), Some(r#"{"a": 1}"#)]),
+ );
+
+ assert_ne!(encoded[0], encoded[1]);
+ }
+
+ #[test]
+ fn columns_form_concatenates_the_columns_in_list_order() {
+ let a = ints(&[Some(1)]);
+ let b: ArrayRef = Arc::new(BooleanArray::from(vec![true]));
+ let integer = Encoding::Scalar(INTEGER);
+ let boolean = Encoding::Scalar(BOOLEAN);
+ let mut entries = Vec::new();
+ let mut forward = Vec::new();
+ let mut backward = Vec::new();
+
+ append_value(&mut forward, &mut entries, &integer, a.as_ref(), 0);
+ append_value(&mut forward, &mut entries, &boolean, b.as_ref(), 0);
+ append_value(&mut backward, &mut entries, &boolean, b.as_ref(), 0);
+ append_value(&mut backward, &mut entries, &integer, a.as_ref(), 0);
+
+ assert_eq!(hex(&forward), "0201000000000000000101");
+ assert_eq!(hex(&backward), "0101020100000000000000");
+ }
+
+ #[test]
+ fn row_form_writes_name_parts_and_leaves_out_null_pairs() {
+ let a = ints(&[Some(1)]);
+ let b: ArrayRef = Arc::new(BooleanArray::from(vec![true]));
+ let missing = ints(&[None]);
+ let null: ArrayRef = Arc::new(NullArray::new(1));
+ let mut entries = Vec::new();
+ let mut row = Vec::new();
+
+ append_pair(&mut row, &mut entries, b"a", &Encoding::Scalar(INTEGER), a.as_ref(), 0);
+ append_pair(&mut row, &mut entries, b"b", &Encoding::Scalar(BOOLEAN), b.as_ref(), 0);
+ append_pair(
+ &mut row,
+ &mut entries,
+ b"c",
+ &Encoding::Scalar(INTEGER),
+ missing.as_ref(),
+ 0,
+ );
+ append_pair(&mut row, &mut entries, b"d", &Encoding::Scalar(NULL), null.as_ref(), 0);
+
+ assert_eq!(hex(&row), "0100000000000000610201000000000000000100000000000000620101");
+ }
+
+ #[test]
+ fn row_lanes_are_the_low_and_high_half_of_xxh3_128() {
+ assert_eq!(
+ row_lanes(b"abc"),
+ [8_696_274_497_037_089_104_u64, 481_984_899_792_396_677_u64]
+ );
+ }
+
+ #[test]
+ fn md5_and_sha256_row_lanes_are_the_first_128_bits_of_the_digest() {
+ assert_eq!(md5_row_lanes(b"abc"), [0xd6963f7d28e17f72_u64, 0x900150983cd24fb0_u64]);
+ assert_eq!(
+ sha256_row_lanes(b"abc"),
+ [0x414140de5dae2223_u64, 0xba7816bf8f01cfea_u64]
+ );
+ }
+
+ #[test]
+ fn nested_maps_share_the_entry_pool_without_mixing_entries() {
+ let inner = string_map(&[&[("b", 2), ("a", 1)]]);
+ let mut entries = vec![b"stale".to_vec(); 3];
+ let encoding = encoding_of(&parse_type(STRING_INTEGER_MAP.as_bytes()).unwrap()).unwrap();
+ let mut out = Vec::new();
+
+ append_value(&mut out, &mut entries, &encoding, inner.as_ref(), 0);
+
+ assert_eq!(
+ hex(&out),
+ "0f02000000000000000401000000000000006102010000000000000004010000000000000062020200000000000000"
+ );
+ }
+
+ #[test]
+ fn an_unknown_type_is_refused() {
+ assert!(matches!(
+ encoding_of(&parse_type(br#"{"type":"mixed"}"#).unwrap()),
+ Err(Error::UnknownType { .. })
+ ));
+ }
+}
diff --git a/src/extension/flow-php-ext/crates/flow-column-kernels/src/grouping.rs b/src/extension/flow-php-ext/crates/flow-column-kernels/src/grouping.rs
index 4e6a9d0f6..fe3aec4cb 100644
--- a/src/extension/flow-php-ext/crates/flow-column-kernels/src/grouping.rs
+++ b/src/extension/flow-php-ext/crates/flow-column-kernels/src/grouping.rs
@@ -1,115 +1,7 @@
-//! Group keys equal exactly when PHP's `KeyEncoder` keys are equal: each value carries the tag of its physical.
+//! The bucket of a canonical key, as PHP's `KeyEncoder::bucketOf()` reads it.
-use arrow_array::cast::AsArray;
-use arrow_array::types::{Date32Type, DurationMicrosecondType, Float64Type, Int64Type, TimestampMicrosecondType};
-use arrow_array::Array;
-use arrow_schema::{DataType, TimeUnit};
use xxhash_rust::xxh3::xxh3_128;
-const DAY_MICROSECONDS: i64 = 86_400_000_000;
-
-pub fn append_native_key(key: &mut Vec, array: &dyn Array, row: usize) -> bool {
- match array.data_type() {
- DataType::Null => key.extend_from_slice(b"\0n"),
- _ if array.is_null(row) => key.extend_from_slice(b"\0n"),
- DataType::Boolean => key.extend_from_slice(if array.as_boolean().value(row) { b"\0t" } else { b"\0f" }),
- DataType::Int64 => append_int(key, array.as_primitive::().value(row)),
- DataType::Timestamp(TimeUnit::Microsecond, _) => {
- append_int(key, array.as_primitive::().value(row));
- }
- DataType::Duration(TimeUnit::Microsecond) => {
- append_int(key, array.as_primitive::().value(row));
- }
- DataType::Date32 => {
- let days = i64::from(array.as_primitive::().value(row));
-
- // a day count past i64 microseconds is a float instant in PHP too
- match days.checked_mul(DAY_MICROSECONDS) {
- Some(instant) => append_int(key, instant),
- None => append_float(key, days as f64 * DAY_MICROSECONDS as f64),
- }
- }
- DataType::Float64 => append_float(key, array.as_primitive::().value(row)),
- DataType::LargeBinary => append_bytes(key, array.as_binary::().value(row)),
- DataType::FixedSizeBinary(_) => append_bytes(key, array.as_fixed_size_binary().value(row)),
- _ => return false,
- }
-
- true
-}
-
-pub fn append_encoded(key: &mut Vec, encoded: &[u8]) {
- // a batch may lack the column (native null) or hold xml where another holds a string: both must key alike
- if encoded == b"\0n" {
- return key.extend_from_slice(b"\0n");
- }
-
- if let Some(text) = encoded_string(encoded) {
- return append_bytes(key, text);
- }
-
- key.extend_from_slice(b"\0z");
- key.extend_from_slice(&(encoded.len() as u64).to_le_bytes());
- key.extend_from_slice(encoded);
-}
-
-/// KeyEncoder's `\0s:`, the tag it gives every string, xml and html text included.
-fn encoded_string(encoded: &[u8]) -> Option<&[u8]> {
- let rest = encoded.strip_prefix(b"\0s")?;
- let colon = rest.iter().position(|&byte| byte == b':')?;
- let length: usize = std::str::from_utf8(&rest[..colon]).ok()?.parse().ok()?;
- let text = &rest[colon + 1..];
-
- (text.len() == length).then_some(text)
-}
-
-fn append_int(key: &mut Vec, value: i64) {
- key.extend_from_slice(b"\0i");
- key.extend_from_slice(&value.to_le_bytes());
-}
-
-fn append_float(key: &mut Vec, value: f64) {
- // ComparableValues::equality() turns NaN into the string 'NaN'; -0.0 === 0.0
- if value.is_nan() {
- return append_bytes(key, b"NaN");
- }
-
- key.extend_from_slice(b"\0d");
- key.extend_from_slice(&(if value == 0.0 { 0.0_f64 } else { value }).to_bits().to_le_bytes());
-}
-
-fn append_bytes(key: &mut Vec, bytes: &[u8]) {
- key.extend_from_slice(b"\0s");
- key.extend_from_slice(&(bytes.len() as u64).to_le_bytes());
- key.extend_from_slice(bytes);
-}
-
-/// KeyEncoder's text key of one Null, Boolean, Int64 or LargeBinary value; `false` for every other kind.
-pub fn append_text_key(key: &mut Vec, array: &dyn Array, row: usize) -> bool {
- match array.data_type() {
- DataType::Null => key.extend_from_slice(b"\0n"),
- DataType::Boolean | DataType::Int64 | DataType::LargeBinary if array.is_null(row) => {
- key.extend_from_slice(b"\0n");
- }
- DataType::Boolean => key.extend_from_slice(if array.as_boolean().value(row) { b"\0t" } else { b"\0f" }),
- DataType::Int64 => {
- key.extend_from_slice(b"\0i");
- key.extend_from_slice(array.as_primitive::().value(row).to_string().as_bytes());
- }
- DataType::LargeBinary => {
- let bytes = array.as_binary::().value(row);
-
- key.extend_from_slice(b"\0s");
- key.extend_from_slice(bytes.len().to_string().as_bytes());
- key.push(b':');
- key.extend_from_slice(bytes);
- }
- _ => return false,
- }
-
- true
-}
-
/// `(int) hexdec(substr(hash('xxh128', $key), $offset, 8)) % $buckets`
pub fn bucket_of(key: &[u8], hash_offset: u32, buckets: u64) -> u64 {
let digits = (xxh3_128(key) >> (128 - 4 * (hash_offset + 8))) & 0xFFFF_FFFF;
@@ -120,205 +12,6 @@ pub fn bucket_of(key: &[u8], hash_offset: u32, buckets: u64) -> u64 {
#[cfg(test)]
mod tests {
use super::*;
- use arrow_array::{
- ArrayRef, BooleanArray, Date32Array, DurationMicrosecondArray, FixedSizeBinaryArray, Float64Array, Int64Array,
- LargeBinaryArray, ListArray, NullArray, TimestampMicrosecondArray,
- };
- use std::sync::Arc;
-
- fn keys(columns: &[ArrayRef]) -> Vec> {
- (0..columns[0].len())
- .map(|row| {
- let mut key = Vec::new();
-
- for column in columns {
- assert!(append_native_key(&mut key, column.as_ref(), row));
- }
-
- key
- })
- .collect()
- }
-
- fn key(column: ArrayRef, row: usize) -> Vec {
- keys(&[column]).swap_remove(row)
- }
-
- #[test]
- fn zero_and_negative_zero_are_one_key() {
- let k = keys(&[Arc::new(Float64Array::from(vec![0.0, -0.0, 1.5]))]);
-
- assert_eq!(k[0], k[1]);
- assert_ne!(k[0], k[2]);
- }
-
- #[test]
- fn nans_are_one_key_equal_to_the_string_nan() {
- let k = keys(&[Arc::new(Float64Array::from(vec![f64::NAN, -f64::NAN, 1.0]))]);
-
- assert_eq!(k[0], k[1]);
- assert_ne!(k[0], k[2]);
- assert_eq!(k[0], key(Arc::new(LargeBinaryArray::from_vec(vec![b"NaN"])), 0));
- }
-
- #[test]
- fn null_is_neither_empty_bytes_nor_zero_nor_false() {
- let strings = keys(&[Arc::new(LargeBinaryArray::from_opt_vec(vec![
- None,
- Some(b""),
- Some(b"0"),
- ]))]);
-
- assert_ne!(strings[0], strings[1]);
- assert_ne!(strings[0], strings[2]);
- assert_eq!(strings[0], key(Arc::new(Int64Array::from(vec![None::])), 0));
- assert_eq!(strings[0], key(Arc::new(NullArray::new(1)), 0));
- assert_ne!(strings[0], key(Arc::new(Int64Array::from(vec![0])), 0));
- assert_ne!(strings[0], key(Arc::new(BooleanArray::from(vec![false])), 0));
- }
-
- #[test]
- fn bools_and_ints_keep_their_own_tags() {
- let bools = keys(&[Arc::new(BooleanArray::from(vec![true, false, true]))]);
-
- assert_eq!(bools[0], bools[2]);
- assert_ne!(bools[0], bools[1]);
- assert_ne!(bools[0], key(Arc::new(Int64Array::from(vec![1])), 0));
- assert_ne!(
- key(Arc::new(Int64Array::from(vec![1])), 0),
- key(Arc::new(Float64Array::from(vec![1.0])), 0)
- );
- }
-
- #[test]
- fn a_two_column_key_never_runs_one_value_into_the_next() {
- let k = keys(&[
- Arc::new(LargeBinaryArray::from_vec(vec![b"ab", b"a"])),
- Arc::new(LargeBinaryArray::from_vec(vec![b"", b"b"])),
- ]);
-
- assert_ne!(k[0], k[1]);
- }
-
- #[test]
- fn a_date_and_a_datetime_at_the_same_instant_are_one_key() {
- let date = key(Arc::new(Date32Array::from(vec![19_723])), 0);
- let datetime = TimestampMicrosecondArray::from(vec![19_723 * DAY_MICROSECONDS]).with_timezone("UTC");
-
- assert_eq!(date, key(Arc::new(datetime), 0));
- assert_eq!(
- date,
- key(Arc::new(Int64Array::from(vec![19_723 * DAY_MICROSECONDS])), 0)
- );
- assert_eq!(
- key(Arc::new(DurationMicrosecondArray::from(vec![5])), 0),
- key(Arc::new(Int64Array::from(vec![5])), 0)
- );
- }
-
- #[test]
- fn a_date_past_i64_microseconds_is_a_float_instant() {
- let far = key(Arc::new(Date32Array::from(vec![i32::MAX])), 0);
-
- assert_eq!(
- far,
- key(
- Arc::new(Float64Array::from(vec![f64::from(i32::MAX) * DAY_MICROSECONDS as f64])),
- 0
- )
- );
- }
-
- #[test]
- fn a_uuid_is_its_sixteen_physical_bytes() {
- let bytes = [7_u8; 16];
- let uuid = FixedSizeBinaryArray::try_from_iter(vec![bytes].into_iter()).unwrap();
-
- assert_eq!(
- key(Arc::new(uuid), 0),
- key(Arc::new(LargeBinaryArray::from_vec(vec![&bytes[..]])), 0)
- );
- }
-
- #[test]
- fn any_other_encoded_part_never_equals_a_native_one() {
- let mut encoded = Vec::new();
- append_encoded(&mut encoded, b"a");
-
- assert_ne!(encoded, key(Arc::new(LargeBinaryArray::from_vec(vec![b"a"])), 0));
- }
-
- #[test]
- fn an_encoded_null_and_string_key_as_native_ones_do() {
- let mut null = Vec::new();
- append_encoded(&mut null, b"\0n");
- let mut text = Vec::new();
- append_encoded(&mut text, b"\0s3:a:b");
-
- assert_eq!(null, key(Arc::new(NullArray::new(1)), 0));
- assert_eq!(text, key(Arc::new(LargeBinaryArray::from_vec(vec![b"a:b"])), 0));
- }
-
- #[test]
- fn a_list_has_no_native_key() {
- let list = ListArray::from_iter_primitive::(vec![Some(vec![Some(1)])]);
-
- assert!(!append_native_key(&mut Vec::new(), &list, 0));
- }
-
- #[test]
- fn text_keys_are_the_key_encoder_strings() {
- let text = |column: ArrayRef, row: usize| {
- let mut key = Vec::new();
- assert!(append_text_key(&mut key, column.as_ref(), row));
-
- key
- };
-
- assert_eq!(text(Arc::new(NullArray::new(1)), 0), b"\0n");
- assert_eq!(text(Arc::new(BooleanArray::from(vec![true, false])), 0), b"\0t");
- assert_eq!(text(Arc::new(BooleanArray::from(vec![true, false])), 1), b"\0f");
- assert_eq!(text(Arc::new(BooleanArray::from(vec![None, Some(true)])), 0), b"\0n");
- assert_eq!(text(Arc::new(Int64Array::from(vec![-42, i64::MAX])), 0), b"\0i-42");
- assert_eq!(
- text(Arc::new(Int64Array::from(vec![-42, i64::MAX])), 1),
- b"\0i9223372036854775807"
- );
- assert_eq!(text(Arc::new(Int64Array::from(vec![None, Some(1)])), 0), b"\0n");
- assert_eq!(
- text(Arc::new(LargeBinaryArray::from(vec![&b"abc"[..], b""])), 0),
- b"\0s3:abc"
- );
- assert_eq!(
- text(Arc::new(LargeBinaryArray::from(vec![&b"abc"[..], b""])), 1),
- b"\0s0:"
- );
- assert_eq!(
- text(
- Arc::new(LargeBinaryArray::from(vec![Some("zażółć".as_bytes()), None])),
- 0
- ),
- "\0s10:zażółć".as_bytes()
- );
- assert_eq!(
- text(Arc::new(LargeBinaryArray::from(vec![Some(&b"x"[..]), None])), 1),
- b"\0n"
- );
- }
-
- #[test]
- fn a_kind_without_an_exact_text_has_no_text_key() {
- let mut key = Vec::new();
-
- assert!(!append_text_key(&mut key, &Float64Array::from(vec![1.5]), 0));
- assert!(!append_text_key(&mut key, &Date32Array::from(vec![1]), 0));
- assert!(!append_text_key(
- &mut key,
- &FixedSizeBinaryArray::try_from_iter(vec![[0u8; 16]].into_iter()).unwrap(),
- 0
- ));
- assert!(key.is_empty());
- }
#[test]
fn buckets_are_the_digits_php_reads_from_the_xxh128_hex() {
diff --git a/src/extension/flow-php-ext/crates/flow-column-kernels/src/lib.rs b/src/extension/flow-php-ext/crates/flow-column-kernels/src/lib.rs
index 5a9f0cf7b..a4f0f8c8c 100644
--- a/src/extension/flow-php-ext/crates/flow-column-kernels/src/lib.rs
+++ b/src/extension/flow-php-ext/crates/flow-column-kernels/src/lib.rs
@@ -1,6 +1,7 @@
//! Column kernels that answer exactly as Flow's PHP backend does.
pub mod arithmetic;
+pub mod canonical;
pub mod compare;
pub mod grouping;
pub mod sort;
diff --git a/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustBackend.php b/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustBackend.php
index 2b55e0720..8a8d9327d 100644
--- a/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustBackend.php
+++ b/src/extension/flow-php-ext/php/Flow/ETL/Values/Column/RustBackend.php
@@ -141,6 +141,16 @@ public function groupedCounts(): GroupedCounts
throw new RuntimeException('flow_php extension is not loaded');
}
+ public function rowHashes(array $columns, int $count): Column
+ {
+ throw new RuntimeException('flow_php extension is not loaded');
+ }
+
+ public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes
+ {
+ throw new RuntimeException('flow_php extension is not loaded');
+ }
+
/**
* @param list $columns
*/
diff --git a/src/extension/flow-php-ext/src/backend.rs b/src/extension/flow-php-ext/src/backend.rs
index f3fef5bb9..df50f1a50 100644
--- a/src/extension/flow-php-ext/src/backend.rs
+++ b/src/extension/flow-php-ext/src/backend.rs
@@ -23,24 +23,28 @@ use flow_batch_frame::frame;
use flow_batch_frame::kind::Kind;
use flow_batch_frame::layout::buffer_count;
use flow_column_kernels::arithmetic::Operator;
+use flow_column_kernels::canonical::{md5_row_lanes, row_lanes, sha256_row_lanes};
use flow_column_kernels::compare::{contains, ends_with, is_not_null, is_null, starts_with};
-use flow_column_kernels::grouping::{append_text_key, bucket_of};
+use flow_column_kernels::grouping::bucket_of;
use crate::arithmetic::{native_arithmetic, native_modulo};
use crate::batch_columns::HeldBatch;
use crate::builder::{throw, RustColumnBuilder};
+use crate::canonical_rows::{named, named_column, ordered, row_columns, STRING_TYPE};
use crate::column::RustColumn;
use crate::compare::{boolean_column, native_comparison, native_text_match};
use crate::ctx::{
call_handle_catching, call_method, call_static, ce_method_ref, column_key, construct, expect_object, find_class,
- ht_for_each, ht_get, ht_insert, ht_insert_long, instance, transparent_exception, zval_long, zval_str,
+ ht_for_each, ht_get, ht_insert, ht_insert_long, instance, read_property, transparent_exception, zval_long,
+ zval_str,
};
use crate::exception::ext_exception;
use crate::frame::{string_of, FrameBody, PhpCodec};
-use crate::group_table::{KeyColumn, RustGroupTable};
+use crate::group_table::RustGroupTable;
use crate::grouped_counts::RustGroupedCounts;
use crate::grouped_totals::RustGroupedTotals;
use crate::interfaces::{backend_ce, describable_ce};
+use crate::multiset_hashes::{RowLanes, RustGroupedMultisetHashes};
use crate::plan::{physical_for_definition, type_plan, TypePlan};
use crate::render::{decode_exception, encode_exception, floe_exception, frame_exception, invalid_argument};
use crate::sort::{handed_off_native_bytes, native_sort, native_sort_working_bytes};
@@ -48,23 +52,11 @@ use crate::sort::{handed_off_native_bytes, native_sort, native_sort_working_byte
const COLUMN_MISMATCH: &str = "Flow\\ETL\\Foundation\\Exception\\ColumnMismatchException";
const DESCRIPTION: &str = "Flow\\ETL\\Foundation\\Describe\\Description";
const DEFINITIONS: &str = "Flow\\ETL\\Values\\Schema\\Definitions";
-const KEY_ENCODER: &str = "Flow\\ETL\\Values\\Grouping\\KeyEncoder";
const MIXED_TYPE: &str = "Flow\\Types\\Type\\Native\\MixedType";
const ROWS: &str = "Flow\\ETL\\Values\\Rows";
const PHP_BACKEND: &str = "Flow\\ETL\\Values\\Column\\PhpBackend";
const RUST_BACKEND: &str = "Flow\\ETL\\Values\\Column\\RustBackend";
const SCHEMA_MISMATCH: &str = "Flow\\ETL\\Foundation\\Exception\\SchemaMismatchException";
-// the types whose KeyEncoder text append_text_key() writes exactly
-const TEXT_KEYS: [&str; 8] = [
- "integer",
- "positive_integer",
- "boolean",
- "null",
- "string",
- "non_empty_string",
- "numeric-string",
- "class_string",
-];
/// A return typed `Flow\ETL\Values\Column\Column`: `adopt()` hands back its argument itself.
pub struct ColumnValue(pub Zval);
@@ -289,6 +281,42 @@ impl RustBackend {
RustGroupedCounts::default()
}
+ #[php(name = "rowHashes")]
+ pub fn row_hashes(&self, columns: &ZendHashTable, count: i64) -> PhpResult {
+ let resolved = row_columns(columns)?;
+ let count = usize::try_from(count).map_err(|_| ext_exception("flow_php expected a row count of 0 or more"))?;
+ let mut row = Vec::new();
+ let mut entries = Vec::new();
+ let hashes = (0..count)
+ .map(|index| {
+ named(&mut row, &mut entries, &resolved, index);
+ let [low, high] = row_lanes(&row);
+
+ format!("{high:016x}{low:016x}")
+ })
+ .collect::>();
+
+ RustColumn::of_type(Arc::new(LargeBinaryArray::from_iter_values(hashes)), STRING_TYPE)
+ }
+
+ #[php(name = "groupedMultisetHashes")]
+ pub fn grouped_multiset_hashes(&self, algorithm: &Zval) -> PhpResult {
+ let name = read_property(expect_object(algorithm, "a MultisetHashAlgorithm")?, "value")?;
+ let row_lanes: RowLanes = match name.zend_str().map(|name| name.as_bytes()) {
+ Some(b"xxh128") => row_lanes,
+ Some(b"md5") => md5_row_lanes,
+ Some(b"sha256") => sha256_row_lanes,
+ unknown => {
+ return Err(ext_exception(format!(
+ "flow_php does not know the multiset hash algorithm \"{}\", update the extension",
+ String::from_utf8_lossy(unknown.unwrap_or_default())
+ )))
+ }
+ };
+
+ Ok(RustGroupedMultisetHashes::of(row_lanes))
+ }
+
#[php(name = "groupTable")]
pub fn group_table(&self, columns: &ZendHashTable, declared: &Zval) -> PhpResult {
RustGroupTable::new(columns, declared)
@@ -327,29 +355,15 @@ impl RustBackend {
let columns = keys
.values()
- .map(|column| partition_key(column, count))
+ .map(|column| named_column(Vec::new(), column))
.collect::>>()?;
let mut slots = AHashMap::::new();
let mut indices: Vec<(u64, Vec)> = Vec::new();
let mut key = Vec::new();
+ let mut entries = Vec::new();
for row in 0..count {
- key.clear();
-
- for column in &columns {
- match column {
- KeyColumn::Native(array) => {
- if !append_text_key(&mut key, array.as_ref(), row) {
- return Err(ext_exception(format!(
- "flow_php has no partition key for {} values",
- array.data_type()
- )));
- }
- }
- KeyColumn::Encoded(encoded) => key.extend_from_slice(&encoded[row]),
- }
- }
-
+ ordered(&mut key, &mut entries, &columns, row);
let bucket = bucket_of(&key, hash_offset, bucket_count);
let slot = *slots.entry(bucket).or_insert_with(|| {
indices.push((bucket, Vec::new()));
@@ -596,32 +610,6 @@ impl NoRows {
}
}
-fn partition_key(column: &Zval, count: usize) -> PhpResult {
- if let Some(native) = column.extract::<&RustColumn>() {
- if TEXT_KEYS.contains(&native.plan().type_name.as_str()) {
- return Ok(KeyColumn::Native(Arc::clone(native.data())));
- }
- }
-
- let mut columns = ZendHashTable::new();
- columns.push(column.shallow_clone())?;
- let mut columns_zv = Zval::new();
- columns_zv.set_hashtable(columns);
- let keys = call_static(KEY_ENCODER, "ofColumns", &mut [columns_zv, zval_long(count as i64)])?;
-
- Ok(KeyColumn::Encoded(
- keys.array()
- .ok_or_else(|| ext_exception("flow_php expected KeyEncoder::ofColumns() to return an array"))?
- .values()
- .map(|key| {
- key.zend_str()
- .map(|key| key.as_bytes().to_vec())
- .ok_or_else(|| ext_exception("flow_php expected KeyEncoder::ofColumns() to return strings"))
- })
- .collect::>>()?,
- ))
-}
-
/// `Rows::fromColumns($schema, $columns, $count)`.
pub fn rows_from_columns(schema: &Zval, columns: ZBox, count: usize) -> Result {
let mut columns_zv = Zval::new();
@@ -681,7 +669,7 @@ pub fn native_column(definition: &Zval, column: &Zval) -> PhpResult<(Rc PhpResult {
+ pub(crate) fn adopt_result(&self, column: Zval) -> PhpResult {
let definition = call_static(
DEFINITIONS,
"of",
diff --git a/src/extension/flow-php-ext/src/canonical_rows.rs b/src/extension/flow-php-ext/src/canonical_rows.rs
new file mode 100644
index 000000000..53dfa1ac1
--- /dev/null
+++ b/src/extension/flow-php-ext/src/canonical_rows.rs
@@ -0,0 +1,63 @@
+//! The canonical bytes of a row from native columns: `ordered` for group, join and bucket keys, `named` for row
+//! hashes. The Rust side of PHP's `CanonicalEncoding::ordered()` and `named()`.
+
+use std::rc::Rc;
+use std::sync::Arc;
+
+use arrow_array::ArrayRef;
+use ext_php_rs::prelude::*;
+use ext_php_rs::types::{ZendHashTable, Zval};
+use flow_column_kernels::canonical::{append_pair, append_value};
+
+use crate::backend::RustBackend;
+use crate::column::RustColumn;
+use crate::exception::ext_exception;
+use crate::plan::TypePlan;
+
+pub const STRING_TYPE: &str = "Flow\\Types\\Type\\Native\\StringType";
+
+/// (name, native array, the plan that holds its encoding)
+pub type RowColumn = (Vec, ArrayRef, Rc);
+
+pub fn ordered(out: &mut Vec, entries: &mut Vec>, columns: &[RowColumn], row: usize) {
+ out.clear();
+
+ for (_, array, plan) in columns {
+ append_value(out, entries, &plan.encoding, array.as_ref(), row);
+ }
+}
+
+/// `columns` must be sorted by name bytes.
+pub fn named(out: &mut Vec, entries: &mut Vec>, columns: &[RowColumn], row: usize) {
+ out.clear();
+
+ for (name, array, plan) in columns {
+ append_pair(out, entries, name, &plan.encoding, array.as_ref(), row);
+ }
+}
+
+/// The columns of `array`, sorted by name bytes.
+pub fn row_columns(columns: &ZendHashTable) -> PhpResult> {
+ let mut resolved = columns
+ .iter()
+ .map(|(name, column)| named_column(name.to_string().into_bytes(), column))
+ .collect::>>()?;
+ resolved.sort_unstable_by(|(left, ..), (right, ..)| left.cmp(right));
+
+ Ok(resolved)
+}
+
+pub fn named_column(name: Vec, column: &Zval) -> PhpResult {
+ let adopted;
+ let native = match column.extract::<&RustColumn>() {
+ Some(native) => native,
+ None => {
+ adopted = RustBackend.adopt_result(column.shallow_clone())?.0;
+ adopted
+ .extract::<&RustColumn>()
+ .ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to return a RustColumn"))?
+ }
+ };
+
+ Ok((name, Arc::clone(native.data()), Rc::clone(native.plan())))
+}
diff --git a/src/extension/flow-php-ext/src/group_table.rs b/src/extension/flow-php-ext/src/group_table.rs
index f9006aa34..ff3971a32 100644
--- a/src/extension/flow-php-ext/src/group_table.rs
+++ b/src/extension/flow-php-ext/src/group_table.rs
@@ -1,44 +1,25 @@
+use std::rc::Rc;
use std::sync::Arc;
use ahash::AHashMap;
-use arrow_array::{ArrayRef, Int64Array, NullArray};
+use arrow_array::{Int64Array, NullArray};
use ext_php_rs::convert::IntoZval;
use ext_php_rs::error::Result as ZvalResult;
use ext_php_rs::flags::{ClassFlags, DataType};
use ext_php_rs::prelude::*;
use ext_php_rs::types::{ZendHashTable, Zval};
-use flow_column_kernels::grouping::{append_encoded, append_native_key};
-use crate::backend::RustBackend;
+use crate::canonical_rows::{named_column, ordered, RowColumn};
use crate::column::RustColumn;
-use crate::ctx::{call_method, construct, expect_object, find_class, zval_long, zval_str};
+use crate::ctx::{call_method, construct, find_class, instance, zval_long, zval_str};
use crate::exception::ext_exception;
use crate::interfaces::group_table_ce;
-use crate::plan::type_plan;
+use crate::plan::{type_plan, TypePlan};
const GROUP_IDS: &str = "Flow\\ETL\\Values\\Grouping\\GroupIds";
const INTEGER_TYPE: &str = "Flow\\Types\\Type\\Native\\IntegerType";
-const KEY_ENCODER: &str = "Flow\\ETL\\Values\\Grouping\\KeyEncoder";
-const MIXED_TYPE: &str = "Flow\\Types\\Type\\Native\\MixedType";
-
-// types whose stored physical is what ComparableValues::equality() compares; xml and html compare by TextValues
-const NATIVE_KEYS: [&str; 15] = [
- "integer",
- "positive_integer",
- "float",
- "boolean",
- "string",
- "non_empty_string",
- "numeric-string",
- "class_string",
- "json",
- "enum",
- "uuid",
- "datetime",
- "date",
- "time",
- "null",
-];
+const NULL_TYPE: &str = "Flow\\Types\\Type\\Native\\NullType";
+const VALUE_EQUALITY: &str = "Flow\\ETL\\Values\\Column\\ValueEquality";
pub struct GroupIdsValue(Zval);
@@ -53,11 +34,6 @@ impl IntoZval for GroupIdsValue {
}
}
-pub(crate) enum KeyColumn {
- Native(ArrayRef),
- Encoded(Vec>),
-}
-
#[php_class]
#[php(
name = "Flow\\ETL\\Values\\Grouping\\RustGroupTable",
@@ -66,6 +42,8 @@ pub(crate) enum KeyColumn {
)]
pub struct RustGroupTable {
columns: Vec,
+ /// The declared type of each key column, by position, that its batches are cast to as `KeyEncoder::columns()` does.
+ declared_types: Vec