From 85705d4d094e05f0e2ddd466a3927594388e1f01 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Sat, 21 Nov 2026 16:19:37 -0600 Subject: [PATCH 1/5] feat: row and dataset hashing on one canonical row encoding - row_hash() scalar function and multiset_hash() aggregate - analyze()->withDatasetHash() reports an order-independent dataset hash - group, join, distinct and bucket keys use the same typed encoding - keys have the declared type of their column - flow_php extension hashes natively, ABI 4 - hash() takes an algorithm name, NativePHPHash renamed to PhpAlgorithm - detached xml elements stored in canonical form - unreachable legacy element physical form removed --- documentation/components/core/aggregations.md | 59 ++ .../components/extensions/flow-php-ext.md | 8 +- documentation/upgrading.md | 40 + src/core/etl/src/Flow/ETL/DSL/functions.php | 31 +- .../Flow/ETL/Foundation/FlowPhpExtension.php | 2 +- src/core/etl/src/Flow/ETL/Functions/Hash.php | 12 +- .../src/Flow/ETL/Functions/MultisetHash.php | 166 ++++ .../ETL/Functions/MultisetHashesByGroup.php | 60 ++ .../etl/src/Flow/ETL/Functions/RowHash.php | 90 ++ .../ETL/Functions/ScalarFunctionChain.php | 3 +- .../{NativePHPHash.php => PhpAlgorithm.php} | 4 +- .../src/Flow/ETL/Operators/Join/HashJoin.php | 19 +- src/core/etl/src/Flow/ETL/Runtime/Analyze.php | 14 + .../Flow/ETL/Runtime/Executor/RunCounts.php | 46 +- .../Runtime/Executor/StatisticsCollector.php | 7 +- .../src/Flow/ETL/Runtime/Metrics/Report.php | 12 +- .../ETL/Runtime/Metrics/Statistics/Column.php | 5 +- .../ETL/Values/Column/AdaptiveBackend.php | 15 + .../src/Flow/ETL/Values/Column/Backend.php | 11 + .../ETL/Values/Column/CanonicalEncoding.php | 429 +++++++++ .../Flow/ETL/Values/Column/DatasetHash.php | 23 + .../Values/Column/GroupedMultisetHashes.php | 31 + .../Flow/ETL/Values/Column/MultisetDigest.php | 66 ++ .../ETL/Values/Column/Php/PhpDatasetHash.php | 52 ++ .../Column/Php/PhpGroupedMultisetHashes.php | 105 +++ .../src/Flow/ETL/Values/Column/PhpBackend.php | 27 + .../Column/Physical/ElementPosition.php | 11 +- .../Column/Physical/HtmlElementPhysical.php | 19 +- .../Column/Physical/XmlElementPhysical.php | 59 +- .../Flow/ETL/Values/Grouping/KeyEncoder.php | 96 +- .../ETL/Tests/Context/AggregatorFixtures.php | 4 + .../ETL/Tests/Context/DescribableFixtures.php | 4 +- .../Tests/Context/ScalarFunctionFixtures.php | 9 +- .../ETL/Tests/Double/AcceptingBackend.php | 17 + .../Double/FixedProcessMemoryBackend.php | 17 + .../ETL/Tests/Double/MistypedColumnStub.php | 84 ++ .../Tests/Double/ReportedMemoryBackend.php | 17 + .../Flow/ETL/Tests/Double/SpyBackend.php | 26 + .../Integration/DataFrame/DatasetHashTest.php | 76 ++ .../Tests/Integration/Functions/HashTest.php | 4 +- .../Functions/MultisetHashTest.php | 30 + .../Flow/ETL/Tests/Mother/ReportMother.php | 2 + .../AllAggregatesDeclareTheirTypeTest.php | 5 +- .../AllFunctionsDeclareTheirTypeTest.php | 6 +- .../ETL/Tests/Unit/Functions/HashTest.php | 47 +- .../Tests/Unit/Functions/MultisetHashTest.php | 194 ++++ .../Functions/MultisetHashesByGroupTest.php | 121 +++ .../ETL/Tests/Unit/Functions/RowHashTest.php | 147 +++ .../Kernels/Bucketing/HashBucketingTest.php | 17 +- .../Unit/Kernels/Hash/NativePHPHashTest.php | 32 - .../Unit/Kernels/Hash/PhpAlgorithmTest.php | 47 + .../Unit/Operators/Join/HashJoinTest.php | 64 ++ .../ETL/Tests/Unit/Runtime/AnalyzeTest.php | 22 + .../Unit/Runtime/Executor/RunCountsTest.php | 78 ++ .../Executor/StatisticsCollectorTest.php | 82 ++ .../Tests/Unit/Runtime/Metrics/ReportTest.php | 5 +- .../Values/Column/AdaptiveBackendTest.php | 18 + .../Values/Column/CanonicalEncodingTest.php | 466 ++++++++++ .../Unit/Values/Column/MultisetDigestTest.php | 74 ++ .../Values/Column/Php/PhpDatasetHashTest.php | 90 ++ .../Php/PhpGroupedMultisetHashesTest.php | 118 +++ .../Unit/Values/Column/PhpBackendTest.php | 51 +- .../Column/Physical/ElementPositionTest.php | 9 - .../Physical/HtmlElementPhysicalTest.php | 12 - .../Physical/XmlElementPhysicalTest.php | 52 +- .../Unit/Values/Column/TextValuesTest.php | 4 +- .../Unit/Values/Grouping/GroupTableTest.php | 23 +- .../Unit/Values/Grouping/KeyEncoderTest.php | 25 + src/extension/flow-php-ext/Cargo.lock | 1 + .../crates/flow-column-kernels/Cargo.toml | 1 + .../flow-column-kernels/src/canonical.rs | 850 ++++++++++++++++++ .../flow-column-kernels/src/grouping.rs | 309 +------ .../crates/flow-column-kernels/src/lib.rs | 1 + .../Flow/ETL/Values/Column/RustBackend.php | 15 + src/extension/flow-php-ext/src/backend.rs | 95 +- .../flow-php-ext/src/canonical_rows.rs | 63 ++ src/extension/flow-php-ext/src/group_table.rs | 153 +--- src/extension/flow-php-ext/src/interfaces.rs | 66 +- src/extension/flow-php-ext/src/lib.rs | 6 +- .../flow-php-ext/src/multiset_hashes.rs | 204 +++++ src/extension/flow-php-ext/src/plan.rs | 4 + .../tests/phpt/001_extension_loaded.phpt | 4 + .../phpt/120_group_table_lookup_parity.phpt | 65 +- .../tests/phpt/121_partition_parity.phpt | 16 +- .../tests/phpt/125_row_hashes_parity.phpt | 160 ++++ .../flow-php-ext/tests/phpt/bootstrap.php | 2 + 86 files changed, 4908 insertions(+), 728 deletions(-) create mode 100644 src/core/etl/src/Flow/ETL/Functions/MultisetHash.php create mode 100644 src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php create mode 100644 src/core/etl/src/Flow/ETL/Functions/RowHash.php rename src/core/etl/src/Flow/ETL/Kernels/Hash/{NativePHPHash.php => PhpAlgorithm.php} (93%) create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/CanonicalEncoding.php create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Double/MistypedColumnStub.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Integration/Functions/MultisetHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php delete mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/NativePHPHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Kernels/Hash/PhpAlgorithmTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/CanonicalEncodingTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetDigestTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpGroupedMultisetHashesTest.php create mode 100644 src/extension/flow-php-ext/crates/flow-column-kernels/src/canonical.rs create mode 100644 src/extension/flow-php-ext/src/canonical_rows.rs create mode 100644 src/extension/flow-php-ext/src/multiset_hashes.rs create mode 100644 src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt diff --git a/documentation/components/core/aggregations.md b/documentation/components/core/aggregations.md index 5786f5608..58ba841ec 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,64 @@ 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 + +```php + 1, 'country' => 'PL'], ['id' => 2, 'country' => 'DE'], ['id' => 3, 'country' => 'PL']]; + +df()->read(from_array($rows))->withColumn('row_id', row_hash(ref('id'), ref('country')))->fetch(); +// row_id: '61d8d2f77533f36e5f23e4e587fa5e41', '01d6077fd12ee579f3a83a381ebfa16f', 'ce0f42e953c400afe5620b05dea4bc35' + +df()->read(from_array($rows))->aggregate([multiset_hash()])->fetch(); +// _multiset_hash: '31be1d609a26d996382e2a23855ebbe5' + +df()->read(from_array($rows))->groupBy('country')->aggregate(multiset_hash(ref('id')))->fetch(); +// PL: 'ab8476f29c95212a306bffff897d7afb', DE: 'f3aebd664d56cdeceed04ea04775ad52' + +df()->read(from_array($rows))->run(analyze: analyze()->withDatasetHash())->datasetHash(); +// '31be1d609a26d996382e2a23855ebbe5' +``` + +Duplicate rows count, and the order of the rows and of the columns does not. + +The hash detects accidental differences. It does not resist tampering. + +Declare the schema to keep the hash the same across runs: an inferred type can depend on the inference budget. + +Json is hashed as its stored text, so whitespace and key order count. + +```php +read(from_array([['id' => 1, 'country' => 'PL']]))->withColumn('row_id', row_hash(ref('id'), ref('countr')))->fetch(); +// SchemaDefinitionNotFoundException: Schema definition for column "countr" not found. Did you mean one of: [country]? +``` + +A named column must exist. `multiset_hash()` without names and the dataset hash take the columns of each batch, and +a column that a batch lacks hashes like a null. + +`hash()` is the digest of the text of one value. `row_hash()` is the typed hash of the named columns: + +```php +read(from_array([['country' => 'PL']]))->withColumn('digest', hash(ref('country'), 'sha256'))->fetch(); +// '293650de072648b9e2790509d8109d0f34f655edfe0b20075b0eaf6a93e95646' + +df()->read(from_array([['country' => 'PL']])) + ->withColumn('digest', ref('country')->hash(hash_algorithm('xxh64', options: ['seed' => 7]))) + ->fetch(); +// '30aa8eee14870cd7' +``` + ## Example ```php diff --git a/documentation/components/extensions/flow-php-ext.md b/documentation/components/extensions/flow-php-ext.md index fa6281591..84fd0efcf 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, +DatasetHash, GroupedMultisetHashes}` (`RustColumn`, `RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`, +`RustDatasetHash`, `RustGroupedMultisetHashes`). It also registers `Flow\ETL\Values\Grouping\GroupTable` +(`RustGroupTable`). `RustBackend` returns the last five. 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..a9a4cf474 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -49,6 +49,46 @@ 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 three new methods, and the flow_php ABI is 4 + +| Before | After | +|------------------|-----------------------------------------------------------| +| - | `Backend::rowHashes(array $columns, int $count): Column` | +| - | `Backend::datasetHash(): DatasetHash` | +| - | `Backend::groupedMultisetHashes(): GroupedMultisetHashes` | +| `FLOW_PHP_ABI` 3 | `FLOW_PHP_ABI` 4 | + +A custom `Backend` must implement the three 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 | + --- ## 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..4d0c6ab67 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php @@ -0,0 +1,166 @@ + $refs [] hashes every column + */ + public function __construct( + private readonly array $refs = [], + ) {} + + 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 === null ? $rows->columns() : array_combine($names, array_map($rows->column(...), $names)); + $this->hash ??= $backend->datasetHash(); + $this->hash->add( + count($indices) === $rows->count() + ? $columns + : array_map(static fn(Column $column): Column => $column->take($indices), $columns), + count($indices), + ); + } + + public function merge(array $partial, Backend $backend): void + { + $this->hash ??= $backend->datasetHash(); + $this->hash->absorb(MultisetDigest::fromArray($partial)); + } + + public function partial(): array + { + return ($this->hash?->digest() ?? MultisetDigest::empty())->normalize(); + } + + public function partialType(): StructureType + { + return type_structure(['low' => type_integer(), 'high' => type_integer()]); + } + + public function grouped(Backend $backend): GroupedAggregation + { + return new MultisetHashesByGroup($this->names(), $backend->groupedMultisetHashes()); + } + + /** + * @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 ($this->hash?->digest() ?? MultisetDigest::empty())->hex(); + } + + /** + * @return null|list + */ + private function names(): ?array + { + return $this->refs === [] ? null : 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..1081eda8e --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php @@ -0,0 +1,60 @@ + $columns null 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 === null + ? $rows->columns() + : array_combine($this->columns, array_map($rows->column(...), $this->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(MultisetDigest $digest): array => $digest->normalize(), $this->hashes->partials()); + } + + 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..fcda637a2 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Functions/RowHash.php @@ -0,0 +1,90 @@ + + */ + 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 + { + $columns = []; + + foreach ($rows->isEmpty() ? [] : $this->refs as $ref) { + $columns[$ref->base()] = $rows->column($ref->base()); + } + + return $backend->rowHashes($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..ed22c47af 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php @@ -8,6 +8,8 @@ final class Analyze { private bool $collectColumnStatistics = false; + private bool $collectDatasetHash = false; + private bool $collectSchema = false; private bool $collectSourceStatistics = false; @@ -19,6 +21,11 @@ public function collectColumnStatistics(): bool return $this->collectColumnStatistics; } + public function collectDatasetHash(): bool + { + return $this->collectDatasetHash; + } + public function collectSchema(): bool { return $this->collectSchema; @@ -36,6 +43,13 @@ public function withColumnStatistics(): self return $this; } + public function withDatasetHash(): self + { + $this->collectDatasetHash = true; + + return $this; + } + public function withSchema(): self { $this->collectSchema = true; 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..183b858c4 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/RunCounts.php @@ -10,6 +10,8 @@ use Flow\ETL\IO\Extractor\Statistics; use Flow\ETL\Runtime\Metrics\Processes; use Flow\ETL\Runtime\Metrics\SourceStatistics; +use Flow\ETL\Values\Column\DatasetHash; +use Flow\ETL\Values\Column\MultisetDigest; use Flow\ETL\Values\Memory\Unit; use Flow\ETL\Values\Rows; use Flow\Telemetry\ObjectExtractor; @@ -19,6 +21,7 @@ use function array_map; use function array_values; use function max; +use function min; final class RunCounts { @@ -40,8 +43,11 @@ final class RunCounts */ private array $workers = []; - public function __construct() - { + private int $rowsCoveredByAbsorbedDigests = 0; + + public function __construct( + private readonly ?DatasetHash $outputHash = null, + ) { /** @var SplObjectStorage $reads */ $reads = new SplObjectStorage(); $this->reads = $reads; @@ -113,6 +119,42 @@ public function absorbWorkers(self $other): void } } + public function hashesOutput(): bool + { + return $this->outputHash !== null; + } + + public function hashOutput(Rows $rows): void + { + if ($this->outputHash === null) { + return; + } + + if ($rows->schema()->count() === 0) { + $covered = min($rows->count(), $this->rowsCoveredByAbsorbedDigests); + $this->rowsCoveredByAbsorbedDigests -= $covered; + $this->outputHash->add([], $rows->count() - $covered); + + return; + } + + $this->outputHash->add($rows->columns(), $rows->count()); + } + + /** + * @param int<0, max> $rows + */ + public function absorbOutputHash(MultisetDigest $digest, int $rows): void + { + $this->outputHash?->absorb($digest); + $this->rowsCoveredByAbsorbedDigests += $rows; + } + + public function outputHash(): ?string + { + return $this->outputHash?->digest()->hex(); + } + 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..bba2092f7 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,9 @@ public function __construct( $this->schema = $this->analyze->collectSchema() ? new Schema() : null; } - $this->counts = new RunCounts(); + $this->counts = new RunCounts( + $this->analyze?->collectDatasetHash() === true ? $this->context->backend()->datasetHash() : null, + ); if ($this->readsColumns() && $this->context->config->launcher() !== null) { $this->context @@ -92,6 +94,8 @@ public function capture(Rows $rows): void $this->columnStatistics->add($definition, $rows->column($name)); } } + + $this->counts->hashOutput($rows); } /** @@ -134,6 +138,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/Metrics/Report.php b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php index c2ec4cfd8..7e42be5ef 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 ?string $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|string} */ public function normalize(): array { @@ -32,9 +33,18 @@ public function normalize(): array 'sources' => $this->sources === null ? null : array_map(static fn(SourceStatistics $source): array => $source->normalize(), $this->sources), + 'dataset_hash' => $this->datasetHash, ]; } + /** + * 32 lowercase hex characters; null when the run was not analyzed with a dataset hash. + */ + public function datasetHash(): ?string + { + 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..5713c3949 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,21 @@ public function groupedCounts(): GroupedCounts return $this->backend->groupedCounts(); } + public function rowHashes(array $columns, int $count): Column + { + return $this->backend->rowHashes($columns, $count); + } + + public function datasetHash(): DatasetHash + { + return $this->backend->datasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return $this->backend->groupedMultisetHashes(); + } + /** * @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..0cb4f248b 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,17 @@ 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 datasetHash(): DatasetHash; + + public function groupedMultisetHashes(): 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/DatasetHash.php b/src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php new file mode 100644 index 000000000..4e4d437a6 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php @@ -0,0 +1,23 @@ + $columns + */ + public function add(array $columns, int $count): void; + + public function digest(): MultisetDigest; + + public function absorb(MultisetDigest $digest): void; +} 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..5bbeaea80 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php @@ -0,0 +1,31 @@ + $columns + */ + public function add(array $columns, Column $ids): void; + + public function hashes(): Column; + + /** + * @return list by group id + */ + public function partials(): array; + + /** + * @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..d3a8a27e5 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php @@ -0,0 +1,66 @@ + $data + */ + public static function fromArray(array $data): self + { + return new self(type_integer()->assert($data['low'] ?? null), type_integer()->assert($data['high'] ?? null)); + } + + /** + * @param int<0, max> $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)); + } + + /** + * @return array{low: int, high: int} + */ + public function normalize(): array + { + return ['low' => $this->low, 'high' => $this->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/Php/PhpDatasetHash.php b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php new file mode 100644 index 000000000..039e5cbf0 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php @@ -0,0 +1,52 @@ +digest = MultisetDigest::empty(); + } + + public function add(array $columns, int $count): void + { + $lowLow = 0; + $lowHigh = 0; + $highLow = 0; + $highHigh = 0; + + foreach ($this->encoding->named($columns, $count) as $bytes) { + /** @var array{1: int<0, max>, 2: int<0, max>, 3: int<0, max>, 4: int<0, max>} $halves */ + $halves = unpack('N4', hash('xxh128', $bytes, true)); + $highHigh += $halves[1]; + $highLow += $halves[2]; + $lowHigh += $halves[3]; + $lowLow += $halves[4]; + } + + $this->digest = $this->digest->plus(MultisetDigest::ofHalfSums($lowLow, $lowHigh, $highLow, $highHigh)); + } + + public function digest(): MultisetDigest + { + return $this->digest; + } + + public function absorb(MultisetDigest $digest): void + { + $this->digest = $this->digest->plus($digest); + } +} 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..8a0849b3b --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php @@ -0,0 +1,105 @@ + + */ + private array $digests = []; + + public function __construct( + 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('xxh128', $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 partials(): array + { + return $this->digests; + } + + public function absorbEarlier(GroupedMultisetHashes $earlier, array $into): void + { + $digests = $earlier->partials(); + + 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..c44389af0 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php @@ -23,7 +23,9 @@ use Flow\ETL\Values\Column\Php\ConstantColumn; use Flow\ETL\Values\Column\Php\ListColumn; use Flow\ETL\Values\Column\Php\MapColumn; +use Flow\ETL\Values\Column\Php\PhpDatasetHash; 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 +54,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 +671,29 @@ 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 datasetHash(): DatasetHash + { + return new PhpDatasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return new PhpGroupedMultisetHashes(); + } + 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..90d4b44e4 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; @@ -338,7 +338,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()]), 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..1d3540269 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php @@ -7,8 +7,10 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; +use Flow\ETL\Values\Column\DatasetHash; 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\PhpBackend; use Flow\ETL\Values\Grouping\GroupTable; @@ -109,6 +111,21 @@ public function groupedCounts(): GroupedCounts return (new PhpBackend())->groupedCounts(); } + public function rowHashes(array $columns, int $count): Column + { + return (new PhpBackend())->rowHashes($columns, $count); + } + + public function datasetHash(): DatasetHash + { + return (new PhpBackend())->datasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return (new PhpBackend())->groupedMultisetHashes(); + } + /** * @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..8e2337a99 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php @@ -7,8 +7,10 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; +use Flow\ETL\Values\Column\DatasetHash; 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\PhpBackend; use Flow\ETL\Values\Grouping\GroupTable; @@ -138,6 +140,21 @@ public function groupedCounts(): GroupedCounts return $this->php->groupedCounts(); } + public function rowHashes(array $columns, int $count): Column + { + return $this->php->rowHashes($columns, $count); + } + + public function datasetHash(): DatasetHash + { + return $this->php->datasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return $this->php->groupedMultisetHashes(); + } + /** * @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..6c9878e66 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php @@ -7,8 +7,10 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; +use Flow\ETL\Values\Column\DatasetHash; 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\PhpBackend; use Flow\ETL\Values\Grouping\GroupTable; @@ -145,6 +147,21 @@ public function groupedCounts(): GroupedCounts return $this->php->groupedCounts(); } + public function rowHashes(array $columns, int $count): Column + { + return $this->php->rowHashes($columns, $count); + } + + public function datasetHash(): DatasetHash + { + return $this->php->datasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return $this->php->groupedMultisetHashes(); + } + /** * @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..66c69a6ac 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php @@ -7,8 +7,10 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; +use Flow\ETL\Values\Column\DatasetHash; 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\PhpBackend; use Flow\ETL\Values\Grouping\GroupTable; @@ -32,6 +34,8 @@ final class SpyBackend implements Backend private int $groupedTotals = 0; + private int $datasetHashes = 0; + private readonly PhpBackend $php; private int $releases = 0; @@ -195,11 +199,33 @@ public function groupedCounts(): GroupedCounts return $this->php->groupedCounts(); } + public function rowHashes(array $columns, int $count): Column + { + return $this->php->rowHashes($columns, $count); + } + + public function datasetHash(): DatasetHash + { + $this->datasetHashes++; + + return $this->php->datasetHash(); + } + + public function groupedMultisetHashes(): GroupedMultisetHashes + { + return $this->php->groupedMultisetHashes(); + } + public function groupedCountsCreated(): int { return $this->groupedCounts; } + public function datasetHashesCreated(): int + { + return $this->datasetHashes; + } + /** * @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..a68ef27cc --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php @@ -0,0 +1,76 @@ + 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(), + ); + static::assertSame( + '72c000bf6397e932faa3a3f30eeaa6db', + df()->read(from_array(self::ROWS))->run(analyze: analyze()->withDatasetHash())->datasetHash(), + ); + } + + 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_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(), + ); + } + + 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(), + ); + } +} 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/Mother/ReportMother.php b/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php index 92cc67ab8..3b6fbef09 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Mother/ReportMother.php @@ -29,6 +29,7 @@ public static function of( ?Schema $schema = null, ?array $sources = null, ?Columns $columns = null, + ?string $datasetHash = null, ): Report { return new Report( $schema, @@ -44,6 +45,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..2b939b4ad --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php @@ -0,0 +1,194 @@ + 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) { + /** @var array{1: int, 2: int} $lanes */ + $lanes = unpack('J2', (string) hex2bin($rowHash)); + $summed->merge(['low' => $lanes[2], 'high' => $lanes[1]], $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(['low' => -5346116962925344867, 'high' => 8675782764775017685], $merged->partial()); + } + + public function test_an_aggregate_that_saw_no_row_is_zero(): void + { + static::assertSame('00000000000000000000000000000000', multiset_hash()->value()); + static::assertSame(['low' => 0, 'high' => 0], 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(['low' => type_integer(), 'high' => type_integer()]), + 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('Column "emal" does not exist. Did you mean one of the following? ["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..077fa6a76 --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php @@ -0,0 +1,121 @@ + 'a', 'v' => 1], ['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema); + $hashes = new MultisetHashesByGroup(null, $backend->groupedMultisetHashes()); + + $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(null, $backend->groupedMultisetHashes()); + $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()); + + $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); + + static::assertSame(['e0191505b9cce3349c6f8093cab56dec'], $hashes->groupValues(1, $backend)->values()); + static::assertSame([['low' => -7174374309128475156, 'high' => -2298783020459695308]], $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(null, $backend->groupedMultisetHashes()); + $later = new MultisetHashesByGroup(null, $backend->groupedMultisetHashes()); + + $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(null, $backend->groupedMultisetHashes()))->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()); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Column "valu" does not exist. Did you mean one of the following? ["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()); + + $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..e9bb96f30 --- /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('Column "emal" does not exist. Did you mean one of the following? ["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/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/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..afbbf2b9a --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php @@ -0,0 +1,22 @@ +collectDatasetHash()); + static::assertSame($analyze, $analyze->withDatasetHash()); + static::assertTrue($analyze->collectDatasetHash()); + static::assertFalse($analyze->collectSchema()); + } +} 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..1070cb128 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 @@ -13,6 +13,8 @@ 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\PhpBackend; use Flow\ETL\Values\Memory\Unit; use Flow\ETL\Values\Rows; @@ -21,7 +23,9 @@ use function Flow\ETL\DSL\from_array; use function Flow\ETL\DSL\int_schema; use function Flow\ETL\DSL\schema; +use function hash; use function iterator_to_array; +use function unpack; final class RunCountsTest extends FlowTestCase { @@ -330,4 +334,78 @@ 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 PhpBackend())->datasetHash()); + $other = new RunCounts((new PhpBackend())->datasetHash()); + $other->absorbOutputHash(new MultisetDigest(1, 2), 1); + + $counts->absorb($other); + $counts->absorbWorkers($other); + + static::assertSame('00000000000000000000000000000000', $counts->outputHash()); + } + + public function test_without_the_hash_slot_nothing_is_hashed_and_no_hash_is_given(): void + { + $counts = new RunCounts(); + $counts->hashOutput(Rows::fromColumns(schema(), [], 3)); + $counts->absorbOutputHash(new MultisetDigest(1, 2), 1); + + static::assertFalse($counts->hashesOutput()); + static::assertNull($counts->outputHash()); + } + + public function test_rows_with_columns_are_hashed(): void + { + $counts = new RunCounts((new PhpBackend())->datasetHash()); + $counts->hashOutput(array_to_rows([['a' => 2]], schema(int_schema('a')))); + $counts->hashOutput(array_to_rows([['a' => 1]], schema(int_schema('a')))); + + static::assertTrue($counts->hashesOutput()); + static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()); + } + + 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 PhpBackend())->datasetHash()); + $counts->hashOutput(Rows::fromColumns(schema(), [], 3)); + + static::assertSame($empty->plus($empty)->plus($empty)->hex(), $counts->outputHash()); + } + + public function test_rows_without_columns_that_absorbed_digests_cover_are_hashed_only_by_those_digests(): void + { + $first = (new PhpBackend())->datasetHash(); + $first->add(array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(), 1); + $second = (new PhpBackend())->datasetHash(); + $second->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); + $counts = new RunCounts((new PhpBackend())->datasetHash()); + $counts->absorbOutputHash($first->digest(), 1); + $counts->absorbOutputHash($second->digest(), 1); + $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); + $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); + + static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()); + } + + 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 PhpBackend())->datasetHash(); + $worker->add(array_to_rows([['a' => 1], ['a' => 2], ['a' => 3]], schema(int_schema('a')))->columns(), 3); + $counts = new RunCounts((new PhpBackend())->datasetHash()); + $counts->absorbOutputHash($worker->digest(), 3); + $counts->hashOutput(Rows::fromColumns(schema(), [], 2)); + $counts->hashOutput(Rows::fromColumns(schema(), [], 2)); + $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); + + static::assertSame($worker->digest()->plus($empty)->plus($empty)->hex(), $counts->outputHash()); + } } 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..d2fcaf164 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 @@ -15,6 +15,7 @@ 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; @@ -312,4 +313,85 @@ 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::assertSame('721f4650154ebb88ac4ec50a605901df', $collector->report()->datasetHash()); + static::assertFalse($collector->readsColumns()); + } + + public function test_a_dataset_hash_of_no_rows_is_zero(): void + { + static::assertSame( + '00000000000000000000000000000000', + (new StatisticsCollector(analyze()->withDatasetHash(), flow_context()))->report()->datasetHash(), + ); + } + + 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->datasetHashesCreated()); + 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(); + + new StatisticsCollector( + analyze()->withDatasetHash(), + flow_context(config_builder()->backend($backend)->build()), + ); + + static::assertSame(1, $backend->datasetHashesCreated()); + } + + 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::assertTrue($collector->counts()?->hashesOutput()); + static::assertSame([], $telemetry->logs->entriesWithSeverity(Severity::WARN)); + } } 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..d1be3d784 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 @@ -31,7 +31,7 @@ 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: '721f4650154ebb88ac4ec50a605901df'); $normalized = $report->normalize(); @@ -46,9 +46,11 @@ public function test_normalize_holds_what_the_typed_getters_hold_and_survives_js 'columns' => null, ], 'sources' => [$source->normalize()], + 'dataset_hash' => '721f4650154ebb88ac4ec50a605901df', ], $normalized, ); + static::assertSame('721f4650154ebb88ac4ec50a605901df', $report->datasetHash()); // JSON keeps the values, not a float's ".0" static::assertEquals($normalized, json_decode( json_encode($normalized, JSON_THROW_ON_ERROR), @@ -63,6 +65,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..a6cd5eb1b 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\Php\PhpDatasetHash; 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,20 @@ 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(PhpDatasetHash::class, (new AdaptiveBackend())->datasetHash()); + static::assertInstanceOf(PhpGroupedMultisetHashes::class, (new AdaptiveBackend())->groupedMultisetHashes()); + } } 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('

a

')->firstElementChild], + ['v' => type_html_element()->cast('

a

')->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..8752c2be5 --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetDigestTest.php @@ -0,0 +1,74 @@ +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_normalize_and_from_array_round_trip_both_lanes(): void + { + static::assertSame(['low' => -1, 'high' => PHP_INT_MIN], (new MultisetDigest(-1, PHP_INT_MIN))->normalize()); + static::assertEquals( + new MultisetDigest(-1, PHP_INT_MIN), + MultisetDigest::fromArray((new MultisetDigest(-1, PHP_INT_MIN))->normalize()), + ); + } + + public function test_from_array_refuses_a_lane_that_is_not_an_integer(): void + { + $this->expectException(InvalidTypeException::class); + + MultisetDigest::fromArray(['low' => 1, 'high' => '2']); + } + + public function test_from_array_refuses_a_missing_lane(): void + { + $this->expectException(InvalidTypeException::class); + + MultisetDigest::fromArray(['low' => 1]); + } + + 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/Php/PhpDatasetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php new file mode 100644 index 000000000..2e35f6f17 --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php @@ -0,0 +1,90 @@ + 1]], schema(int_schema('a'))); + $hash = new PhpDatasetHash(); + $hash->add($rows->columns(), 1); + + static::assertSame('8e18789eac90baf2a1f6bc7cceafa11a', $hash->digest()->hex()); + static::assertSame( + (new PhpBackend()) + ->rowHashes($rows->columns(), 1) + ->physicals(), + [$hash->digest()->hex()], + ); + } + + public function test_row_order_does_not_count(): void + { + $forward = new PhpDatasetHash(); + $forward->add(array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(), 2); + $backward = new PhpDatasetHash(); + $backward->add(array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(), 1); + $backward->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); + + static::assertSame('721f4650154ebb88ac4ec50a605901df', $forward->digest()->hex()); + static::assertEquals($forward->digest(), $backward->digest()); + } + + public function test_a_duplicate_row_counts(): void + { + $hash = new PhpDatasetHash(); + $hash->add(array_to_rows([['a' => 1], ['a' => 1]], schema(int_schema('a')))->columns(), 2); + + static::assertSame('1c30f13d592175e443ed78f99d5f4234', $hash->digest()->hex()); + } + + public function test_a_row_of_only_nulls_counts_as_a_row(): void + { + $hash = new PhpDatasetHash(); + $hash->add(array_to_rows([['a' => null]], schema(int_schema('a', true)))->columns(), 1); + + static::assertSame('99aa06d3014798d86001c324468d497f', $hash->digest()->hex()); + } + + 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]); + $nulls = new PhpDatasetHash(); + $nulls->add(array_to_rows([['a' => null], ['a' => null]], schema(int_schema('a', true)))->columns(), 2); + $hash = new PhpDatasetHash(); + $hash->add([], 2); + + static::assertEquals($empty->plus($empty), $hash->digest()); + static::assertEquals($nulls->digest(), $hash->digest()); + } + + public function test_an_empty_hash_is_zero(): void + { + static::assertEquals(MultisetDigest::empty(), (new PhpDatasetHash())->digest()); + } + + public function test_absorb_adds_to_the_rows_already_hashed(): void + { + $hash = new PhpDatasetHash(); + $hash->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); + $hash->absorb(new MultisetDigest(745355142457024709, -2015697621351530346)); + + static::assertSame('721f4650154ebb88ac4ec50a605901df', $hash->digest()->hex()); + } +} 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..50709b072 --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpGroupedMultisetHashesTest.php @@ -0,0 +1,118 @@ +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(), + ); + } + + public function test_a_group_below_the_highest_seen_one_is_zero(): void + { + $hashes = new PhpGroupedMultisetHashes(); + $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(), + ); + static::assertEquals(MultisetDigest::empty(), $hashes->partials()[0]); + } + + public function test_no_rows_give_no_groups(): void + { + $hashes = new PhpGroupedMultisetHashes(); + $hashes->add([], ColumnMother::of(int_schema('id'), [])); + + static::assertSame([], $hashes->hashes()->physicals()); + static::assertSame([], $hashes->partials()); + } + + public function test_partials_are_the_digests_by_group(): void + { + $hashes = new PhpGroupedMultisetHashes(); + $hashes->add( + array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(), + ColumnMother::of(int_schema('id'), [0, 1]), + ); + + static::assertEquals( + [ + new MultisetDigest(-6776021345102749414, -8207677697987396878), + new MultisetDigest(745355142457024709, -2015697621351530346), + ], + $hashes->partials(), + ); + } + + public function test_earlier_groups_are_added_to_the_groups_they_map_to(): void + { + $earlier = new PhpGroupedMultisetHashes(); + $earlier->add( + array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(), + ColumnMother::of(int_schema('id'), [0, 1]), + ); + $later = new PhpGroupedMultisetHashes(); + $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(); + $hashes->add([], ColumnMother::of(int_schema('id'), [1, 0, 1])); + + static::assertSame([$empty->hex(), $empty->plus($empty)->hex()], $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())->absorbEarlier(new PhpGroupedMultisetHashes(), [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\x00

Name

01
"; - $element = type_html_element()->assert($physical->fromPhysical($bytes)); - - static::assertSame('SECTION', $element->tagName); - static::assertSame('ARTICLE', $element->parentElement?->tagName); - static::assertSame('

Name

', $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..9a107119d 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 @@ -175,4 +175,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..a1976dd6f 100644 --- a/src/extension/flow-php-ext/Cargo.lock +++ b/src/extension/flow-php-ext/Cargo.lock @@ -711,6 +711,7 @@ dependencies = [ "arrow-buffer", "arrow-ord", "arrow-schema", + "flow-batch-frame", "memchr", "xxhash-rust", ] 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..581a82451 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,6 @@ arrow-buffer.workspace = true arrow-arith = "60" arrow-ord = "60" arrow-schema.workspace = true +flow-batch-frame = { path = "../flow-batch-frame" } memchr.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..9812e6182 --- /dev/null +++ b/src/extension/flow-php-ext/crates/flow-column-kernels/src/canonical.rs @@ -0,0 +1,850 @@ +//! 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 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, u64) { + let hash = xxh3_128(encoded); + + (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

", "

a

"), + &positioned("1", "

a

", "

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 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..324db3541 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,21 @@ 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 datasetHash(): DatasetHash + { + throw new RuntimeException('flow_php extension is not loaded'); + } + + public function groupedMultisetHashes(): 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..d265298c4 100644 --- a/src/extension/flow-php-ext/src/backend.rs +++ b/src/extension/flow-php-ext/src/backend.rs @@ -23,12 +23,14 @@ 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::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::{ @@ -37,10 +39,11 @@ use crate::ctx::{ }; 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::{RustDatasetHash, 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 +51,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 +280,34 @@ 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 = "datasetHash")] + pub fn dataset_hash(&self) -> RustDatasetHash { + RustDatasetHash::default() + } + + #[php(name = "groupedMultisetHashes")] + pub fn grouped_multiset_hashes(&self) -> RustGroupedMultisetHashes { + RustGroupedMultisetHashes::default() + } + #[php(name = "groupTable")] pub fn group_table(&self, columns: &ZendHashTable, declared: &Zval) -> PhpResult { RustGroupTable::new(columns, declared) @@ -327,29 +346,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 +601,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 +660,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)>>, declared: Zval, ids: AHashMap, i64>, } @@ -80,49 +58,55 @@ impl RustGroupTable { .ok_or_else(|| ext_exception("flow_php expected group by columns as strings")) }) .collect::>>()?; + let declared_types = columns + .iter() + .map(|name| { + let definition = call_method(declared, "findDefinition", &mut [name.shallow_clone()])?; + + if definition.is_null() { + return Ok(None); + } + + let declared_type = call_method(&definition, "type", &mut [])?; + let plan = type_plan(&declared_type)?; + + Ok(Some((declared_type, plan))) + }) + .collect::>>()?; Ok(Self { columns, + declared_types, declared: declared.shallow_clone(), ids: AHashMap::new(), }) } - fn key_column(&self, rows: &Zval, schema: &Zval, name: &Zval, count: usize) -> PhpResult { + fn key_column(&self, rows: &Zval, schema: &Zval, position: usize, count: usize) -> PhpResult { + let name = &self.columns[position]; + if call_method(schema, "findDefinition", &mut [name.shallow_clone()])?.is_null() && self.declared_nullable(name)? { - return Ok(KeyColumn::Native(Arc::new(NullArray::new(count)))); - } + let nulls = RustColumn::of_type(Arc::new(NullArray::new(count)), NULL_TYPE)?.into_zval(false)?; - let column = call_method(rows, "column", &mut [name.shallow_clone()])?; - - if let Some(native) = column.extract::<&RustColumn>() { - return if NATIVE_KEYS.contains(&native.plan().type_name.as_str()) { - Ok(KeyColumn::Native(Arc::clone(native.data()))) - } else { - self.encoded(rows, name) - }; + return named_column(Vec::new(), &nulls); } - let column_type = call_method(&column, "type", &mut [])?; - - if expect_object(&column_type, "a Type")?.instance_of(find_class(MIXED_TYPE)?) - || !NATIVE_KEYS.contains(&type_plan(&column_type)?.type_name.as_str()) - { - return self.encoded(rows, name); + let column = call_method(rows, "column", &mut [name.shallow_clone()])?; + let key = named_column(Vec::new(), &column)?; + + match &self.declared_types[position] { + Some((declared_type, plan)) if plan.type_name != key.2.type_name => named_column( + Vec::new(), + &call_method( + &instance(VALUE_EQUALITY)?, + "cast", + &mut [column, declared_type.shallow_clone(), name.shallow_clone()], + )?, + ), + _ => Ok(key), } - - // adopted, so a column keeps one encoding whichever backend built its batch - let definition = call_method(schema, "get", &mut [name.shallow_clone()])?; - let adopted = RustBackend.adopt(&definition, &column)?.0; - - Ok(KeyColumn::Native(Arc::clone( - adopted - .extract::<&RustColumn>() - .ok_or_else(|| ext_exception("flow_php expected RustBackend::adopt() to return a RustColumn"))? - .data(), - ))) } fn declared_nullable(&self, name: &Zval) -> PhpResult { @@ -131,33 +115,6 @@ impl RustGroupTable { Ok(!definition.is_null() && call_method(&definition, "isNullable", &mut [])?.bool() == Some(true)) } - fn encoded(&self, rows: &Zval, name: &Zval) -> PhpResult { - let mut names = ZendHashTable::new(); - names.push(name.shallow_clone())?; - let mut names_zv = Zval::new(); - names_zv.set_hashtable(names); - let mut types = Zval::new(); - types.set_hashtable(ZendHashTable::new()); - let encoder = construct( - find_class(KEY_ENCODER)?, - &mut [names_zv, types, self.declared.shallow_clone()], - )? - .into_zval(false)?; - let keys = call_method(&encoder, "of", &mut [rows.shallow_clone()])?; - - Ok(KeyColumn::Encoded( - keys.array() - .ok_or_else(|| ext_exception("flow_php expected KeyEncoder::of() 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::of() to return strings")) - }) - .collect::>>()?, - )) - } - fn each_key( &self, rows: &Zval, @@ -169,30 +126,14 @@ impl RustGroupTable { } let schema = call_method(rows, "schema", &mut [])?; - let columns = self - .columns - .iter() - .map(|name| self.key_column(rows, &schema, name, count)) + let columns = (0..self.columns.len()) + .map(|position| self.key_column(rows, &schema, position, count)) .collect::>>()?; 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_native_key(&mut key, array.as_ref(), row) { - return Err(ext_exception(format!( - "flow_php has no group key for {} values", - array.data_type() - ))); - } - } - KeyColumn::Encoded(keys) => append_encoded(&mut key, &keys[row]), - } - } - + ordered(&mut key, &mut entries, &columns, row); visit(row, &key)?; } diff --git a/src/extension/flow-php-ext/src/interfaces.rs b/src/extension/flow-php-ext/src/interfaces.rs index 60b62bd18..27e6428c5 100644 --- a/src/extension/flow-php-ext/src/interfaces.rs +++ b/src/extension/flow-php-ext/src/interfaces.rs @@ -1,4 +1,4 @@ -//! `Flow\ETL\Foundation\Describe\Describable`, `Flow\ETL\Values\Column\{Column, ColumnBuilder, Backend, GroupedTotals, GroupedCounts}`, `Flow\ETL\Values\Grouping\GroupTable`, `Flow\ETL\IO\Loader\File\FileWriter` and the CSV / JSON / Parquet +//! `Flow\ETL\Foundation\Describe\Describable`, `Flow\ETL\Values\Column\{Column, ColumnBuilder, Backend, GroupedTotals, GroupedCounts, DatasetHash, GroupedMultisetHashes}`, `Flow\ETL\Values\Grouping\GroupTable`, `Flow\ETL\IO\Loader\File\FileWriter` and the CSV / JSON / Parquet //! adapters' encoder and open source contracts: registered at MINIT with the package //! files' exact signatures, so the extension's classes implement them and the package files (autoloaded only without //! flow_php) stay unused. @@ -20,6 +20,9 @@ const ROWS: DataType = DataType::object("Flow\\ETL\\Values\\Rows"); const SCHEMA: DataType = DataType::object("Flow\\ETL\\Values\\Schema"); const SCHEMA_INFERENCE: DataType = DataType::object("Flow\\ETL\\IO\\Inference\\SchemaInference"); const GROUPED_COUNTS: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedCounts"); +const DATASET_HASH: DataType = DataType::object("Flow\\ETL\\Values\\Column\\DatasetHash"); +const GROUPED_MULTISET_HASHES: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedMultisetHashes"); +const MULTISET_DIGEST: DataType = DataType::object("Flow\\ETL\\Values\\Column\\MultisetDigest"); const GROUP_TABLE: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupTable"); const GROUP_IDS: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupIds"); const GROUPED_TOTALS: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedTotals"); @@ -40,6 +43,8 @@ static BACKEND_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUPED_TOTALS_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static DESCRIBABLE_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUPED_COUNTS_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); +static DATASET_HASH_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); +static GROUPED_MULTISET_HASHES_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUP_TABLE_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static FILE_WRITER_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static CSV_ENCODER_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); @@ -68,6 +73,16 @@ fn store_grouped_counts(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { GROUPED_COUNTS_CE.store(ce, Ordering::Release); } +fn store_dataset_hash(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { + keep(arg_info); + DATASET_HASH_CE.store(ce, Ordering::Release); +} + +fn store_grouped_multiset_hashes(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { + keep(arg_info); + GROUPED_MULTISET_HASHES_CE.store(ce, Ordering::Release); +} + fn store_group_table(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { keep(arg_info); GROUP_TABLE_CE.store(ce, Ordering::Release); @@ -138,6 +153,17 @@ pub fn grouped_counts_ce() -> &'static ClassEntry { load(&GROUPED_COUNTS_CE, "Flow\\ETL\\Values\\Column\\GroupedCounts") } +pub fn dataset_hash_ce() -> &'static ClassEntry { + load(&DATASET_HASH_CE, "Flow\\ETL\\Values\\Column\\DatasetHash") +} + +pub fn grouped_multiset_hashes_ce() -> &'static ClassEntry { + load( + &GROUPED_MULTISET_HASHES_CE, + "Flow\\ETL\\Values\\Column\\GroupedMultisetHashes", + ) +} + pub fn group_table_ce() -> &'static ClassEntry { load(&GROUP_TABLE_CE, "Flow\\ETL\\Values\\Grouping\\GroupTable") } @@ -307,6 +333,37 @@ pub fn register() -> Result<()> { ), ], )?; + interface( + "Flow\\ETL\\Values\\Column\\DatasetHash", + store_dataset_hash, + vec![ + method( + "add", + vec![Arg::new("columns", DataType::Array), Arg::new("count", DataType::Long)], + DataType::Void, + ), + method("digest", vec![], MULTISET_DIGEST), + method("absorb", vec![Arg::new("digest", MULTISET_DIGEST)], DataType::Void), + ], + )?; + interface( + "Flow\\ETL\\Values\\Column\\GroupedMultisetHashes", + store_grouped_multiset_hashes, + vec![ + method( + "add", + vec![Arg::new("columns", DataType::Array), Arg::new("ids", COLUMN)], + DataType::Void, + ), + method("hashes", vec![], COLUMN), + method("partials", vec![], DataType::Array), + method( + "absorbEarlier", + vec![Arg::new("earlier", SELF), Arg::new("into", DataType::Array)], + DataType::Void, + ), + ], + )?; interface( "Flow\\ETL\\Values\\Grouping\\GroupTable", store_group_table, @@ -410,6 +467,13 @@ pub fn register() -> Result<()> { ), method("groupedTotals", vec![], GROUPED_TOTALS), method("groupedCounts", vec![], GROUPED_COUNTS), + method( + "rowHashes", + vec![Arg::new("columns", DataType::Array), Arg::new("count", DataType::Long)], + COLUMN, + ), + method("datasetHash", vec![], DATASET_HASH), + method("groupedMultisetHashes", vec![], GROUPED_MULTISET_HASHES), method( "groupTable", vec![Arg::new("columns", DataType::Array), Arg::new("declared", SCHEMA)], diff --git a/src/extension/flow-php-ext/src/lib.rs b/src/extension/flow-php-ext/src/lib.rs index 950b185b7..e8c26cb5e 100644 --- a/src/extension/flow-php-ext/src/lib.rs +++ b/src/extension/flow-php-ext/src/lib.rs @@ -3,6 +3,7 @@ mod arithmetic; mod backend; mod batch_columns; mod builder; +mod canonical_rows; mod cast; mod column; mod compare; @@ -20,6 +21,7 @@ mod interfaces; mod iterator; mod json; mod json_check; +mod multiset_hashes; mod parquet; mod physical; mod plan; @@ -36,7 +38,7 @@ use ext_php_rs::{info_table_end, info_table_row, info_table_start}; /// The contract version flow-php/etl expects (`Flow\ETL\Foundation\FlowPhpExtension::ABI`); both change together whenever a /// registered class or interface changes. -const FLOW_PHP_ABI: i64 = 3; +const FLOW_PHP_ABI: i64 = 4; pub extern "C" fn php_module_info(_module: *mut ModuleEntry) { info_table_start!(); @@ -79,6 +81,8 @@ pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { .class::() .class::() .class::() + .class::() + .class::() .class::() .class::() .class::() diff --git a/src/extension/flow-php-ext/src/multiset_hashes.rs b/src/extension/flow-php-ext/src/multiset_hashes.rs new file mode 100644 index 000000000..c222da4d4 --- /dev/null +++ b/src/extension/flow-php-ext/src/multiset_hashes.rs @@ -0,0 +1,204 @@ +//! `Flow\ETL\Values\Column\{RustDatasetHash, RustGroupedMultisetHashes}`: wrapping sums of the row hash lanes, held +//! natively between batches, one sum for the dataset or one per group. + +use std::sync::Arc; + +use arrow_array::LargeBinaryArray; +use ext_php_rs::boxed::ZBox; +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::{ArrayKey, ZendHashTable, Zval}; +use flow_column_kernels::canonical::row_lanes; + +use crate::canonical_rows::{named, row_columns, STRING_TYPE}; +use crate::column::RustColumn; +use crate::ctx::{call_method, construct, expect_object, find_class, read_property, zval_long}; +use crate::exception::ext_exception; +use crate::grouped_totals::group_ids; +use crate::interfaces::{dataset_hash_ce, grouped_multiset_hashes_ce}; +use crate::render::invalid_argument; + +const MULTISET_DIGEST: &str = "Flow\\ETL\\Values\\Column\\MultisetDigest"; + +/// [low, high] +type Lanes = [u64; 2]; + +/// A `MultisetDigest` object, so `digest()` declares that return type. +pub struct DigestValue(Zval); + +impl IntoZval for DigestValue { + const TYPE: DataType = DataType::object(MULTISET_DIGEST); + const NULLABLE: bool = false; + + fn set_zval(self, zv: &mut Zval, _persistent: bool) -> ZvalResult<()> { + *zv = self.0; + + Ok(()) + } +} + +#[php_class] +#[php( + name = "Flow\\ETL\\Values\\Column\\RustDatasetHash", + flags = ClassFlags::Final, + implements(ce = dataset_hash_ce, stub = "Flow\\ETL\\Values\\Column\\DatasetHash") +)] +#[derive(Default)] +pub struct RustDatasetHash { + lanes: Lanes, +} + +#[php_impl] +impl RustDatasetHash { + pub fn add(&mut 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(); + + for index in 0..count { + named(&mut row, &mut entries, &resolved, index); + add_lanes(&mut self.lanes, row_lanes(&row).into()); + } + + Ok(()) + } + + pub fn digest(&self) -> PhpResult { + Ok(DigestValue(digest(self.lanes)?)) + } + + pub fn absorb(&mut self, digest: &Zval) -> PhpResult<()> { + add_lanes(&mut self.lanes, lanes_of(digest)?); + + Ok(()) + } +} + +#[php_class] +#[php( + name = "Flow\\ETL\\Values\\Column\\RustGroupedMultisetHashes", + flags = ClassFlags::Final, + implements(ce = grouped_multiset_hashes_ce, stub = "Flow\\ETL\\Values\\Column\\GroupedMultisetHashes") +)] +#[derive(Default)] +pub struct RustGroupedMultisetHashes { + lanes: Vec, +} + +#[php_impl] +impl RustGroupedMultisetHashes { + pub fn add(&mut self, columns: &ZendHashTable, ids: &Zval) -> PhpResult<()> { + let resolved = row_columns(columns)?; + let ids = group_ids(ids)?; + let mut row = Vec::new(); + let mut entries = Vec::new(); + + if let Some(&last) = ids.iter().max() { + self.grow(last); + } + + for (index, id) in ids.into_iter().enumerate() { + named(&mut row, &mut entries, &resolved, index); + add_lanes(&mut self.lanes[id], row_lanes(&row).into()); + } + + Ok(()) + } + + pub fn hashes(&self) -> PhpResult { + let hashes = self + .lanes + .iter() + .map(|[low, high]| format!("{high:016x}{low:016x}")) + .collect::>(); + + RustColumn::of_type(Arc::new(LargeBinaryArray::from_iter_values(hashes)), STRING_TYPE) + } + + pub fn partials(&self) -> PhpResult> { + let mut partials = ZendHashTable::with_capacity(self.lanes.len() as u32); + + for lanes in &self.lanes { + partials.push(digest(*lanes)?)?; + } + + Ok(partials) + } + + #[php(name = "absorbEarlier")] + pub fn absorb_earlier(&mut self, earlier: &Zval, into: &ZendHashTable) -> PhpResult<()> { + let lanes = match earlier.extract::<&RustGroupedMultisetHashes>() { + Some(native) => native.lanes.clone(), + None => call_method(earlier, "partials", &mut [])? + .array() + .ok_or_else(|| ext_exception("flow_php expected GroupedMultisetHashes::partials() to return an array"))? + .values() + .map(lanes_of) + .collect::>>()?, + }; + + for (earlier_id, id) in into.iter() { + let earlier_id = match earlier_id { + ArrayKey::Long(id) => usize::try_from(id).ok(), + _ => None, + } + .ok_or_else(|| ext_exception("flow_php expected earlier group ids as int keys"))?; + let id = id + .long() + .and_then(|id| usize::try_from(id).ok()) + .ok_or_else(|| ext_exception("flow_php expected group ids as ints of 0 or more"))?; + let earlier = lanes + .get(earlier_id) + .copied() + .ok_or_else(|| invalid_argument(format!("Earlier group {earlier_id} has no hash")))?; + + self.grow(id); + add_lanes(&mut self.lanes[id], earlier); + } + + Ok(()) + } +} + +impl RustGroupedMultisetHashes { + fn grow(&mut self, id: usize) { + if self.lanes.len() <= id { + self.lanes.resize(id + 1, [0, 0]); + } + } +} + +fn add_lanes(lanes: &mut Lanes, [low, high]: Lanes) { + lanes[0] = lanes[0].wrapping_add(low); + lanes[1] = lanes[1].wrapping_add(high); +} + +fn digest([low, high]: Lanes) -> PhpResult { + let mut object = construct( + find_class(MULTISET_DIGEST)?, + &mut [zval_long(low as i64), zval_long(high as i64)], + )?; + let mut zv = Zval::new(); + zv.set_object(&mut object); + + Ok(zv) +} + +fn lanes_of(digest: &Zval) -> PhpResult { + let object = expect_object(digest, "a MultisetDigest")?; + let lane = |name: &str| { + read_property(object, name)? + .long() + .map(|lane| lane as u64) + .ok_or_else(|| { + ext_exception(format!( + "flow_php expected the '{name}' lane of a MultisetDigest as an int" + )) + }) + }; + + Ok([lane("low")?, lane("high")?]) +} diff --git a/src/extension/flow-php-ext/src/plan.rs b/src/extension/flow-php-ext/src/plan.rs index de812877a..f115e51d3 100644 --- a/src/extension/flow-php-ext/src/plan.rs +++ b/src/extension/flow-php-ext/src/plan.rs @@ -8,6 +8,7 @@ use ext_php_rs::exception::PhpException; use ext_php_rs::types::Zval; use ext_php_rs::zend::Function; use flow_batch_frame::kind::{self, kind_of, parse_type, Kind, Markup}; +use flow_column_kernels::canonical::{encoding_of, Encoding}; use crate::cast::{build_cast_kind, CastKind}; use crate::ctx::{self, call_handle, call_method, ce_method_ref, expect_object, find_class, instance}; @@ -18,6 +19,8 @@ const IDENTITY: &str = "Flow\\ETL\\Values\\Column\\Physical\\IdentityPhysical"; pub struct TypePlan { pub kind: Kind, + /// The canonical encoding of a value of this type, for row hashes. + pub encoding: Encoding, pub type_name: String, pub type_zv: Zval, pub values: ValueNode, @@ -66,6 +69,7 @@ fn json_plan(type_zv: &Zval) -> Result, PhpException> { let physical = call_method(&instance(PHYSICAL_FOR)?, "physical", &mut [type_zv.shallow_clone()])?; let plan = Rc::new(TypePlan { kind: kind_of(&parsed).map_err(json_exception)?, + encoding: encoding_of(&parsed).map_err(json_exception)?, type_name: parsed.base().unwrap_or(&parsed).type_.clone(), type_zv: type_zv.shallow_clone(), values: kind::value_node(&parsed) diff --git a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt index ebae0ba74..eb2506be6 100644 --- a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt +++ b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt @@ -46,12 +46,16 @@ interface Flow\ETL\IO\Loader\File\FileWriter interface Flow\ETL\Values\Column\Backend interface Flow\ETL\Values\Column\Column interface Flow\ETL\Values\Column\ColumnBuilder +interface Flow\ETL\Values\Column\DatasetHash interface Flow\ETL\Values\Column\GroupedCounts +interface Flow\ETL\Values\Column\GroupedMultisetHashes interface Flow\ETL\Values\Column\GroupedTotals class Flow\ETL\Values\Column\RustBackend implements Flow\ETL\Values\Column\Backend, Flow\ETL\Foundation\Describe\Describable class Flow\ETL\Values\Column\RustColumn implements Flow\ETL\Values\Column\Column class Flow\ETL\Values\Column\RustColumnBuilder implements Flow\ETL\Values\Column\ColumnBuilder +class Flow\ETL\Values\Column\RustDatasetHash implements Flow\ETL\Values\Column\DatasetHash class Flow\ETL\Values\Column\RustGroupedCounts implements Flow\ETL\Values\Column\GroupedCounts +class Flow\ETL\Values\Column\RustGroupedMultisetHashes implements Flow\ETL\Values\Column\GroupedMultisetHashes class Flow\ETL\Values\Column\RustGroupedTotals implements Flow\ETL\Values\Column\GroupedTotals interface Flow\ETL\Values\Grouping\GroupTable class Flow\ETL\Values\Grouping\RustGroupTable implements Flow\ETL\Values\Grouping\GroupTable diff --git a/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt b/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt index ab0873007..9e85122c2 100644 --- a/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt @@ -1,5 +1,5 @@ --TEST-- -RustGroupTable::lookup() returns the group of every row exactly as PhpGroupTable::lookup(): known and unknown keys, null keys, lists and structures, columns from either backend, and it never adds a group +RustGroupTable::lookup() returns the group of every row exactly as PhpGroupTable::lookup(), on the canonical encoding without a call back into PHP: known and unknown keys, null keys, lists, structures, maps, xml and html, columns from either backend, a batch cast to its declared type and a value that does not cast, and it never adds a group --SKIPIF-- --FILE-- @@ -8,8 +8,8 @@ require __DIR__ . '/bootstrap.php'; use Flow\ETL\Values\Column\{Backend, PhpBackend, RustBackend}; -use function Flow\ETL\DSL\{array_to_rows, int_schema, list_schema, schema, str_schema, structure_schema}; -use function Flow\Types\DSL\{type_integer, type_list, type_string, type_structure}; +use function Flow\ETL\DSL\{array_to_rows, date_schema, datetime_schema, html_schema, int_schema, list_schema, map_schema, schema, str_schema, structure_schema, xml_schema}; +use function Flow\Types\DSL\{type_integer, type_list, type_map, type_string, type_structure}; $cases = [ 'nullable strings' => [str_schema('v', nullable: true), ['a', null, 'b', ''], ['b', 'c', null, '', 'a', '0']], @@ -38,6 +38,59 @@ foreach ($cases as $label => [$definition, $known, $probed]) { ', php columns ', $looked($rust, $php, $definition, $known, $probed) === $expected ? 'same' : 'MISMATCH', ', ', json_encode($expected), "\n"; } + +$nested = [ + 'maps' => [map_schema('v', type_map(type_string(), type_integer()), nullable: true), [['a' => 1], ['b' => 2, 'a' => 1], null], [['a' => 1, 'b' => 2], ['a' => 1], ['c' => 3], null]], + 'xml' => [xml_schema('v'), ['', '1'], ['1', '', '']], + 'html' => [html_schema('v'), ['

a

'], ['

b

', '

a

']], +]; + +foreach ($nested as $label => [$definition, $known, $probed]) { + if ($label === 'html' && !class_exists('\Dom\HTMLDocument')) { + echo "html: same, php columns same\n"; + + continue; + } + + $expected = $looked($php, $php, $definition, $known, $probed); + + echo $label, ': ', $looked($rust, $rust, $definition, $known, $probed) === $expected ? 'same' : 'MISMATCH', + ', php columns ', $looked($rust, $php, $definition, $known, $probed) === $expected ? 'same' : 'MISMATCH', "\n"; +} + +// a batch whose column type differs from the declared one is cast to it, as after a group-by spill merge +$castLooked = static function (Backend $tables, Backend $columns, $declared, $batch, array $known, array $probed): array { + $table = $tables->groupTable(['v'], schema($declared)); + $table->assign(array_to_rows(array_map(static fn($value) => ['v' => $value], $known), schema($declared), $columns)); + $groups = $table->lookup(array_to_rows(array_map(static fn($value) => ['v' => $value], $probed), schema($batch), $columns)); + + return [$groups->physicals(), $table->count()]; +}; +$mismatches = [ + 'a date batch against datetime keys' => [datetime_schema('v'), date_schema('v'), [new DateTimeImmutable('2026-01-01 00:00:00 UTC'), new DateTimeImmutable('2026-01-02 12:00:00 UTC')], [new DateTimeImmutable('2026-01-01'), new DateTimeImmutable('2026-01-02')]], + 'an xml batch against string keys' => [str_schema('v'), xml_schema('v'), ['
', 'x'], ['', '']], +]; + +foreach ($mismatches as $label => [$declared, $batch, $known, $probed]) { + $expected = $castLooked($php, $php, $declared, $batch, $known, $probed); + + echo $label, ': ', $castLooked($rust, $rust, $declared, $batch, $known, $probed) === $expected ? 'same' : 'MISMATCH ' . json_encode($castLooked($rust, $rust, $declared, $batch, $known, $probed)), + ', php columns ', $castLooked($rust, $php, $declared, $batch, $known, $probed) === $expected ? 'same' : 'MISMATCH', + ', ', json_encode($expected), "\n"; +} + +$refusal = static function (Backend $backend): string { + try { + $table = $backend->groupTable(['v'], schema(int_schema('v'))); + $table->assign(array_to_rows([['v' => 'abc']], schema(str_schema('v')), $backend)); + + return 'no exception'; + } catch (Throwable $e) { + return $e::class . ': ' . $e->getMessage(); + } +}; + +echo 'a value that does not cast: ', $refusal($rust) === $refusal($php) ? 'same ' . $refusal($rust) : 'MISMATCH ' . $refusal($rust) . ' | ' . $refusal($php), "\n"; ?> --EXPECT-- nullable strings: same, php columns same, [[2,null,1,3,0,null],2,"integer",4] @@ -45,3 +98,9 @@ ints: same, php columns same, [[2,null,0,1,null],2,"integer",3] lists with nulls: same, php columns same, [[2,null,1,0],1,"integer",3] structures with nulls: same, php columns same, [[null,1,0],1,"integer",2] only nulls: same, php columns same, [[0,0],0,"integer",1] +maps: same, php columns same +xml: same, php columns same +html: same, php columns same +a date batch against datetime keys: same, php columns same, [[0,null],2] +an xml batch against string keys: same, php columns same, [[0,null],2] +a value that does not cast: same Flow\ETL\Foundation\Exception\EvaluationException: Column "v" value 'abc' cannot be cast to integer to compare: "abc" is not a number (row 0) diff --git a/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt b/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt index a4de7f0b6..c54c69275 100644 --- a/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt @@ -1,5 +1,5 @@ --TEST-- -RustBackend::partition() puts every row in the bucket PhpBackend::partition() gives it, in row order: text keys natively, the other types through KeyEncoder, composite keys, columns from either backend, offsets 0 and 8, 1, 4 and 16 buckets +RustBackend::partition() puts every row in the bucket PhpBackend::partition() gives it, in row order, on the canonical encoding without a call back into PHP: scalar, list, structure, map, xml and html keys, composite keys, columns from either backend, offsets 0 and 8, 1, 4 and 16 buckets --SKIPIF-- --FILE-- @@ -8,8 +8,8 @@ require __DIR__ . '/bootstrap.php'; use Flow\ETL\Values\Column\{Backend, PhpBackend, RustBackend}; -use function Flow\ETL\DSL\{array_to_rows, bool_schema, float_schema, int_schema, list_schema, schema, str_schema, structure_schema}; -use function Flow\Types\DSL\{type_integer, type_list, type_string, type_structure}; +use function Flow\ETL\DSL\{array_to_rows, bool_schema, float_schema, html_schema, int_schema, list_schema, map_schema, schema, str_schema, structure_schema, xml_schema}; +use function Flow\Types\DSL\{type_integer, type_list, type_map, type_string, type_structure}; $cases = [ 'nullable strings' => [[str_schema('k', nullable: true)], [['a'], [null], ['b'], [''], [null], ['a'], ['0']]], @@ -20,6 +20,9 @@ $cases = [ 'structures with nulls' => [[structure_schema('k', type_structure(['a' => type_string()]), nullable: true)], [[['a' => 'x']], [null], [['a' => 'y']], [['a' => 'x']]]], 'only nulls' => [[str_schema('k', nullable: true)], [[null], [null]]], 'a composite key' => [[int_schema('k'), str_schema('s')], [[1, 'a'], [1, 'b'], [2, 'a'], [1, 'a']]], + 'maps with nulls' => [[map_schema('k', type_map(type_string(), type_integer()), nullable: true)], [[['a' => 1]], [['b' => 2, 'a' => 1]], [null], [['a' => 1, 'b' => 2]]]], + 'xml' => [[xml_schema('k')], [[''], ['1'], ['']]], + ...(class_exists('\Dom\HTMLDocument') ? ['html' => [[html_schema('k')], [['

a

'], ['

b

'], ['

a

']]]] : []), ]; $partitioned = static function (Backend $partitioner, Backend $columns, array $definitions, array $values, int $buckets, int $offset): array { @@ -52,6 +55,10 @@ foreach ($cases as $label => [$definitions, $values]) { echo $label, ': ', implode(', ', array_unique($outcomes)), "\n"; } +if (!class_exists('\Dom\HTMLDocument')) { + echo "html: same\n"; +} + $empty = array_to_rows([], schema(int_schema('k')), $rust); echo 'empty batch: ', json_encode($rust->partition($empty, [$empty->column('k')], 4, 0)), "\n"; $one = array_to_rows([['k' => 1], ['k' => 2]], schema(int_schema('k')), $rust); @@ -80,6 +87,9 @@ lists with nulls: same structures with nulls: same only nulls: same a composite key: same +maps with nulls: same +xml: same +html: same empty batch: [] one bucket is the batch itself: true a bucket count of 0: same Flow\ETL\Foundation\Exception\InvalidArgumentException Buckets count must be greater than 0, given: 0 diff --git a/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt new file mode 100644 index 000000000..431ec6e92 --- /dev/null +++ b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt @@ -0,0 +1,160 @@ +--TEST-- +RustBackend::rowHashes(), datasetHash() and groupedMultisetHashes() give the hashes PhpBackend gives: every tag, the canonical edge cases, a native map with the key "1", positioned and bare xml elements, columns from either backend, batches split differently, batches without columns, digests, partials, absorb and absorbEarlier +--SKIPIF-- + +--FILE-- + type_integer(), + 'a' => type_optional(type_structure(['x' => type_string()])), + ])), + xml_element_schema('element'), + ), + [ + ['float' => -0.0, 'utc' => '2026-01-01T00:00:00Z', 'warsaw' => '2026-01-01T01:00:00+01:00', 'json' => '{"a":1}', 'text' => null, 'id' => 1, 'nested' => ['b' => 1, 'a' => ['x' => 'y']], 'element' => type_xml_element()->cast('
')->firstElementChild], + ['float' => NAN, 'utc' => '1969-07-20T20:17:40.123456Z', 'warsaw' => '1969-07-20T20:17:40.123456Z', 'json' => '{"a": 1}', 'text' => '', 'id' => null, 'nested' => ['b' => 2, 'a' => null], 'element' => type_xml_element()->cast('
')->lastElementChild], + ['float' => -NAN, 'utc' => '1970-01-01T00:00:00Z', 'warsaw' => '1970-01-01T00:00:00Z', 'json' => '[1]', 'text' => 'NaN', 'id' => null, 'nested' => ['b' => 3, 'a' => ['x' => '']], 'element' => (new DOMDocument())->createElement('a')], + ['float' => 0.0, 'utc' => '2038-01-19T03:14:08.000001Z', 'warsaw' => '2038-01-19T03:14:08.000001Z', 'json' => '{}', 'text' => '1', 'id' => 1, 'nested' => ['b' => 1, 'a' => ['x' => 'y']], 'element' => type_xml_element()->cast('
')->firstElementChild], + ], +]; +$cases = ['every tag' => [all_types_schema(), all_types_values()], 'edge cases' => $edges]; + +$rows = static fn(Backend $backend, Rows $source): Rows => $source->adoptedBy($backend); +$lanes = static fn(MultisetDigest $digest): array => [$digest->low, $digest->high]; +$hashes = static function (Backend $backend, Rows $rows, int $batch, ?array $ids = null) use ($lanes): array { + $dataset = $backend->datasetHash(); + $grouped = $backend->groupedMultisetHashes(); + + foreach ($rows->chunks($batch) as $index => $part) { + $ids === null + ? $dataset->add($part->columns(), $part->count()) + : $grouped->add($part->columns(), array_to_rows( + array_map(static fn(int $id): array => ['id' => $id], array_slice($ids, $index * $batch, $part->count())), + schema(int_schema('id')), + $backend, + )->column('id')); + } + + return $ids === null + ? [$dataset->digest()->hex(), $lanes($dataset->digest())] + : [$grouped->hashes()->physicals(), array_map($lanes, $grouped->partials())]; +}; + +foreach ($cases as $label => [$schema, $values]) { + $source = php_rows($schema, $values); + $ids = array_map(static fn(int $row): int => $row % 2, array_keys($values)); + $expected = $php->rowHashes($source->columns(), $source->count())->physicals(); + $outcomes = []; + + foreach (['php columns' => $php, 'native columns' => $rust] as $from => $backend) { + $built = $rows($backend, $source); + $reversed = array_reverse($built->columns(), true); + + $outcomes[] = $rust->rowHashes($built->columns(), $built->count())->physicals() === $expected + && $rust->rowHashes($reversed, $built->count())->physicals() === $expected + && $php->rowHashes($built->columns(), $built->count())->physicals() === $expected + ? 'same' + : "MISMATCH rowHashes {$from}"; + + foreach ([1, 2, count($values)] as $batch) { + $outcomes[] = $hashes($rust, $built, $batch) === $hashes($php, $source, count($values)) + && $hashes($rust, $built, $batch, $ids) === $hashes($php, $source, count($values), $ids) + ? 'same' + : "MISMATCH multiset {$from} batch {$batch} " . json_encode($hashes($rust, $built, $batch)) . ' ' . json_encode($hashes($php, $source, count($values))); + } + } + + echo $label, ': ', implode(', ', array_unique($outcomes)), "\n"; +} + +$entries = array_to_rows([['k' => '1', 'v' => 1], ['k' => 'a', 'v' => 2]], schema(str_schema('k'), int_schema('v')), $php); +$map = new MapColumn(type_map(type_string(), type_integer()), [0, 1, 2], $entries->column('k'), $entries->column('v'), []); +$native = $rust->decode(map_schema('m', type_map(type_string(), type_integer())), $map->encode(), 2, 0); +echo 'native map with the key "1": ', $native instanceof Flow\ETL\Values\Column\RustColumn ? 'native' : 'php', ', ', + $rust->rowHashes(['m' => $native], 2)->physicals() === $php->rowHashes(['m' => $map], 2)->physicals() ? 'same' : 'MISMATCH', "\n"; + +$source = php_rows(...$edges); +$groupIds = static fn(Backend $backend) => array_to_rows([['id' => 0], ['id' => 2], ['id' => 0], ['id' => 2]], schema(int_schema('id')), $backend)->column('id'); +$fromPhp = $php->groupedMultisetHashes(); +$fromPhp->add($source->columns(), $groupIds($php)); +$direct = $rust->groupedMultisetHashes(); +$direct->add($source->adoptedBy($rust)->columns(), $groupIds($rust)); +$intoPhp = $rust->groupedMultisetHashes(); +$intoPhp->absorbEarlier($fromPhp, [0 => 0, 1 => 1, 2 => 2]); +$intoNative = $rust->groupedMultisetHashes(); +$intoNative->absorbEarlier($direct, [0 => 0, 1 => 1, 2 => 2]); +$phpInto = $php->groupedMultisetHashes(); +$phpInto->absorbEarlier($direct, [0 => 0, 1 => 1, 2 => 2]); +echo 'absorbEarlier of php, native and into php: ', $intoPhp->hashes()->physicals() === $direct->hashes()->physicals() + && $intoNative->hashes()->physicals() === $direct->hashes()->physicals() + && $phpInto->hashes()->physicals() === $direct->hashes()->physicals() + && array_map($lanes, $intoPhp->partials()) === array_map($lanes, $fromPhp->partials()) ? 'same' : 'MISMATCH', "\n"; +echo 'unseen group: ', $direct->hashes()->physicals()[1], "\n"; +echo 'empty: ', $rust->datasetHash()->digest()->hex(), ' ', json_encode($rust->groupedMultisetHashes()->hashes()->physicals()), ' ', json_encode($rust->groupedMultisetHashes()->partials()), "\n"; + +$withoutColumns = static function (Backend $backend): array { + $dataset = $backend->datasetHash(); + $dataset->add([], 3); + $grouped = $backend->groupedMultisetHashes(); + $grouped->add([], array_to_rows([['id' => 1], ['id' => 0], ['id' => 1]], schema(int_schema('id')), $backend)->column('id')); + + return [$dataset->digest()->hex(), $grouped->hashes()->physicals()]; +}; +echo 'batch without columns: ', $withoutColumns($rust) === $withoutColumns($php) ? 'same' : 'MISMATCH', ' ', json_encode($withoutColumns($rust)), "\n"; + +$datasetFromPhp = $php->datasetHash(); +$datasetFromPhp->add($source->columns(), $source->count()); +$absorbed = $rust->datasetHash(); +$absorbed->absorb($datasetFromPhp->digest()); +$datasetDirect = $rust->datasetHash(); +$datasetDirect->add($source->adoptedBy($rust)->columns(), $source->count()); +echo 'absorb of a php digest: ', $absorbed->digest() == $datasetDirect->digest() ? 'same' : 'MISMATCH', "\n"; + +$carry = $rust->datasetHash(); +$carry->absorb(new MultisetDigest(0xFFFFFFFF, PHP_INT_MAX)); +$carry->absorb(new MultisetDigest(0xFFFFFFFF, 1)); +echo 'carry: ', $carry->digest()->hex(), ' ', json_encode($lanes($carry->digest())), "\n"; + +try { + $rust->groupedMultisetHashes()->absorbEarlier($rust->groupedMultisetHashes(), [3 => 0]); +} catch (Throwable $e) { + echo 'missing earlier group: ', $e::class, ': ', $e->getMessage(), "\n"; +} + +$only = array_to_rows([['a' => null]], schema(int_schema('a', true)), $rust); +echo 'only nulls: ', $rust->rowHashes($only->columns(), 1)->physicals()[0], "\n"; +echo 'no columns: ', json_encode($rust->rowHashes([], 2)->physicals()), "\n"; +?> +--EXPECT-- +every tag: same +edge cases: same +native map with the key "1": native, same +absorbEarlier of php, native and into php: same +unseen group: 00000000000000000000000000000000 +empty: 00000000000000000000000000000000 [] [] +batch without columns: same ["ccfe147903d6ca882005496cd3a7dc7d",["99aa06d3014798d86001c324468d497f","33540da6028f31b0c00386488d1a92fe"]] +absorb of a php digest: same +carry: 800000000000000000000001fffffffe [8589934590,-9223372036854775808] +missing earlier group: Flow\ETL\Foundation\Exception\InvalidArgumentException: Earlier group 3 has no hash +only nulls: 99aa06d3014798d86001c324468d497f +no columns: ["99aa06d3014798d86001c324468d497f","99aa06d3014798d86001c324468d497f"] diff --git a/src/extension/flow-php-ext/tests/phpt/bootstrap.php b/src/extension/flow-php-ext/tests/phpt/bootstrap.php index 2cfb836e6..6cdc568e2 100644 --- a/src/extension/flow-php-ext/tests/phpt/bootstrap.php +++ b/src/extension/flow-php-ext/tests/phpt/bootstrap.php @@ -332,7 +332,9 @@ function interfaces_reflection(): string 'Flow\\ETL\\Values\\Column\\Backend', 'Flow\\ETL\\Values\\Column\\Column', 'Flow\\ETL\\Values\\Column\\ColumnBuilder', + 'Flow\\ETL\\Values\\Column\\DatasetHash', 'Flow\\ETL\\Values\\Column\\GroupedCounts', + 'Flow\\ETL\\Values\\Column\\GroupedMultisetHashes', 'Flow\\ETL\\Values\\Column\\GroupedTotals', 'Flow\\ETL\\Values\\Grouping\\GroupTable', 'Flow\\ETL\\IO\\Loader\\File\\FileWriter', From 7e6fd5f3dec5b46d931a65d5729bbcde54be0295 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Sun, 22 Nov 2026 11:48:38 -0600 Subject: [PATCH 2/5] feat(flow-php/etl): partition hashes in analyze()->withDatasetHash() - per-partition dataset hashes, combined with DatasetHash::plus() - Hash, PartitionHash and DatasetHash report types - multiset digest travels only as hex, Rust and PHP accept the same form - empty string partition values written as name= and read back - ExternalSortTest scripts its memory instead of reading the process --- documentation/components/core/aggregations.md | 86 ++++- documentation/components/core/partitioning.md | 2 + .../components/extensions/flow-php-ext.md | 6 +- documentation/upgrading.md | 14 +- .../src/Flow/ETL/Functions/MultisetHash.php | 38 ++- .../ETL/Functions/MultisetHashesByGroup.php | 12 +- .../etl/src/Flow/ETL/Functions/RowHash.php | 17 +- src/core/etl/src/Flow/ETL/Runtime/Analyze.php | 28 +- .../ETL/Runtime/Executor/OutputHasher.php | 19 ++ .../Executor/PartitionedOutputHasher.php | 154 +++++++++ .../Flow/ETL/Runtime/Executor/RunCounts.php | 38 +-- .../Runtime/Executor/StatisticsCollector.php | 6 +- .../Runtime/Executor/WholeOutputHasher.php | 69 ++++ .../Flow/ETL/Runtime/Metrics/DatasetHash.php | 88 +++++ .../etl/src/Flow/ETL/Runtime/Metrics/Hash.php | 59 ++++ .../ETL/Runtime/Metrics/PartitionHash.php | 62 ++++ .../src/Flow/ETL/Runtime/Metrics/Report.php | 11 +- .../ETL/Values/Column/AdaptiveBackend.php | 5 - .../src/Flow/ETL/Values/Column/Backend.php | 2 - .../Flow/ETL/Values/Column/DatasetHash.php | 23 -- .../Values/Column/GroupedMultisetHashes.php | 5 - .../Flow/ETL/Values/Column/MultisetDigest.php | 31 +- .../ETL/Values/Column/Php/PhpDatasetHash.php | 52 --- .../Column/Php/PhpGroupedMultisetHashes.php | 11 +- .../src/Flow/ETL/Values/Column/PhpBackend.php | 6 - .../ETL/Tests/Context/DescribableFixtures.php | 7 + .../ETL/Tests/Double/AcceptingBackend.php | 6 - .../Double/FixedProcessMemoryBackend.php | 6 - .../Tests/Double/ReportedMemoryBackend.php | 6 - .../Flow/ETL/Tests/Double/SpyBackend.php | 16 +- .../Integration/DataFrame/DatasetHashTest.php | 95 +++++- .../IO/Loader/PartitionedWriteTest.php | 25 ++ .../Flow/ETL/Tests/Mother/ReportMother.php | 3 +- .../Tests/Unit/Functions/MultisetHashTest.php | 18 +- .../Functions/MultisetHashesByGroupTest.php | 14 +- .../ETL/Tests/Unit/Functions/RowHashTest.php | 2 +- .../Unit/IO/Loader/RowPartitionsTest.php | 11 + .../Unit/Kernels/Sort/ExternalSortTest.php | 91 +++-- .../ETL/Tests/Unit/Runtime/AnalyzeTest.php | 23 +- .../Executor/PartitionedOutputHasherTest.php | 323 ++++++++++++++++++ .../Unit/Runtime/Executor/RunCountsTest.php | 196 +++++++++-- .../Executor/StatisticsCollectorTest.php | 55 ++- .../Executor/WholeOutputHasherTest.php | 74 ++++ .../Unit/Runtime/Metrics/DatasetHashTest.php | 214 ++++++++++++ .../Tests/Unit/Runtime/Metrics/HashTest.php | 59 ++++ .../Runtime/Metrics/PartitionHashTest.php | 63 ++++ .../Tests/Unit/Runtime/Metrics/ReportTest.php | 32 +- .../Values/Column/AdaptiveBackendTest.php | 2 - .../Unit/Values/Column/MultisetDigestTest.php | 28 +- .../Values/Column/Php/PhpDatasetHashTest.php | 90 ----- .../Php/PhpGroupedMultisetHashesTest.php | 61 +++- .../Unit/Values/Grouping/KeyEncoderTest.php | 56 +++ .../Flow/ETL/Values/Column/RustBackend.php | 5 - src/extension/flow-php-ext/src/backend.rs | 7 +- src/extension/flow-php-ext/src/interfaces.rs | 29 +- src/extension/flow-php-ext/src/lib.rs | 1 - .../flow-php-ext/src/multiset_hashes.rs | 121 ++----- .../tests/phpt/001_extension_loaded.phpt | 2 - .../tests/phpt/125_row_hashes_parity.phpt | 79 +++-- .../flow-php-ext/tests/phpt/bootstrap.php | 1 - .../src/Flow/Filesystem/Partition.php | 50 +-- .../Filesystem/Tests/Unit/PartitionTest.php | 65 +++- 62 files changed, 2138 insertions(+), 642 deletions(-) create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Executor/OutputHasher.php create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Executor/PartitionedOutputHasher.php create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Metrics/Hash.php create mode 100644 src/core/etl/src/Flow/ETL/Runtime/Metrics/PartitionHash.php delete mode 100644 src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php delete mode 100644 src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/PartitionedOutputHasherTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/WholeOutputHasherTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/DatasetHashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/HashTest.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/PartitionHashTest.php delete mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php diff --git a/documentation/components/core/aggregations.md b/documentation/components/core/aggregations.md index 58ba841ec..3caf6a75f 100644 --- a/documentation/components/core/aggregations.md +++ b/documentation/components/core/aggregations.md @@ -110,6 +110,90 @@ df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'), e ## Hashing rows +A sync job writes orders partitioned by day and country. The partition hashes tell which folders changed since the +last run: + +```php +read($externalOrders->withSchema($orders)) + ->write(to_parquet('orders')->partitionBy(partition_by('date', 'country'))) + ->run(analyze: analyze()->withDatasetHash(ref('date'), ref('country'))); + +$previous = file_exists('orders.hashes.json') + ? json_decode((string) file_get_contents('orders.hashes.json'), true, flags: JSON_THROW_ON_ERROR) + : []; +$current = []; + +foreach ($report->datasetHash()->partitions as $partition) { + $segments = array_map(static fn(Partition $p): string => $p->segment(), $partition->partitions->toArray()); + $current[implode('/', $segments)] = $partition->hash->value; +} + +$changed = array_keys(array_diff_assoc($current, $previous)); // ['date=2026-11-20/country=PL', ...] +$removed = array_keys(array_diff_key($previous, $current)); +file_put_contents('orders.hashes.json', json_encode($current)); +``` + +A partition hash covers every column of every row of the partition. The named columns only group the rows. +`$report->datasetHash()->total` is the hash of all rows: `->value` is the hash and `->rows` is the number of rows. +It equals the hash of `withDatasetHash()` without columns, and then `->partitions` is `[]`. `$partition->hash->rows` +is the number of rows of one partition. + +`PartitionHash::normalize()` gives the stored form of one entry, +`['partitions' => ['date' => '2026-11-20', 'country' => 'PL'], 'hash' => ['rows' => 120, 'value' => '...']]`. +`PartitionHash::fromArray()` reads it back. + +```php +plus($tuesday->datasetHash()); + +$week->total->value; // '31be1d609a26d996382e2a23855ebbe5', the hash of one run over both days +$week->partitions; // PL: 2 rows, DE: 1 row +``` + +`plus()` adds the totals and the partitions with the same values. The result equals the hash of one run over the +rows of both. + +A null value is the partition `__HIVE_DEFAULT_PARTITION__`, as the loader writes it: +`country=__HIVE_DEFAULT_PARTITION__`. + +A list, map, structure, json, xml or html column cannot be named. A float column cannot be named either, because +`0.0` and `-0.0` are one value but two folder names. Cast it first: + +```php +read($rates)->run(analyze: analyze()->withDatasetHash(ref('rate'))); +// analyze()->withDatasetHash() cannot group by the float column "rate": 0.0 and -0.0 are one value but two partition +// names. Cast it to a decimal string or an integer first. + +data_frame() + ->read($rates) + ->withColumn('rate_key', ref('rate')->cast(type_string())) + ->run(analyze: analyze()->withDatasetHash(ref('rate_key'))); +``` + +The key column `rate_key` is part of the output, so it is part of every partition hash. + +Declare the schema of the partition columns, as in the first sample. Then the hash of a partition is the same between +runs and between workers. The batch size, the order of the files and the number of workers do not change a hash. + ```php read(from_array($rows))->aggregate([multiset_hash()])->fetch(); df()->read(from_array($rows))->groupBy('country')->aggregate(multiset_hash(ref('id')))->fetch(); // PL: 'ab8476f29c95212a306bffff897d7afb', DE: 'f3aebd664d56cdeceed04ea04775ad52' -df()->read(from_array($rows))->run(analyze: analyze()->withDatasetHash())->datasetHash(); +df()->read(from_array($rows))->run(analyze: analyze()->withDatasetHash())->datasetHash()->total->value; // '31be1d609a26d996382e2a23855ebbe5' ``` diff --git a/documentation/components/core/partitioning.md b/documentation/components/core/partitioning.md index befdc7a5d..71dcede26 100644 --- a/documentation/components/core/partitioning.md +++ b/documentation/components/core/partitioning.md @@ -141,6 +141,8 @@ 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=` | 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 84fd0efcf..bd164d943 100644 --- a/documentation/components/extensions/flow-php-ext.md +++ b/documentation/components/extensions/flow-php-ext.md @@ -81,9 +81,9 @@ Each contract with a Rust and a PHP implementation follows one pattern: | `Flow\ETL\IO\Loader\File\FileWriter` | `RustParquetFileWriter` | `ParquetFileWriter` | `ParquetFileWriterFactory::writer()` | The extension also registers `Flow\ETL\Values\Column\{Column, ColumnBuilder, GroupedTotals, GroupedCounts, -DatasetHash, GroupedMultisetHashes}` (`RustColumn`, `RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`, -`RustDatasetHash`, `RustGroupedMultisetHashes`). It also registers `Flow\ETL\Values\Grouping\GroupTable` -(`RustGroupTable`). `RustBackend` returns the last five. Its sources return the iterator `Flow\ETL\Values\RustIterator`. +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 a9a4cf474..78a618d72 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -69,16 +69,15 @@ writes such a value in that raw form. Write the file again with this version to Catch `Flow\ETL\Foundation\Exception\InvalidArgumentException` instead of `\InvalidArgumentException` for an unknown algorithm name. -### 6) `flow-php/etl` - `Backend` has three new methods, and the flow_php ABI is 4 +### 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::datasetHash(): DatasetHash` | | - | `Backend::groupedMultisetHashes(): GroupedMultisetHashes` | | `FLOW_PHP_ABI` 3 | `FLOW_PHP_ABI` 4 | -A custom `Backend` must implement the three methods. Update or rebuild the flow_php extension together with the library. +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 @@ -89,6 +88,15 @@ A custom `Backend` must implement the three methods. Update or rebuild the flow_ | 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/Functions/MultisetHash.php b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php index 4d0c6ab67..f00a83181 100644 --- a/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php +++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php @@ -10,14 +10,14 @@ use Flow\ETL\Functions\Reference\Reference; use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; -use Flow\ETL\Values\Column\DatasetHash; +use Flow\ETL\Values\Column\GroupedMultisetHashes; use Flow\ETL\Values\Column\MultisetDigest; use Flow\ETL\Values\Rows; +use Flow\ETL\Values\Schema\Definitions; use Flow\Types\Type; use Flow\Types\Type\Logical\StructureType; use SensitiveParameter; -use function array_combine; use function array_map; use function array_values; use function count; @@ -27,14 +27,18 @@ final class MultisetHash implements AggregatesByGroup { - private ?DatasetHash $hash = null; + private ?GroupedMultisetHashes $hash = null; + + private MultisetDigest $absorbed; /** * @param list $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 { @@ -53,30 +57,30 @@ public function aggregate(Rows $rows, array $indices, Backend $backend): void } $names = $this->names(); - $columns = $names === null ? $rows->columns() : array_combine($names, array_map($rows->column(...), $names)); - $this->hash ??= $backend->datasetHash(); - $this->hash->add( + $columns = $names === [] ? $rows->columns() : $rows->select(...$names)->columns(); + ($this->hash ??= $backend->groupedMultisetHashes())->add( count($indices) === $rows->count() ? $columns : array_map(static fn(Column $column): Column => $column->take($indices), $columns), - count($indices), + $backend->constant(Definitions::of('group', type_integer()), 0, count($indices)), ); } public function merge(array $partial, Backend $backend): void { - $this->hash ??= $backend->datasetHash(); - $this->hash->absorb(MultisetDigest::fromArray($partial)); + $this->absorbed = $this->absorbed->plus(MultisetDigest::fromHex(type_string()->assert( + $partial['hash'] ?? null, + ))); } public function partial(): array { - return ($this->hash?->digest() ?? MultisetDigest::empty())->normalize(); + return ['hash' => $this->value()]; } public function partialType(): StructureType { - return type_structure(['low' => type_integer(), 'high' => type_integer()]); + return type_structure(['hash' => type_string()]); } public function grouped(Backend $backend): GroupedAggregation @@ -153,14 +157,16 @@ public function returns(): Type public function value(): string { - return ($this->hash?->digest() ?? MultisetDigest::empty())->hex(); + return MultisetDigest::fromHex(type_string()->assert( + $this->hash?->hashes()->physicals()[0] ?? MultisetDigest::empty()->hex(), + ))->plus($this->absorbed)->hex(); } /** - * @return null|list + * @return list */ - private function names(): ?array + private function names(): array { - return $this->refs === [] ? null : array_map(static fn(Reference $ref): string => $ref->base(), $this->refs); + 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 index 1081eda8e..636b65ce2 100644 --- a/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php +++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHashesByGroup.php @@ -8,20 +8,18 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\GroupedMultisetHashes; -use Flow\ETL\Values\Column\MultisetDigest; use Flow\ETL\Values\Grouping\GroupIds; use Flow\ETL\Values\Rows; -use function array_combine; use function array_map; final readonly class MultisetHashesByGroup implements GroupedAggregation { /** - * @param null|list $columns null takes every column of each batch + * @param list $columns [] takes every column of each batch */ public function __construct( - private ?array $columns, + private array $columns, private GroupedMultisetHashes $hashes, ) {} @@ -32,9 +30,7 @@ public function aggregateGroups(Rows $rows, GroupIds $ids, Backend $backend): vo } $this->hashes->add( - $this->columns === null - ? $rows->columns() - : array_combine($this->columns, array_map($rows->column(...), $this->columns)), + $this->columns === [] ? $rows->columns() : $rows->select(...$this->columns)->columns(), $ids->ids, ); } @@ -46,7 +42,7 @@ public function groupValues(int $groups, Backend $backend): Column public function partials(int $groups): array { - return array_map(static fn(MultisetDigest $digest): array => $digest->normalize(), $this->hashes->partials()); + return array_map(static fn(mixed $hash): array => ['hash' => $hash], $this->hashes->hashes()->physicals()); } public function absorbEarlier(GroupedAggregation $earlier, array $into, Backend $backend): void diff --git a/src/core/etl/src/Flow/ETL/Functions/RowHash.php b/src/core/etl/src/Flow/ETL/Functions/RowHash.php index fcda637a2..f53d9ff44 100644 --- a/src/core/etl/src/Flow/ETL/Functions/RowHash.php +++ b/src/core/etl/src/Flow/ETL/Functions/RowHash.php @@ -14,6 +14,7 @@ use Flow\Types\Type; use SensitiveParameter; +use function array_map; use function array_values; use function Flow\Types\DSL\type_string; @@ -79,12 +80,14 @@ public function returns(): Type public function eval(Rows $rows, Backend $backend): Column { - $columns = []; - - foreach ($rows->isEmpty() ? [] : $this->refs as $ref) { - $columns[$ref->base()] = $rows->column($ref->base()); - } - - return $backend->rowHashes($columns, $rows->count()); + 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/Runtime/Analyze.php b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php index ed22c47af..dd8da927c 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php @@ -4,16 +4,22 @@ 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; + final class Analyze { private bool $collectColumnStatistics = false; - private bool $collectDatasetHash = false; - private bool $collectSchema = false; private bool $collectSourceStatistics = false; + private ?References $datasetHashBy = null; + public function __construct() {} public function collectColumnStatistics(): bool @@ -21,11 +27,6 @@ public function collectColumnStatistics(): bool return $this->collectColumnStatistics; } - public function collectDatasetHash(): bool - { - return $this->collectDatasetHash; - } - public function collectSchema(): bool { return $this->collectSchema; @@ -43,9 +44,18 @@ public function withColumnStatistics(): self return $this; } - public function withDatasetHash(): self + public function newOutputHasher(): ?OutputHasher + { + return match (true) { + $this->datasetHashBy === null => null, + $this->datasetHashBy->count() === 0 => new WholeOutputHasher(), + default => new PartitionedOutputHasher($this->datasetHashBy), + }; + } + + public function withDatasetHash(Reference ...$partitions): self { - $this->collectDatasetHash = true; + $this->datasetHashBy = new References(...$partitions); return $this; } 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, + ) { + $this->absorbed = new DatasetHash(Hash::empty(), []); + $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)); + } + + public function describe(): ?Description + { + return Description::compose(self::class, ['by' => $this->by]); + } + + 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())->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)); + } + + 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 183b858c4..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,12 +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\DatasetHash; -use Flow\ETL\Values\Column\MultisetDigest; +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; @@ -43,10 +44,10 @@ final class RunCounts */ private array $workers = []; - private int $rowsCoveredByAbsorbedDigests = 0; + private int $rowsCoveredByAbsorbedHashes = 0; public function __construct( - private readonly ?DatasetHash $outputHash = null, + private readonly ?OutputHasher $outputHasher = null, ) { /** @var SplObjectStorage $reads */ $reads = new SplObjectStorage(); @@ -119,40 +120,37 @@ public function absorbWorkers(self $other): void } } - public function hashesOutput(): bool + public function outputHasher(): ?OutputHasher { - return $this->outputHash !== null; + return $this->outputHasher; } - public function hashOutput(Rows $rows): void + public function hashOutput(Rows $rows, Backend $backend): void { - if ($this->outputHash === null) { + if ($this->outputHasher === null) { return; } if ($rows->schema()->count() === 0) { - $covered = min($rows->count(), $this->rowsCoveredByAbsorbedDigests); - $this->rowsCoveredByAbsorbedDigests -= $covered; - $this->outputHash->add([], $rows->count() - $covered); + $covered = min($rows->count(), $this->rowsCoveredByAbsorbedHashes); + $this->rowsCoveredByAbsorbedHashes -= $covered; + $this->outputHasher->add(Rows::fromColumns(new Schema(), [], $rows->count() - $covered), $backend); return; } - $this->outputHash->add($rows->columns(), $rows->count()); + $this->outputHasher->add($rows, $backend); } - /** - * @param int<0, max> $rows - */ - public function absorbOutputHash(MultisetDigest $digest, int $rows): void + public function absorbOutputHash(DatasetHash $partial): void { - $this->outputHash?->absorb($digest); - $this->rowsCoveredByAbsorbedDigests += $rows; + $this->outputHasher?->absorb($partial); + $this->rowsCoveredByAbsorbedHashes += $partial->total->rows; } - public function outputHash(): ?string + public function outputHash(): ?DatasetHash { - return $this->outputHash?->digest()->hex(); + return $this->outputHasher?->hash(); } public function worker(int $pid, int $peakBytes): void 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 bba2092f7..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,9 +57,7 @@ public function __construct( $this->schema = $this->analyze->collectSchema() ? new Schema() : null; } - $this->counts = new RunCounts( - $this->analyze?->collectDatasetHash() === true ? $this->context->backend()->datasetHash() : null, - ); + $this->counts = new RunCounts($this->analyze?->newOutputHasher()); if ($this->readsColumns() && $this->context->config->launcher() !== null) { $this->context @@ -95,7 +93,7 @@ public function capture(Rows $rows): void } } - $this->counts->hashOutput($rows); + $this->counts->hashOutput($rows, $this->context->backend()); } /** 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..39a129330 --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php @@ -0,0 +1,69 @@ +absorbed = new DatasetHash(Hash::empty(), []); + } + + public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static + { + return new self(); + } + + public function describe(): ?Description + { + return new Description(self::class, []); + } + + public function add(Rows $rows, Backend $backend): void + { + $this->rows += $rows->count(); + ($this->hasher ??= $backend->groupedMultisetHashes())->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, [])); + } + + public function hash(): DatasetHash + { + return (new DatasetHash( + new Hash( + $this->rows, + type_string()->assert($this->hasher?->hashes()->physicals()[0] ?? MultisetDigest::empty()->hex()), + ), + [], + ))->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..1f48a95fb --- /dev/null +++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php @@ -0,0 +1,88 @@ + $partitions + */ + public function __construct( + public Hash $total, + public array $partitions, + ) {} + + /** + * @param array $data + * + * @throws InvalidArgumentException + */ + public static function fromArray(array $data): self + { + foreach (['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{total: array, partitions: list>} $data */ + return new self(Hash::fromArray($data['total']), array_map(PartitionHash::fromArray(...), $data['partitions'])); + } + + public function plus(self $other): self + { + $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)); + } + + /** + * @return array{total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>} + */ + public function normalize(): array + { + return [ + '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 7e42be5ef..1c5d54299 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php @@ -17,13 +17,13 @@ public function __construct( private ?Schema $schema, private Statistics $statistics, private ?array $sources, - private ?string $datasetHash = null, + 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>, dataset_hash: null|string} + * @return array{schema: null|array, statistics: array, sources: null|list>, dataset_hash: null|array{total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>}} */ public function normalize(): array { @@ -33,14 +33,11 @@ public function normalize(): array 'sources' => $this->sources === null ? null : array_map(static fn(SourceStatistics $source): array => $source->normalize(), $this->sources), - 'dataset_hash' => $this->datasetHash, + 'dataset_hash' => $this->datasetHash?->normalize(), ]; } - /** - * 32 lowercase hex characters; null when the run was not analyzed with a dataset hash. - */ - public function datasetHash(): ?string + public function datasetHash(): ?DatasetHash { return $this->datasetHash; } 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 5713c3949..fcee62fd5 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php @@ -144,11 +144,6 @@ public function rowHashes(array $columns, int $count): Column return $this->backend->rowHashes($columns, $count); } - public function datasetHash(): DatasetHash - { - return $this->backend->datasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { return $this->backend->groupedMultisetHashes(); 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 0cb4f248b..7a4b7138f 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/Backend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/Backend.php @@ -134,8 +134,6 @@ public function groupedCounts(): GroupedCounts; */ public function rowHashes(array $columns, int $count): Column; - public function datasetHash(): DatasetHash; - public function groupedMultisetHashes(): GroupedMultisetHashes; /** diff --git a/src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php b/src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php deleted file mode 100644 index 4e4d437a6..000000000 --- a/src/core/etl/src/Flow/ETL/Values/Column/DatasetHash.php +++ /dev/null @@ -1,23 +0,0 @@ - $columns - */ - public function add(array $columns, int $count): void; - - public function digest(): MultisetDigest; - - public function absorb(MultisetDigest $digest): void; -} diff --git a/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php b/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php index 5bbeaea80..df7bcf7b5 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/GroupedMultisetHashes.php @@ -19,11 +19,6 @@ public function add(array $columns, Column $ids): void; public function hashes(): Column; - /** - * @return list by group id - */ - public function partials(): array; - /** * @param array $into earlier group id => this group id */ diff --git a/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php b/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php index d3a8a27e5..0cccf8dce 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/MultisetDigest.php @@ -4,8 +4,12 @@ namespace Flow\ETL\Values\Column; -use function Flow\Types\DSL\type_integer; +use Flow\ETL\Foundation\Exception\InvalidArgumentException; + +use function hex2bin; +use function preg_match; use function sprintf; +use function unpack; final readonly class MultisetDigest { @@ -19,12 +23,19 @@ public static function empty(): self return new self(0, 0); } - /** - * @param array $data - */ - public static function fromArray(array $data): self + public static function fromHex(string $hex): self { - return new self(type_integer()->assert($data['low'] ?? null), type_integer()->assert($data['high'] ?? null)); + if (preg_match('/^[0-9a-f]{32}$/', $hex) !== 1) { + throw new InvalidArgumentException(sprintf( + 'A multiset digest is 32 lowercase hex characters, high lane first, given: "%s"', + $hex, + )); + } + + /** @var array{1: int, 2: int} $lanes */ + $lanes = unpack('J2', (string) hex2bin($hex)); + + return new self($lanes[2], $lanes[1]); } /** @@ -43,14 +54,6 @@ public function plus(self $other): self return new self(self::wrappingAdd($this->low, $other->low), self::wrappingAdd($this->high, $other->high)); } - /** - * @return array{low: int, high: int} - */ - public function normalize(): array - { - return ['low' => $this->low, 'high' => $this->high]; - } - public function hex(): string { return sprintf('%016x%016x', $this->high, $this->low); diff --git a/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php deleted file mode 100644 index 039e5cbf0..000000000 --- a/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpDatasetHash.php +++ /dev/null @@ -1,52 +0,0 @@ -digest = MultisetDigest::empty(); - } - - public function add(array $columns, int $count): void - { - $lowLow = 0; - $lowHigh = 0; - $highLow = 0; - $highHigh = 0; - - foreach ($this->encoding->named($columns, $count) as $bytes) { - /** @var array{1: int<0, max>, 2: int<0, max>, 3: int<0, max>, 4: int<0, max>} $halves */ - $halves = unpack('N4', hash('xxh128', $bytes, true)); - $highHigh += $halves[1]; - $highLow += $halves[2]; - $lowHigh += $halves[3]; - $lowLow += $halves[4]; - } - - $this->digest = $this->digest->plus(MultisetDigest::ofHalfSums($lowLow, $lowHigh, $highLow, $highHigh)); - } - - public function digest(): MultisetDigest - { - return $this->digest; - } - - public function absorb(MultisetDigest $digest): void - { - $this->digest = $this->digest->plus($digest); - } -} 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 index 8a0849b3b..0979cac29 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php @@ -79,14 +79,13 @@ public function hashes(): Column ); } - public function partials(): array - { - return $this->digests; - } - public function absorbEarlier(GroupedMultisetHashes $earlier, array $into): void { - $digests = $earlier->partials(); + $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); 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 c44389af0..94e72ee47 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php @@ -23,7 +23,6 @@ use Flow\ETL\Values\Column\Php\ConstantColumn; use Flow\ETL\Values\Column\Php\ListColumn; use Flow\ETL\Values\Column\Php\MapColumn; -use Flow\ETL\Values\Column\Php\PhpDatasetHash; use Flow\ETL\Values\Column\Php\PhpGroupedCounts; use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes; use Flow\ETL\Values\Column\Php\PhpGroupedTotals; @@ -684,11 +683,6 @@ public function rowHashes(array $columns, int $count): Column ); } - public function datasetHash(): DatasetHash - { - return new PhpDatasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { return new PhpGroupedMultisetHashes(); 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 90d4b44e4..e0824e45a 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php @@ -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; @@ -390,6 +392,11 @@ 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', + )), + WholeOutputHasher::class => static fn(): Describable => new WholeOutputHasher(), 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/Double/AcceptingBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php index 1d3540269..708d4ed63 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php @@ -7,7 +7,6 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; -use Flow\ETL\Values\Column\DatasetHash; use Flow\ETL\Values\Column\Frame\Codec; use Flow\ETL\Values\Column\GroupedCounts; use Flow\ETL\Values\Column\GroupedMultisetHashes; @@ -116,11 +115,6 @@ public function rowHashes(array $columns, int $count): Column return (new PhpBackend())->rowHashes($columns, $count); } - public function datasetHash(): DatasetHash - { - return (new PhpBackend())->datasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { return (new PhpBackend())->groupedMultisetHashes(); 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 8e2337a99..8c19b716f 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php @@ -7,7 +7,6 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; -use Flow\ETL\Values\Column\DatasetHash; use Flow\ETL\Values\Column\Frame\Codec; use Flow\ETL\Values\Column\GroupedCounts; use Flow\ETL\Values\Column\GroupedMultisetHashes; @@ -145,11 +144,6 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function datasetHash(): DatasetHash - { - return $this->php->datasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { return $this->php->groupedMultisetHashes(); 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 6c9878e66..0242381d8 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php @@ -7,7 +7,6 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; -use Flow\ETL\Values\Column\DatasetHash; use Flow\ETL\Values\Column\Frame\Codec; use Flow\ETL\Values\Column\GroupedCounts; use Flow\ETL\Values\Column\GroupedMultisetHashes; @@ -152,11 +151,6 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function datasetHash(): DatasetHash - { - return $this->php->datasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { return $this->php->groupedMultisetHashes(); 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 66c69a6ac..7e92b1877 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php @@ -7,7 +7,6 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\ColumnBuilder; -use Flow\ETL\Values\Column\DatasetHash; use Flow\ETL\Values\Column\Frame\Codec; use Flow\ETL\Values\Column\GroupedCounts; use Flow\ETL\Values\Column\GroupedMultisetHashes; @@ -34,7 +33,7 @@ final class SpyBackend implements Backend private int $groupedTotals = 0; - private int $datasetHashes = 0; + private int $groupedMultisetHashes = 0; private readonly PhpBackend $php; @@ -204,15 +203,10 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function datasetHash(): DatasetHash - { - $this->datasetHashes++; - - return $this->php->datasetHash(); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { + $this->groupedMultisetHashes++; + return $this->php->groupedMultisetHashes(); } @@ -221,9 +215,9 @@ public function groupedCountsCreated(): int return $this->groupedCounts; } - public function datasetHashesCreated(): int + public function groupedMultisetHashesCreated(): int { - return $this->datasetHashes; + return $this->groupedMultisetHashes; } /** 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 index a68ef27cc..294938042 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php @@ -4,18 +4,36 @@ namespace Flow\ETL\Tests\Integration\DataFrame; +use DateTimeImmutable; use Flow\ETL\Tests\FlowIntegrationTestCase; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\Filesystem\Partition; +use PHPUnit\Framework\Attributes\TestWith; +use function array_map; use function Flow\ETL\DSL\analyze; +use function Flow\ETL\DSL\date_schema; use function Flow\ETL\DSL\df; use function Flow\ETL\DSL\from_array; use function Flow\ETL\DSL\int_schema; use function Flow\ETL\DSL\multiset_hash; +use function Flow\ETL\DSL\overwrite; +use function Flow\ETL\DSL\partition_by; +use function Flow\ETL\DSL\ref; use function Flow\ETL\DSL\schema; +use function Flow\ETL\DSL\str_schema; +use function Flow\Floe\DSL\to_floe; +use function glob; use function hash; +use function implode; +use function ksort; +use function sort; +use function strlen; +use function substr; use function unpack; +use const GLOB_ONLYDIR; + final class DatasetHashTest extends FlowIntegrationTestCase { public const array ROWS = [ @@ -31,11 +49,18 @@ public function test_the_dataset_hash_does_not_depend_on_the_batch_size(): void df() ->read(from_array(self::ROWS)->withBatchSize(1)) ->run(analyze: analyze()->withDatasetHash()) - ->datasetHash(), + ->datasetHash() + ?->total + ->value, ); static::assertSame( '72c000bf6397e932faa3a3f30eeaa6db', - df()->read(from_array(self::ROWS))->run(analyze: analyze()->withDatasetHash())->datasetHash(), + df() + ->read(from_array(self::ROWS)) + ->run(analyze: analyze()->withDatasetHash()) + ->datasetHash() + ?->total + ->value, ); } @@ -59,7 +84,9 @@ public function test_rows_without_columns_hash_as_empty_rows(): void ->read(from_array(self::ROWS)) ->drop('id', 'price', 'payload') ->run(analyze: analyze()->withDatasetHash()) - ->datasetHash(), + ->datasetHash() + ?->total + ->value, ); } @@ -70,7 +97,67 @@ public function test_an_empty_dataset_hashes_to_zero(): void df() ->read(from_array([])->withSchema(schema(int_schema('id')))) ->run(analyze: analyze()->withDatasetHash()) - ->datasetHash(), + ->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/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 3b6fbef09..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,7 +30,7 @@ public static function of( ?Schema $schema = null, ?array $sources = null, ?Columns $columns = null, - ?string $datasetHash = null, + ?DatasetHash $datasetHash = null, ): Report { return new Report( $schema, 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 index 2b939b4ad..97b35755a 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashTest.php @@ -18,12 +18,9 @@ use function Flow\ETL\DSL\row_hash; use function Flow\ETL\DSL\schema; use function Flow\ETL\DSL\str_schema; -use function Flow\Types\DSL\type_integer; use function Flow\Types\DSL\type_list; use function Flow\Types\DSL\type_string; use function Flow\Types\DSL\type_structure; -use function hex2bin; -use function unpack; final class MultisetHashTest extends FlowTestCase { @@ -40,9 +37,7 @@ public function test_the_value_is_the_wrapping_lane_sum_of_the_row_hashes(): voi $summed = multiset_hash(); foreach ($rowHashes as $rowHash) { - /** @var array{1: int, 2: int} $lanes */ - $lanes = unpack('J2', (string) hex2bin($rowHash)); - $summed->merge(['low' => $lanes[2], 'high' => $lanes[1]], $backend); + $summed->merge(['hash' => $rowHash], $backend); } static::assertSame(['bdea5ee4847f3df6cb724988fb66ecd4', 'ba7c3390ce5fcedfea5c7d697dbe1ac9'], $rowHashes); @@ -118,23 +113,20 @@ public function test_merging_two_partials_equals_one_pass(): void $merged->merge($second->partial(), $backend); static::assertSame('7866927552df0cd5b5cec6f27925079d', $merged->value()); - static::assertSame(['low' => -5346116962925344867, 'high' => 8675782764775017685], $merged->partial()); + 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(['low' => 0, 'high' => 0], multiset_hash()->partial()); + 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(['low' => type_integer(), 'high' => type_integer()]), - multiset_hash()->partialType(), - ); + static::assertEquals(type_structure(['hash' => type_string()]), multiset_hash()->partialType()); } public function test_a_rebuilt_aggregate_keeps_its_references(): void @@ -163,7 +155,7 @@ public function test_with_children_refuses_another_number_of_children(): void public function test_a_named_column_the_batch_lacks_is_refused_with_a_suggestion(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Column "emal" does not exist. Did you mean one of the following? ["email"]'); + $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()); 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 index 077fa6a76..8f12242b9 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php @@ -22,7 +22,7 @@ public function test_each_group_hashes_its_rows_with_every_column_of_the_batch() $backend = new PhpBackend(); $schema = schema(str_schema('g'), int_schema('v')); $rows = array_to_rows([['g' => 'a', 'v' => 1], ['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema); - $hashes = new MultisetHashesByGroup(null, $backend->groupedMultisetHashes()); + $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); @@ -37,7 +37,7 @@ 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(null, $backend->groupedMultisetHashes()); + $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); $first = array_to_rows([['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema); $second = array_to_rows([['g' => 'a', 'v' => 1]], $schema); @@ -60,7 +60,7 @@ public function test_named_columns_hash_only_those_columns(): void $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); static::assertSame(['e0191505b9cce3349c6f8093cab56dec'], $hashes->groupValues(1, $backend)->values()); - static::assertSame([['low' => -7174374309128475156, 'high' => -2298783020459695308]], $hashes->partials(1)); + static::assertSame([['hash' => 'e0191505b9cce3349c6f8093cab56dec']], $hashes->partials(1)); } public function test_earlier_groups_are_absorbed_into_the_groups_they_map_to(): void @@ -69,8 +69,8 @@ public function test_earlier_groups_are_absorbed_into_the_groups_they_map_to(): $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(null, $backend->groupedMultisetHashes()); - $later = new MultisetHashesByGroup(null, $backend->groupedMultisetHashes()); + $earlier = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); + $later = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); $earlier->aggregateGroups($earlierRows, $backend->groupTable(['g'], $schema)->assign($earlierRows), $backend); $later->aggregateGroups($laterRows, $backend->groupTable(['g'], $schema)->assign($laterRows), $backend); @@ -87,7 +87,7 @@ public function test_it_absorbs_only_grouped_multiset_hashes(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Grouped multiset hashes absorb only other grouped multiset hashes'); - (new MultisetHashesByGroup(null, $backend->groupedMultisetHashes()))->absorbEarlier( + (new MultisetHashesByGroup([], $backend->groupedMultisetHashes()))->absorbEarlier( new CountsByGroup(null, $backend->groupedCounts()), [0 => 0], $backend, @@ -102,7 +102,7 @@ public function test_a_named_column_the_batch_lacks_is_refused_with_a_suggestion $hashes = new MultisetHashesByGroup(['valu'], $backend->groupedMultisetHashes()); $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Column "valu" does not exist. Did you mean one of the following? ["value"]'); + $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); } 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 index e9bb96f30..bc21cd24d 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/RowHashTest.php @@ -80,7 +80,7 @@ public function test_a_renamed_column_gives_another_hash(): void public function test_a_reference_the_batch_lacks_is_refused_with_a_suggestion(): void { $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage('Column "emal" does not exist. Did you mean one of the following? ["email"]'); + $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'))), 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/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/Runtime/AnalyzeTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php index afbbf2b9a..ad3fb7195 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php @@ -4,9 +4,13 @@ namespace Flow\ETL\Tests\Unit\Runtime; +use Flow\ETL\Runtime\Executor\PartitionedOutputHasher; +use Flow\ETL\Runtime\Executor\WholeOutputHasher; use Flow\ETL\Tests\FlowTestCase; use function Flow\ETL\DSL\analyze; +use function Flow\ETL\DSL\ref; +use function Flow\ETL\DSL\refs; final class AnalyzeTest extends FlowTestCase { @@ -14,9 +18,24 @@ public function test_the_dataset_hash_is_collected_only_when_asked(): void { $analyze = analyze(); - static::assertFalse($analyze->collectDatasetHash()); + static::assertNull($analyze->newOutputHasher()); static::assertSame($analyze, $analyze->withDatasetHash()); - static::assertTrue($analyze->collectDatasetHash()); + static::assertEquals(new WholeOutputHasher(), $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'))), + analyze()->withDatasetHash(ref('date'), ref('country'))->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..357f58aea --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/PartitionedOutputHasherTest.php @@ -0,0 +1,323 @@ +add(array_to_rows([ + ['country' => 'PL', 'id' => 1], + ['country' => 'PL', 'id' => 3], + ], $schema), new PhpBackend()); + $de = new WholeOutputHasher(); + $de->add(array_to_rows([['country' => 'DE', 'id' => 2]], $schema), new PhpBackend()); + $hasher = new PartitionedOutputHasher(refs('country')); + $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(); + $whole->add($rows, new PhpBackend()); + $hasher = new PartitionedOutputHasher(refs('country')); + $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')); + $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(); + $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')); + $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')); + $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')); + $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')); + $forward->add($utc, new PhpBackend()); + $forward->add($warsaw, new PhpBackend()); + $backward = new PartitionedOutputHasher(refs('at')); + $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')); + $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')))->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')))->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')))->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')); + $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')); + $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')); + $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')); + $all->add(array_to_rows([ + ['country' => 'PL', 'id' => 1], + ['country' => 'PL', 'id' => 2], + ], $schema), new PhpBackend()); + $worker = new PartitionedOutputHasher(refs('country')); + $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend()); + $hasher = new PartitionedOutputHasher(refs('country')); + $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')); + $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend()); + $hasher = new PartitionedOutputHasher(refs('country')); + $hasher->absorb($worker->hash()); + + static::assertEquals($worker->hash(), $hasher->hash()); + } + + public function test_describe_writes_no_state(): void + { + $hasher = new PartitionedOutputHasher(refs('country')); + $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'), []), + DescribeRoundTrip::rebuilt($hasher)->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'))))->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 1070cb128..0dace6da7 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,10 +4,16 @@ 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; @@ -17,12 +23,16 @@ 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; @@ -337,34 +347,38 @@ public function test_open_returns_the_same_read_per_extractor(): void public function test_absorb_leaves_the_output_hash_alone(): void { - $counts = new RunCounts((new PhpBackend())->datasetHash()); - $other = new RunCounts((new PhpBackend())->datasetHash()); - $other->absorbOutputHash(new MultisetDigest(1, 2), 1); + $counts = new RunCounts(new WholeOutputHasher()); + $other = new RunCounts(new WholeOutputHasher()); + $other->absorbOutputHash(new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [])); $counts->absorb($other); $counts->absorbWorkers($other); - static::assertSame('00000000000000000000000000000000', $counts->outputHash()); + static::assertEquals( + new DatasetHash(new Hash(0, '00000000000000000000000000000000'), []), + $counts->outputHash(), + ); } - public function test_without_the_hash_slot_nothing_is_hashed_and_no_hash_is_given(): void + public function test_without_a_hasher_nothing_is_hashed_and_no_hash_is_given(): void { $counts = new RunCounts(); - $counts->hashOutput(Rows::fromColumns(schema(), [], 3)); - $counts->absorbOutputHash(new MultisetDigest(1, 2), 1); + $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend()); + $counts->absorbOutputHash(new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [])); - static::assertFalse($counts->hashesOutput()); + static::assertNull($counts->outputHasher()); static::assertNull($counts->outputHash()); } public function test_rows_with_columns_are_hashed(): void { - $counts = new RunCounts((new PhpBackend())->datasetHash()); - $counts->hashOutput(array_to_rows([['a' => 2]], schema(int_schema('a')))); - $counts->hashOutput(array_to_rows([['a' => 1]], schema(int_schema('a')))); + $hasher = new WholeOutputHasher(); + $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::assertTrue($counts->hashesOutput()); - static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()); + static::assertSame($hasher, $counts->outputHasher()); + static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()?->total->value); } public function test_rows_without_columns_hash_as_empty_rows(): void @@ -372,25 +386,25 @@ 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 PhpBackend())->datasetHash()); - $counts->hashOutput(Rows::fromColumns(schema(), [], 3)); + $counts = new RunCounts(new WholeOutputHasher()); + $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend()); - static::assertSame($empty->plus($empty)->plus($empty)->hex(), $counts->outputHash()); + 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 PhpBackend())->datasetHash(); - $first->add(array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(), 1); - $second = (new PhpBackend())->datasetHash(); - $second->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); - $counts = new RunCounts((new PhpBackend())->datasetHash()); - $counts->absorbOutputHash($first->digest(), 1); - $counts->absorbOutputHash($second->digest(), 1); - $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); - $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); - - static::assertSame('721f4650154ebb88ac4ec50a605901df', $counts->outputHash()); + $first = new WholeOutputHasher(); + $first->add(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend()); + $second = new WholeOutputHasher(); + $second->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend()); + $counts = new RunCounts(new WholeOutputHasher()); + $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 @@ -398,14 +412,124 @@ public function test_rows_without_columns_beyond_the_covered_rows_hash_as_empty_ /** @var array{1: int, 2: int} $lanes */ $lanes = unpack('J2', hash('xxh128', '', true)); $empty = new MultisetDigest($lanes[2], $lanes[1]); - $worker = (new PhpBackend())->datasetHash(); - $worker->add(array_to_rows([['a' => 1], ['a' => 2], ['a' => 3]], schema(int_schema('a')))->columns(), 3); - $counts = new RunCounts((new PhpBackend())->datasetHash()); - $counts->absorbOutputHash($worker->digest(), 3); - $counts->hashOutput(Rows::fromColumns(schema(), [], 2)); - $counts->hashOutput(Rows::fromColumns(schema(), [], 2)); - $counts->hashOutput(Rows::fromColumns(schema(), [], 1)); - - static::assertSame($worker->digest()->plus($empty)->plus($empty)->hex(), $counts->outputHash()); + $worker = new WholeOutputHasher(); + $worker->add(array_to_rows([['a' => 1], ['a' => 2], ['a' => 3]], schema(int_schema('a'))), new PhpBackend()); + $counts = new RunCounts(new WholeOutputHasher()); + $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')); + $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'))); + $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'))); + + $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')); + $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'))); + $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(); + $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')); + $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'))); + $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'))); + $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 d2fcaf164..bbb7b0183 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,6 +11,9 @@ 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; @@ -20,6 +23,8 @@ 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; @@ -30,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; @@ -322,15 +328,19 @@ public function test_the_dataset_hash_is_the_multiset_hash_of_every_captured_row $collector->capture(array_to_rows([], schema(int_schema('a')))); $collector->capture(array_to_rows([['a' => 1]], schema(int_schema('a')))); - static::assertSame('721f4650154ebb88ac4ec50a605901df', $collector->report()->datasetHash()); + 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::assertSame( - '00000000000000000000000000000000', - (new StatisticsCollector(analyze()->withDatasetHash(), flow_context()))->report()->datasetHash(), + static::assertEquals( + new Hash(0, '00000000000000000000000000000000'), + (new StatisticsCollector(analyze()->withDatasetHash(), flow_context()))->report()->datasetHash()?->total, ); } @@ -345,7 +355,7 @@ public function test_without_the_dataset_hash_no_accumulator_is_created_and_none $collector->capture(array_to_rows([['a' => 1]], schema(int_schema('a')), $backend)); static::assertNull($collector->report()->datasetHash()); - static::assertSame(0, $backend->datasetHashesCreated()); + static::assertSame(0, $backend->groupedMultisetHashesCreated()); static::assertFalse( (new StatisticsCollector( analyze()->withSourceStatistics(), @@ -358,12 +368,13 @@ public function test_the_dataset_hash_takes_its_accumulator_from_the_context_bac { $backend = new SpyBackend(); - new StatisticsCollector( + $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->datasetHashesCreated()); + static::assertSame(1, $backend->groupedMultisetHashesCreated()); } public function test_the_dataset_hash_under_a_launcher_is_not_named_in_the_warning(): void @@ -391,7 +402,35 @@ public function test_the_dataset_hash_alone_under_a_launcher_keeps_the_writes_pa ); static::assertFalse($collector->readsColumns()); - static::assertTrue($collector->counts()?->hashesOutput()); + 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..272240071 --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Executor/WholeOutputHasherTest.php @@ -0,0 +1,74 @@ + 1], ['a' => 2]], schema(int_schema('a'))); + $kernel = (new PhpBackend())->groupedMultisetHashes(); + $kernel->add($rows->columns(), ColumnMother::of(int_schema('id'), [0, 0])); + $hasher = new WholeOutputHasher(); + $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'), []), $hasher->hash()); + static::assertSame([$hasher->hash()->total->value], $kernel->hashes()->physicals()); + } + + public function test_absorb_reads_only_the_total_of_a_partial(): void + { + $hasher = new WholeOutputHasher(); + $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')), + ])); + + static::assertEquals(new DatasetHash(new Hash(2, '721f4650154ebb88ac4ec50a605901df'), []), $hasher->hash()); + } + + public function test_a_hasher_that_saw_nothing_gives_the_empty_digest(): void + { + static::assertEquals( + new DatasetHash(new Hash(0, '00000000000000000000000000000000'), []), + (new WholeOutputHasher())->hash(), + ); + } + + public function test_a_hasher_whose_kernel_saw_no_row_gives_the_empty_digest(): void + { + $hasher = new WholeOutputHasher(); + $hasher->add(array_to_rows([], schema(int_schema('a'))), new PhpBackend()); + + static::assertEquals(new DatasetHash(new Hash(0, '00000000000000000000000000000000'), []), $hasher->hash()); + } + + public function test_describe_writes_no_state(): void + { + $hasher = new WholeOutputHasher(); + $hasher->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend()); + + static::assertEquals( + new DatasetHash(new Hash(0, '00000000000000000000000000000000'), []), + 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..131d0cecb --- /dev/null +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/Metrics/DatasetHashTest.php @@ -0,0 +1,214 @@ +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'), + ), + ]), (new DatasetHash(new Hash(1, '00000000000000000000000000000001'), [ + new PartitionHash( + new Partitions(new Partition('country', 'PL')), + new Hash(1, '00000000000000000000000000000001'), + ), + ]))->plus(new DatasetHash(new Hash(2, '00000000000000000000000000000002'), [ + new PartitionHash( + new Partitions(new Partition('country', 'PL')), + new Hash(2, '00000000000000000000000000000002'), + ), + ]))); + } + + 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]))->plus( + new DatasetHash(new Hash(1, '00000000000000000000000000000004'), [$us]), + )->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'), + ), + ]))->plus(new DatasetHash(Hash::empty(), []))->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'), + ), + ]))->plus(new DatasetHash(new Hash(1, '00000000000000000000000000000002'), [ + new PartitionHash( + new Partitions(new Partition('country', Partition::NULL_VALUE)), + new Hash(1, '00000000000000000000000000000002'), + ), + ]))->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'), + ), + ]); + + static::assertEquals($hash, $hash->plus(new DatasetHash(Hash::empty(), []))); + static::assertEquals($hash, (new DatasetHash(Hash::empty(), []))->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'), []), + (new DatasetHash(new Hash(2, 'ffffffffffffffffffffffffffffffff'), []))->plus( + new DatasetHash(new Hash(3, '00000000000000000000000000000001'), []), + ), + ); + } + + public function test_normalize_writes_the_total_and_each_partition(): void + { + static::assertSame( + [ + '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'), + ), + ]))->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'), + ), + ]); + + 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'), []); + + static::assertSame( + ['total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'], 'partitions' => []], + $hash->normalize(), + ); + static::assertEquals($hash, DatasetHash::fromArray($hash->normalize())); + } + + 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(['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([ + '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(['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 d1be3d784..7968e42ce 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; @@ -13,6 +16,8 @@ use Flow\ETL\Tests\Mother\ReportMother; use Flow\ETL\Values\Cardinality; 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; @@ -29,9 +34,18 @@ final class ReportTest extends FlowTestCase public function test_normalize_holds_what_the_typed_getters_hold_and_survives_json(): void { $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], datasetHash: '721f4650154ebb88ac4ec50a605901df'); + $report = ReportMother::of( + new Processes(Unit::fromBytes(25), [Unit::fromBytes(40)]), + 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'), + ), + ]), + ); $normalized = $report->normalize(); @@ -46,11 +60,19 @@ public function test_normalize_holds_what_the_typed_getters_hold_and_survives_js 'columns' => null, ], 'sources' => [$source->normalize()], - 'dataset_hash' => '721f4650154ebb88ac4ec50a605901df', + 'dataset_hash' => [ + 'total' => ['rows' => 2, 'value' => '721f4650154ebb88ac4ec50a605901df'], + 'partitions' => [ + [ + 'partitions' => ['country' => null], + 'hash' => ['rows' => 2, 'value' => '721f4650154ebb88ac4ec50a605901df'], + ], + ], + ], ], $normalized, ); - static::assertSame('721f4650154ebb88ac4ec50a605901df', $report->datasetHash()); + 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), 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 a6cd5eb1b..56798ec0d 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,6 @@ use Flow\ETL\Tests\Mother\RowsMother; use Flow\ETL\Values\Column\AdaptiveBackend; use Flow\ETL\Values\Column\Frame\NoopCodec; -use Flow\ETL\Values\Column\Php\PhpDatasetHash; use Flow\ETL\Values\Column\Php\PhpGroupedCounts; use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes; use Flow\ETL\Values\Column\Php\PhpGroupedTotals; @@ -303,7 +302,6 @@ public function test_row_hashes_and_multiset_hashes_are_the_php_backends(): void ->rowHashes($rows->columns(), 2) ->physicals(), ); - static::assertInstanceOf(PhpDatasetHash::class, (new AdaptiveBackend())->datasetHash()); static::assertInstanceOf(PhpGroupedMultisetHashes::class, (new AdaptiveBackend())->groupedMultisetHashes()); } } 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 index 8752c2be5..9bb080ea8 100644 --- 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 @@ -4,8 +4,8 @@ namespace Flow\ETL\Tests\Unit\Values\Column; +use Flow\ETL\Foundation\Exception\InvalidArgumentException; use Flow\ETL\Values\Column\MultisetDigest; -use Flow\Types\Exception\InvalidTypeException; use PHPUnit\Framework\TestCase; use const PHP_INT_MAX; @@ -35,27 +35,33 @@ public function test_half_sums_carry_the_low_halves_into_the_high_halves_and_wra ); } - public function test_normalize_and_from_array_round_trip_both_lanes(): void + public function test_from_hex_reads_back_both_lanes_at_the_limits(): void { - static::assertSame(['low' => -1, 'high' => PHP_INT_MIN], (new MultisetDigest(-1, PHP_INT_MIN))->normalize()); static::assertEquals( - new MultisetDigest(-1, PHP_INT_MIN), - MultisetDigest::fromArray((new MultisetDigest(-1, PHP_INT_MIN))->normalize()), + 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_array_refuses_a_lane_that_is_not_an_integer(): void + public function test_from_hex_refuses_a_string_that_is_not_32_lowercase_hex_characters(): void { - $this->expectException(InvalidTypeException::class); + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage( + 'A multiset digest is 32 lowercase hex characters, high lane first, given: "0000000000000000000000000000000"', + ); - MultisetDigest::fromArray(['low' => 1, 'high' => '2']); + MultisetDigest::fromHex('0000000000000000000000000000000'); } - public function test_from_array_refuses_a_missing_lane(): void + public function test_from_hex_refuses_uppercase_hex(): void { - $this->expectException(InvalidTypeException::class); + $this->expectException(InvalidArgumentException::class); - MultisetDigest::fromArray(['low' => 1]); + MultisetDigest::fromHex('0000000000000000000000000000000A'); } public function test_both_lanes_wrap_past_minus_one(): void diff --git a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php b/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php deleted file mode 100644 index 2e35f6f17..000000000 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/Php/PhpDatasetHashTest.php +++ /dev/null @@ -1,90 +0,0 @@ - 1]], schema(int_schema('a'))); - $hash = new PhpDatasetHash(); - $hash->add($rows->columns(), 1); - - static::assertSame('8e18789eac90baf2a1f6bc7cceafa11a', $hash->digest()->hex()); - static::assertSame( - (new PhpBackend()) - ->rowHashes($rows->columns(), 1) - ->physicals(), - [$hash->digest()->hex()], - ); - } - - public function test_row_order_does_not_count(): void - { - $forward = new PhpDatasetHash(); - $forward->add(array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(), 2); - $backward = new PhpDatasetHash(); - $backward->add(array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(), 1); - $backward->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); - - static::assertSame('721f4650154ebb88ac4ec50a605901df', $forward->digest()->hex()); - static::assertEquals($forward->digest(), $backward->digest()); - } - - public function test_a_duplicate_row_counts(): void - { - $hash = new PhpDatasetHash(); - $hash->add(array_to_rows([['a' => 1], ['a' => 1]], schema(int_schema('a')))->columns(), 2); - - static::assertSame('1c30f13d592175e443ed78f99d5f4234', $hash->digest()->hex()); - } - - public function test_a_row_of_only_nulls_counts_as_a_row(): void - { - $hash = new PhpDatasetHash(); - $hash->add(array_to_rows([['a' => null]], schema(int_schema('a', true)))->columns(), 1); - - static::assertSame('99aa06d3014798d86001c324468d497f', $hash->digest()->hex()); - } - - 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]); - $nulls = new PhpDatasetHash(); - $nulls->add(array_to_rows([['a' => null], ['a' => null]], schema(int_schema('a', true)))->columns(), 2); - $hash = new PhpDatasetHash(); - $hash->add([], 2); - - static::assertEquals($empty->plus($empty), $hash->digest()); - static::assertEquals($nulls->digest(), $hash->digest()); - } - - public function test_an_empty_hash_is_zero(): void - { - static::assertEquals(MultisetDigest::empty(), (new PhpDatasetHash())->digest()); - } - - public function test_absorb_adds_to_the_rows_already_hashed(): void - { - $hash = new PhpDatasetHash(); - $hash->add(array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), 1); - $hash->absorb(new MultisetDigest(745355142457024709, -2015697621351530346)); - - static::assertSame('721f4650154ebb88ac4ec50a605901df', $hash->digest()->hex()); - } -} 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 index 50709b072..9169ea070 100644 --- 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 @@ -8,6 +8,7 @@ use Flow\ETL\Tests\Mother\ColumnMother; use Flow\ETL\Values\Column\MultisetDigest; use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes; +use Flow\ETL\Values\Column\PhpBackend; use PHPUnit\Framework\TestCase; use function Flow\ETL\DSL\array_to_rows; @@ -44,7 +45,6 @@ public function test_a_group_below_the_highest_seen_one_is_zero(): void ['00000000000000000000000000000000', '8e18789eac90baf2a1f6bc7cceafa11a'], $hashes->hashes()->physicals(), ); - static::assertEquals(MultisetDigest::empty(), $hashes->partials()[0]); } public function test_no_rows_give_no_groups(): void @@ -53,10 +53,9 @@ public function test_no_rows_give_no_groups(): void $hashes->add([], ColumnMother::of(int_schema('id'), [])); static::assertSame([], $hashes->hashes()->physicals()); - static::assertSame([], $hashes->partials()); } - public function test_partials_are_the_digests_by_group(): void + public function test_hashes_are_the_digests_by_group(): void { $hashes = new PhpGroupedMultisetHashes(); $hashes->add( @@ -64,12 +63,9 @@ public function test_partials_are_the_digests_by_group(): void ColumnMother::of(int_schema('id'), [0, 1]), ); - static::assertEquals( - [ - new MultisetDigest(-6776021345102749414, -8207677697987396878), - new MultisetDigest(745355142457024709, -2015697621351530346), - ], - $hashes->partials(), + static::assertSame( + ['8e18789eac90baf2a1f6bc7cceafa11a', 'e406cdb168be00960a58088d91a960c5'], + $hashes->hashes()->physicals(), ); } @@ -108,6 +104,53 @@ public function test_a_batch_without_columns_hashes_each_row_as_the_empty_row(): 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(); + $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(); + $forward->add( + array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a')))->columns(), + ColumnMother::of(int_schema('id'), [0, 0]), + ); + $backward = new PhpGroupedMultisetHashes(); + $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(); + $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); 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 9a107119d..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'))))); 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 324db3541..1994bd2fa 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 @@ -146,11 +146,6 @@ public function rowHashes(array $columns, int $count): Column throw new RuntimeException('flow_php extension is not loaded'); } - public function datasetHash(): DatasetHash - { - throw new RuntimeException('flow_php extension is not loaded'); - } - public function groupedMultisetHashes(): GroupedMultisetHashes { throw new RuntimeException('flow_php extension is not loaded'); diff --git a/src/extension/flow-php-ext/src/backend.rs b/src/extension/flow-php-ext/src/backend.rs index d265298c4..04e237a1b 100644 --- a/src/extension/flow-php-ext/src/backend.rs +++ b/src/extension/flow-php-ext/src/backend.rs @@ -43,7 +43,7 @@ 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::{RustDatasetHash, RustGroupedMultisetHashes}; +use crate::multiset_hashes::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}; @@ -298,11 +298,6 @@ impl RustBackend { RustColumn::of_type(Arc::new(LargeBinaryArray::from_iter_values(hashes)), STRING_TYPE) } - #[php(name = "datasetHash")] - pub fn dataset_hash(&self) -> RustDatasetHash { - RustDatasetHash::default() - } - #[php(name = "groupedMultisetHashes")] pub fn grouped_multiset_hashes(&self) -> RustGroupedMultisetHashes { RustGroupedMultisetHashes::default() diff --git a/src/extension/flow-php-ext/src/interfaces.rs b/src/extension/flow-php-ext/src/interfaces.rs index 27e6428c5..5f46cbd1c 100644 --- a/src/extension/flow-php-ext/src/interfaces.rs +++ b/src/extension/flow-php-ext/src/interfaces.rs @@ -1,4 +1,4 @@ -//! `Flow\ETL\Foundation\Describe\Describable`, `Flow\ETL\Values\Column\{Column, ColumnBuilder, Backend, GroupedTotals, GroupedCounts, DatasetHash, GroupedMultisetHashes}`, `Flow\ETL\Values\Grouping\GroupTable`, `Flow\ETL\IO\Loader\File\FileWriter` and the CSV / JSON / Parquet +//! `Flow\ETL\Foundation\Describe\Describable`, `Flow\ETL\Values\Column\{Column, ColumnBuilder, Backend, GroupedTotals, GroupedCounts, GroupedMultisetHashes}`, `Flow\ETL\Values\Grouping\GroupTable`, `Flow\ETL\IO\Loader\File\FileWriter` and the CSV / JSON / Parquet //! adapters' encoder and open source contracts: registered at MINIT with the package //! files' exact signatures, so the extension's classes implement them and the package files (autoloaded only without //! flow_php) stay unused. @@ -20,9 +20,7 @@ const ROWS: DataType = DataType::object("Flow\\ETL\\Values\\Rows"); const SCHEMA: DataType = DataType::object("Flow\\ETL\\Values\\Schema"); const SCHEMA_INFERENCE: DataType = DataType::object("Flow\\ETL\\IO\\Inference\\SchemaInference"); const GROUPED_COUNTS: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedCounts"); -const DATASET_HASH: DataType = DataType::object("Flow\\ETL\\Values\\Column\\DatasetHash"); const GROUPED_MULTISET_HASHES: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedMultisetHashes"); -const MULTISET_DIGEST: DataType = DataType::object("Flow\\ETL\\Values\\Column\\MultisetDigest"); const GROUP_TABLE: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupTable"); const GROUP_IDS: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupIds"); const GROUPED_TOTALS: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedTotals"); @@ -43,7 +41,6 @@ static BACKEND_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUPED_TOTALS_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static DESCRIBABLE_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUPED_COUNTS_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); -static DATASET_HASH_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUPED_MULTISET_HASHES_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static GROUP_TABLE_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); static FILE_WRITER_CE: AtomicPtr = AtomicPtr::new(std::ptr::null_mut()); @@ -73,11 +70,6 @@ fn store_grouped_counts(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { GROUPED_COUNTS_CE.store(ce, Ordering::Release); } -fn store_dataset_hash(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { - keep(arg_info); - DATASET_HASH_CE.store(ce, Ordering::Release); -} - fn store_grouped_multiset_hashes(ce: &'static mut ClassEntry, arg_info: ArgInfoTables) { keep(arg_info); GROUPED_MULTISET_HASHES_CE.store(ce, Ordering::Release); @@ -153,10 +145,6 @@ pub fn grouped_counts_ce() -> &'static ClassEntry { load(&GROUPED_COUNTS_CE, "Flow\\ETL\\Values\\Column\\GroupedCounts") } -pub fn dataset_hash_ce() -> &'static ClassEntry { - load(&DATASET_HASH_CE, "Flow\\ETL\\Values\\Column\\DatasetHash") -} - pub fn grouped_multiset_hashes_ce() -> &'static ClassEntry { load( &GROUPED_MULTISET_HASHES_CE, @@ -333,19 +321,6 @@ pub fn register() -> Result<()> { ), ], )?; - interface( - "Flow\\ETL\\Values\\Column\\DatasetHash", - store_dataset_hash, - vec![ - method( - "add", - vec![Arg::new("columns", DataType::Array), Arg::new("count", DataType::Long)], - DataType::Void, - ), - method("digest", vec![], MULTISET_DIGEST), - method("absorb", vec![Arg::new("digest", MULTISET_DIGEST)], DataType::Void), - ], - )?; interface( "Flow\\ETL\\Values\\Column\\GroupedMultisetHashes", store_grouped_multiset_hashes, @@ -356,7 +331,6 @@ pub fn register() -> Result<()> { DataType::Void, ), method("hashes", vec![], COLUMN), - method("partials", vec![], DataType::Array), method( "absorbEarlier", vec![Arg::new("earlier", SELF), Arg::new("into", DataType::Array)], @@ -472,7 +446,6 @@ pub fn register() -> Result<()> { vec![Arg::new("columns", DataType::Array), Arg::new("count", DataType::Long)], COLUMN, ), - method("datasetHash", vec![], DATASET_HASH), method("groupedMultisetHashes", vec![], GROUPED_MULTISET_HASHES), method( "groupTable", diff --git a/src/extension/flow-php-ext/src/lib.rs b/src/extension/flow-php-ext/src/lib.rs index e8c26cb5e..346afd59c 100644 --- a/src/extension/flow-php-ext/src/lib.rs +++ b/src/extension/flow-php-ext/src/lib.rs @@ -81,7 +81,6 @@ pub fn get_module(module: ModuleBuilder) -> ModuleBuilder { .class::() .class::() .class::() - .class::() .class::() .class::() .class::() diff --git a/src/extension/flow-php-ext/src/multiset_hashes.rs b/src/extension/flow-php-ext/src/multiset_hashes.rs index c222da4d4..18511ae5e 100644 --- a/src/extension/flow-php-ext/src/multiset_hashes.rs +++ b/src/extension/flow-php-ext/src/multiset_hashes.rs @@ -1,82 +1,25 @@ -//! `Flow\ETL\Values\Column\{RustDatasetHash, RustGroupedMultisetHashes}`: wrapping sums of the row hash lanes, held -//! natively between batches, one sum for the dataset or one per group. +//! `Flow\ETL\Values\Column\RustGroupedMultisetHashes`: wrapping sums of the row hash lanes, held natively between +//! batches, one sum per group. use std::sync::Arc; use arrow_array::LargeBinaryArray; -use ext_php_rs::boxed::ZBox; -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::flags::ClassFlags; use ext_php_rs::prelude::*; use ext_php_rs::types::{ArrayKey, ZendHashTable, Zval}; use flow_column_kernels::canonical::row_lanes; use crate::canonical_rows::{named, row_columns, STRING_TYPE}; use crate::column::RustColumn; -use crate::ctx::{call_method, construct, expect_object, find_class, read_property, zval_long}; +use crate::ctx::call_method; use crate::exception::ext_exception; use crate::grouped_totals::group_ids; -use crate::interfaces::{dataset_hash_ce, grouped_multiset_hashes_ce}; +use crate::interfaces::grouped_multiset_hashes_ce; use crate::render::invalid_argument; -const MULTISET_DIGEST: &str = "Flow\\ETL\\Values\\Column\\MultisetDigest"; - /// [low, high] type Lanes = [u64; 2]; -/// A `MultisetDigest` object, so `digest()` declares that return type. -pub struct DigestValue(Zval); - -impl IntoZval for DigestValue { - const TYPE: DataType = DataType::object(MULTISET_DIGEST); - const NULLABLE: bool = false; - - fn set_zval(self, zv: &mut Zval, _persistent: bool) -> ZvalResult<()> { - *zv = self.0; - - Ok(()) - } -} - -#[php_class] -#[php( - name = "Flow\\ETL\\Values\\Column\\RustDatasetHash", - flags = ClassFlags::Final, - implements(ce = dataset_hash_ce, stub = "Flow\\ETL\\Values\\Column\\DatasetHash") -)] -#[derive(Default)] -pub struct RustDatasetHash { - lanes: Lanes, -} - -#[php_impl] -impl RustDatasetHash { - pub fn add(&mut 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(); - - for index in 0..count { - named(&mut row, &mut entries, &resolved, index); - add_lanes(&mut self.lanes, row_lanes(&row).into()); - } - - Ok(()) - } - - pub fn digest(&self) -> PhpResult { - Ok(DigestValue(digest(self.lanes)?)) - } - - pub fn absorb(&mut self, digest: &Zval) -> PhpResult<()> { - add_lanes(&mut self.lanes, lanes_of(digest)?); - - Ok(()) - } -} - #[php_class] #[php( name = "Flow\\ETL\\Values\\Column\\RustGroupedMultisetHashes", @@ -118,23 +61,13 @@ impl RustGroupedMultisetHashes { RustColumn::of_type(Arc::new(LargeBinaryArray::from_iter_values(hashes)), STRING_TYPE) } - pub fn partials(&self) -> PhpResult> { - let mut partials = ZendHashTable::with_capacity(self.lanes.len() as u32); - - for lanes in &self.lanes { - partials.push(digest(*lanes)?)?; - } - - Ok(partials) - } - #[php(name = "absorbEarlier")] pub fn absorb_earlier(&mut self, earlier: &Zval, into: &ZendHashTable) -> PhpResult<()> { let lanes = match earlier.extract::<&RustGroupedMultisetHashes>() { Some(native) => native.lanes.clone(), - None => call_method(earlier, "partials", &mut [])? + None => call_method(&call_method(earlier, "hashes", &mut [])?, "physicals", &mut [])? .array() - .ok_or_else(|| ext_exception("flow_php expected GroupedMultisetHashes::partials() to return an array"))? + .ok_or_else(|| ext_exception("flow_php expected Column::physicals() to return an array"))? .values() .map(lanes_of) .collect::>>()?, @@ -176,29 +109,19 @@ fn add_lanes(lanes: &mut Lanes, [low, high]: Lanes) { lanes[1] = lanes[1].wrapping_add(high); } -fn digest([low, high]: Lanes) -> PhpResult { - let mut object = construct( - find_class(MULTISET_DIGEST)?, - &mut [zval_long(low as i64), zval_long(high as i64)], - )?; - let mut zv = Zval::new(); - zv.set_object(&mut object); - - Ok(zv) -} - -fn lanes_of(digest: &Zval) -> PhpResult { - let object = expect_object(digest, "a MultisetDigest")?; - let lane = |name: &str| { - read_property(object, name)? - .long() - .map(|lane| lane as u64) - .ok_or_else(|| { - ext_exception(format!( - "flow_php expected the '{name}' lane of a MultisetDigest as an int" - )) - }) - }; - - Ok([lane("low")?, lane("high")?]) +fn lanes_of(hex: &Zval) -> PhpResult { + let hex = hex + .str() + .ok_or_else(|| ext_exception("flow_php expected a multiset hash as a string"))?; + let lowercase_hex = hex.len() == 32 && hex.bytes().all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f')); + let digest = u128::from_str_radix(hex, 16) + .ok() + .filter(|_| lowercase_hex) + .ok_or_else(|| { + invalid_argument(format!( + "A multiset digest is 32 lowercase hex characters, high lane first, given: \"{hex}\"" + )) + })?; + + Ok([digest as u64, (digest >> 64) as u64]) } diff --git a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt index eb2506be6..4f1ae80a1 100644 --- a/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt +++ b/src/extension/flow-php-ext/tests/phpt/001_extension_loaded.phpt @@ -46,14 +46,12 @@ interface Flow\ETL\IO\Loader\File\FileWriter interface Flow\ETL\Values\Column\Backend interface Flow\ETL\Values\Column\Column interface Flow\ETL\Values\Column\ColumnBuilder -interface Flow\ETL\Values\Column\DatasetHash interface Flow\ETL\Values\Column\GroupedCounts interface Flow\ETL\Values\Column\GroupedMultisetHashes interface Flow\ETL\Values\Column\GroupedTotals class Flow\ETL\Values\Column\RustBackend implements Flow\ETL\Values\Column\Backend, Flow\ETL\Foundation\Describe\Describable class Flow\ETL\Values\Column\RustColumn implements Flow\ETL\Values\Column\Column class Flow\ETL\Values\Column\RustColumnBuilder implements Flow\ETL\Values\Column\ColumnBuilder -class Flow\ETL\Values\Column\RustDatasetHash implements Flow\ETL\Values\Column\DatasetHash class Flow\ETL\Values\Column\RustGroupedCounts implements Flow\ETL\Values\Column\GroupedCounts class Flow\ETL\Values\Column\RustGroupedMultisetHashes implements Flow\ETL\Values\Column\GroupedMultisetHashes class Flow\ETL\Values\Column\RustGroupedTotals implements Flow\ETL\Values\Column\GroupedTotals diff --git a/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt index 431ec6e92..07c92620c 100644 --- a/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt @@ -1,12 +1,12 @@ --TEST-- -RustBackend::rowHashes(), datasetHash() and groupedMultisetHashes() give the hashes PhpBackend gives: every tag, the canonical edge cases, a native map with the key "1", positioned and bare xml elements, columns from either backend, batches split differently, batches without columns, digests, partials, absorb and absorbEarlier +RustBackend::rowHashes() and groupedMultisetHashes() give the hashes PhpBackend gives: every tag, the canonical edge cases, a native map with the key "1", positioned and bare xml elements, columns from either backend, batches split differently, batches without columns, one group, absorbEarlier and the carry between lanes --SKIPIF-- --FILE-- [all_types_schema(), all_types_values()], 'edge cases' => $edges]; $rows = static fn(Backend $backend, Rows $source): Rows => $source->adoptedBy($backend); -$lanes = static fn(MultisetDigest $digest): array => [$digest->low, $digest->high]; -$hashes = static function (Backend $backend, Rows $rows, int $batch, ?array $ids = null) use ($lanes): array { - $dataset = $backend->datasetHash(); +$hashes = static function (Backend $backend, Rows $rows, int $batch, ?array $ids = null): array { + $ids ??= array_fill(0, $rows->count(), 0); $grouped = $backend->groupedMultisetHashes(); foreach ($rows->chunks($batch) as $index => $part) { - $ids === null - ? $dataset->add($part->columns(), $part->count()) - : $grouped->add($part->columns(), array_to_rows( - array_map(static fn(int $id): array => ['id' => $id], array_slice($ids, $index * $batch, $part->count())), - schema(int_schema('id')), - $backend, - )->column('id')); + $grouped->add($part->columns(), array_to_rows( + array_map(static fn(int $id): array => ['id' => $id], array_slice($ids, $index * $batch, $part->count())), + schema(int_schema('id')), + $backend, + )->column('id')); } - return $ids === null - ? [$dataset->digest()->hex(), $lanes($dataset->digest())] - : [$grouped->hashes()->physicals(), array_map($lanes, $grouped->partials())]; + return $grouped->hashes()->physicals(); }; foreach ($cases as $label => [$schema, $values]) { @@ -108,32 +103,41 @@ $phpInto->absorbEarlier($direct, [0 => 0, 1 => 1, 2 => 2]); echo 'absorbEarlier of php, native and into php: ', $intoPhp->hashes()->physicals() === $direct->hashes()->physicals() && $intoNative->hashes()->physicals() === $direct->hashes()->physicals() && $phpInto->hashes()->physicals() === $direct->hashes()->physicals() - && array_map($lanes, $intoPhp->partials()) === array_map($lanes, $fromPhp->partials()) ? 'same' : 'MISMATCH', "\n"; + && $intoPhp->hashes()->physicals() === $fromPhp->hashes()->physicals() ? 'same' : 'MISMATCH', "\n"; echo 'unseen group: ', $direct->hashes()->physicals()[1], "\n"; -echo 'empty: ', $rust->datasetHash()->digest()->hex(), ' ', json_encode($rust->groupedMultisetHashes()->hashes()->physicals()), ' ', json_encode($rust->groupedMultisetHashes()->partials()), "\n"; +echo 'empty: ', json_encode($rust->groupedMultisetHashes()->hashes()->physicals()), "\n"; $withoutColumns = static function (Backend $backend): array { - $dataset = $backend->datasetHash(); - $dataset->add([], 3); + $one = $backend->groupedMultisetHashes(); + $one->add([], array_to_rows([['id' => 0], ['id' => 0], ['id' => 0]], schema(int_schema('id')), $backend)->column('id')); $grouped = $backend->groupedMultisetHashes(); $grouped->add([], array_to_rows([['id' => 1], ['id' => 0], ['id' => 1]], schema(int_schema('id')), $backend)->column('id')); - return [$dataset->digest()->hex(), $grouped->hashes()->physicals()]; + return [$one->hashes()->physicals(), $grouped->hashes()->physicals()]; }; echo 'batch without columns: ', $withoutColumns($rust) === $withoutColumns($php) ? 'same' : 'MISMATCH', ' ', json_encode($withoutColumns($rust)), "\n"; -$datasetFromPhp = $php->datasetHash(); -$datasetFromPhp->add($source->columns(), $source->count()); -$absorbed = $rust->datasetHash(); -$absorbed->absorb($datasetFromPhp->digest()); -$datasetDirect = $rust->datasetHash(); -$datasetDirect->add($source->adoptedBy($rust)->columns(), $source->count()); -echo 'absorb of a php digest: ', $absorbed->digest() == $datasetDirect->digest() ? 'same' : 'MISMATCH', "\n"; - -$carry = $rust->datasetHash(); -$carry->absorb(new MultisetDigest(0xFFFFFFFF, PHP_INT_MAX)); -$carry->absorb(new MultisetDigest(0xFFFFFFFF, 1)); -echo 'carry: ', $carry->digest()->hex(), ' ', json_encode($lanes($carry->digest())), "\n"; +$earlier = static fn(string $hex): GroupedMultisetHashes => new class($hex) implements GroupedMultisetHashes { + public function __construct(private readonly string $hex) {} + public function add(array $columns, Column $ids): void {} + public function hashes(): Column { return array_to_rows([['h' => $this->hex]], schema(str_schema('h')), new PhpBackend())->column('h'); } + public function absorbEarlier(GroupedMultisetHashes $earlier, array $into): void {} +}; +$carry = $rust->groupedMultisetHashes(); +$carry->absorbEarlier($earlier((new MultisetDigest(0xFFFFFFFF, PHP_INT_MAX))->hex()), [0 => 0]); +$carry->absorbEarlier($earlier((new MultisetDigest(0xFFFFFFFF, 1))->hex()), [0 => 0]); +echo 'carry: ', $carry->hashes()->physicals()[0], "\n"; + +foreach (['uppercase' => '0000000000000000000000000000000A', 'sign' => '+0000000000000000000000000000000'] as $label => $hex) { + foreach (['php' => $php, 'rust' => $rust] as $side => $backend) { + try { + $backend->groupedMultisetHashes()->absorbEarlier($earlier($hex), [0 => 0]); + echo "{$label} into {$side}: accepted\n"; + } catch (Throwable $e) { + echo "{$label} into {$side}: ", $e::class, ': ', $e->getMessage(), "\n"; + } + } +} try { $rust->groupedMultisetHashes()->absorbEarlier($rust->groupedMultisetHashes(), [3 => 0]); @@ -151,10 +155,13 @@ edge cases: same native map with the key "1": native, same absorbEarlier of php, native and into php: same unseen group: 00000000000000000000000000000000 -empty: 00000000000000000000000000000000 [] [] -batch without columns: same ["ccfe147903d6ca882005496cd3a7dc7d",["99aa06d3014798d86001c324468d497f","33540da6028f31b0c00386488d1a92fe"]] -absorb of a php digest: same -carry: 800000000000000000000001fffffffe [8589934590,-9223372036854775808] +empty: [] +batch without columns: same [["ccfe147903d6ca882005496cd3a7dc7d"],["99aa06d3014798d86001c324468d497f","33540da6028f31b0c00386488d1a92fe"]] +carry: 800000000000000000000001fffffffe +uppercase into php: Flow\ETL\Foundation\Exception\InvalidArgumentException: A multiset digest is 32 lowercase hex characters, high lane first, given: "0000000000000000000000000000000A" +uppercase into rust: Flow\ETL\Foundation\Exception\InvalidArgumentException: A multiset digest is 32 lowercase hex characters, high lane first, given: "0000000000000000000000000000000A" +sign into php: Flow\ETL\Foundation\Exception\InvalidArgumentException: A multiset digest is 32 lowercase hex characters, high lane first, given: "+0000000000000000000000000000000" +sign into rust: Flow\ETL\Foundation\Exception\InvalidArgumentException: A multiset digest is 32 lowercase hex characters, high lane first, given: "+0000000000000000000000000000000" missing earlier group: Flow\ETL\Foundation\Exception\InvalidArgumentException: Earlier group 3 has no hash only nulls: 99aa06d3014798d86001c324468d497f no columns: ["99aa06d3014798d86001c324468d497f","99aa06d3014798d86001c324468d497f"] diff --git a/src/extension/flow-php-ext/tests/phpt/bootstrap.php b/src/extension/flow-php-ext/tests/phpt/bootstrap.php index 6cdc568e2..c7dbd4696 100644 --- a/src/extension/flow-php-ext/tests/phpt/bootstrap.php +++ b/src/extension/flow-php-ext/tests/phpt/bootstrap.php @@ -332,7 +332,6 @@ function interfaces_reflection(): string 'Flow\\ETL\\Values\\Column\\Backend', 'Flow\\ETL\\Values\\Column\\Column', 'Flow\\ETL\\Values\\Column\\ColumnBuilder', - 'Flow\\ETL\\Values\\Column\\DatasetHash', 'Flow\\ETL\\Values\\Column\\GroupedCounts', 'Flow\\ETL\\Values\\Column\\GroupedMultisetHashes', 'Flow\\ETL\\Values\\Column\\GroupedTotals', diff --git a/src/lib/filesystem/src/Flow/Filesystem/Partition.php b/src/lib/filesystem/src/Flow/Filesystem/Partition.php index 5c767c653..c413d5399 100644 --- a/src/lib/filesystem/src/Flow/Filesystem/Partition.php +++ b/src/lib/filesystem/src/Flow/Filesystem/Partition.php @@ -50,10 +50,6 @@ public function __construct( if ('' === $this->name) { throw new InvalidArgumentException("Partition name can't be empty"); } - - if ('' === $this->value) { - throw new InvalidArgumentException("Partition value can't be empty"); - } } public static function decode(string $segment): string @@ -92,7 +88,7 @@ public static function fromSegment(string $segment): ?self { $matches = []; - if (!preg_match('/^([^=]+)=([^=]+)$/', $segment, $matches)) { + if (!preg_match('/^([^=]+)=([^=]*)$/', $segment, $matches)) { return null; } @@ -114,11 +110,38 @@ public static function fromUri(string $uri): Partitions return new Partitions(...$partitions); } + /** + * @param Type $type + * + * @throws InvalidArgumentException + */ + public static function assertPartitionable(string $name, Type $type): void + { + if ( + $type instanceof HTMLType + || $type instanceof HTMLElementType + || $type instanceof XMLType + || $type instanceof XMLElementType + || $type instanceof JsonType + || $type instanceof ListType + || $type instanceof StructureType + || $type instanceof MapType + ) { + throw new InvalidArgumentException(sprintf( + 'Column "%s" of type %s can\'t be used as a partition', + $name, + $type->toString(), + )); + } + } + /** * @param Type $type */ public static function fromValue(string $name, Type $type, mixed $value): string { + self::assertPartitionable($name, $type); + if ($type instanceof DateTimeType) { $datetime = $type->cast($type->assert($value)); @@ -142,23 +165,6 @@ public static function fromValue(string $name, Type $type, mixed $value): string } } - if ( - $type instanceof HTMLType - || $type instanceof HTMLElementType - || $type instanceof XMLType - || $type instanceof XMLElementType - || $type instanceof JsonType - || $type instanceof ListType - || $type instanceof StructureType - || $type instanceof MapType - ) { - throw new InvalidArgumentException(sprintf( - 'Column "%s" of type %s can\'t be used as a partition', - $name, - $type->toString(), - )); - } - return (new TypedValueFormatter())->format($type, $value); } diff --git a/src/lib/filesystem/tests/Flow/Filesystem/Tests/Unit/PartitionTest.php b/src/lib/filesystem/tests/Flow/Filesystem/Tests/Unit/PartitionTest.php index 471ae04be..043c2f257 100644 --- a/src/lib/filesystem/tests/Flow/Filesystem/Tests/Unit/PartitionTest.php +++ b/src/lib/filesystem/tests/Flow/Filesystem/Tests/Unit/PartitionTest.php @@ -17,13 +17,51 @@ use function Flow\Types\DSL\type_datetime; use function Flow\Types\DSL\type_float; use function Flow\Types\DSL\type_html; +use function Flow\Types\DSL\type_html_element; use function Flow\Types\DSL\type_integer; +use function Flow\Types\DSL\type_json; +use function Flow\Types\DSL\type_list; +use function Flow\Types\DSL\type_map; +use function Flow\Types\DSL\type_string; +use function Flow\Types\DSL\type_structure; use function Flow\Types\DSL\type_xml; +use function Flow\Types\DSL\type_xml_element; use function ini_get; use function ini_set; final class PartitionTest extends TestCase { + public static function unpartitionable_types(): Generator + { + yield 'html' => [type_html(), 'html']; + yield 'html element' => [type_html_element(), 'html_element']; + yield 'xml' => [type_xml(), 'xml']; + yield 'xml element' => [type_xml_element(), 'xml_element']; + yield 'json' => [type_json(), 'json']; + yield 'list' => [type_list(type_integer()), 'list']; + yield 'structure' => [type_structure(['a' => type_integer()]), 'structure{a: integer}']; + yield 'map' => [type_map(type_string(), type_integer()), 'map']; + } + + /** + * @param Type $type + */ + #[DataProvider('unpartitionable_types')] + public function test_assert_partitionable_refuses_a_type_without_a_folder_name(Type $type, string $name): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Column "c" of type ' . $name . ' can\'t be used as a partition'); + + Partition::assertPartitionable('c', $type); + } + + public function test_assert_partitionable_accepts_a_scalar_type(): void + { + Partition::assertPartitionable('c', type_float()); + + $this->addToAssertionCount(1); + } + /** * @return array> */ @@ -176,12 +214,31 @@ public function test_a_null_value_is_written_and_read_back_as_the_hive_sentinel( ); } - public function test_an_empty_value_is_still_refused(): void + public function test_an_empty_value_is_written_and_read_back_apart_from_null(): void { - $this->expectException(InvalidArgumentException::class); - $this->expectExceptionMessage("Partition value can't be empty"); + static::assertSame('region=', (new Partition('region', ''))->segment()); + static::assertSame('region', Partition::fromSegment('region=')?->name); + static::assertSame('', Partition::fromSegment('region=')?->value); + } - new Partition('name', ''); + public function test_creating_partitions_from_uri_reads_an_empty_value(): void + { + static::assertSame( + ['country' => '', 'year' => '2026'], + array_column( + array_map(static fn(Partition $p): array => [ + 'name' => $p->name, + 'value' => $p->value, + ], Partition::fromUri('/dataset/country=/year=2026/file.parquet')->toArray()), + 'value', + 'name', + ), + ); + } + + public function test_a_segment_without_a_name_is_not_a_partition(): void + { + static::assertNull(Partition::fromSegment('=value')); } public function test_an_empty_name_is_still_refused(): void From e37bf743b0bef1c339d053e8d36f3b8c7a255483 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Sun, 22 Nov 2026 14:35:54 -0600 Subject: [PATCH 3/5] docs(flow-php/etl): hashing page - row, group, run and partition hashes on one page with run examples - null and empty partition values in partitioning --- documentation/components/core/aggregations.md | 141 +----------- documentation/components/core/core.md | 3 +- documentation/components/core/hashing.md | 205 ++++++++++++++++++ documentation/components/core/partitioning.md | 40 ++++ .../documentation/navigation_left.html.twig | 1 + 5 files changed, 250 insertions(+), 140 deletions(-) create mode 100644 documentation/components/core/hashing.md diff --git a/documentation/components/core/aggregations.md b/documentation/components/core/aggregations.md index 3caf6a75f..d03662e24 100644 --- a/documentation/components/core/aggregations.md +++ b/documentation/components/core/aggregations.md @@ -110,145 +110,8 @@ df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'), e ## Hashing rows -A sync job writes orders partitioned by day and country. The partition hashes tell which folders changed since the -last run: - -```php -read($externalOrders->withSchema($orders)) - ->write(to_parquet('orders')->partitionBy(partition_by('date', 'country'))) - ->run(analyze: analyze()->withDatasetHash(ref('date'), ref('country'))); - -$previous = file_exists('orders.hashes.json') - ? json_decode((string) file_get_contents('orders.hashes.json'), true, flags: JSON_THROW_ON_ERROR) - : []; -$current = []; - -foreach ($report->datasetHash()->partitions as $partition) { - $segments = array_map(static fn(Partition $p): string => $p->segment(), $partition->partitions->toArray()); - $current[implode('/', $segments)] = $partition->hash->value; -} - -$changed = array_keys(array_diff_assoc($current, $previous)); // ['date=2026-11-20/country=PL', ...] -$removed = array_keys(array_diff_key($previous, $current)); -file_put_contents('orders.hashes.json', json_encode($current)); -``` - -A partition hash covers every column of every row of the partition. The named columns only group the rows. -`$report->datasetHash()->total` is the hash of all rows: `->value` is the hash and `->rows` is the number of rows. -It equals the hash of `withDatasetHash()` without columns, and then `->partitions` is `[]`. `$partition->hash->rows` -is the number of rows of one partition. - -`PartitionHash::normalize()` gives the stored form of one entry, -`['partitions' => ['date' => '2026-11-20', 'country' => 'PL'], 'hash' => ['rows' => 120, 'value' => '...']]`. -`PartitionHash::fromArray()` reads it back. - -```php -plus($tuesday->datasetHash()); - -$week->total->value; // '31be1d609a26d996382e2a23855ebbe5', the hash of one run over both days -$week->partitions; // PL: 2 rows, DE: 1 row -``` - -`plus()` adds the totals and the partitions with the same values. The result equals the hash of one run over the -rows of both. - -A null value is the partition `__HIVE_DEFAULT_PARTITION__`, as the loader writes it: -`country=__HIVE_DEFAULT_PARTITION__`. - -A list, map, structure, json, xml or html column cannot be named. A float column cannot be named either, because -`0.0` and `-0.0` are one value but two folder names. Cast it first: - -```php -read($rates)->run(analyze: analyze()->withDatasetHash(ref('rate'))); -// analyze()->withDatasetHash() cannot group by the float column "rate": 0.0 and -0.0 are one value but two partition -// names. Cast it to a decimal string or an integer first. - -data_frame() - ->read($rates) - ->withColumn('rate_key', ref('rate')->cast(type_string())) - ->run(analyze: analyze()->withDatasetHash(ref('rate_key'))); -``` - -The key column `rate_key` is part of the output, so it is part of every partition hash. - -Declare the schema of the partition columns, as in the first sample. Then the hash of a partition is the same between -runs and between workers. The batch size, the order of the files and the number of workers do not change a hash. - -```php - 1, 'country' => 'PL'], ['id' => 2, 'country' => 'DE'], ['id' => 3, 'country' => 'PL']]; - -df()->read(from_array($rows))->withColumn('row_id', row_hash(ref('id'), ref('country')))->fetch(); -// row_id: '61d8d2f77533f36e5f23e4e587fa5e41', '01d6077fd12ee579f3a83a381ebfa16f', 'ce0f42e953c400afe5620b05dea4bc35' - -df()->read(from_array($rows))->aggregate([multiset_hash()])->fetch(); -// _multiset_hash: '31be1d609a26d996382e2a23855ebbe5' - -df()->read(from_array($rows))->groupBy('country')->aggregate(multiset_hash(ref('id')))->fetch(); -// PL: 'ab8476f29c95212a306bffff897d7afb', DE: 'f3aebd664d56cdeceed04ea04775ad52' - -df()->read(from_array($rows))->run(analyze: analyze()->withDatasetHash())->datasetHash()->total->value; -// '31be1d609a26d996382e2a23855ebbe5' -``` - -Duplicate rows count, and the order of the rows and of the columns does not. - -The hash detects accidental differences. It does not resist tampering. - -Declare the schema to keep the hash the same across runs: an inferred type can depend on the inference budget. - -Json is hashed as its stored text, so whitespace and key order count. - -```php -read(from_array([['id' => 1, 'country' => 'PL']]))->withColumn('row_id', row_hash(ref('id'), ref('countr')))->fetch(); -// SchemaDefinitionNotFoundException: Schema definition for column "countr" not found. Did you mean one of: [country]? -``` - -A named column must exist. `multiset_hash()` without names and the dataset hash take the columns of each batch, and -a column that a batch lacks hashes like a null. - -`hash()` is the digest of the text of one value. `row_hash()` is the typed hash of the named columns: - -```php -read(from_array([['country' => 'PL']]))->withColumn('digest', hash(ref('country'), 'sha256'))->fetch(); -// '293650de072648b9e2790509d8109d0f34f655edfe0b20075b0eaf6a93e95646' - -df()->read(from_array([['country' => 'PL']])) - ->withColumn('digest', ref('country')->hash(hash_algorithm('xxh64', options: ['seed' => 7]))) - ->fetch(); -// '30aa8eee14870cd7' -``` +`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 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..6202e93f5 --- /dev/null +++ b/documentation/components/core/hashing.md @@ -0,0 +1,205 @@ +# 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->total->rows; // 3 +$written->total->value; // 'f2920d3f120d5130873032ec79839580' +$stored->total->value; // 'f2920d3f120d5130873032ec79839580', the copy is complete +``` + +## 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())); + +// {"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. + +## 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 71dcede26..1248fbf26 100644 --- a/documentation/components/core/partitioning.md +++ b/documentation/components/core/partitioning.md @@ -144,6 +144,46 @@ Flow writes each value in full. A typed read gets the value back without changes | `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`: ```php diff --git a/web/landing/templates/documentation/navigation_left.html.twig b/web/landing/templates/documentation/navigation_left.html.twig index 7154f7ecc..035acd3be 100644 --- a/web/landing/templates/documentation/navigation_left.html.twig +++ b/web/landing/templates/documentation/navigation_left.html.twig @@ -66,6 +66,7 @@
  • {{ nav.nav_link('/documentation/components/core/caching', 'Caching', currentPath) }}
  • {{ nav.nav_link('/documentation/components/core/floe', 'Floe File Format', currentPath) }}
  • {{ nav.nav_link('/documentation/components/core/partitioning', 'Partitioning', currentPath) }}
  • +
  • {{ nav.nav_link('/documentation/components/core/hashing', 'Hashing', currentPath) }}
  • {{ nav.nav_link('/documentation/components/core/statistics', 'Source Statistics', currentPath) }}
  • {{ nav.nav_link('/documentation/components/core/constraints', 'Constraints', currentPath) }}
  • {{ nav.nav_link('/documentation/components/core/schema', 'Schema', currentPath) }}
  • From 8772119daa46a5dabb54e037d0ae1a96106b6671 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Sun, 22 Nov 2026 18:56:39 -0600 Subject: [PATCH 4/5] feat(flow-php/etl): dataset hash algorithm - MultisetHashAlgorithm: xxh128, md5, sha256 - withDatasetHash(array $partitions, MultisetHashAlgorithm $algorithm) - DatasetHash reports its algorithm - plus() refuses hashes of different algorithms - flow_php extension hashes with the same algorithms --- documentation/components/core/hashing.md | 53 +++- documentation/upgrading.md | 10 +- .../src/Flow/ETL/Functions/MultisetHash.php | 8 +- src/core/etl/src/Flow/ETL/Runtime/Analyze.php | 17 +- .../Executor/PartitionedOutputHasher.php | 15 +- .../Runtime/Executor/WholeOutputHasher.php | 17 +- .../Flow/ETL/Runtime/Metrics/DatasetHash.php | 33 ++- .../src/Flow/ETL/Runtime/Metrics/Report.php | 2 +- .../ETL/Values/Column/AdaptiveBackend.php | 4 +- .../src/Flow/ETL/Values/Column/Backend.php | 2 +- .../Values/Column/MultisetHashAlgorithm.php | 32 +++ .../Column/Php/PhpGroupedMultisetHashes.php | 4 +- .../src/Flow/ETL/Values/Column/PhpBackend.php | 4 +- .../ETL/Tests/Context/DescribableFixtures.php | 13 +- .../ETL/Tests/Double/AcceptingBackend.php | 5 +- .../Double/FixedProcessMemoryBackend.php | 5 +- .../Tests/Double/ReportedMemoryBackend.php | 5 +- .../Flow/ETL/Tests/Double/SpyBackend.php | 5 +- .../Integration/DataFrame/DatasetHashTest.php | 18 +- .../Functions/MultisetHashesByGroupTest.php | 20 +- .../ETL/Tests/Unit/Runtime/AnalyzeTest.php | 19 +- .../Executor/PartitionedOutputHasherTest.php | 78 ++++-- .../Unit/Runtime/Executor/RunCountsTest.php | 47 ++-- .../Executor/StatisticsCollectorTest.php | 2 +- .../Executor/WholeOutputHasherTest.php | 70 ++++-- .../Unit/Runtime/Metrics/DatasetHashTest.php | 232 +++++++++++++----- .../Tests/Unit/Runtime/Metrics/ReportTest.php | 22 +- .../Values/Column/AdaptiveBackendTest.php | 6 +- .../Column/MultisetHashAlgorithmTest.php | 25 ++ .../Php/PhpGroupedMultisetHashesTest.php | 45 +++- src/extension/flow-php-ext/Cargo.lock | 93 ++++++- src/extension/flow-php-ext/Cargo.toml | 2 + .../crates/flow-column-kernels/Cargo.toml | 2 + .../flow-column-kernels/src/canonical.rs | 37 ++- .../Flow/ETL/Values/Column/RustBackend.php | 2 +- src/extension/flow-php-ext/src/backend.rs | 26 +- src/extension/flow-php-ext/src/interfaces.rs | 7 +- .../flow-php-ext/src/multiset_hashes.rs | 15 +- .../tests/phpt/125_row_hashes_parity.phpt | 42 ++-- 39 files changed, 782 insertions(+), 262 deletions(-) create mode 100644 src/core/etl/src/Flow/ETL/Values/Column/MultisetHashAlgorithm.php create mode 100644 src/core/etl/tests/Flow/ETL/Tests/Unit/Values/Column/MultisetHashAlgorithmTest.php diff --git a/documentation/components/core/hashing.md b/documentation/components/core/hashing.md index 6202e93f5..39d54b8c3 100644 --- a/documentation/components/core/hashing.md +++ b/documentation/components/core/hashing.md @@ -6,12 +6,12 @@ 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('...'))` | +| 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 @@ -129,11 +129,46 @@ $stored = data_frame() ->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 @@ -146,7 +181,7 @@ use function Flow\ETL\DSL\{analyze, data_frame, partition_by, ref}; $report = data_frame() ->read(from_csv('orders.csv')->withSchema($orders)) ->write(to_parquet('orders/orders.parquet')->partitionBy(partition_by('date'))) - ->run(analyze: analyze()->withDatasetHash(ref('date'))); + ->run(analyze: analyze()->withDatasetHash([ref('date')])); $current = []; @@ -186,7 +221,7 @@ use Flow\ETL\Runtime\Metrics\DatasetHash; file_put_contents('monday.json', json_encode($monday->datasetHash()->normalize())); -// {"total":{"rows":1,"value":"61d8d2f77533f36e5f23e4e587fa5e41"},"partitions":[]} +// {"algorithm":"xxh128","total":{"rows":1,"value":"61d8d2f77533f36e5f23e4e587fa5e41"},"partitions":[]} $stored = json_decode(file_get_contents('monday.json'), true); $week = DatasetHash::fromArray($stored)->plus($tuesday->datasetHash()); @@ -195,7 +230,7 @@ $week->total->rows; // 3 $week->total->value; // '31be1d609a26d996382e2a23855ebbe5', equal to one run over both days ``` -`plus()` also adds the partitions with the same values. +`plus()` also adds the partitions with the same values. If the two hashes have different algorithms, `plus()` throws. ## Rules diff --git a/documentation/upgrading.md b/documentation/upgrading.md index 78a618d72..181d52349 100644 --- a/documentation/upgrading.md +++ b/documentation/upgrading.md @@ -71,11 +71,11 @@ Catch `Flow\ETL\Foundation\Exception\InvalidArgumentException` instead of `\Inva ### 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(): GroupedMultisetHashes` | -| `FLOW_PHP_ABI` 3 | `FLOW_PHP_ABI` 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. diff --git a/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php index f00a83181..f9d28de7b 100644 --- a/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php +++ b/src/core/etl/src/Flow/ETL/Functions/MultisetHash.php @@ -12,6 +12,7 @@ use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\GroupedMultisetHashes; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Rows; use Flow\ETL\Values\Schema\Definitions; use Flow\Types\Type; @@ -58,7 +59,7 @@ public function aggregate(Rows $rows, array $indices, Backend $backend): void $names = $this->names(); $columns = $names === [] ? $rows->columns() : $rows->select(...$names)->columns(); - ($this->hash ??= $backend->groupedMultisetHashes())->add( + ($this->hash ??= $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128))->add( count($indices) === $rows->count() ? $columns : array_map(static fn(Column $column): Column => $column->take($indices), $columns), @@ -85,7 +86,10 @@ public function partialType(): StructureType public function grouped(Backend $backend): GroupedAggregation { - return new MultisetHashesByGroup($this->names(), $backend->groupedMultisetHashes()); + return new MultisetHashesByGroup( + $this->names(), + $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128), + ); } /** diff --git a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php index dd8da927c..0f60d8f05 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Analyze.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Analyze.php @@ -9,6 +9,7 @@ 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 { @@ -20,6 +21,8 @@ final class Analyze private ?References $datasetHashBy = null; + private MultisetHashAlgorithm $datasetHashAlgorithm; + public function __construct() {} public function collectColumnStatistics(): bool @@ -48,14 +51,20 @@ public function newOutputHasher(): ?OutputHasher { return match (true) { $this->datasetHashBy === null => null, - $this->datasetHashBy->count() === 0 => new WholeOutputHasher(), - default => new PartitionedOutputHasher($this->datasetHashBy), + $this->datasetHashBy->count() === 0 => new WholeOutputHasher($this->datasetHashAlgorithm), + default => new PartitionedOutputHasher($this->datasetHashBy, $this->datasetHashAlgorithm), }; } - public function withDatasetHash(Reference ...$partitions): self - { + /** + * @param array $partitions + */ + public function withDatasetHash( + array $partitions = [], + MultisetHashAlgorithm $algorithm = MultisetHashAlgorithm::xxh128, + ): self { $this->datasetHashBy = new References(...$partitions); + $this->datasetHashAlgorithm = $algorithm; return $this; } diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/PartitionedOutputHasher.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/PartitionedOutputHasher.php index 90677ba94..3570764cf 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Executor/PartitionedOutputHasher.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/PartitionedOutputHasher.php @@ -16,6 +16,7 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\GroupedCounts; use Flow\ETL\Values\Column\GroupedMultisetHashes; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Grouping\GroupTable; use Flow\ETL\Values\Rows; use Flow\ETL\Values\Schema; @@ -50,20 +51,24 @@ final class PartitionedOutputHasher implements OutputHasher public function __construct( private readonly References $by, + private readonly MultisetHashAlgorithm $algorithm, ) { - $this->absorbed = new DatasetHash(Hash::empty(), []); + $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)); + 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]); + return Description::compose(self::class, ['by' => $this->by, 'algorithm' => $this->algorithm->value]); } public function add(Rows $rows, Backend $backend): void @@ -91,7 +96,7 @@ public function add(Rows $rows, Backend $backend): void } $ids = $this->table->assign($rows); - ($this->digests ??= $backend->groupedMultisetHashes())->add($rows->columns(), $ids->ids); + ($this->digests ??= $backend->groupedMultisetHashes($this->algorithm))->add($rows->columns(), $ids->ids); ($this->rows ??= $backend->groupedCounts())->add($ids->ids, $ids->ids); if ($ids->firstRows === []) { @@ -122,7 +127,7 @@ public function hash(): DatasetHash $total = $total->plus($local[$id]->hash); } - return $this->absorbed->plus(new DatasetHash($total, $local)); + return $this->absorbed->plus(new DatasetHash($total, $local, $this->algorithm)); } private static function missing(string $column): InvalidArgumentException diff --git a/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php b/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php index 39a129330..c8885153f 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Executor/WholeOutputHasher.php @@ -11,6 +11,7 @@ use Flow\ETL\Values\Column\Backend; use Flow\ETL\Values\Column\GroupedMultisetHashes; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Rows; use Flow\ETL\Values\Schema\Definitions; use SensitiveParameter; @@ -26,25 +27,26 @@ final class WholeOutputHasher implements OutputHasher private DatasetHash $absorbed; - public function __construct() - { - $this->absorbed = new DatasetHash(Hash::empty(), []); + public function __construct( + private readonly MultisetHashAlgorithm $algorithm, + ) { + $this->absorbed = new DatasetHash(Hash::empty(), [], $algorithm); } public static function fromDescription(#[SensitiveParameter] array $data, Rebuild $rebuild): static { - return new self(); + return new self(MultisetHashAlgorithm::named(type_string()->assert($data['algorithm'] ?? null))); } public function describe(): ?Description { - return new Description(self::class, []); + 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())->add($rows->columns(), $backend->constant( + ($this->hasher ??= $backend->groupedMultisetHashes($this->algorithm))->add($rows->columns(), $backend->constant( Definitions::of('group', type_integer()), 0, $rows->count(), @@ -53,7 +55,7 @@ public function add(Rows $rows, Backend $backend): void public function absorb(DatasetHash $partial): void { - $this->absorbed = $this->absorbed->plus(new DatasetHash($partial->total, [])); + $this->absorbed = $this->absorbed->plus(new DatasetHash($partial->total, [], $partial->algorithm)); } public function hash(): DatasetHash @@ -64,6 +66,7 @@ public function hash(): DatasetHash 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 index 1f48a95fb..891610f43 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/DatasetHash.php @@ -5,6 +5,7 @@ namespace Flow\ETL\Runtime\Metrics; use Flow\ETL\Foundation\Exception\InvalidArgumentException; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\Filesystem\Partition; use function array_key_exists; @@ -12,6 +13,7 @@ use function array_values; use function Flow\Types\DSL\type_array; use function Flow\Types\DSL\type_list; +use function Flow\Types\DSL\type_string; use function json_encode; use function sprintf; @@ -25,6 +27,7 @@ public function __construct( public Hash $total, public array $partitions, + public MultisetHashAlgorithm $algorithm, ) {} /** @@ -34,7 +37,11 @@ public function __construct( */ public static function fromArray(array $data): self { - foreach (['total' => type_array(), 'partitions' => type_list(type_array())] as $key => $type) { + 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', @@ -44,12 +51,27 @@ public static function fromArray(array $data): self } } - /** @var array{total: array, partitions: list>} $data */ - return new self(Hash::fromArray($data['total']), array_map(PartitionHash::fromArray(...), $data['partitions'])); + /** @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) { @@ -69,15 +91,16 @@ public function plus(self $other): self : $partition; } - return new self($this->total->plus($other->total), array_values($partitions)); + return new self($this->total->plus($other->total), array_values($partitions), $this->algorithm); } /** - * @return array{total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>} + * @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(), 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 1c5d54299..aaf8c5c27 100644 --- a/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php +++ b/src/core/etl/src/Flow/ETL/Runtime/Metrics/Report.php @@ -23,7 +23,7 @@ public function __construct( /** * 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>, dataset_hash: null|array{total: array{rows: int, value: string}, partitions: list, hash: array{rows: int, value: string}}>}} + * @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 { 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 fcee62fd5..0651b89cf 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/AdaptiveBackend.php @@ -144,9 +144,9 @@ public function rowHashes(array $columns, int $count): Column return $this->backend->rowHashes($columns, $count); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { - return $this->backend->groupedMultisetHashes(); + return $this->backend->groupedMultisetHashes($algorithm); } /** 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 7a4b7138f..045a66be1 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/Backend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/Backend.php @@ -134,7 +134,7 @@ public function groupedCounts(): GroupedCounts; */ public function rowHashes(array $columns, int $count): Column; - public function groupedMultisetHashes(): GroupedMultisetHashes; + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes; /** * @param list $columns 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 index 0979cac29..14c77e637 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/Php/PhpGroupedMultisetHashes.php @@ -9,6 +9,7 @@ use Flow\ETL\Values\Column\Column; use Flow\ETL\Values\Column\GroupedMultisetHashes; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Column\Physical\PhysicalFor; use function array_map; @@ -27,6 +28,7 @@ final class PhpGroupedMultisetHashes implements GroupedMultisetHashes private array $digests = []; public function __construct( + private readonly MultisetHashAlgorithm $algorithm, private readonly CanonicalEncoding $encoding = new CanonicalEncoding(), ) {} @@ -51,7 +53,7 @@ public function add(array $columns, Column $ids): void 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('xxh128', $bytes, true)); + $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]; 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 94e72ee47..24d2a28e5 100644 --- a/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php +++ b/src/core/etl/src/Flow/ETL/Values/Column/PhpBackend.php @@ -683,9 +683,9 @@ public function rowHashes(array $columns, int $count): Column ); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { - return new PhpGroupedMultisetHashes(); + return new PhpGroupedMultisetHashes($algorithm); } public function groupTable(array $columns, Schema $declared): GroupTable 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 e0824e45a..456bf5a43 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Context/DescribableFixtures.php @@ -115,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; @@ -392,11 +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', - )), - WholeOutputHasher::class => static fn(): Describable => new WholeOutputHasher(), + 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/Double/AcceptingBackend.php b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php index 708d4ed63..559e9bb5b 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/AcceptingBackend.php @@ -11,6 +11,7 @@ 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; @@ -115,9 +116,9 @@ public function rowHashes(array $columns, int $count): Column return (new PhpBackend())->rowHashes($columns, $count); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { - return (new PhpBackend())->groupedMultisetHashes(); + return (new PhpBackend())->groupedMultisetHashes($algorithm); } /** 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 8c19b716f..e8dd4539a 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/FixedProcessMemoryBackend.php @@ -11,6 +11,7 @@ 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; @@ -144,9 +145,9 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { - return $this->php->groupedMultisetHashes(); + return $this->php->groupedMultisetHashes($algorithm); } /** 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 0242381d8..8baff3c82 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/ReportedMemoryBackend.php @@ -11,6 +11,7 @@ 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; @@ -151,9 +152,9 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { - return $this->php->groupedMultisetHashes(); + return $this->php->groupedMultisetHashes($algorithm); } /** 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 7e92b1877..73c93ce0b 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Double/SpyBackend.php @@ -11,6 +11,7 @@ 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; @@ -203,11 +204,11 @@ public function rowHashes(array $columns, int $count): Column return $this->php->rowHashes($columns, $count); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { $this->groupedMultisetHashes++; - return $this->php->groupedMultisetHashes(); + return $this->php->groupedMultisetHashes($algorithm); } public function groupedCountsCreated(): int 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 index 294938042..001b2062f 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Integration/DataFrame/DatasetHashTest.php @@ -7,6 +7,7 @@ use DateTimeImmutable; use Flow\ETL\Tests\FlowIntegrationTestCase; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\Filesystem\Partition; use PHPUnit\Framework\Attributes\TestWith; @@ -72,6 +73,21 @@ public function test_the_dataset_hash_equals_the_multiset_hash_aggregate(): void ); } + 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 */ @@ -123,7 +139,7 @@ public function test_a_partitioned_write_gets_one_partition_hash_per_folder(int ->saveMode(overwrite()) ->partitionBy(partition_by('date', 'country')), ) - ->run(analyze: analyze()->withDatasetHash(ref('date'), ref('country'))) + ->run(analyze: analyze()->withDatasetHash([ref('date'), ref('country')])) ->datasetHash(); $folders = []; 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 index 8f12242b9..78adffe41 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Functions/MultisetHashesByGroupTest.php @@ -8,6 +8,7 @@ use Flow\ETL\Functions\CountsByGroup; use Flow\ETL\Functions\MultisetHashesByGroup; use Flow\ETL\Tests\FlowTestCase; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Column\PhpBackend; use function Flow\ETL\DSL\array_to_rows; @@ -22,7 +23,7 @@ public function test_each_group_hashes_its_rows_with_every_column_of_the_batch() $backend = new PhpBackend(); $schema = schema(str_schema('g'), int_schema('v')); $rows = array_to_rows([['g' => 'a', 'v' => 1], ['g' => 'a', 'v' => 2], ['g' => 'b', 'v' => 1]], $schema); - $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); + $hashes = new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)); $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); @@ -37,7 +38,7 @@ 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()); + $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); @@ -55,7 +56,7 @@ 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()); + $hashes = new MultisetHashesByGroup(['v'], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)); $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); @@ -69,8 +70,8 @@ public function test_earlier_groups_are_absorbed_into_the_groups_they_map_to(): $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()); - $later = new MultisetHashesByGroup([], $backend->groupedMultisetHashes()); + $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); @@ -87,7 +88,7 @@ public function test_it_absorbs_only_grouped_multiset_hashes(): void $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Grouped multiset hashes absorb only other grouped multiset hashes'); - (new MultisetHashesByGroup([], $backend->groupedMultisetHashes()))->absorbEarlier( + (new MultisetHashesByGroup([], $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)))->absorbEarlier( new CountsByGroup(null, $backend->groupedCounts()), [0 => 0], $backend, @@ -99,7 +100,7 @@ public function test_a_named_column_the_batch_lacks_is_refused_with_a_suggestion $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()); + $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]?'); @@ -112,7 +113,10 @@ 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()); + $hashes = new MultisetHashesByGroup( + ['missing'], + $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128), + ); $hashes->aggregateGroups($rows, $backend->groupTable(['g'], $schema)->assign($rows), $backend); 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 index ad3fb7195..f82a76d51 100644 --- a/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php +++ b/src/core/etl/tests/Flow/ETL/Tests/Unit/Runtime/AnalyzeTest.php @@ -7,6 +7,7 @@ use Flow\ETL\Runtime\Executor\PartitionedOutputHasher; use Flow\ETL\Runtime\Executor\WholeOutputHasher; use Flow\ETL\Tests\FlowTestCase; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use function Flow\ETL\DSL\analyze; use function Flow\ETL\DSL\ref; @@ -20,15 +21,27 @@ public function test_the_dataset_hash_is_collected_only_when_asked(): void static::assertNull($analyze->newOutputHasher()); static::assertSame($analyze, $analyze->withDatasetHash()); - static::assertEquals(new WholeOutputHasher(), $analyze->newOutputHasher()); + 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'))), - analyze()->withDatasetHash(ref('date'), ref('country'))->newOutputHasher(), + 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(), ); } 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 index 357f58aea..07dba8309 100644 --- 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 @@ -13,6 +13,7 @@ use Flow\ETL\Runtime\Metrics\Hash; use Flow\ETL\Runtime\Metrics\PartitionHash; use Flow\ETL\Tests\Context\DescribeRoundTrip; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Column\PhpBackend; use Flow\Filesystem\Exception\InvalidArgumentException as PartitionException; use Flow\Filesystem\Partition; @@ -36,14 +37,14 @@ final class PartitionedOutputHasherTest extends TestCase public function test_each_partition_hashes_every_column_of_its_rows_over_batches(): void { $schema = schema(str_schema('country'), int_schema('id')); - $pl = new WholeOutputHasher(); + $pl = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $pl->add(array_to_rows([ ['country' => 'PL', 'id' => 1], ['country' => 'PL', 'id' => 3], ], $schema), new PhpBackend()); - $de = new WholeOutputHasher(); + $de = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $de->add(array_to_rows([['country' => 'DE', 'id' => 2]], $schema), new PhpBackend()); - $hasher = new PartitionedOutputHasher(refs('country')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add(array_to_rows([ ['country' => 'PL', 'id' => 1], ['country' => 'DE', 'id' => 2], @@ -67,9 +68,9 @@ public function test_the_total_equals_the_hash_of_the_whole_output(): void ['country' => 'DE', 'id' => 2], ['country' => 'PL', 'id' => 3], ], $schema); - $whole = new WholeOutputHasher(); + $whole = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $whole->add($rows, new PhpBackend()); - $hasher = new PartitionedOutputHasher(refs('country')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add($rows, new PhpBackend()); static::assertEquals($whole->hash()->total, $hasher->hash()->total); @@ -78,7 +79,7 @@ public function test_the_total_equals_the_hash_of_the_whole_output(): void 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')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add(array_to_rows([ ['country' => null, 'id' => 1], ['country' => null, 'id' => 2], @@ -94,13 +95,13 @@ public function test_a_null_partition_value_is_one_partition_with_the_rows_of_th 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(); + $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')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add($rows, new PhpBackend()); static::assertCount(1, $hasher->hash()->partitions); @@ -110,7 +111,7 @@ public function test_null_and_the_null_folder_name_are_one_partition(): void public function test_an_empty_string_and_null_are_two_partitions(): void { - $hasher = new PartitionedOutputHasher(refs('country')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add( array_to_rows( [ @@ -134,7 +135,7 @@ public function test_an_empty_string_and_null_are_two_partitions(): void 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')); + $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'], @@ -150,10 +151,10 @@ public function test_one_datetime_instant_gives_one_partition_in_either_batch_or $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')); + $forward = new PartitionedOutputHasher(refs('at'), MultisetHashAlgorithm::xxh128); $forward->add($utc, new PhpBackend()); $forward->add($warsaw, new PhpBackend()); - $backward = new PartitionedOutputHasher(refs('at')); + $backward = new PartitionedOutputHasher(refs('at'), MultisetHashAlgorithm::xxh128); $backward->add($warsaw, new PhpBackend()); $backward->add($utc, new PhpBackend()); @@ -163,7 +164,7 @@ public function test_one_datetime_instant_gives_one_partition_in_either_batch_or public function test_a_later_batch_of_another_type_names_its_partition_in_the_declared_type(): void { - $hasher = new PartitionedOutputHasher(refs('day')); + $hasher = new PartitionedOutputHasher(refs('day'), MultisetHashAlgorithm::xxh128); $hasher->add( array_to_rows( [['day' => new DateTimeImmutable('2026-11-19'), 'id' => 1]], @@ -196,7 +197,7 @@ public function test_a_float_partition_column_is_refused(): void . 'partition names. Cast it to a decimal string or an integer first.', ); - (new PartitionedOutputHasher(refs('price')))->add(array_to_rows([[ + (new PartitionedOutputHasher(refs('price'), MultisetHashAlgorithm::xxh128))->add(array_to_rows([[ 'price' => 1.5, ]], schema(float_schema('price'))), new PhpBackend()); } @@ -206,7 +207,7 @@ 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')))->add(array_to_rows([[ + (new PartitionedOutputHasher(refs('payload'), MultisetHashAlgorithm::xxh128))->add(array_to_rows([[ 'payload' => '{"a":1}', ]], schema(json_schema('payload'))), new PhpBackend()); } @@ -219,14 +220,14 @@ public function test_a_first_batch_without_a_named_column_is_refused(): void . 'that every row of the output has.', ); - (new PartitionedOutputHasher(refs('country')))->add(array_to_rows([[ + (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')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add( array_to_rows( [['country' => null, 'id' => 1]], @@ -242,7 +243,7 @@ public function test_a_later_batch_without_a_nullable_named_column_hashes_into_t public function test_a_later_batch_without_a_non_nullable_named_column_is_refused(): void { - $hasher = new PartitionedOutputHasher(refs('country')); + $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(), @@ -258,7 +259,7 @@ public function test_a_later_batch_without_a_non_nullable_named_column_is_refuse public function test_an_empty_batch_first_does_not_fix_the_columns(): void { - $hasher = new PartitionedOutputHasher(refs('country')); + $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'))), @@ -271,14 +272,14 @@ public function test_an_empty_batch_first_does_not_fix_the_columns(): void 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')); + $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')); + $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend()); - $hasher = new PartitionedOutputHasher(refs('country')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->add(array_to_rows([['country' => 'PL', 'id' => 1]], $schema), new PhpBackend()); $hasher->absorb($worker->hash()); @@ -288,9 +289,9 @@ public function test_absorb_merges_a_partial_into_the_partition_with_the_same_va 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')); + $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $worker->add(array_to_rows([['country' => 'PL', 'id' => 2]], $schema), new PhpBackend()); - $hasher = new PartitionedOutputHasher(refs('country')); + $hasher = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $hasher->absorb($worker->hash()); static::assertEquals($worker->hash(), $hasher->hash()); @@ -298,24 +299,47 @@ public function test_absorb_into_an_empty_hasher_gives_the_partial_with_its_tota public function test_describe_writes_no_state(): void { - $hasher = new PartitionedOutputHasher(refs('country')); + $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'), []), + 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'))))->add( + (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 0dace6da7..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 @@ -20,6 +20,7 @@ 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; @@ -347,15 +348,17 @@ public function test_open_returns_the_same_read_per_extractor(): void public function test_absorb_leaves_the_output_hash_alone(): void { - $counts = new RunCounts(new WholeOutputHasher()); - $other = new RunCounts(new WholeOutputHasher()); - $other->absorbOutputHash(new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [])); + $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'), []), + new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128), $counts->outputHash(), ); } @@ -364,7 +367,9 @@ public function test_without_a_hasher_nothing_is_hashed_and_no_hash_is_given(): { $counts = new RunCounts(); $counts->hashOutput(Rows::fromColumns(schema(), [], 3), new PhpBackend()); - $counts->absorbOutputHash(new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [])); + $counts->absorbOutputHash( + new DatasetHash(new Hash(1, '00000000000000020000000000000001'), [], MultisetHashAlgorithm::xxh128), + ); static::assertNull($counts->outputHasher()); static::assertNull($counts->outputHash()); @@ -372,7 +377,7 @@ public function test_without_a_hasher_nothing_is_hashed_and_no_hash_is_given(): public function test_rows_with_columns_are_hashed(): void { - $hasher = new WholeOutputHasher(); + $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()); @@ -386,7 +391,7 @@ 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()); + $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); @@ -394,11 +399,11 @@ public function test_rows_without_columns_hash_as_empty_rows(): void public function test_rows_without_columns_that_absorbed_digests_cover_are_hashed_only_by_those_digests(): void { - $first = new WholeOutputHasher(); + $first = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $first->add(array_to_rows([['a' => 2]], schema(int_schema('a'))), new PhpBackend()); - $second = new WholeOutputHasher(); + $second = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $second->add(array_to_rows([['a' => 1]], schema(int_schema('a'))), new PhpBackend()); - $counts = new RunCounts(new WholeOutputHasher()); + $counts = new RunCounts(new WholeOutputHasher(MultisetHashAlgorithm::xxh128)); $counts->absorbOutputHash($first->hash()); $counts->absorbOutputHash($second->hash()); $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend()); @@ -412,9 +417,9 @@ public function test_rows_without_columns_beyond_the_covered_rows_hash_as_empty_ /** @var array{1: int, 2: int} $lanes */ $lanes = unpack('J2', hash('xxh128', '', true)); $empty = new MultisetDigest($lanes[2], $lanes[1]); - $worker = new WholeOutputHasher(); + $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()); + $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()); @@ -428,12 +433,12 @@ public function test_rows_without_columns_beyond_the_covered_rows_hash_as_empty_ public function test_a_partitioned_hash_takes_the_partitions_of_the_covered_rows_from_the_partial(): void { - $worker = new PartitionedOutputHasher(refs('country')); + $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'))); + $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128)); $counts->absorbOutputHash($worker->hash()); $counts->hashOutput(Rows::fromColumns(schema(), [], 1), new PhpBackend()); @@ -442,7 +447,7 @@ public function test_a_partitioned_hash_takes_the_partitions_of_the_covered_rows public function test_a_partitioned_hash_refuses_rows_without_columns_that_no_partial_covers(): void { - $counts = new RunCounts(new PartitionedOutputHasher(refs('country'))); + $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128)); $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( @@ -454,12 +459,12 @@ public function test_a_partitioned_hash_refuses_rows_without_columns_that_no_par public function test_a_partitioned_hash_refuses_the_uncovered_part_of_partly_covered_rows_before_a_first_batch(): void { - $worker = new PartitionedOutputHasher(refs('country')); + $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'))); + $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128)); $counts->absorbOutputHash($worker->hash()); $this->expectException(InvalidArgumentException::class); @@ -475,7 +480,7 @@ public function test_a_partitioned_hash_puts_uncovered_rows_without_columns_into /** @var array{1: int, 2: int} $lanes */ $lanes = unpack('J2', hash('xxh128', '', true)); $empty = new MultisetDigest($lanes[2], $lanes[1]); - $nulls = new WholeOutputHasher(); + $nulls = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $nulls->add( array_to_rows( [['country' => null, 'id' => 1]], @@ -483,7 +488,7 @@ public function test_a_partitioned_hash_puts_uncovered_rows_without_columns_into ), new PhpBackend(), ); - $worker = new PartitionedOutputHasher(refs('country')); + $worker = new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128); $worker->add( array_to_rows( [['country' => 'PL', 'id' => 2]], @@ -491,7 +496,7 @@ public function test_a_partitioned_hash_puts_uncovered_rows_without_columns_into ), new PhpBackend(), ); - $counts = new RunCounts(new PartitionedOutputHasher(refs('country'))); + $counts = new RunCounts(new PartitionedOutputHasher(refs('country'), MultisetHashAlgorithm::xxh128)); $counts->hashOutput( array_to_rows( [['country' => null, 'id' => 1]], @@ -519,7 +524,7 @@ public function test_a_partitioned_hash_puts_uncovered_rows_without_columns_into 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'))); + $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(), 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 bbb7b0183..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 @@ -410,7 +410,7 @@ public function test_a_partitioned_dataset_hash_reports_one_hash_per_partition_a { $schema = schema(str_schema('country'), int_schema('id')); $whole = new StatisticsCollector(analyze()->withDatasetHash(), flow_context()); - $collector = new StatisticsCollector(analyze()->withDatasetHash(ref('country')), 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)); 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 index 272240071..ee0b55a9d 100644 --- 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 @@ -4,12 +4,14 @@ namespace Flow\ETL\Tests\Unit\Runtime\Executor; +use Flow\ETL\Foundation\Exception\InvalidArgumentException; 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\Tests\Context\DescribeRoundTrip; use Flow\ETL\Tests\Mother\ColumnMother; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Column\PhpBackend; use Flow\Filesystem\Partition; use Flow\Filesystem\Partitions; @@ -24,50 +26,90 @@ final class WholeOutputHasherTest extends TestCase public function test_it_gives_the_hash_of_all_rows_and_no_partitions(): void { $rows = array_to_rows([['a' => 1], ['a' => 2]], schema(int_schema('a'))); - $kernel = (new PhpBackend())->groupedMultisetHashes(); + $kernel = (new PhpBackend())->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $kernel->add($rows->columns(), ColumnMother::of(int_schema('id'), [0, 0])); - $hasher = new WholeOutputHasher(); + $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'), []), $hasher->hash()); + 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(); + $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')), - ])); + $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'), []), $hasher->hash()); + 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'), []), - (new WholeOutputHasher())->hash(), + 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(); + $hasher = new WholeOutputHasher(MultisetHashAlgorithm::xxh128); $hasher->add(array_to_rows([], schema(int_schema('a'))), new PhpBackend()); - static::assertEquals(new DatasetHash(new Hash(0, '00000000000000000000000000000000'), []), $hasher->hash()); + static::assertEquals( + new DatasetHash(new Hash(0, '00000000000000000000000000000000'), [], MultisetHashAlgorithm::xxh128), + $hasher->hash(), + ); } public function test_describe_writes_no_state(): void { - $hasher = new WholeOutputHasher(); + $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'), []), + 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 index 131d0cecb..f0116bfb3 100644 --- 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 @@ -8,6 +8,7 @@ use Flow\ETL\Runtime\Metrics\DatasetHash; use Flow\ETL\Runtime\Metrics\Hash; use Flow\ETL\Runtime\Metrics\PartitionHash; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\Filesystem\Partition; use Flow\Filesystem\Partitions; use PHPUnit\Framework\TestCase; @@ -20,7 +21,11 @@ public function test_it_gives_the_total_and_the_partitions(): void new Partitions(new Partition('country', 'PL')), new Hash(2, 'ab8476f29c95212a306bffff897d7afb'), ); - $hash = new DatasetHash(new Hash(3, '31be1d609a26d996382e2a23855ebbe5'), [$partition]); + $hash = new DatasetHash( + new Hash(3, '31be1d609a26d996382e2a23855ebbe5'), + [$partition], + MultisetHashAlgorithm::xxh128, + ); static::assertEquals(new Hash(3, '31be1d609a26d996382e2a23855ebbe5'), $hash->total); static::assertSame([$partition], $hash->partitions); @@ -28,22 +33,39 @@ public function test_it_gives_the_total_and_the_partitions(): void 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')), + 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 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, + ), ), - ]))->plus(new DatasetHash(new Hash(2, '00000000000000000000000000000002'), [ - new PartitionHash( - new Partitions(new Partition('country', 'PL')), - new Hash(2, '00000000000000000000000000000002'), - ), - ]))); + ); } public function test_plus_keeps_different_partitions_in_order_of_first_appearance(): void @@ -63,8 +85,12 @@ public function test_plus_keeps_different_partitions_in_order_of_first_appearanc static::assertEquals( [$pl, $de, $us], - (new DatasetHash(new Hash(2, '00000000000000000000000000000003'), [$pl, $de]))->plus( - new DatasetHash(new Hash(1, '00000000000000000000000000000004'), [$us]), + (new DatasetHash( + new Hash(2, '00000000000000000000000000000003'), + [$pl, $de], + MultisetHashAlgorithm::xxh128, + ))->plus( + new DatasetHash(new Hash(1, '00000000000000000000000000000004'), [$us], MultisetHashAlgorithm::xxh128), )->partitions, ); } @@ -76,16 +102,20 @@ public function test_plus_merges_equal_partitions_of_one_operand(): void 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'), - ), - ]))->plus(new DatasetHash(Hash::empty(), []))->partitions, + (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, ); } @@ -96,39 +126,53 @@ public function test_plus_takes_null_and_the_null_folder_name_as_one_partition() 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'), - ), - ]))->plus(new DatasetHash(new Hash(1, '00000000000000000000000000000002'), [ - new PartitionHash( - new Partitions(new Partition('country', Partition::NULL_VALUE)), + (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, + )->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'), - ), - ]); + $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(), []))); - static::assertEquals($hash, (new DatasetHash(Hash::empty(), []))->plus($hash)); + 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'), []), - (new DatasetHash(new Hash(2, 'ffffffffffffffffffffffffffffffff'), []))->plus( - new DatasetHash(new Hash(3, '00000000000000000000000000000001'), []), + 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), ), ); } @@ -137,6 +181,7 @@ public function test_normalize_writes_the_total_and_each_partition(): void { static::assertSame( [ + 'algorithm' => 'xxh128', 'total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'], 'partitions' => [ [ @@ -149,48 +194,104 @@ public function test_normalize_writes_the_total_and_each_partition(): void ], ], ], - (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'), - ), - ]))->normalize(), + (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'), - ), - ]); + $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'), []); + $hash = new DatasetHash(new Hash(3, '31be1d609a26d996382e2a23855ebbe5'), [], MultisetHashAlgorithm::xxh128); static::assertSame( - ['total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'], 'partitions' => []], + [ + '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(['partitions' => []]); + DatasetHash::fromArray(['algorithm' => 'xxh128', 'partitions' => []]); } public function test_from_array_names_a_key_of_another_type(): void @@ -199,6 +300,7 @@ public function test_from_array_names_a_key_of_another_type(): void $this->expectExceptionMessage('A dataset hash needs "partitions" of type list>'); DatasetHash::fromArray([ + 'algorithm' => 'xxh128', 'total' => ['rows' => 3, 'value' => '31be1d609a26d996382e2a23855ebbe5'], 'partitions' => 'none', ]); @@ -209,6 +311,6 @@ 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(['total' => ['rows' => 3], 'partitions' => []]); + DatasetHash::fromArray(['algorithm' => 'xxh128', 'total' => ['rows' => 3], 'partitions' => []]); } } 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 7968e42ce..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 @@ -15,6 +15,7 @@ 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; @@ -34,18 +35,14 @@ final class ReportTest extends FlowTestCase public function test_normalize_holds_what_the_typed_getters_hold_and_survives_json(): void { $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], - datasetHash: new DatasetHash(new Hash(2, '721f4650154ebb88ac4ec50a605901df'), [ - new PartitionHash( - new Partitions(new Partition('country', null)), - new Hash(2, '721f4650154ebb88ac4ec50a605901df'), - ), - ]), - ); + $report = ReportMother::of(new Processes(Unit::fromBytes(25), [Unit::fromBytes( + 40, + )]), 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(); @@ -61,6 +58,7 @@ public function test_normalize_holds_what_the_typed_getters_hold_and_survives_js ], 'sources' => [$source->normalize()], 'dataset_hash' => [ + 'algorithm' => 'xxh128', 'total' => ['rows' => 2, 'value' => '721f4650154ebb88ac4ec50a605901df'], 'partitions' => [ [ 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 56798ec0d..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,6 +13,7 @@ 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; @@ -302,6 +303,9 @@ public function test_row_hashes_and_multiset_hashes_are_the_php_backends(): void ->rowHashes($rows->columns(), 2) ->physicals(), ); - static::assertInstanceOf(PhpGroupedMultisetHashes::class, (new AdaptiveBackend())->groupedMultisetHashes()); + static::assertInstanceOf( + PhpGroupedMultisetHashes::class, + (new AdaptiveBackend())->groupedMultisetHashes(MultisetHashAlgorithm::xxh128), + ); } } 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 index 9169ea070..3969f04a6 100644 --- 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 @@ -7,8 +7,10 @@ use Flow\ETL\Foundation\Exception\InvalidArgumentException; use Flow\ETL\Tests\Mother\ColumnMother; use Flow\ETL\Values\Column\MultisetDigest; +use Flow\ETL\Values\Column\MultisetHashAlgorithm; use Flow\ETL\Values\Column\Php\PhpGroupedMultisetHashes; use Flow\ETL\Values\Column\PhpBackend; +use PHPUnit\Framework\Attributes\TestWith; use PHPUnit\Framework\TestCase; use function Flow\ETL\DSL\array_to_rows; @@ -21,7 +23,7 @@ final class PhpGroupedMultisetHashesTest extends TestCase { public function test_each_row_is_summed_into_its_group(): void { - $hashes = new PhpGroupedMultisetHashes(); + $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $hashes->add( array_to_rows([['a' => 1], ['a' => 2], ['a' => 1]], schema(int_schema('a')))->columns(), ColumnMother::of(int_schema('id'), [0, 1, 0]), @@ -33,9 +35,25 @@ public function test_each_row_is_summed_into_its_group(): void ); } + #[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(); + $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $hashes->add( array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), ColumnMother::of(int_schema('id'), [1]), @@ -49,7 +67,7 @@ public function test_a_group_below_the_highest_seen_one_is_zero(): void public function test_no_rows_give_no_groups(): void { - $hashes = new PhpGroupedMultisetHashes(); + $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $hashes->add([], ColumnMother::of(int_schema('id'), [])); static::assertSame([], $hashes->hashes()->physicals()); @@ -57,7 +75,7 @@ public function test_no_rows_give_no_groups(): void public function test_hashes_are_the_digests_by_group(): void { - $hashes = new PhpGroupedMultisetHashes(); + $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]), @@ -71,12 +89,12 @@ public function test_hashes_are_the_digests_by_group(): void public function test_earlier_groups_are_added_to_the_groups_they_map_to(): void { - $earlier = new PhpGroupedMultisetHashes(); + $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(); + $later = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $later->add( array_to_rows([['a' => 1]], schema(int_schema('a')))->columns(), ColumnMother::of(int_schema('id'), [0]), @@ -98,7 +116,7 @@ public function test_a_batch_without_columns_hashes_each_row_as_the_empty_row(): /** @var array{1: int, 2: int} $lanes */ $lanes = unpack('J2', hash('xxh128', '', true)); $empty = new MultisetDigest($lanes[2], $lanes[1]); - $hashes = new PhpGroupedMultisetHashes(); + $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()); @@ -107,7 +125,7 @@ public function test_a_batch_without_columns_hashes_each_row_as_the_empty_row(): 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(); + $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $hashes->add($rows->columns(), ColumnMother::of(int_schema('id'), [0])); static::assertSame(['8e18789eac90baf2a1f6bc7cceafa11a'], $hashes->hashes()->physicals()); @@ -121,12 +139,12 @@ public function test_one_row_in_one_group_equals_its_row_hash(): void public function test_row_order_over_batches_does_not_count(): void { - $forward = new PhpGroupedMultisetHashes(); + $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(); + $backward = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $backward->add( array_to_rows([['a' => 2]], schema(int_schema('a')))->columns(), ColumnMother::of(int_schema('id'), [0]), @@ -142,7 +160,7 @@ public function test_row_order_over_batches_does_not_count(): void public function test_a_row_of_only_nulls_counts_as_a_row(): void { - $hashes = new PhpGroupedMultisetHashes(); + $hashes = new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128); $hashes->add( array_to_rows([['a' => null]], schema(int_schema('a', true)))->columns(), ColumnMother::of(int_schema('id'), [0]), @@ -156,6 +174,9 @@ 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())->absorbEarlier(new PhpGroupedMultisetHashes(), [3 => 0]); + (new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128))->absorbEarlier( + new PhpGroupedMultisetHashes(MultisetHashAlgorithm::xxh128), + [3 => 0], + ); } } diff --git a/src/extension/flow-php-ext/Cargo.lock b/src/extension/flow-php-ext/Cargo.lock index a1976dd6f..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", ] @@ -712,7 +750,9 @@ dependencies = [ "arrow-ord", "arrow-schema", "flow-batch-frame", + "md-5", "memchr", + "sha2 0.10.9", "xxhash-rust", ] @@ -800,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" @@ -866,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]] @@ -1051,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]] @@ -1268,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", ] @@ -1540,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]] @@ -1551,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 581a82451..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 @@ -13,5 +13,7 @@ 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 index 9812e6182..48d42a31e 100644 --- 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 @@ -7,6 +7,8 @@ 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; @@ -120,11 +122,29 @@ pub fn append_name(out: &mut Vec, name: &[u8]) { out.extend_from_slice(name); } -/// (low, high) of `xxh3_128(encoded)`. -pub fn row_lanes(encoded: &[u8]) -> (u64, u64) { +/// [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) + [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( @@ -821,7 +841,16 @@ mod tests { 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) + [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] ); } 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 1994bd2fa..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 @@ -146,7 +146,7 @@ public function rowHashes(array $columns, int $count): Column throw new RuntimeException('flow_php extension is not loaded'); } - public function groupedMultisetHashes(): GroupedMultisetHashes + public function groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes { throw new RuntimeException('flow_php extension is not loaded'); } diff --git a/src/extension/flow-php-ext/src/backend.rs b/src/extension/flow-php-ext/src/backend.rs index 04e237a1b..df50f1a50 100644 --- a/src/extension/flow-php-ext/src/backend.rs +++ b/src/extension/flow-php-ext/src/backend.rs @@ -23,7 +23,7 @@ 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::row_lanes; +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::bucket_of; @@ -35,7 +35,8 @@ 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}; @@ -43,7 +44,7 @@ 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::RustGroupedMultisetHashes; +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}; @@ -289,7 +290,7 @@ impl RustBackend { let hashes = (0..count) .map(|index| { named(&mut row, &mut entries, &resolved, index); - let (low, high) = row_lanes(&row); + let [low, high] = row_lanes(&row); format!("{high:016x}{low:016x}") }) @@ -299,8 +300,21 @@ impl RustBackend { } #[php(name = "groupedMultisetHashes")] - pub fn grouped_multiset_hashes(&self) -> RustGroupedMultisetHashes { - RustGroupedMultisetHashes::default() + 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")] diff --git a/src/extension/flow-php-ext/src/interfaces.rs b/src/extension/flow-php-ext/src/interfaces.rs index 5f46cbd1c..762a0a7f7 100644 --- a/src/extension/flow-php-ext/src/interfaces.rs +++ b/src/extension/flow-php-ext/src/interfaces.rs @@ -20,6 +20,7 @@ const ROWS: DataType = DataType::object("Flow\\ETL\\Values\\Rows"); const SCHEMA: DataType = DataType::object("Flow\\ETL\\Values\\Schema"); const SCHEMA_INFERENCE: DataType = DataType::object("Flow\\ETL\\IO\\Inference\\SchemaInference"); const GROUPED_COUNTS: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedCounts"); +const MULTISET_HASH_ALGORITHM: DataType = DataType::object("Flow\\ETL\\Values\\Column\\MultisetHashAlgorithm"); const GROUPED_MULTISET_HASHES: DataType = DataType::object("Flow\\ETL\\Values\\Column\\GroupedMultisetHashes"); const GROUP_TABLE: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupTable"); const GROUP_IDS: DataType = DataType::object("Flow\\ETL\\Values\\Grouping\\GroupIds"); @@ -446,7 +447,11 @@ pub fn register() -> Result<()> { vec![Arg::new("columns", DataType::Array), Arg::new("count", DataType::Long)], COLUMN, ), - method("groupedMultisetHashes", vec![], GROUPED_MULTISET_HASHES), + method( + "groupedMultisetHashes", + vec![Arg::new("algorithm", MULTISET_HASH_ALGORITHM)], + GROUPED_MULTISET_HASHES, + ), method( "groupTable", vec![Arg::new("columns", DataType::Array), Arg::new("declared", SCHEMA)], diff --git a/src/extension/flow-php-ext/src/multiset_hashes.rs b/src/extension/flow-php-ext/src/multiset_hashes.rs index 18511ae5e..f9add9ff1 100644 --- a/src/extension/flow-php-ext/src/multiset_hashes.rs +++ b/src/extension/flow-php-ext/src/multiset_hashes.rs @@ -7,7 +7,6 @@ use arrow_array::LargeBinaryArray; use ext_php_rs::flags::ClassFlags; use ext_php_rs::prelude::*; use ext_php_rs::types::{ArrayKey, ZendHashTable, Zval}; -use flow_column_kernels::canonical::row_lanes; use crate::canonical_rows::{named, row_columns, STRING_TYPE}; use crate::column::RustColumn; @@ -20,15 +19,18 @@ use crate::render::invalid_argument; /// [low, high] type Lanes = [u64; 2]; +/// the lanes of the digest of one encoded row +pub type RowLanes = fn(&[u8]) -> Lanes; + #[php_class] #[php( name = "Flow\\ETL\\Values\\Column\\RustGroupedMultisetHashes", flags = ClassFlags::Final, implements(ce = grouped_multiset_hashes_ce, stub = "Flow\\ETL\\Values\\Column\\GroupedMultisetHashes") )] -#[derive(Default)] pub struct RustGroupedMultisetHashes { lanes: Vec, + row_lanes: RowLanes, } #[php_impl] @@ -45,7 +47,7 @@ impl RustGroupedMultisetHashes { for (index, id) in ids.into_iter().enumerate() { named(&mut row, &mut entries, &resolved, index); - add_lanes(&mut self.lanes[id], row_lanes(&row).into()); + add_lanes(&mut self.lanes[id], (self.row_lanes)(&row)); } Ok(()) @@ -97,6 +99,13 @@ impl RustGroupedMultisetHashes { } impl RustGroupedMultisetHashes { + pub fn of(row_lanes: RowLanes) -> Self { + Self { + lanes: Vec::new(), + row_lanes, + } + } + fn grow(&mut self, id: usize) { if self.lanes.len() <= id { self.lanes.resize(id + 1, [0, 0]); diff --git a/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt index 07c92620c..d7e6effc7 100644 --- a/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/125_row_hashes_parity.phpt @@ -1,12 +1,12 @@ --TEST-- -RustBackend::rowHashes() and groupedMultisetHashes() give the hashes PhpBackend gives: every tag, the canonical edge cases, a native map with the key "1", positioned and bare xml elements, columns from either backend, batches split differently, batches without columns, one group, absorbEarlier and the carry between lanes +RustBackend::rowHashes() and groupedMultisetHashes() give the hashes PhpBackend gives: every tag, the canonical edge cases, a native map with the key "1", positioned and bare xml elements, columns from either backend, batches split differently, batches without columns, one group, absorbEarlier and the carry between lanes, md5 and sha256 --SKIPIF-- --FILE-- [all_types_schema(), all_types_values()], 'edge cases' $rows = static fn(Backend $backend, Rows $source): Rows => $source->adoptedBy($backend); $hashes = static function (Backend $backend, Rows $rows, int $batch, ?array $ids = null): array { $ids ??= array_fill(0, $rows->count(), 0); - $grouped = $backend->groupedMultisetHashes(); + $grouped = $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); foreach ($rows->chunks($batch) as $index => $part) { $grouped->add($part->columns(), array_to_rows( @@ -90,27 +90,27 @@ echo 'native map with the key "1": ', $native instanceof Flow\ETL\Values\Column\ $source = php_rows(...$edges); $groupIds = static fn(Backend $backend) => array_to_rows([['id' => 0], ['id' => 2], ['id' => 0], ['id' => 2]], schema(int_schema('id')), $backend)->column('id'); -$fromPhp = $php->groupedMultisetHashes(); +$fromPhp = $php->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $fromPhp->add($source->columns(), $groupIds($php)); -$direct = $rust->groupedMultisetHashes(); +$direct = $rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $direct->add($source->adoptedBy($rust)->columns(), $groupIds($rust)); -$intoPhp = $rust->groupedMultisetHashes(); +$intoPhp = $rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $intoPhp->absorbEarlier($fromPhp, [0 => 0, 1 => 1, 2 => 2]); -$intoNative = $rust->groupedMultisetHashes(); +$intoNative = $rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $intoNative->absorbEarlier($direct, [0 => 0, 1 => 1, 2 => 2]); -$phpInto = $php->groupedMultisetHashes(); +$phpInto = $php->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $phpInto->absorbEarlier($direct, [0 => 0, 1 => 1, 2 => 2]); echo 'absorbEarlier of php, native and into php: ', $intoPhp->hashes()->physicals() === $direct->hashes()->physicals() && $intoNative->hashes()->physicals() === $direct->hashes()->physicals() && $phpInto->hashes()->physicals() === $direct->hashes()->physicals() && $intoPhp->hashes()->physicals() === $fromPhp->hashes()->physicals() ? 'same' : 'MISMATCH', "\n"; echo 'unseen group: ', $direct->hashes()->physicals()[1], "\n"; -echo 'empty: ', json_encode($rust->groupedMultisetHashes()->hashes()->physicals()), "\n"; +echo 'empty: ', json_encode($rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)->hashes()->physicals()), "\n"; $withoutColumns = static function (Backend $backend): array { - $one = $backend->groupedMultisetHashes(); + $one = $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $one->add([], array_to_rows([['id' => 0], ['id' => 0], ['id' => 0]], schema(int_schema('id')), $backend)->column('id')); - $grouped = $backend->groupedMultisetHashes(); + $grouped = $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $grouped->add([], array_to_rows([['id' => 1], ['id' => 0], ['id' => 1]], schema(int_schema('id')), $backend)->column('id')); return [$one->hashes()->physicals(), $grouped->hashes()->physicals()]; @@ -123,7 +123,7 @@ $earlier = static fn(string $hex): GroupedMultisetHashes => new class($hex) impl public function hashes(): Column { return array_to_rows([['h' => $this->hex]], schema(str_schema('h')), new PhpBackend())->column('h'); } public function absorbEarlier(GroupedMultisetHashes $earlier, array $into): void {} }; -$carry = $rust->groupedMultisetHashes(); +$carry = $rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128); $carry->absorbEarlier($earlier((new MultisetDigest(0xFFFFFFFF, PHP_INT_MAX))->hex()), [0 => 0]); $carry->absorbEarlier($earlier((new MultisetDigest(0xFFFFFFFF, 1))->hex()), [0 => 0]); echo 'carry: ', $carry->hashes()->physicals()[0], "\n"; @@ -131,7 +131,7 @@ echo 'carry: ', $carry->hashes()->physicals()[0], "\n"; foreach (['uppercase' => '0000000000000000000000000000000A', 'sign' => '+0000000000000000000000000000000'] as $label => $hex) { foreach (['php' => $php, 'rust' => $rust] as $side => $backend) { try { - $backend->groupedMultisetHashes()->absorbEarlier($earlier($hex), [0 => 0]); + $backend->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)->absorbEarlier($earlier($hex), [0 => 0]); echo "{$label} into {$side}: accepted\n"; } catch (Throwable $e) { echo "{$label} into {$side}: ", $e::class, ': ', $e->getMessage(), "\n"; @@ -140,7 +140,7 @@ foreach (['uppercase' => '0000000000000000000000000000000A', 'sign' => '+0000000 } try { - $rust->groupedMultisetHashes()->absorbEarlier($rust->groupedMultisetHashes(), [3 => 0]); + $rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128)->absorbEarlier($rust->groupedMultisetHashes(MultisetHashAlgorithm::xxh128), [3 => 0]); } catch (Throwable $e) { echo 'missing earlier group: ', $e::class, ': ', $e->getMessage(), "\n"; } @@ -148,6 +148,18 @@ try { $only = array_to_rows([['a' => null]], schema(int_schema('a', true)), $rust); echo 'only nulls: ', $rust->rowHashes($only->columns(), 1)->physicals()[0], "\n"; echo 'no columns: ', json_encode($rust->rowHashes([], 2)->physicals()), "\n"; + +$small = array_to_rows([['a' => 1], ['a' => 2], ['a' => 1]], schema(int_schema('a')), $php); + +foreach ([MultisetHashAlgorithm::md5, MultisetHashAlgorithm::sha256] as $algorithm) { + $of = static function (Backend $backend) use ($small, $algorithm, $rows): array { + $grouped = $backend->groupedMultisetHashes($algorithm); + $grouped->add($rows($backend, $small)->columns(), array_to_rows([['id' => 0], ['id' => 1], ['id' => 0]], schema(int_schema('id')), $backend)->column('id')); + + return $grouped->hashes()->physicals(); + }; + echo $algorithm->value, ': ', $of($rust) === $of($php) ? 'same' : 'MISMATCH', ' ', json_encode($of($rust)), "\n"; +} ?> --EXPECT-- every tag: same @@ -165,3 +177,5 @@ sign into rust: Flow\ETL\Foundation\Exception\InvalidArgumentException: A multis missing earlier group: Flow\ETL\Foundation\Exception\InvalidArgumentException: Earlier group 3 has no hash only nulls: 99aa06d3014798d86001c324468d497f no columns: ["99aa06d3014798d86001c324468d497f","99aa06d3014798d86001c324468d497f"] +md5: same ["53b117ed69552c4ee4c638e6c72a526a","8c589f902ff9330489f46e8138ef3fff"] +sha256: same ["8f55cd2c66338b181c9f478cff77d05c","7c396438b2b1506bc82ea94d4ad238cd"] From 273a29be62230b716fca89c1dab3520e5b718507 Mon Sep 17 00:00:00 2001 From: Norbert Orzechowicz Date: Mon, 23 Nov 2026 10:38:10 -0600 Subject: [PATCH 5/5] test(flow-php/flow-php-ext): html fixtures of parity tests are full documents --- .../tests/phpt/120_group_table_lookup_parity.phpt | 4 +++- .../flow-php-ext/tests/phpt/121_partition_parity.phpt | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt b/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt index 9e85122c2..dd602b9c8 100644 --- a/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/120_group_table_lookup_parity.phpt @@ -39,10 +39,12 @@ foreach ($cases as $label => [$definition, $known, $probed]) { ', ', json_encode($expected), "\n"; } +$html = static fn (string $text): string => "

    {$text}

    "; + $nested = [ 'maps' => [map_schema('v', type_map(type_string(), type_integer()), nullable: true), [['a' => 1], ['b' => 2, 'a' => 1], null], [['a' => 1, 'b' => 2], ['a' => 1], ['c' => 3], null]], 'xml' => [xml_schema('v'), ['
    ', '1'], ['1', '', '']], - 'html' => [html_schema('v'), ['

    a

    '], ['

    b

    ', '

    a

    ']], + 'html' => [html_schema('v'), [$html('a')], [$html('b'), $html('a')]], ]; foreach ($nested as $label => [$definition, $known, $probed]) { diff --git a/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt b/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt index c54c69275..fc9f06307 100644 --- a/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt +++ b/src/extension/flow-php-ext/tests/phpt/121_partition_parity.phpt @@ -11,6 +11,8 @@ use Flow\ETL\Values\Column\{Backend, PhpBackend, RustBackend}; use function Flow\ETL\DSL\{array_to_rows, bool_schema, float_schema, html_schema, int_schema, list_schema, map_schema, schema, str_schema, structure_schema, xml_schema}; use function Flow\Types\DSL\{type_integer, type_list, type_map, type_string, type_structure}; +$html = static fn (string $text): string => "

    {$text}

    "; + $cases = [ 'nullable strings' => [[str_schema('k', nullable: true)], [['a'], [null], ['b'], [''], [null], ['a'], ['0']]], 'ints' => [[int_schema('k')], array_map(static fn(int $i): array => [$i % 11 - 5], range(0, 40))], @@ -22,7 +24,7 @@ $cases = [ 'a composite key' => [[int_schema('k'), str_schema('s')], [[1, 'a'], [1, 'b'], [2, 'a'], [1, 'a']]], 'maps with nulls' => [[map_schema('k', type_map(type_string(), type_integer()), nullable: true)], [[['a' => 1]], [['b' => 2, 'a' => 1]], [null], [['a' => 1, 'b' => 2]]]], 'xml' => [[xml_schema('k')], [['
    '], ['1'], ['']]], - ...(class_exists('\Dom\HTMLDocument') ? ['html' => [[html_schema('k')], [['

    a

    '], ['

    b

    '], ['

    a

    ']]]] : []), + ...(class_exists('\Dom\HTMLDocument') ? ['html' => [[html_schema('k')], [[$html('a')], [$html('b')], [$html('a')]]]] : []), ]; $partitioned = static function (Backend $partitioner, Backend $columns, array $definitions, array $values, int $buckets, int $offset): array {