Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions documentation/components/core/aggregations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -107,6 +108,11 @@ df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'))])
df()->read(from_array([['a' => 0.1], ['a' => 0.2]]))->aggregate([sum(ref('a'), exact: true)])->fetch(); // 0.3
```

## Hashing rows

`multiset_hash()` hashes the rows of each group. The order of the rows does not change it. See
[Hashing](/documentation/components/core/hashing.md).

## Example

```php
Expand Down
3 changes: 2 additions & 1 deletion documentation/components/core/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
240 changes: 240 additions & 0 deletions documentation/components/core/hashing.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
# Hashing

[DOC_LINK:/documentation/components/core/core.md]

[TOC]

A hash is 32 hex characters. Equal rows give equal hashes, in any row order and any column order.

| You want the hash of | Use |
|----------------------|--------------------------------------------|
| each row | `row_hash()` |
| each group of rows | `multiset_hash()` |
| the output of a run | `analyze()->withDatasetHash()` |
| each partition | `analyze()->withDatasetHash([ref('...')])` |

## Hash of each row

```php
<?php

use function Flow\ETL\DSL\{data_frame, from_array, ref, row_hash};

$users = [
['id' => 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
<?php

use Flow\ETL\Values\Join\JoinType;

use function Flow\ETL\DSL\{data_frame, from_array, join_on, ref, row_hash};

$yesterday = [
['id' => 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
<?php

use function Flow\ETL\DSL\{data_frame, from_array, multiset_hash};

$source = [
['id' => 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
<?php

use function Flow\ETL\Adapter\CSV\from_csv;
use function Flow\ETL\Adapter\Parquet\{from_parquet, to_parquet};
use function Flow\ETL\DSL\{analyze, data_frame, date_schema, int_schema, schema, str_schema};

$orders = schema(int_schema('id'), date_schema('date'), str_schema('country'));

$written = data_frame()
->read(from_csv('orders.csv')->withSchema($orders))
->write(to_parquet('orders.parquet'))
->run(analyze: analyze()->withDatasetHash())
->datasetHash();

$stored = data_frame()
->read(from_parquet('orders.parquet'))
->run(analyze: analyze()->withDatasetHash())
->datasetHash();

$written->algorithm; // MultisetHashAlgorithm::xxh128
$written->total->rows; // 3
$written->total->value; // 'f2920d3f120d5130873032ec79839580'
$stored->total->value; // 'f2920d3f120d5130873032ec79839580', the copy is complete
```

### Choose the algorithm

The default is `xxh128`. A run can use `md5` or `sha256` instead:

```php
<?php

use Flow\ETL\Values\Column\MultisetHashAlgorithm;

use function Flow\ETL\DSL\{analyze, data_frame, from_array};

$hash = data_frame()
->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
<?php

use function Flow\ETL\Adapter\CSV\from_csv;
use function Flow\ETL\Adapter\Parquet\to_parquet;
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')]));

$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
<?php

$changed = array_keys(array_diff_assoc($current, $previous)); // ['date=2026-11-21']
$removed = array_keys(array_diff_key($previous, $current)); // []
```

A null value is the folder `date=__HIVE_DEFAULT_PARTITION__`. An empty string is the folder `date=`.

## Combine runs

`normalize()` gives a hash as an array that you can store. `fromArray()` reads it back. `plus()` adds two hashes:

```php
<?php

use Flow\ETL\Runtime\Metrics\DatasetHash;

file_put_contents('monday.json', json_encode($monday->datasetHash()->normalize()));

// {"algorithm":"xxh128","total":{"rows":1,"value":"61d8d2f77533f36e5f23e4e587fa5e41"},"partitions":[]}

$stored = json_decode(file_get_contents('monday.json'), true);
$week = DatasetHash::fromArray($stored)->plus($tuesday->datasetHash());

$week->total->rows; // 3
$week->total->value; // '31be1d609a26d996382e2a23855ebbe5', equal to one run over both days
```

`plus()` also adds the partitions with the same values. If the two hashes have different algorithms, `plus()` throws.

## Rules

- Duplicate rows count: two equal rows give another hash than one.
- Declare the schema. The same value with another type gives another hash.
- A float, list, map, structure, json, xml or html column cannot be a partition column.
- The hash finds accidental differences. It does not protect against tampering.
42 changes: 42 additions & 0 deletions documentation/components/core/partitioning.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,48 @@ Flow writes each value in full. A typed read gets the value back without changes
| `datetime` | `2026-10-02 13:00:00.123456 UTC` | `date=2026-10-02T13%3A00%3A00.123456%2B00%3A00` |
| `date` | `2026-10-02` | `date=2026-10-02` |
| `float` | `1.0E-9` | `x=1.0e-9` |
| `string` | `null` | `country=__HIVE_DEFAULT_PARTITION__` |
| `string` | `''` | `country=` |

### Null and Empty Values

A null value goes to the directory `__HIVE_DEFAULT_PARTITION__`, the name that Hive, Spark and DuckDB use. An empty
string goes to a directory with no value. A read gives both back:

```php
<?php

use function Flow\ETL\Adapter\Parquet\{from_parquet, to_parquet};
use function Flow\ETL\DSL\{data_frame, from_array, int_schema, overwrite, partition_by, schema, str_schema};

$users = schema(int_schema('id'), str_schema('country', nullable: true));

data_frame()
->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`:

Expand Down
8 changes: 4 additions & 4 deletions documentation/components/extensions/flow-php-ext.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,10 +80,10 @@ Each contract with a Rust and a PHP implementation follows one pattern:
| `Flow\ETL\Adapter\Parquet\IO\Extractor\ParquetOpenSource` | `RustParquetOpenSource` | `PhpParquetOpenSource` | `ParquetSourceFile::open()` |
| `Flow\ETL\IO\Loader\File\FileWriter` | `RustParquetFileWriter` | `ParquetFileWriter` | `ParquetFileWriterFactory::writer()` |

The extension also registers `Flow\ETL\Values\Column\{Column, ColumnBuilder, GroupedTotals, GroupedCounts}` (`RustColumn`,
`RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`), `Flow\ETL\Values\Grouping\GroupTable`
(`RustGroupTable`), the last three returned by `RustBackend`, and `Flow\ETL\Values\RustIterator`, the iterator its
sources return.
The extension also registers `Flow\ETL\Values\Column\{Column, ColumnBuilder, GroupedTotals, GroupedCounts,
GroupedMultisetHashes}` (`RustColumn`, `RustColumnBuilder`, `RustGroupedTotals`, `RustGroupedCounts`,
`RustGroupedMultisetHashes`). It also registers `Flow\ETL\Values\Grouping\GroupTable` (`RustGroupTable`).
`RustBackend` returns the last four. Its sources return the iterator `Flow\ETL\Values\RustIterator`.

## CSV and JSON writers

Expand Down
48 changes: 48 additions & 0 deletions documentation/upgrading.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,54 @@ with(cte('tree', $query))->recursive()->select(star())->from(table('tree'));

Applies to the delete, update, insert and merge builders.

### 4) `flow-php/etl` - a detached xml element is stored by its canonical markup

| Before | After |
|----------------------------------------------------------------|--------------------------------------|
| a detached xml element is stored as `saveXML()`, `<a/>` | stored as its C14N markup, `<a></a>` |
| an xml element with no owner document throws in `toPhysical()` | stored as its C14N markup |

Floe files and caches written by 0.45 to 0.48 keep the raw form of a detached xml element. Flow compares, hashes and
writes such a value in that raw form. Write the file again with this version to store the C14N markup.

### 5) `flow-php/etl` - `NativePHPHash` is renamed to `PhpAlgorithm`, and `hash()` takes an algorithm name

| Before | After |
|--------------------------------------------------------------------------|-----------------------------------------------------------------------|
| `Flow\ETL\Kernels\Hash\NativePHPHash` | `Flow\ETL\Kernels\Hash\PhpAlgorithm` |
| `hash(ref('email'), new NativePHPHash('sha256'))` | `hash(ref('email'), 'sha256')` |
| `ref('email')->hash(new NativePHPHash('xxh64', options: ['seed' => 7]))` | `ref('email')->hash(hash_algorithm('xxh64', options: ['seed' => 7]))` |

Catch `Flow\ETL\Foundation\Exception\InvalidArgumentException` instead of `\InvalidArgumentException` for an unknown algorithm name.

### 6) `flow-php/etl` - `Backend` has two new methods, and the flow_php ABI is 4

| Before | After |
|------------------|-------------------------------------------------------------------------------------------|
| - | `Backend::rowHashes(array $columns, int $count): Column` |
| - | `Backend::groupedMultisetHashes(MultisetHashAlgorithm $algorithm): GroupedMultisetHashes` |
| `FLOW_PHP_ABI` 3 | `FLOW_PHP_ABI` 4 |

A custom `Backend` must implement the two methods. Update or rebuild the flow_php extension together with the library.

### 7) `flow-php/etl` - group, join, distinct and bucket keys have the declared type of their column

| Before | After |
|--------------------------------------------------------------------|--------------------------------------------------------------------|
| a datetime batch under a date key column groups by instant | it is cast to the date first and groups by day |
| an xml value under a string key column keys by its stored document | it keys by the text that the string cast gives |
| int `1` and float `1.0` under a float key column are two keys | one key |
| a join with an undeclared left schema buckets the right side first | it reads the first left batch first, so both sides key in one type |

### 8) `flow-php/filesystem` - an empty string is a valid partition value

| Before | After |
|----------------------------------------------|---------------------------------------------------|
| `new Partition('country', '')` throws | it is the partition `country` with the value `''` |
| `Partition::fromSegment('country=')` is null | it is the partition `country` with the value `''` |
| a partitioned write refuses an empty value | it writes the folder `country=` |
| a read ignores a folder `country=` | it reads it as the partition column `country` |

---

## Upgrading from 0.47.x to 0.48.x
Expand Down
Loading
Loading