Add flink-multi-window-aggregation example and repository index
diff --git a/README.md b/README.md index 4cf11c2..2ce2414 100644 --- a/README.md +++ b/README.md
@@ -6,9 +6,11 @@ ## Examples -> **Status:** This repository has just been initialized and does not yet contain any published examples on `main`. Runnable examples will be added through pull requests and listed here once merged. +| Example | Stack | What It Demonstrates | +| --- | --- | --- | +| [Multi-Window Group Aggregation with Flink](flink-multi-window-aggregation/README.md) (`flink-multi-window-aggregation/`) | Apache Flink 1.20.3, Apache Fluss 1.0.0, Fluss Flink 1.20 connector 1.0.0 | Offloading keyed multi-window `SUM` accumulation from Flink's `GroupAggregate` operator to the Fluss Aggregation Merge Engine, including signed-delta changelog translation, a Flink baseline path, an independent snapshot oracle, and checkpoint undo recovery across TaskManager `SIGKILL` restarts. | -Until the first examples are published, see the [Apache Fluss website](https://fluss.apache.org/) and the [Apache Fluss repository](https://github.com/apache/fluss) for documentation and project information. +Open an example directory and follow its `README.md` for prerequisites, setup, verification, and cleanup instructions. ## How Examples Are Organized @@ -25,7 +27,7 @@ 1. Place the example in its own top-level directory with a clear, descriptive name. 2. Keep the example self-contained with pinned dependency and runtime versions. 3. Include a `README.md` covering prerequisites, step-by-step run and verification instructions, and cleanup commands. -4. Add an entry for the example to the **Examples** section of this root `README.md` in the same pull request. +4. Add an entry for the example to the **Examples** table in this root `README.md` in the same pull request. ## Resources
diff --git a/flink-multi-window-aggregation/.dockerignore b/flink-multi-window-aggregation/.dockerignore new file mode 100644 index 0000000..289bbd8 --- /dev/null +++ b/flink-multi-window-aggregation/.dockerignore
@@ -0,0 +1,7 @@ +** +!runtime/ +!runtime/Dockerfile.flink +!.runtime/ +!.runtime/connector.jar +!src/ +!src/AssignWindows.java
diff --git a/flink-multi-window-aggregation/.gitignore b/flink-multi-window-aggregation/.gitignore new file mode 100644 index 0000000..772251d --- /dev/null +++ b/flink-multi-window-aggregation/.gitignore
@@ -0,0 +1,4 @@ +/.runtime/ +/target/ +/evidence/ +/__pycache__/
diff --git a/flink-multi-window-aggregation/README.md b/flink-multi-window-aggregation/README.md new file mode 100644 index 0000000..4587c37 --- /dev/null +++ b/flink-multi-window-aggregation/README.md
@@ -0,0 +1,89 @@ +# Hotel demand windows with Flink and Fluss + +This directory runs an isolated, synthetic Flink SQL example with Apache Flink 1.20.3, Apache Fluss 1.0.0 and the Fluss Flink 1.20 connector 1.0.0. Flink SQL Client executes the pipeline via `sql/transform.sql` and `sql/write.sql` (`EXECUTE STATEMENT SET`), with `sql/catalog.sql` and `sql/setup.sql` for catalog configuration and DDL; only `src/AssignWindows.java` (`blog.AssignWindows`) is Java. It compares a Flink `GroupAggregate` reference with Fluss `SUM` accumulation against an independent current-order snapshot oracle. + +## Prerequisites + +- Docker Engine with Docker Compose v2 or newer, at least 6 GiB available to Docker, and approximately 8 GiB of free disk for images, the connector cache and the small cluster. +- Python 3.11 or newer and `curl`. No host JDK, Maven, `tar` or Python packages are required; `src/AssignWindows.java` is compiled inside the Docker build. +- Network access to Docker Hub and Maven Central for initial preparation. +- TCP port 18096 available on localhost. Do not run multiple copies with the same Compose project name. + +## Run + +From this directory: + +```sh +./prepare.sh +python3 run.py verify +python3 run.py query +``` + +`prepare.sh` downloads the Fluss Flink 1.20 connector 1.0.0 into `.runtime/` (re-verifying its SHA-256 against `runtime/artifacts.json` before reusing any cached copy), then runs Docker Compose to build the custom Flink image and start five containers. Flink REST is available at http://127.0.0.1:18096. + +Container images follow official upstream bases pinned for reproducibility: + +- **Fluss Coordinator and TabletServer**: official `apache/fluss:1.0.0` (Java 17), pinned by multi-platform manifest digest. +- **ZooKeeper**: official `zookeeper:3.9.2`, pinned by version tag. +- **Flink JobManager and TaskManager**: built by `runtime/Dockerfile.flink` from official `flink:1.20.3-scala_2.12-java11` (pinned by multi-platform manifest digest, retaining the default official entrypoint). The build stage uses a digest-pinned Eclipse Temurin Java 11 JDK to compile `src/AssignWindows.java` (`blog.AssignWindows`) against the libraries bundled in that Flink image and the verified connector JAR (`runtime/connector.sha1` records the upstream checksum source); the runtime stage layers the connector JAR and `/opt/flink/assign-windows.jar` onto the same Flink Java 11 JRE base. + +The current Flink SQL implementation has passed all seven verification phases—including both real TaskManager `SIGKILL` recoveries from checkpoints 1 and 2, matching all 10 final window keys with unchanged results—using the pinned Flink 1.20.3 and Fluss 1.0.0 binaries in local archive-built containers. Cold-start verification against the official container images defined in `compose.yaml` and `runtime/Dockerfile.flink` is separately pending. + +`verify` requires a fresh tutorial cluster. Python (`run.py`) drives Flink SQL Client (`sql-client.sh`) for catalog/DDL setup (`sql/catalog.sql` and `sql/setup.sql`, which create the `hotel_blog` database and four tables—`orders`, `channels`, `window_totals`, and `baseline`—and seed `channels`), streaming job submission (`sql/transform.sql` and `sql/write.sql`), staged fixture writes into `orders`, and bounded batch snapshot queries against `window_totals` and `baseline`. It controls checkpoints and failure injection, and prints progress only after complete snapshots from both result tables match the independent Python oracle. + +The script deliberately kills this project's TaskManager twice: after a successful write beyond a completed checkpoint, and after a subsequent completed checkpoint. Other Docker projects are not touched. Checkpoints and Fluss data are retained in this project's named volumes across TaskManager restarts. JobManager or storage-server loss, rescaling, mutable dimensions and online migration are outside this experiment. + +The verification stages are: + +1. Insert orders A and B into `orders`; reconcile all four metrics for every window key. +2. Complete checkpoint 1, recording the `orders$changelog` source offset and `window_totals` sink undo recovery state. +3. Update A's amount in `orders` from 10000 to 12000 cents and verify the uncheckpointed write. +4. Kill/restart TaskManager, verify restored checkpoint 1, and reconcile the replayed update. +5. Cancel A in `orders`; verify business cancellation and changelog `_change_type` retraction are separate. +6. Delete B from `orders`; check retained zero rows. +7. Insert C into `orders` with a missing dimension key; check default channel flag and continued accumulation into previously zero windows. +8. Complete checkpoint 2 and kill/restart TaskManager again; reconcile the committed state across all 10 final keys. + +Evidence is written to `evidence/`: the actual physical plan (`job-graph.json`, which shows `GroupAggregate` only in the `baseline` path), stage snapshots, checkpoint metadata, recovery records and `result.json`. A PASS is written only after every stage succeeds. `run.py` paces stages by writing batches of changes into `orders` via SQL Client; it does not supply or change business timestamps. + +To rerun from a fresh cluster, first clean up and run preparation again. Starting a new job against previously accumulated SUM tables would count the input again. + +## Input and contract + +`data/images.csv` contains eight ordered, complete changelog images, without a header. Columns are: + +```text +RowKind,hotel_id,order_id,stay_date,observed_at,created_at,updated_at,cancelled,amount_cents,rate_code +``` + +The logical order key is `(hotel_id, order_id, stay_date)`, which is also the primary key of the Fluss `orders` table. When staging fixture changes via SQL Client, `run.py` issues `INSERT INTO orders` for `INSERT` and `UPDATE_AFTER` rows (skipping `UPDATE_BEFORE` because the `orders` primary-key table generates the old image automatically) and `DELETE FROM orders` for `DELETE` rows. The streaming SQL job reads the resulting full changelog from the Fluss 1.0.0 `orders$changelog` virtual table. All timestamps are naive UTC values; SQL Client sets `table.local-time-zone = 'UTC'`. `observed_at` is the fixed first-observation timestamp for an order and is preserved in each image. This is explicitly different from the original processing-time architecture. + +Two window specifications (length 2 and 4 minutes, both step 1 minute) are enumerated by `blog.AssignWindows` (`src/AssignWindows.java`, registered as `ASSIGN_WINDOWS`), a stateless Java table function. Membership is `[start,end)`. The creation and cancellation expressions retain inclusive `BETWEEN` endpoints. Filters use `updated_at >= observed_at - window_length` and `stay_date >= DATE(observed_at)`. There is no watermark, window finalization or TTL; old windows remain correctable. + +Amounts are non-null integer cents. The small fixture stays safely within BIGINT range. NULL amounts and arithmetic overflow are outside this example's input contract. The static `channels` table maps OTA to 1, DIRECT to 0, and a missing key to 0. Dimension values must stay fixed for this run: a live, changing lookup dimension would require a separate contract for the enriched before-image. + +`sql/transform.sql` defines `images` over `orders$changelog` with `PROCTIME() AS lookup_pt` for the static `channels` lookup, and maps `_change_type` in SQL `CASE` (`'insert'` and `'update_after'` -> `+1`; `'update_before'` and `'delete'` -> `-1`) to `row_sign`. Both statements in `sql/write.sql` (`EXECUTE STATEMENT SET`) consume `contributions` and multiply each metric by `row_sign` as append-only signed `INSERT` rows. The business cancellation flag is evaluated inside each image's `factor` before applying `row_sign`. The Fluss path (`window_totals`) does not send business `DELETE` operations to the aggregation merge engine. + +`window_totals` is the published output. Its full key is `(hotel_id,stay_date,window_minutes,window_start,window_end)`. Net-zero rows remain present. There is no wide-table projection or implicit choice of a “latest” window. + +Flink checkpoint recovery pairs the `orders$changelog` source offset with the connector's undo state. The SUM table does not deduplicate arbitrary business events or business IDs. Starting a new job to re-read `orders$changelog` against the same table is not a valid recovery procedure. + +## Files + +- `src/AssignWindows.java`: the only Java source file; top-level stateless `blog.AssignWindows` UDTF enumerating the 2- and 4-minute windows. +- `sql/catalog.sql`: Fluss catalog configuration (`fluss` catalog pointing at `coordinator:9123`). +- `sql/setup.sql`: `hotel_blog` database, `orders` primary-key input table, static `channels` lookup table (seeded with `DIRECT` and `OTA`), `window_totals` aggregation table (with `sum` explicitly configured on every metric), and `baseline` standard PK reference table. +- `sql/transform.sql`: loads `/opt/flink/assign-windows.jar`, registers `ASSIGN_WINDOWS`, defines the `images` view over `orders$changelog` with `PROCTIME() AS lookup_pt`, maps `_change_type` to `row_sign` via SQL `CASE`, performs static dimension lookup, stateless window expansion, deterministic filtering, and per-image `contributions`. +- `sql/write.sql`: `EXECUTE STATEMENT SET` submitting direct Fluss accumulation into `window_totals` and the Flink `GroupAggregate` reference into `baseline` from `contributions`. +- `run.py`: runs Flink SQL Client for setup, staged `orders` fixture writes, job submission, and bounded batch snapshot queries; controls checkpoints and real TaskManager `SIGKILL` recovery; and independently reconciles both tables against the Python oracle. +- `runtime/`: `Dockerfile.flink` (multi-stage Flink image build compiling `src/AssignWindows.java` into `assign-windows.jar`), `artifacts.json` (pinned connector SHA-256) and `connector.sha1` (upstream Maven Central checksum source). + +The oracle retains the current complete order image and recomputes its windows from scratch; it does not add the candidate's signed deltas. Historical touched keys are filled with zero to match the agreed zero-row retention contract. Comparing both paths alone would miss a shared expansion or sign bug. + +## Cleanup + +```sh +python3 run.py cleanup +``` + +This removes only the `hotel-window-blog` Compose project's containers, network and named volumes, including its checkpoints and table data. Evidence and source files remain on disk. The connector cache in `.runtime/` and local Docker images can be removed separately when no longer needed.
diff --git a/flink-multi-window-aggregation/compose.yaml b/flink-multi-window-aggregation/compose.yaml new file mode 100644 index 0000000..b10cb0c --- /dev/null +++ b/flink-multi-window-aggregation/compose.yaml
@@ -0,0 +1,61 @@ +name: hotel-window-blog +services: + zookeeper: + image: zookeeper:3.9.2 + coordinator: + image: apache/fluss:1.0.0@sha256:ff461b45438033da4fd1c2556d3f978f3603bb3632fe075c2bd57388339a58cb + command: coordinatorServer + depends_on: [zookeeper] + environment: + FLUSS_PROPERTIES: | + zookeeper.address: zookeeper:2181 + bind.listeners: FLUSS://coordinator:9123 + remote.data.dir: /shared/remote + default.replication.factor: 1 + volumes: ["remote:/shared"] + tablet: + image: apache/fluss:1.0.0@sha256:ff461b45438033da4fd1c2556d3f978f3603bb3632fe075c2bd57388339a58cb + command: tabletServer + depends_on: [coordinator] + environment: + FLUSS_PROPERTIES: | + zookeeper.address: zookeeper:2181 + bind.listeners: FLUSS://tablet:9123 + remote.data.dir: /shared/remote + data.dir: /shared/tablet + tablet-server.id: 0 + default.replication.factor: 1 + volumes: ["remote:/shared"] + jobmanager: + build: + context: . + dockerfile: runtime/Dockerfile.flink + image: flink-multi-window-aggregation:1.20.3-fluss1.0.0 + command: jobmanager + ports: ["127.0.0.1:18096:8081"] + environment: + FLINK_PROPERTIES: | + jobmanager.rpc.address: jobmanager + rest.bind-address: 0.0.0.0 + jobmanager.memory.process.size: 1536m + execution.checkpointing.interval: 3600s + execution.checkpointing.timeout: 60s + state.checkpoints.dir: file:///checkpoints + restart-strategy.type: fixed-delay + restart-strategy.fixed-delay.attempts: 5 + restart-strategy.fixed-delay.delay: 3s + volumes: ["./:/example", "checkpoints:/checkpoints", "remote:/shared"] + taskmanager: + image: flink-multi-window-aggregation:1.20.3-fluss1.0.0 + command: taskmanager + depends_on: [jobmanager] + environment: + FLINK_PROPERTIES: | + jobmanager.rpc.address: jobmanager + taskmanager.numberOfTaskSlots: 8 + taskmanager.memory.process.size: 2048m + state.checkpoints.dir: file:///checkpoints + volumes: ["./:/example", "checkpoints:/checkpoints", "remote:/shared"] +volumes: + remote: + checkpoints:
diff --git a/flink-multi-window-aggregation/data/expected-final.json b/flink-multi-window-aggregation/data/expected-final.json new file mode 100644 index 0000000..21e8cb9 --- /dev/null +++ b/flink-multi-window-aggregation/data/expected-final.json
@@ -0,0 +1,152 @@ +[ + { + "key": [ + "H1", + "2026-06-02", + "2", + "2026-06-01 09:59:00", + "2026-06-01 10:01:00" + ], + "values": [ + 0, + 0, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "2", + "2026-06-01 10:00:00", + "2026-06-01 10:02:00" + ], + "values": [ + 0, + 0, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "2", + "2026-06-01 10:01:00", + "2026-06-01 10:03:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "2", + "2026-06-01 10:02:00", + "2026-06-01 10:04:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 09:57:00", + "2026-06-01 10:01:00" + ], + "values": [ + 0, + 0, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 09:58:00", + "2026-06-01 10:02:00" + ], + "values": [ + 0, + 0, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 09:59:00", + "2026-06-01 10:03:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 10:00:00", + "2026-06-01 10:04:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 10:01:00", + "2026-06-01 10:05:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + }, + { + "key": [ + "H1", + "2026-06-02", + "4", + "2026-06-01 10:02:00", + "2026-06-01 10:06:00" + ], + "values": [ + 1, + 7000, + 0, + 0 + ] + } +] \ No newline at end of file
diff --git a/flink-multi-window-aggregation/data/images.csv b/flink-multi-window-aggregation/data/images.csv new file mode 100644 index 0000000..9fd1b13 --- /dev/null +++ b/flink-multi-window-aggregation/data/images.csv
@@ -0,0 +1,8 @@ +INSERT,H1,A,2026-06-02,2026-06-01 10:00:30.000,2026-06-01 10:00:00.000,2026-06-01 10:00:30.000,0,10000,OTA +INSERT,H1,B,2026-06-02,2026-06-01 10:01:00.000,2026-06-01 10:01:00.000,2026-06-01 10:01:00.000,0,5000,DIRECT +UPDATE_BEFORE,H1,A,2026-06-02,2026-06-01 10:00:30.000,2026-06-01 10:00:00.000,2026-06-01 10:00:30.000,0,10000,OTA +UPDATE_AFTER,H1,A,2026-06-02,2026-06-01 10:00:30.000,2026-06-01 10:00:00.000,2026-06-01 10:00:30.000,0,12000,OTA +UPDATE_BEFORE,H1,A,2026-06-02,2026-06-01 10:00:30.000,2026-06-01 10:00:00.000,2026-06-01 10:00:30.000,0,12000,OTA +UPDATE_AFTER,H1,A,2026-06-02,2026-06-01 10:00:30.000,2026-06-01 10:00:00.000,2026-06-01 10:01:00.000,1,12000,OTA +DELETE,H1,B,2026-06-02,2026-06-01 10:01:00.000,2026-06-01 10:01:00.000,2026-06-01 10:01:00.000,0,5000,DIRECT +INSERT,H1,C,2026-06-02,2026-06-01 10:02:00.000,2026-06-01 10:02:00.000,2026-06-01 10:02:00.000,0,7000,MISSING
diff --git a/flink-multi-window-aggregation/prepare.sh b/flink-multi-window-aggregation/prepare.sh new file mode 100755 index 0000000..f0ef100 --- /dev/null +++ b/flink-multi-window-aggregation/prepare.sh
@@ -0,0 +1,32 @@ +#!/bin/bash +set -euo pipefail +cd "$(dirname "$0")" +mkdir -p .runtime evidence +connector=.runtime/connector.jar +if [ ! -s "$connector" ]; then + curl -fL --retry 2 --connect-timeout 20 --max-time 900 \ + https://repo.maven.apache.org/maven2/org/apache/fluss/fluss-flink-1.20/1.0.0/fluss-flink-1.20-1.0.0.jar \ + -o "$connector.tmp" + mv "$connector.tmp" "$connector" +fi +python3 - <<'PY2' +import hashlib,json +from pathlib import Path +expected=json.loads(Path('runtime/artifacts.json').read_text())['connector']['sha256'] +with open('.runtime/connector.jar','rb') as connector: + actual=hashlib.file_digest(connector,'sha256').hexdigest() +if actual != expected: + raise SystemExit('Connector checksum mismatch') +PY2 +docker compose build +docker compose up -d + +python3 - <<'PYWAIT' +import time,urllib.request +for i in range(90): + try: + urllib.request.urlopen('http://127.0.0.1:18096/overview',timeout=2).close() + break + except OSError:time.sleep(1) +else:raise SystemExit('Flink REST endpoint did not become ready') +PYWAIT
diff --git a/flink-multi-window-aggregation/run.py b/flink-multi-window-aggregation/run.py new file mode 100644 index 0000000..7ec360d --- /dev/null +++ b/flink-multi-window-aggregation/run.py
@@ -0,0 +1,209 @@ +#!/usr/bin/env python3 +"""Run the isolated tutorial and compare live tables with a current-image oracle.""" +from pathlib import Path +import argparse,csv,datetime as dt,json,subprocess,time,urllib.request,re +ROOT=Path(__file__).resolve().parent +E=ROOT/'evidence' +BASE='http://127.0.0.1:18096' + +def command(args,log=None,timeout=180,input=None): + p=subprocess.run(args,cwd=ROOT,input=input,text=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,timeout=timeout) + if log:(E/log).write_text(p.stdout) + if p.returncode:raise RuntimeError(f'{args[:4]} exited {p.returncode}\n{p.stdout[-6000:]}') + return p.stdout + +def compose(*args,**kw):return command(['docker','compose',*args],**kw) +def api(path,data=None): + request=urllib.request.Request(BASE+path,data=None if data is None else json.dumps(data).encode(),headers={'Content-Type':'application/json'}) + with urllib.request.urlopen(request,timeout=10) as r:return json.load(r) +def until(fn,timeout=120): + end=time.monotonic()+timeout + while time.monotonic()<end: + value=fn() + if value:return value + time.sleep(1) + raise TimeoutError('Condition did not become true') +def sql_file(name): + return (ROOT / 'sql' / name).read_text() + + +def sql_client(statements, log=None, *, batch=False, use_database=True): + settings = ["SET 'parallelism.default' = '1';", "SET 'table.local-time-zone' = 'UTC';"] + if batch: + settings.extend([ + "SET 'execution.runtime-mode' = 'batch';", + "SET 'table.dml-sync' = 'true';", + "SET 'sql-client.execution.result-mode' = 'tableau';", + "SET 'sql-client.display.max-column-width' = '256';", + ]) + script = settings + [sql_file('catalog.sql')] + if use_database: + script.append('USE hotel_blog;') + script.append(statements) + out = compose('exec', '-T', 'jobmanager', '/opt/flink/bin/sql-client.sh', + '-f', '/dev/stdin', input='\n'.join(script) + '\n', log=log) + if '[ERROR]' in out: + raise RuntimeError(out[-6000:]) + return out + + +def snapshot(table, label): + columns = 'hotel_id stay_date window_minutes window_start window_end nights revenue_cents channel_nights channel_revenue_cents'.split() + fields = ', '.join(f'CAST({column} AS STRING)' for column in columns) + out = sql_client(f"SELECT CONCAT_WS('|', 'RESULT', {fields}) FROM {table};", + log=f'{label}-{table}.log', batch=True) + result = {} + for record in re.findall(r'^\|\s+RESULT\|(.+?)\s+\|$', out, re.MULTILINE): + fields = record.split('|') + fields[3:5] = [dt.datetime.fromisoformat(value).isoformat(sep=' ') for value in fields[3:5]] + result[tuple(fields[:5])] = list(map(int, fields[5:])) + if not result: + raise AssertionError('No snapshot rows: ' + out[-2000:]) + return result + + +def oracle(limit): + # Independent algorithm: retain current order images, then recompute every group. + images={};touched=set() + def row_windows(row): + hotel,order,stay,obs,created,updated,cancel,amount,rate=row + obs,created,updated=map(dt.datetime.fromisoformat,(obs,created,updated)) + if dt.date.fromisoformat(stay)<obs.date():return [] + epoch=dt.datetime(1970,1,1) + minute=int((obs-epoch).total_seconds()//60) + out=[] + for length in (2,4): + if updated<obs-dt.timedelta(minutes=length):continue + # Enumerate starts, independently of the SQL's end-offset expansion. + for start_minute in range(minute-length+1,minute+1): + start=epoch+dt.timedelta(minutes=start_minute);end=start+dt.timedelta(minutes=length) + if not start<=obs<end:continue + factor=int(start<=created<=end)-int(int(cancel)==1 and start<=updated<=end) + selected=int(rate=='OTA');amount=int(amount) + key=(hotel,stay,str(length),start.isoformat(sep=' '),end.isoformat(sep=' ')) + out.append((key,[factor,factor*amount,selected*factor,selected*factor*amount])) + return out + for c in list(csv.reader((ROOT/'data/images.csv').open()))[:limit]: + op,*row=c + key=tuple(row[:3]) + touched.update(k for k,_ in row_windows(row)) + if op in ('INSERT','UPDATE_AFTER'):images[key]=row + else: + if images.get(key)!=row:raise AssertionError('Incomplete/inconsistent before image: '+str(c)) + images.pop(key) + result={k:[0,0,0,0] for k in touched} + for row in images.values(): + for key,values in row_windows(row): + for i,n in enumerate(values):result[key][i]+=n + return result + +def append_order_changes(start, stop, label): + changes = list(csv.reader((ROOT / 'data/images.csv').open()))[start:stop] + + def quote(value): + return "'" + value.replace("'", "''") + "'" + + statements = [] + for kind, *image in changes: + if kind == 'UPDATE_BEFORE': + # The primary-key table generates this old image from its current value. + continue + if kind == 'DELETE': + hotel, order, stay = map(quote, image[:3]) + statements.append( + f'DELETE FROM orders WHERE hotel_id = {hotel} AND order_id = {order}' + f' AND stay_date = {stay};' + ) + else: + values = [*map(quote, image[:6]), str(int(image[6])), str(int(image[7])), quote(image[8])] + statements.append(f"INSERT INTO orders VALUES ({', '.join(values)});") + sql_client('\n'.join(statements), log=f'{label}-orders.log', batch=True) + + +def compare(limit,label): + expected=oracle(limit) + # This bounded demo has tiny input; wait for asynchronous sink flush, then snapshot. + time.sleep(3) + for attempt in range(6): + candidate=snapshot('window_totals',label) + baseline=snapshot('baseline',label) + if candidate==baseline==expected: + report={'input_images':limit,'window_groups':len(expected),'candidate_matches_oracle':True,'baseline_matches_oracle':True, + 'rows':[{'key':list(k),'values':v} for k,v in sorted(expected.items())]} + (E/f'{label}.json').write_text(json.dumps(report,indent=2)) + print(label,'PASS',len(expected),'groups',flush=True);return report + time.sleep(2) + (E/f'{label}-mismatch.json').write_text(json.dumps({'expected':[(k,v) for k,v in expected.items()], + 'candidate':[(k,v) for k,v in candidate.items()],'baseline':[(k,v) for k,v in baseline.items()]},indent=2)) + raise AssertionError(label+' differs; inspect evidence') + +def checkpoint(job,label): + request=api('/jobs/'+job+'/checkpoints',{'checkpointType':'FULL'}) + trigger=request['request-id'] + def completed(): + status=api('/jobs/'+job+'/checkpoints/'+trigger) + if status.get('status',{}).get('id')=='COMPLETED': + if 'failure-cause' in status.get('operation',{}):raise RuntimeError(str(status)) + return status + result=until(completed) + info=api('/jobs/'+job+'/checkpoints') + (E/(label+'.json')).write_text(json.dumps({'trigger':result,'checkpoints':info},indent=2)) + return info['latest']['completed']['id'] + +def verify(): + E.mkdir(exist_ok=True) + jobs=api('/jobs/overview')['jobs'] + if any(j['state']=='RUNNING' for j in jobs):raise RuntimeError('Tutorial already has a running job; use cleanup before a fresh verification') + sql_client(sql_file('setup.sql'), log='setup.log', batch=True, use_database=False) + out = sql_client(sql_file('transform.sql') + sql_file('write.sql'), log='job-submission.log') + match=re.search(r'Job ID:\s*([0-9a-f]{32})',out) + if not match:raise RuntimeError(out) + job=match.group(1) + def running(): + state=api('/jobs/'+job)['state'] + if state in ('FAILED','CANCELED'):raise RuntimeError('Job state '+state) + return state=='RUNNING' + until(running) + graph=api('/jobs/'+job+'/plan') + (E/'job-graph.json').write_text(json.dumps(graph,indent=2)) + nodes=[n['description'] for n in graph['plan']['nodes']] + if any('Source: Values' in n for n in nodes):raise AssertionError('Window expansion must not use a replaying constant source') + append_order_changes(0, 2, '01-created') + compare(2,'01-created') + saved=checkpoint(job,'02-checkpoint') + append_order_changes(2, 4, '03-price-corrected-uncheckpointed') + compare(4,'03-price-corrected-uncheckpointed') + # Force replay of successful writes after the completed source/sink checkpoint. + compose('kill','-s','SIGKILL','taskmanager',log='taskmanager-kill.log') + compose('up','-d','taskmanager',log='taskmanager-restart.log') + until(lambda:(api('/jobs/'+job+'/checkpoints')['latest']['restored'] or {}).get('id')==saved and running(),timeout=120) + compare(4,'04-recovered') + restored=api('/jobs/'+job+'/checkpoints') + if restored['latest']['restored']['id']!=saved:raise AssertionError('Wrong restored checkpoint') + (E/'recovery.json').write_text(json.dumps(restored,indent=2)) + previous = 4 + for limit,label in [(6,'05-cancelled'),(7,'06-deleted'),(8,'07-new-order')]: + append_order_changes(previous, limit, label) + compare(limit, label) + previous = limit + committed=checkpoint(job,'08-checkpoint-after-recovery') + before=api('/jobs/'+job+'/checkpoints')['latest']['restored']['restore_timestamp'] + compose('kill','-s','SIGKILL','taskmanager',log='committed-taskmanager-kill.log') + compose('up','-d','taskmanager',log='committed-taskmanager-restart.log') + def restored_again(): + latest=api('/jobs/'+job+'/checkpoints')['latest']['restored'] + return latest and latest['id']==committed and latest['restore_timestamp']>before and running() + until(restored_again,timeout=120) + compare(8,'09-recovered-committed') + (E/'committed-recovery.json').write_text(json.dumps(api('/jobs/'+job+'/checkpoints'),indent=2)) + report={'status':'PASS','job_id':job,'flink':'1.20.3','fluss':'1.0.0','restored_checkpoint':saved,'committed_checkpoint':committed, + 'scope':'single job, parallelism 1, static lookup, full window keys; source replay after TaskManager SIGKILL', + 'phases':['01-created','03-price-corrected-uncheckpointed','04-recovered','05-cancelled','06-deleted','07-new-order','09-recovered-committed']} + (E/'result.json').write_text(json.dumps(report,indent=2)) + print(json.dumps(report,indent=2)) + +if __name__=='__main__': + parser=argparse.ArgumentParser();parser.add_argument('action',choices=['verify','query','cleanup']);args=parser.parse_args() + if args.action=='verify':verify() + elif args.action=='query':print(json.dumps([{'key':k,'values':v} for k,v in sorted(snapshot('window_totals','query').items())],indent=2)) + else:compose('down','-v','--remove-orphans')
diff --git a/flink-multi-window-aggregation/runtime/Dockerfile.flink b/flink-multi-window-aggregation/runtime/Dockerfile.flink new file mode 100644 index 0000000..0e53054 --- /dev/null +++ b/flink-multi-window-aggregation/runtime/Dockerfile.flink
@@ -0,0 +1,15 @@ +FROM flink:1.20.3-scala_2.12-java11@sha256:1f3ada93c2d60ae65e8d1de2e099844e8905650788b3e560cfcee48c112eb4d2 AS flink + +FROM eclipse-temurin:11-jdk-jammy@sha256:56baf52be9510d77b5eaca50f3b0d5b4553ceffe6f98a52d4c82b5f4c73c5b82 AS compiler +WORKDIR /build +COPY --from=flink /opt/flink/lib/ ./lib/ +COPY .runtime/connector.jar ./lib/fluss-connector.jar +COPY src/AssignWindows.java ./ +RUN mkdir classes \ + && javac --release 11 -cp 'lib/*' -d classes AssignWindows.java \ + && jar cf assign-windows.jar -C classes . + +FROM flink +COPY --from=compiler /build/lib/fluss-connector.jar /opt/flink/lib/fluss-connector.jar +COPY --from=compiler /build/assign-windows.jar /opt/flink/assign-windows.jar +RUN install -d -o flink -g flink /checkpoints
diff --git a/flink-multi-window-aggregation/runtime/artifacts.json b/flink-multi-window-aggregation/runtime/artifacts.json new file mode 100644 index 0000000..0d58b44 --- /dev/null +++ b/flink-multi-window-aggregation/runtime/artifacts.json
@@ -0,0 +1,5 @@ +{ + "connector": { + "sha256": "656f72277e138b1e10c1ae3fcfe3b7780803c1d203ecca70fa0ce15128635363" + } +}
diff --git a/flink-multi-window-aggregation/runtime/connector.sha1 b/flink-multi-window-aggregation/runtime/connector.sha1 new file mode 100644 index 0000000..9c3aaaf --- /dev/null +++ b/flink-multi-window-aggregation/runtime/connector.sha1
@@ -0,0 +1 @@ +d142fd702787164cdfdd725683d4a66c30fbe4bb
diff --git a/flink-multi-window-aggregation/sql/catalog.sql b/flink-multi-window-aggregation/sql/catalog.sql new file mode 100644 index 0000000..24357cd --- /dev/null +++ b/flink-multi-window-aggregation/sql/catalog.sql
@@ -0,0 +1,5 @@ +CREATE CATALOG fluss WITH ( + 'type' = 'fluss', + 'bootstrap.servers' = 'coordinator:9123' +); +USE CATALOG fluss;
diff --git a/flink-multi-window-aggregation/sql/setup.sql b/flink-multi-window-aggregation/sql/setup.sql new file mode 100644 index 0000000..6c09f67 --- /dev/null +++ b/flink-multi-window-aggregation/sql/setup.sql
@@ -0,0 +1,22 @@ +CREATE DATABASE hotel_blog; +USE hotel_blog; +CREATE TABLE orders ( + hotel_id STRING, order_id STRING, stay_date STRING, + observed_at STRING, created_at STRING, updated_at STRING, + cancelled BIGINT, amount_cents BIGINT, rate_code STRING, + PRIMARY KEY (hotel_id, order_id, stay_date) NOT ENFORCED +) WITH ('bucket.num'='1'); +CREATE TABLE channels (rate_code STRING, selected BIGINT, PRIMARY KEY(rate_code) NOT ENFORCED) WITH ('bucket.num'='1'); +CREATE TABLE window_totals ( + hotel_id STRING,stay_date STRING,window_minutes INT,window_start TIMESTAMP(3),window_end TIMESTAMP(3), + nights BIGINT,revenue_cents BIGINT,channel_nights BIGINT,channel_revenue_cents BIGINT, + PRIMARY KEY(hotel_id,stay_date,window_minutes,window_start,window_end) NOT ENFORCED +) WITH ('bucket.num'='1','table.merge-engine'='aggregation', + 'fields.nights.agg'='sum','fields.revenue_cents.agg'='sum','fields.channel_nights.agg'='sum','fields.channel_revenue_cents.agg'='sum'); +CREATE TABLE baseline ( + hotel_id STRING,stay_date STRING,window_minutes INT,window_start TIMESTAMP(3),window_end TIMESTAMP(3), + nights BIGINT,revenue_cents BIGINT,channel_nights BIGINT,channel_revenue_cents BIGINT, + PRIMARY KEY(hotel_id,stay_date,window_minutes,window_start,window_end) NOT ENFORCED +) WITH ('bucket.num'='1'); + +INSERT INTO channels VALUES ('DIRECT',0),('OTA',1);
diff --git a/flink-multi-window-aggregation/sql/transform.sql b/flink-multi-window-aggregation/sql/transform.sql new file mode 100644 index 0000000..d4663e5 --- /dev/null +++ b/flink-multi-window-aggregation/sql/transform.sql
@@ -0,0 +1,34 @@ +ADD JAR '/opt/flink/assign-windows.jar'; + +CREATE TEMPORARY SYSTEM FUNCTION ASSIGN_WINDOWS AS 'blog.AssignWindows'; + +CREATE TEMPORARY VIEW images AS +SELECT *, PROCTIME() AS lookup_pt +FROM `orders$changelog`; + +CREATE TEMPORARY VIEW enriched AS +SELECT i.hotel_id,i.stay_date,CAST(i.observed_at AS TIMESTAMP(3)) AS observed_at, + CAST(i.created_at AS TIMESTAMP(3)) AS created_at,CAST(i.updated_at AS TIMESTAMP(3)) AS updated_at, + i.cancelled,i.amount_cents,COALESCE(c.selected,CAST(0 AS BIGINT)) AS selected, + CASE i._change_type + WHEN 'insert' THEN CAST(1 AS BIGINT) + WHEN 'update_after' THEN CAST(1 AS BIGINT) + WHEN 'update_before' THEN CAST(-1 AS BIGINT) + WHEN 'delete' THEN CAST(-1 AS BIGINT) + END AS row_sign +FROM images i +LEFT JOIN channels FOR SYSTEM_TIME AS OF i.lookup_pt c ON i.rate_code=c.rate_code; +CREATE TEMPORARY VIEW assigned AS +SELECT e.*,w.window_minutes,w.window_start,w.window_end +FROM enriched e, LATERAL TABLE(ASSIGN_WINDOWS(e.observed_at)) AS w(window_minutes,window_start,window_end) +WHERE e.updated_at>=TIMESTAMPADD(MINUTE,-w.window_minutes,e.observed_at) + AND CAST(e.stay_date AS DATE)>=CAST(e.observed_at AS DATE); +CREATE TEMPORARY VIEW factors AS +SELECT *, CAST(CASE WHEN created_at BETWEEN window_start AND window_end THEN 1 ELSE 0 END + + CASE WHEN cancelled=1 AND updated_at BETWEEN window_start AND window_end THEN -1 ELSE 0 END AS BIGINT) AS factor +FROM assigned; +CREATE TEMPORARY VIEW contributions AS +SELECT hotel_id,stay_date,window_minutes,window_start,window_end,row_sign, + factor AS nights,factor*amount_cents AS revenue_cents, + selected*factor AS channel_nights,selected*factor*amount_cents AS channel_revenue_cents +FROM factors;
diff --git a/flink-multi-window-aggregation/sql/write.sql b/flink-multi-window-aggregation/sql/write.sql new file mode 100644 index 0000000..d17d67a --- /dev/null +++ b/flink-multi-window-aggregation/sql/write.sql
@@ -0,0 +1,11 @@ +EXECUTE STATEMENT SET BEGIN +INSERT INTO window_totals +SELECT hotel_id,stay_date,window_minutes,window_start,window_end, + row_sign*nights,row_sign*revenue_cents,row_sign*channel_nights,row_sign*channel_revenue_cents +FROM contributions; +INSERT INTO baseline +SELECT hotel_id,stay_date,window_minutes,window_start,window_end, + SUM(row_sign*nights),SUM(row_sign*revenue_cents),SUM(row_sign*channel_nights),SUM(row_sign*channel_revenue_cents) +FROM contributions +GROUP BY hotel_id,stay_date,window_minutes,window_start,window_end; +END;
diff --git a/flink-multi-window-aggregation/src/AssignWindows.java b/flink-multi-window-aggregation/src/AssignWindows.java new file mode 100644 index 0000000..e94228b --- /dev/null +++ b/flink-multi-window-aggregation/src/AssignWindows.java
@@ -0,0 +1,26 @@ +package blog; + +import java.time.LocalDateTime; +import java.time.temporal.ChronoUnit; + +import org.apache.flink.table.annotation.DataTypeHint; +import org.apache.flink.table.annotation.FunctionHint; +import org.apache.flink.table.functions.TableFunction; +import org.apache.flink.types.Row; + +/** Expands a timestamp into the demo's 2- and 4-minute windows with a one-minute hop. */ +@FunctionHint(output = @DataTypeHint( + "ROW<window_minutes INT, window_start TIMESTAMP(3), window_end TIMESTAMP(3)>")) +public class AssignWindows extends TableFunction<Row> { + private static final int[] WINDOW_LENGTHS_MINUTES = {2, 4}; + + public void eval(LocalDateTime observedAt) { + LocalDateTime minute = observedAt.truncatedTo(ChronoUnit.MINUTES); + for (int windowMinutes : WINDOW_LENGTHS_MINUTES) { + for (int endOffsetMinutes = 1; endOffsetMinutes <= windowMinutes; endOffsetMinutes++) { + LocalDateTime end = minute.plusMinutes(endOffsetMinutes); + collect(Row.of(windowMinutes, end.minusMinutes(windowMinutes), end)); + } + } + } +}