Skip to content

Commit 2188671

Browse files
committed
fix comments
1 parent 7e7de36 commit 2188671

9 files changed

Lines changed: 188 additions & 94 deletions

File tree

‎.github/workflows/hudi_lakehouse_docker_live.yml‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,23 @@ jobs:
2525
docker compose -f hudi-lakehouse/docker/compose.yaml up -d --no-deps --wait gateway
2626
./hudi-lakehouse/docker/lakehouse.sh test
2727
- name: Verify repeat installation does not duplicate sample data
28-
run: ./hudi-lakehouse/docker/lakehouse.sh up
28+
run: |
29+
./hudi-lakehouse/docker/lakehouse.sh up
30+
./hudi-lakehouse/docker/lakehouse.sh test
31+
- name: Preserve user edits, deletions and empty tables across restart
32+
run: |
33+
set -euo pipefail
34+
docker compose -f hudi-lakehouse/docker/compose.yaml exec -T spark-connect python3 - modify < hudi-lakehouse/tests/docker_data_lifecycle.py
35+
./hudi-lakehouse/docker/lakehouse.sh down
36+
./hudi-lakehouse/docker/lakehouse.sh up
37+
docker compose -f hudi-lakehouse/docker/compose.yaml exec -T spark-connect python3 - verify < hudi-lakehouse/tests/docker_data_lifecycle.py
38+
if ./hudi-lakehouse/docker/lakehouse.sh test > /tmp/demo-validation.log 2>&1; then
39+
echo 'Strict demo validation unexpectedly accepted modified data.' >&2
40+
exit 1
41+
fi
42+
cat /tmp/demo-validation.log
43+
grep -q 'no longer match' /tmp/demo-validation.log
44+
docker compose -f hudi-lakehouse/docker/compose.yaml exec -T spark-connect python3 - verify < hudi-lakehouse/tests/docker_data_lifecycle.py
2945
- name: Diagnostics on failure
3046
if: failure()
3147
run: |

‎hudi-lakehouse/docker/.env.example‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ GATEWAY_LLM_PROVIDER=ollama
2424
GATEWAY_LLM_MODEL=qwen3:8b
2525
GATEWAY_OLLAMA_BASE_URL=http://host.docker.internal:11434
2626

27-
# Alternatively: anthropic + ANTHROPIC_API_KEY, openai + OPENAI_API_KEY,
27+
# Explicitly set GATEWAY_LLM_PROVIDER to anthropic + ANTHROPIC_API_KEY, openai + OPENAI_API_KEY,
2828
# or openai-compatible + GATEWAY_OPENAI_BASE_URL and optionally OPENAI_API_KEY.
29-
# Set GATEWAY_LLM_MODEL to a model supported by that provider.
29+
# API keys alone do not select a provider. Set GATEWAY_LLM_MODEL to a supported model.
3030
# ANTHROPIC_API_KEY=
3131
# OPENAI_API_KEY=
3232
# GATEWAY_OPENAI_BASE_URL=

‎hudi-lakehouse/docker/README.md‎

Lines changed: 26 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,8 @@ codex mcp add hudi --url http://localhost:8000/mcp/
7777
Start a new client session and ask it to query the lakehouse. The sample tables are
7878
`default.trips` (9 rows, partitioned by `trip_date`) and `default.drivers` (3 rows).
7979
The MCP tools `list_tables`, `describe_table` and `query_lakehouse` are read-only.
80+
The counts and expected query results below describe the initial demo dataset;
81+
they may differ after you modify data through Spark Connect.
8082

8183
Try: “List the tables”, “Describe trips”, or “For completed trips, sum fare_amount
8284
plus tip_amount by city”. The last question should return:
@@ -135,17 +137,17 @@ docker compose -f hudi-lakehouse/docker/compose.yaml --profile local-llm exec ol
135137

136138
### API provider
137139

138-
Export your key and model, then start the stack:
140+
Explicitly select your provider and export its key and model, then start the stack:
139141

140142
```bash
141-
export OPENAI_API_KEY=... # or ANTHROPIC_API_KEY
143+
export GATEWAY_LLM_PROVIDER=openai # or anthropic
144+
export OPENAI_API_KEY=... # use ANTHROPIC_API_KEY for anthropic
142145
export GATEWAY_LLM_MODEL=... # a model available to your provider/account
143146
./hudi-lakehouse/docker/lakehouse.sh up
144147
```
145148

146-
Without a `.env` or explicit provider, the script selects Anthropic when
147-
`ANTHROPIC_API_KEY` is set, then OpenAI when `OPENAI_API_KEY` is set, otherwise
148-
host Ollama. Keys are passed to the container and are never written by the installer.
149+
The default provider is Ollama. API keys alone do not change the provider.
150+
Keys are passed to the container and are never written by the installer.
149151

150152
### Save chat configuration
151153

@@ -165,15 +167,16 @@ configuration can prevent the service itself from starting.
165167

166168
## Manage the lakehouse
167169

168-
- **Start:** `./hudi-lakehouse/docker/lakehouse.sh up` starts services and verifies
169-
sample data in the seed job before starting the Gateway, then checks MCP and
170-
reports chat readiness separately.
170+
- **Start:** `./hudi-lakehouse/docker/lakehouse.sh up` starts services, initializes
171+
and validates missing demo tables, and preserves existing tables. It then checks
172+
MCP query availability and reports chat readiness separately.
171173
- **Inspect status:** `./hudi-lakehouse/docker/lakehouse.sh status` lists the
172174
installation's containers and their state.
173175
- **View logs:** `./hudi-lakehouse/docker/lakehouse.sh logs` shows recent service logs.
174-
- **Verify data and queries:** `./hudi-lakehouse/docker/lakehouse.sh test` checks
175-
stored data and queries the running Gateway over MCP without reseeding or
176-
requiring an LLM.
176+
- **Verify demo data and queries:** `./hudi-lakehouse/docker/lakehouse.sh test`
177+
strictly checks the original demo counts, totals and JOIN results without
178+
modifying data or requiring an LLM. User changes can make this command fail
179+
even when the lakehouse and MCP are working normally.
177180
- **Stop:** `./hudi-lakehouse/docker/lakehouse.sh down` removes containers and the
178181
network, preserving MinIO, HMS and Ollama volumes. Starting again with the same
179182
Compose project reuses them.
@@ -222,13 +225,13 @@ the existing Derby schema and restores the marker. A partial or invalid database
222225
preserved and startup stops with repair/restore guidance; it is never reinitialized
223226
in place.
224227

225-
The seed container uses direct Spark Connect SQL to create the sample tables.
226-
Dates are yesterday at the first seed. Stable record keys and inserts filtered against
227-
existing keys make retries safe without overwriting existing demo rows. The seed
228-
verifies counts, partitions and totals before the Gateway starts. Reserve these demo
229-
table names: existing incompatible schemas or modified sample data fail validation
230-
rather than being dropped or reset. No semantic-layer service or catalog abstraction
231-
is added.
228+
The seed container creates, populates and validates missing demo tables through
229+
Spark Connect SQL. Existing tables are preserved, including user changes and empty
230+
tables. If a missing table's storage path is still occupied, initialization fails
231+
without overwriting its files.
232+
233+
Startup checks MCP query availability. Use `lakehouse.sh test` for strict demo-data
234+
validation.
232235

233236
### Chat readiness checks
234237

@@ -245,7 +248,7 @@ is added.
245248
not validate the key or make a paid inference call.
246249
- **Chat unavailable:** missing models and discovery failures produce warnings
247250
without failing installation. Chat routes remain exposed regardless of readiness.
248-
- **Installation failures:** service startup, sample-data validation and MCP
251+
- **Installation failures:** service startup, validation of newly created sample tables and MCP
249252
failures still return a nonzero exit status.
250253

251254
### Release images
@@ -280,7 +283,9 @@ docker compose -f hudi-lakehouse/docker/compose.yaml up -d --force-recreate --wa
280283
```
281284

282285
The opt-in `Hudi Lakehouse Docker live acceptance` GitHub Actions workflow builds
283-
the images, starts a clean installation, checks MCP, recreates containers without
284-
reseeding to check persistence, and repeats installation to check seed idempotency.
286+
the images, starts a clean installation, checks MCP, and recreates containers without
287+
reseeding to check persistence. It also checks repeat installation, preservation of
288+
user edits/deletions and empty tables across restarts, and strict demo validation
289+
rejecting modified data without changing it.
285290
It requires no LLM credentials. A real model chat can be tested separately through
286291
the UI using the sample question above.

‎hudi-lakehouse/docker/compose.yaml‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,10 +101,11 @@ services:
101101
start_period: 30s
102102
stop_grace_period: 30s
103103

104-
# One-shot Python Connect client: create/populate trips and drivers, then verify
105-
# the sample data. Reuses the Spark image without starting another Spark server.
104+
# One-shot Python Connect client: create and verify missing demo tables, leaving
105+
# existing tables untouched. Reuses the Spark image without another Spark server.
106106
seed:
107107
image: ${SPARK_CONNECT_IMAGE:-hudi-lakehouse-spark-connect:4.1.3-hudi1.2.0}
108+
init: true # Keep Python out of PID 1 so its SIGALRM timeout can terminate it.
108109
depends_on:
109110
spark-connect:
110111
condition: service_healthy

‎hudi-lakehouse/docker/lakehouse.sh‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -94,15 +94,6 @@ if [[ "$ACTION" == up ]]; then
9494
echo 'Allocate at least 8 GB of memory to Docker (more for containerized Ollama).' >&2
9595
exit 1
9696
fi
97-
# Auto-select API credentials from the environment only when the user has not
98-
# supplied a .env configuration or an explicit provider. Never persist API keys.
99-
if [[ ! -f "$HERE/.env" && -z "${GATEWAY_LLM_PROVIDER:-}" ]]; then
100-
if [[ -n "${ANTHROPIC_API_KEY:-}" ]]; then
101-
export GATEWAY_LLM_PROVIDER=anthropic
102-
elif [[ -n "${OPENAI_API_KEY:-}" ]]; then
103-
export GATEWAY_LLM_PROVIDER=openai
104-
fi
105-
fi
10697
# Let Compose resolve .env interpolation and shell precedence. Read only the
10798
# provider/model; never eval or print this output because it can contain keys.
10899
CONFIG_ENV="$("${COMPOSE[@]}" config --environment)"
@@ -135,11 +126,13 @@ if [[ "$ACTION" == up ]]; then
135126
exit 1
136127
fi
137128
fi
138-
# up already verified the data in the seed dependency; test must not reseed it.
129+
# Startup validates newly created samples only; explicit tests never reseed data.
139130
if [[ "$ACTION" == test ]]; then
140131
"${COMPOSE[@]}" exec -T spark-connect python3 - --verify-only < "$HERE/scripts/seed.py"
132+
"${COMPOSE[@]}" exec -T gateway python /lakehouse/smoke-test.py --verify-sample
133+
else
134+
"${COMPOSE[@]}" exec -T gateway python /lakehouse/smoke-test.py
141135
fi
142-
"${COMPOSE[@]}" exec -T gateway python /lakehouse/smoke-test.py
143136
echo 'Lakehouse and MCP are ready.'
144137
if [[ "$ACTION" == up ]]; then
145138
if [[ -n "$CHAT_CONFIG_ERROR" ]]; then

‎hudi-lakehouse/docker/scripts/seed.py‎

Lines changed: 44 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -14,37 +14,20 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616

17-
"""Seed the demo tables through Spark Connect; retries never replace existing rows."""
17+
"""Initialize missing demo tables; preserve existing tables and all user changes."""
1818
import argparse
1919
import signal
2020

21-
from pyspark.sql import SparkSession
22-
23-
24-
def seed(spark):
25-
spark.sql("""CREATE TABLE IF NOT EXISTS default.drivers (
26-
driver_id STRING, driver_name STRING, home_city STRING,
27-
vehicle_type STRING, onboarded_date DATE
28-
) USING hudi TBLPROPERTIES (type = 'cow', primaryKey = 'driver_id')""").collect()
29-
spark.sql("""CREATE TABLE IF NOT EXISTS default.trips (
30-
trip_id STRING, rider_id STRING, driver_id STRING, city STRING,
31-
trip_status STRING, fare_amount DECIMAL(10,2), tip_amount DECIMAL(10,2),
32-
distance_km DOUBLE, pickup_ts TIMESTAMP, dropoff_ts TIMESTAMP, trip_date DATE
33-
) USING hudi PARTITIONED BY (trip_date)
34-
TBLPROPERTIES (type = 'cow', primaryKey = 'trip_id', preCombineField = 'pickup_ts')""").collect()
35-
spark.sql("""INSERT INTO default.drivers
36-
SELECT source.* FROM (
21+
DEMO_TABLES = {
22+
'drivers': """CREATE TABLE default.drivers USING hudi
23+
TBLPROPERTIES (type = 'cow', primaryKey = 'driver_id') AS
3724
SELECT * FROM VALUES
3825
('driver_1', 'Ananya', 'chennai', 'sedan', DATE '2024-01-01'),
3926
('driver_2', 'Alex', 'san_francisco', 'sedan', DATE '2024-01-01'),
4027
('driver_3', 'Ana', 'sao_paulo', 'sedan', DATE '2024-01-01')
41-
AS drivers(driver_id, driver_name, home_city, vehicle_type, onboarded_date)
42-
) source LEFT ANTI JOIN default.drivers target
43-
ON target.driver_id = source.driver_id""").collect()
44-
# Stable keys make reruns safe, including a retry after only one table committed.
45-
# First-run dates are yesterday; subsequent installs preserve the original data.
46-
spark.sql("""INSERT INTO default.trips
47-
SELECT source.* FROM (
28+
AS drivers(driver_id, driver_name, home_city, vehicle_type, onboarded_date)""",
29+
'trips': """CREATE TABLE default.trips USING hudi PARTITIONED BY (trip_date)
30+
TBLPROPERTIES (type = 'cow', primaryKey = 'trip_id', preCombineField = 'ts') AS
4831
SELECT concat('trip_', CAST(id AS STRING)) AS trip_id,
4932
concat('rider_', CAST(id AS STRING)) AS rider_id,
5033
concat('driver_', CAST(CAST(id / 3 AS INT) + 1 AS STRING)) AS driver_id,
@@ -56,38 +39,60 @@ def seed(spark):
5639
CAST(5 + id AS DOUBLE) AS distance_km,
5740
CAST(date_sub(current_date(), 1) AS TIMESTAMP) AS pickup_ts,
5841
CAST(date_sub(current_date(), 1) AS TIMESTAMP) + INTERVAL 15 MINUTES AS dropoff_ts,
42+
unix_millis(CAST(date_sub(current_date(), 1) AS TIMESTAMP)) AS ts,
5943
date_sub(current_date(), 1) AS trip_date
60-
FROM range(9)
61-
) source LEFT ANTI JOIN default.trips target
62-
ON target.trip_id = source.trip_id""").collect()
44+
FROM range(9)""",
45+
}
6346

6447

65-
def verify(spark):
48+
def seed(spark):
49+
for table, create_sql in DEMO_TABLES.items():
50+
if spark.catalog.tableExists(f'spark_catalog.default.{table}'):
51+
print(f'Preserving existing table default.{table}; skipping sample initialization.', flush=True)
52+
continue
53+
# Create and populate together rather than leaving an empty table between
54+
# separate CREATE and INSERT operations. Never repair an existing table.
55+
spark.sql(create_sql).collect()
56+
verify(spark, (table,))
57+
58+
59+
def verify(spark, expected_tables=('drivers', 'trips')):
6660
assert spark.conf.get("spark.sql.catalog.spark_catalog") == (
6761
"org.apache.spark.sql.hudi.catalog.HoodieCatalog"
6862
)
6963
tables = {row.tableName for row in spark.sql("SHOW TABLES IN spark_catalog.default").collect()}
70-
assert {"trips", "drivers"} <= tables, tables
71-
assert spark.sql("SELECT count(*) FROM default.trips").collect()[0][0] == 9
72-
assert spark.sql("SELECT count(*) FROM default.drivers").collect()[0][0] == 3
73-
rows = spark.sql("""SELECT city, SUM(fare_amount + tip_amount) AS gross_bookings
74-
FROM default.trips WHERE trip_status = 'completed' GROUP BY city ORDER BY city""").collect()
75-
actual = [(row.city, str(row.gross_bookings)) for row in rows]
76-
assert actual == [("chennai", "33.00"), ("san_francisco", "55.00"), ("sao_paulo", "77.00")], actual
77-
assert spark.sql("SHOW PARTITIONS default.trips").collect()
78-
print("PASS: HMS tables, partitions and sample Hudi data: " + str(actual), flush=True)
64+
assert set(expected_tables) <= tables, f'Missing demo tables: {set(expected_tables) - tables}'
65+
for table in expected_tables:
66+
expected_count = 3 if table == 'drivers' else 9
67+
actual_count = spark.sql(f'SELECT count(*) FROM default.{table}').collect()[0][0]
68+
assert actual_count == expected_count, (
69+
f'default.{table} no longer matches the demo dataset: '
70+
f'expected {expected_count} rows, found {actual_count}. Data was not modified.'
71+
)
72+
if 'trips' in expected_tables:
73+
rows = spark.sql("""SELECT city, SUM(fare_amount + tip_amount) AS gross_bookings
74+
FROM default.trips WHERE trip_status = 'completed' GROUP BY city ORDER BY city""").collect()
75+
actual = [(row.city, str(row.gross_bookings)) for row in rows]
76+
assert actual == [("chennai", "33.00"), ("san_francisco", "55.00"), ("sao_paulo", "77.00")], (
77+
f'default.trips totals no longer match the demo dataset: {actual}. Data was not modified.'
78+
)
79+
assert spark.sql("SHOW PARTITIONS default.trips").collect(), 'Missing default.trips partitions'
80+
print('PASS: sample Hudi data in ' + ', '.join(expected_tables), flush=True)
7981

8082

8183
def main():
84+
from pyspark.sql import SparkSession
85+
8286
parser = argparse.ArgumentParser(description=__doc__)
8387
parser.add_argument('--verify-only', action='store_true')
8488
args = parser.parse_args()
8589
signal.alarm(600)
8690
spark = SparkSession.builder.remote("sc://spark-connect:15002").getOrCreate()
8791
try:
88-
if not args.verify_only:
92+
if args.verify_only:
93+
verify(spark)
94+
else:
8995
seed(spark)
90-
verify(spark)
9196
finally:
9297
spark.stop()
9398

‎hudi-lakehouse/docker/scripts/smoke-test.py‎

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# limitations under the License.
1616

1717
"""Check the running gateway's real MCP -> Connect -> HMS -> MinIO path, without an LLM."""
18+
import argparse
1819
import asyncio
1920
import json
2021
import signal
@@ -23,7 +24,7 @@
2324
from fastmcp import Client
2425

2526

26-
async def main():
27+
async def main(verify_sample=False):
2728
with urllib.request.urlopen("http://127.0.0.1:8000/ui/", timeout=10) as response:
2829
assert response.status == 200
2930
async with Client("http://127.0.0.1:8000/mcp/") as client:
@@ -38,16 +39,26 @@ async def call(name, arguments):
3839

3940
tables = await call("list_tables", {})
4041
assert {"trips", "drivers"} <= {row[1] for row in tables["rows"]}, tables
41-
schema = await call("describe_table", {"table": "trips"})
42-
assert "trip_id" in {row[0] for row in schema["rows"]}, schema
43-
result = await call("query_lakehouse", {"sql":
44-
"SELECT d.home_city, count(*) AS trips FROM trips t "
45-
"JOIN drivers d ON t.driver_id = d.driver_id "
46-
"GROUP BY d.home_city ORDER BY d.home_city"})
47-
assert result["rows"] == [["chennai", 3], ["san_francisco", 3], ["sao_paulo", 3]], result
48-
print("PASS: chat UI, MCP discovery, schema and Hudi join through Spark Connect", flush=True)
42+
for table in ('trips', 'drivers'):
43+
schema = await call("describe_table", {"table": table})
44+
assert schema['rows'], schema
45+
# Probe readability without counting the whole table; empty tables are valid.
46+
result = await call("query_lakehouse", {"sql": f"SELECT * FROM {table} LIMIT 1"})
47+
assert len(result['rows']) <= 1, result
48+
if verify_sample:
49+
result = await call("query_lakehouse", {"sql":
50+
"SELECT d.home_city, count(*) AS trips FROM trips t "
51+
"JOIN drivers d ON t.driver_id = d.driver_id "
52+
"GROUP BY d.home_city ORDER BY d.home_city"})
53+
assert result["rows"] == [["chennai", 3], ["san_francisco", 3], ["sao_paulo", 3]], (
54+
f'Demo JOIN results differ from the original dataset: {result}. Data was not modified.'
55+
)
56+
print("PASS: chat UI, MCP discovery, schemas and Hudi queries through Spark Connect", flush=True)
4957

5058

5159
if __name__ == '__main__':
60+
parser = argparse.ArgumentParser(description=__doc__)
61+
parser.add_argument('--verify-sample', action='store_true')
62+
args = parser.parse_args()
5263
signal.alarm(180)
53-
asyncio.run(main())
64+
asyncio.run(main(verify_sample=args.verify_sample))

0 commit comments

Comments
 (0)