Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Cross-Source SQL Without ETL: Dojao's Reduced Spill & Python UDFs in a Distributed MPP Engine
Big Data 52 min read

Cross-Source SQL Without ETL: Dojao's Reduced Spill & Python UDFs in a Distributed MPP Engine

Dojao is a distributed MPP engine that runs cross-source SQL across Hive, MySQL, Excel and more without ETL, using a reduced spill-to-disk pipeline that shrinks intermediate data, a unified memory model with high/low watermarks, and Python UDFs via Arrow Flight sidecars — all startable on a single machine.

What Is Dojao?

Dojao is a distributed MPP compute engine for data scientists and analysts. It is not a database nor just a SQL parser. Its core goals:

Data stays in place — federated queries across sources; large queries follow memory-first, spill-as-fallback to finish rather than crash the node; Python (and other languages) extend distributed computation via a language-neutral protocol.

Built on Java 21, Apache Arrow 15.0.0, Arrow Flight 15.0.0, Python 3.11+ sidecar, Apache 2.0 license. Virtual threads handle blocking I/O for spill; not yet used throughout execution. Current version 0.1.0.

Deployment is flexible: default system.role = both launches Master and Worker as two JVMs on one machine for a full distributed path; system.deploy.mode = standalone (single JVM) exists in code but not yet in packaged config.

One SQL, Multiple Sources

Hive Detail JOIN MySQL Dimension

Cross-source queries usually require ETL: export dimension tables, create intermediates, configure scheduling, manage permissions. Dojao uses three-part names catalog.schema.table. Register a catalog once, then cross-source JOIN looks like a single-database query:

SELECT u.city, COUNT(*) AS c, ROUND(SUM(b.amount), 2) AS gmv
FROM hive.dojao_test.ods_user_behavior b
JOIN mydb.dga.users u ON b.user_id = u.user_id
WHERE b.dt BETWEEN '2026-09-01' AND '2026-09-30'
  AND b.event_type = 'pay'
GROUP BY u.city
ORDER BY gmv DESC
LIMIT 20;

The planner does column pruning; connectors declare predicate pushdown capability honestly — no pretending to push down because wrong results are worse than slowness.

Python Stats & Small Models as SQL Functions

Data scientists write NumPy/Polars/PyArrow functions. Dojao registers them as SQL functions via Arrow Flight to an independent sidecar — not row-by-row serialization but batched Arrow RecordBatch transfer, enabling true vectorized compute. Python is the reference implementation; the protocol is language-neutral.

pgvector Vectors Stay in PostgreSQL

PostgreSQL connector maps pgvector columns to Arrow FixedSizeList<Float32>. SQL can call cosine_similarity, l2_distance, inner_product directly — vectors never leave the source database.

Built-in ReAct Agent for AI-Assisted Analysis

Dojao includes a streaming ReAct Agent with 13 tools: read-only SQL & metadata exploration, cluster/query/operator diagnostics, log viewing, CSV/Excel/HTML/PNG/PDF export, chart rendering (11 types, dual Y-axis). Result sets cached via rs3 and last for multi-turn reuse. Permissions: read-only queries auto-execute; DDL/write require human confirmation (300s timeout); tool access role-based.

Web Console Opens the Black Box

Console at port 2380 includes SQL editor with autocomplete, task history/progress/cancel, memory/disk/spill monitoring, lineage DAG, catalog/function management, node resource monitoring (CPU, physical memory, JVM heap, threads), AI chat & charts. CLI and JDBC driver also provided.

Reduced Spill: Not Just Dumping Memory to Disk

Large JOIN, high-cardinality GROUP BY, window dedup, global sort — the pain is not slowness but mid-query failure. Many engines spill by dumping full data to disk. Dojao: fit in memory → compute; overflow → spill while reducing , so written intermediates are smaller than raw input.

Comparison (from project README/source comments, not independent benchmarks):

Primary positioning : Dojao — small memory, cross-source, high-determinism compute; Trino — large-scale pure-memory interactive query; Spark — large-scale ETL & batch.

Spill role : Dojao — core main path, shared by four operators; Trino — legacy positioning; Spark — mature shuffle spill.

Spill strategy : Dojao — reduced, trim while writing; Trino — full-volume dump, may slow drastically when forced; Spark — full-volume dump, heavy disk I/O.

High-cardinality grouping : Dojao — K-way merge controls peak memory; Trino — memory-first bias; Spark — relies on shuffle.

Python functions : Dojao — DFP protocol + independent sidecar; Trino — Java UDF or external frameworks; Spark — PySpark, bound to Spark runtime.

Memory config : Dojao — single node total derives key params; Trino — multiple interdependent params; Spark — separate heap/off-heap/shuffle accounting.

Single-node start : Dojao — system.role = both; Trino — Coordinator + Worker; Spark — local mode still relatively heavy.

AI-assisted query : Dojao — built-in Agent, tools, charting; Trino — usually external integration; Spark — usually external integration.

Dojao targets the realistic zone: limited memory, heterogeneous sources, spill almost inevitable, but queries should not fail.

Four Operators Share One Three-Slot Spill Pipeline

GroupBy, Window, SortMergeJoin, HashJoin share a physical path: organize by key → spill when memory low → merge → output . HashJoin stays out: build side must fit in memory; planner picks algorithm automatically; force sort-merge with query.join.algorithm = sort_merge.

Common logic in AbstractSpillableOperator (single-node and distributed share same operator code). New operators implement Slot interface and output logic to gain spill ability.

protected static final int SLOT_COUNT = 3;
private static final int OUTPUT_QUEUE_CAPACITY = 8;

Each partition holds 3 rotating slots: one receives data, up to two async-write to disk; slot shortage blocks. Pipeline: P1 batching & spill, P2 merge output; window sort adds P1.5 K-way merge; sort-merge join adds P3 to compact key-interleaved files. This abstraction centralizes backpressure, failure handling, heartbeats, ordering guarantees.

Window Dedup: Trim Before Spill

Example: ROW_NUMBER() OVER (PARTITION BY uid ORDER BY dt DESC) AS rn, keep rn = 1. Conventional approach writes full partition to disk, merges, then filters. Dojao prunes to top-N per partition before spill.

Core logic in WindowSortOperator.pruneKeepRows():

private int pruneKeepRows() {
  WindowFilterConfig f = filterConfig;
  if (f == null || !f.isActive() || !f.isPositional() || f.noOrderBy()) {
    return Integer.MAX_VALUE;
  }
  long n = f.targetValue();
  return switch (f.operator()) {
    case EQ, LE -> (int) Math.min(Integer.MAX_VALUE, Math.max(1L, n));
    case LT -> (int) Math.min(Integer.MAX_VALUE, Math.max(0L, n - 1));
    case GE, GT -> Integer.MAX_VALUE;
  };
}

Relies on: top-N (union) = top-N (union of each partition's top-N) . Partition/batch/file-level prune then merge yields row-identical results to full merge then prune.

Spill files changed from row-split many small files to one multi-batch Arrow file per slot spill , reducing file count to spill occurrences; merge usually finishes in one round. Pruning means only target rows per partition hit disk.

Pruning is not unconditional: RANK, DENSE_RANK have ties — use pruneRankGroup. GE, GT need tail rows — no prune.

No ORDER BY — positional semantics undefined — no prune.

Non-monotonic window filters (MIN, MAX, SUM, AVG) — no unsafe prune.

After prune, writeSortedBatches must use order.length, not acc.rowCount, to avoid out-of-bounds garbage rows.

Determinism over peak performance — concrete cases where optimization is deliberately skipped.

High-cardinality GROUP BY uses K-way merge to control memory, avoiding linear growth with key count. Data stays, indexes move : Arrow column data immobile; Map/Sort rearrange row IDs; spill does one-time rearranged output, enabling zero-copy transfer and spill paths.

Bounded Output Queue: Solve "Computed But Cannot Emit"

Early version used unbounded ConcurrentLinkedQueue and waited for all partitions to merge before emitting first page — billion-row results stuck in off-heap memory, release decoupled from downstream consumption.

Now output queue capacity fixed at 8 :

Merge task emits pages incrementally via emitPage.

Queue full blocks producer.

Peak queued memory ≈ 8 × page size.

Memory no longer grows with total result rows.

Downstream consumption speed back-propagates to merge task.

Parallel Merge Must Preserve Window Partition Order

Multiple shuffle buckets merging in parallel can interleave pages from different partitions, causing downstream Window operator to mis-detect partition boundaries and silently compute wrong RANK. orderedEmit ensures: merge phase parallel heavy lifting; emit phase serializes order-sensitive parts by ascending active partition . This design decides correctness, not just speed.

Production-Hardened Details

phase2Failure

fail-fast: first partition merge failure recorded, no partial results returned as success. mergeTicks increments during long merges to prove liveness to Master watchdog, avoiding false kill. emitBlockNanos separately records downstream backpressure time, distinguishing "merge slow" from "result return slow".

Single-slot spill threshold computed from actual shuffle buckets held by fragment, not diluted by global partition config (e.g., fragment with 1 bucket gets full operator budget, not 1/24).

Disk Protection: No Silent Node Fill

Spill directories support multi-disk rotation; query.spill.disk.maxUsage caps disk usage. Exceed threshold → switch candidate disk; all candidates exceed → explicit error, not system disk fill. Logs and console show spill volume and location.

Hard default: global ORDER BY without LIMIT refuses spill when over memory budget ( query.sort.topSpillPolicy = error). Such queries pull entire table to Master for single-node sort; spill would fill Master disk. Add LIMIT for bounded Top-N; if full sort needed, change policy to warn (alert then spill) or spill (silent spill).

Unified Memory Model: Declare Total, Rest Derived

Typical distributed engines require tuning JVM heap, off-heap, per-query slots, network buffers independently — change one, forget another, still OOM. Dojao config:

system.master.memory = 2g
system.worker.memory = 5g

query.spill.ratio = 0.8
query.spill.dir = /data1/dojao-spill,/data2/dojao-spill

query.memory.highWatermark = 0.85
query.memory.lowWatermark = 0.75

From system.worker.memory = 5g, default splits to heap 2.5g, off-heap 2.5g, then derives:

query.direct.limit
query.slot.memory

Fragment off-heap quota

Single-slot spill threshold

Values are computable and printable; user doesn't maintain a web of coupled params.

Memory model diagram
Memory model diagram

Core principle: Data in off-heap, indexes in heap, but they share one budget. Real column data in Arrow off-heap allocator; heap holds indexes, batch buffers, control objects. Single root allocator NodeMemory shared by operators, connectors, transport — unified accounting.

Previously each consumer created its own RootAllocator, each thinking it could use full machine memory. Crossing MaxDirectMemorySize caused Arrow OOM or kernel OOM kill with no Java exception. Unified hard limit makes goal: query fails, node stays alive. Off-heap quota reserves space for Netty/gRPC/Flight buffers to avoid JVM direct OOM on result transport.

Soft Backpressure When Memory Nears Limit

Beyond hard limit, throttle() slows readers:

public void throttle() {
  if (directUsageRatio() < highWatermark) return;
  long deadline = System.nanoTime() + throttleMaxMs * 1_000_000L;
  while (directUsageRatio() >= lowWatermark && System.nanoTime() < deadline) {
    try { Thread.sleep(20); }
    catch (InterruptedException e) { Thread.currentThread().interrupt(); return; }
  }
}

Default high=0.85, low=0.75, max wait 1000ms. Called only on readers about to consume more memory, never on spill/release paths (otherwise memory-releasing actions would stall). Two constraints: judge by actual usage not reserved quota (avoid cross-query deadlock), wait must be bounded (no permanent hang). This translates "out of memory" into "read slower", giving spill threads catch-up time.

Two Classic Config Pitfalls

Don't blindly increase heap. High-cardinality grouping may push heap indexes to GBs, but more heap only lengthens Full GC and makes JVM hold physical memory longer.

Don't put spill dir on /tmp . Many Linux systems mount /tmp as tmpfs (memory disk). You think you're spilling to disk but still eat memory — magical failure. Use dedicated disk directories for query.spill.dir; don't stress-test on system disk.

Memory Allocation Optimization Rounds

Early versions had "resources available yet spilling aggressively". After several convergence rounds, packaged config reflects optimized approach:

Single-slot threshold divided by actual shuffle buckets owned by fragment, not global partition count: fragment with 1 bucket gets full operator budget, not divided by 24; data skew won't leave budget idle. query.spill.minPartitionBytes floor (default 16M), capped by query.direct.limit and operator budget: avoids tiny spills and budget overflow.

Explicit query.slot.memory = 128M, query.memory.maxFragments = 6 — no longer derived from "worst-case concurrency" (~71M): 6 fragments × 3 slots × 128M × 0.8 ≈ 1.84G, fits in 2G Arrow budget.

Spill files changed from row-split many small files to one multi-batch Arrow file per slot spill; merge usually one round; window sort prunes by group/rank during spill; aggregation merges too-small spill files to avoid small-file storm.

Remaining boundary: chained fragments with multiple spill operators each take full budget at plan time, possible ~2x overcommit; currently guarded by query.direct.limit and NodeMemory.throttle(). docs/memory-model-optimization.md lags implementation — further per-operator budget splitting undecided. Hence 0.1.0 suits verification/trial, not production core replacement without stress testing.

DFP Protocol: Python UDF as Language-Neutral Contract, Not Plugin

Many Java engines claim Python UDF support but suffer either row-by-row serialization slowness or embedded interpreter crashes taking down the JVM. Dojao moves function runtime to independent sidecar process, governed by a language-neutral contract: DFP (Dojao Function Protocol) v2.

Engine recognizes only three function shapes — scalar, incremental aggregate, collect-evaluate aggregate (table/window functions reserved); it doesn't know or care if sidecar runs Python, Rust, Go.

Three Channels: Data Plane + Two Control Entrypoints

All over Arrow Flight (gRPC + Arrow IPC), three entrypoints:

Data plane : doExchange(path="invoke") — one function call, one batch in, one batch out.

Health : doAction("ping") — reports runtime status & protocol version.

Validation : doAction("check_function") — registration-time smoke test returning structured signature.

Native Arrow RecordBatch streams directly; control fields ( UdfControl / UdfMeta) sent in each batch's application_metadata. Protocol forbids wrapping Arrow IPC in bytes fields (double serialization loses performance). This is the multi-language point: Python is reference; any language implementing these three entrypoints with Arrow batch I/O plugs into same engine, zero Java execution-layer changes.

Data Plane: One Batch In, One Batch Out

One invoke = one request batch + one response batch; "response returned" = "batch completed". Even no-output ops must send empty batch then completed().

Request: RecordBatch(input) + application_metadata(UdfControl)
Response: RecordBatch(output) + application_metadata(UdfMeta, empty bytes = OK)

Empty UdfMeta = success (OK=0 protobuf default omitted); failure carries ERROR + readable message; connection stays open, subsequent batches continue. Aggregation state passed via opaque_state — protocol just transports bytes; Python uses pickle, others choose own serialization. Engine never interprets state, so state size/storage is language's concern.

Six Operations: Scalar, Incremental Aggregate, Collect-Evaluate

UdfControl.Op

defines semantics:

EVAL : scalar call, vectorized, input columns → output column same length.

CREATE_STATE / ACCUMULATE / MERGE / EVALUATE : incremental aggregate four phases; intermediate state in opaque_state; MERGE has extra source_state.

COLLECT_EVALUATE : engine groups by key, each key gets one row of collected value lists; sidecar evaluates per row. SHIP_CODE reserved for future code/bytecode/wasm push; not enabled.

Key trade-off: keep aggregation state in engine, not sidecar . Reason follows.

Aggregation State Stays in Engine, Sidecar Just Computes

Recommended aggregate UDF uses COLLECT_EVALUATE. Engine groups by key, input batch per key one row:

First key_column_count columns are GROUP BY keys.

Remaining columns are Arrow List columns per SQL argument position, each row holds all values collected for that key.

Sidecar extracts List, calls user function; N groups → N result rows.

Aggregation intermediate state lives entirely in engine Arrow columnar storage — engine can measure, spill, redistribute across nodes. Sidecar maintains no cross-batch state, only "given a batch of values, compute one result" — no cross-runtime state passing, no partition-splitting code in each language.

Arguments matched by position, not name. Function declared (num), called as stddev(discount_amount) → collected column is discount_amount. Column name is just positional label; sidecar looking up by name would silently grab wrong column after JOIN with duplicate names.

Type System Speaks Arrow, Not Language Dialects

DFP doesn't use "double" etc. requiring cross-language mapping tables. Instead passes Arrow schema IPC bytes ( FunctionSignature.output_schema, equivalent to pyarrow Schema.serialize()). Each language maps its types to Arrow; mainstream languages have Arrow libraries.

Input types provided by engine via batch's Arrow schema; NULLs via Arrow validity bitmap, no sentinel values. Function reference string function_ref opaque to engine; syntax defined by each language's SDK:

Python (official) : module.ClassName or module.function_name.

Error classification:

User code exception: Flight INTERNAL with UdfMeta.ERROR.

Transport crash/process crash: Flight UNAVAILABLE.

Call timeout (watchdog): Flight TIMED_OUT.

Engine maps to SidecarException.Kind (USER_CODE_ERROR, CRASHED, WATCHDOG_TIMEOUT, PROTOCOL_MISMATCH...) returning diagnosable info to query control plane, not crashing the JVM.

Standard Deviation Function: From Python to SQL

Python SDK example ( python/dojao_udf/examples/my_fns.py):

import pyarrow.compute as pc
from dojao_udf import collect_aggregate

@collect_aggregate(("num",), "double")
def stddev(num):
    return float(pc.stddev(num).as_py()) if len(num) > 0 else None

Register in engine:

CREATE FUNCTION stddev_py WITH (
    type = 'python',
    code_path = 'shared://udf/my_fns.py',
    class_name = 'my_fns.stddev'
);
code_path

resolved by backend: file://, shared://, http(s)://, hdfs://, s3://; shared:// maps to engine's shared function dir ( system.function.shared.dir, default <workdir>/shared). Function code declared once, all Workers fetch.

Then use like any SQL function:

SELECT product_id, stddev_py(amount) AS sd
FROM hive.dojao_test.ods_user_behavior
WHERE dt BETWEEN '2026-09-01' AND '2026-09-30'
GROUP BY product_id;

NumPy/Polars/PyArrow batch capabilities reused directly, no per-row Python calls. Process isolation gives timeout, auto-restart, fault isolation: function crash only affects that sidecar, not the JVM. Trade-off: cross-process + Flight overhead, schema alignment more complex than JAR loading. Extreme in-process performance vs. language ecosystem & fault isolation — two different accounts.

Adding a New Language: Four Steps, Zero Engine Changes

DFP cleanly separates engine and language runtime. New language integration:

Implement sidecar: provide ping, check_function, doExchange(path="invoke") per protocol, read/write Arrow batches & control envelopes, ping reports protocol_version = 2.

Implement Java backend: implement com.dojao.spi.function.FunctionBackend ( type() returns language name), use SidecarPool.Runtime(name, command, env) to describe launch command & environment — process orchestration, health checks, version negotiation, pooling all reused.

Register backend: BackendRegistry.register(...) or via ServiceLoader on classpath.

Optional: thin SDK (Arrow I/O, control envelope handling, function contract declaration) to lower user barrier.

Reference implementation is Python: python/dojao_udf/sidecar.py (protocol server), base.py (function contract), examples/ (scalar, incremental aggregate, collect aggregate). Full protocol in repo root UDF_PROTOCOL.md, message definitions in udf.proto.

Code Distribution & Python Environment

Sidecar Python environment determined by three keys, recommended in each node's conf/dojao.conf:

system.python.home = /opt/dojao-pyenv
# Official SDK path, default <DOJAO_HOME>/python — this is engine-bundled sidecar runtime, NOT user function code
system.python.udf.runtime = <DOJAO_HOME>/python
# Sidecar process count, default 4, recommend ≥ partition parallelism
system.python.pool = 4
system.python.udf.runtime

often misunderstood: points to Dojao's bundled Python function runtime ( dojao_udf package), not user business code from CREATE FUNCTION; user code injected via code_path. No local Python interpreter → only Python functions unavailable; Java functions and other queries unaffected.

Can override via env:

DOJAO_JVM_OPTS="-Dsystem.python.home=/opt/dojao-pyenv" ./bin/dojao

.

Connector SPI: JDBC Not Baked Into Soul

Many federated query projects become "JDBC wrappers for many databases". Dojao connector contract has only three layers:

ConnectorFactory : declares type, display name, config items; validates params at registration.

DojaoConnector : metadata discovery, planSplits → openSplit → ScanReader for reads; implements write(WriteRequest) for writes (read-only connectors explicitly throw UnsupportedOperationException); hooks for column pruning, predicate pushdown, parallel slicing.

Split & ScanReader : a split = independently describable, serializable, dispatchable, readable work unit.

Relational DBs, Hive, ClickHouse, Doris, Excel all fit. Future Kafka, Elasticsearch, MongoDB, Iceberg can design splits around topic/partition, file, shard — no forcing into JDBC model.

Custom connector without engine changes:

Depend on dojao-spi with provided scope.

Implement ConnectorFactory and DojaoConnector.

Build JAR, drop in lib/connectors/.

Each JAR loaded by isolated classloader.

Repo includes csvdir example ( examples/dojao-connector-example) reading local directory as database: 4 classes, ~850 lines, zero third-party deps — good for learning full contract.

Two "Must-Know" Defaults That Bite

request.columns() Empty Means All Columns, Not Zero

If interpreted as zero columns, query succeeds but returns zero rows. Wastes time because SQL looks perfectly fine.

supportsPredicatePushdown() Defaults to False

Conservative and correct:

No declared pushdown → just one missed optimization; engine wraps a Filter, result still correct.

Default true but connector doesn't actually filter, local Filter may be optimized away → silent wrong results.

Also, SPI copy() defaults to this (stateless/immutable safe); if connector holds mutable state, must override.

Slicing Follows Data Source Nature

Dojao doesn't force one parallelism style for all sources:

OLTP databases : predicate-based splits by PK or row ranges.

Hive, data lake : by file groups; huge files further split by ORC stripe / Parquet row group.

ClickHouse, Doris, SQL Server : predicate-based: PK, numeric range, OFFSET/LIMIT three-level fallback.

Excel : constant single partition; parallelism pushed to downstream aggregation/JOIN.

Type mapping handles common pitfalls:

SQL Server tinyint (0..255) read as SMALLINT to avoid sign issues.

Oracle NUMBER without precision → NUMBER(38,10).

Oracle FLOAT → BINARY_DOUBLE.

Excel single partition is deliberate: .xlsx / .xlsm are ZIP packages; one table = one XML stream. Forcing multi-split makes each Worker re-unzip same ZIP and scan from start to its offset — total I/O multiplies by split count. Knowing when NOT to parallelize is more professional than claiming "parallel acceleration" everywhere.

Five Minutes to Run: Single-Node First, Then Cluster

Option 1: Distribution Package

Prefer dojao-0.1.0.tar.gz/.zip: engine, connectors, Python reference, dependency JARs all inside; unpack and run (JDK 21 required separately).

# Download dojao-0.1.0.tar.gz from GitHub Releases
tar -xzf dojao-0.1.0.tar.gz
cd dojao

# Default system.role = both (launches Master + Worker as two JVMs on this machine)
./bin/dojao

Another terminal for CLI: ./bin/dojao-cli CLI connects to Arrow Flight port 6530. Browser at http://localhost:2380 for SQL editor, task dashboard, monitoring, AI chat.

Option 2: Build from Source

Requires JDK 21, Maven 3.9+:

git clone https://github.com/Jason1008Jia/Dojao.git
cd Dojao
mvn clean package -DskipTests

Then enter distribution dir and start:

cd distribution/target/dojao-0.1.0/dojao
./bin/dojao

Minimal config confirm these two:

system.role = both
query.spill.dir = /data1/dojao-spill,/data2/dojao-spill

Again: don't put spill dir on /tmp , don't stress-test on system disk.

No MySQL/Hive Yet? Try Excel

Built-in Excel connector zero third-party deps. Drop a workbook in a directory, register catalog:

CREATE CATALOG local USING excel
WITH (
  'catalog.excel.path' = '/data/mybooks'
);

SELECT * FROM local.sales.Sheet1 LIMIT 10;
catalog.excel.path

must be absolute path; factory validates. Naming hierarchy:

Catalog: configured directory

Schema: workbook filename without extension

Table: Sheet name

Above query reads /data/mybooks/sales.xlsx sheet Sheet1.

Register Hive and MySQL

For the cross-source GMV query, register two catalogs:

CREATE CATALOG hive USING hive3  -- Hive 2.x use hive2
WITH (
  'catalog.hive.metastore.uris' = 'thrift://localhost:9083'
);

CREATE CATALOG mydb USING mysql
WITH (
  'catalog.mysql.jdbcUrl' = 'jdbc:mysql://localhost:3306/dga',
  'catalog.mysql.username' = 'root',
  'catalog.mysql.password' = '***'
);

Registration is one-time; then use hive.dojao_test.ods_user_behavior and mydb.dga.users directly in cross-source SQL.

Configure Python Sidecar

Recommend dedicated venv for sidecar:

python3 -m venv /opt/dojao-pyenv
/opt/dojao-pyenv/bin/pip install -r python/requirements.txt

Master and each Worker need Python env and sidecar runtime. Put in each node's conf/dojao.conf:

system.python.home = /opt/dojao-pyenv
# Official SDK path, default <DOJAO_HOME>/python — engine-bundled sidecar runtime, NOT user function code
system.python.udf.runtime = <DOJAO_HOME>/python
# Sidecar process count, default 4, recommend ≥ partition parallelism
system.python.pool = 4

Or override via env:

DOJAO_JVM_OPTS="-Dsystem.python.home=/opt/dojao-pyenv" ./bin/dojao

. Then register stddev_py etc. to plug Python compute into SQL.

Scale to Multi-Node Cluster

Edit each machine's conf/dojao.conf.

Machine A as standalone Master:

system.role = master
system.master.host = 0.0.0.0

Machines B, C as Workers:

system.role = worker
system.master.host = <A machine IP>
system.worker.host = <this machine LAN IP>

Each machine runs ./bin/dojao. Workers auto-register to Master; no node list maintenance. Small deployments can let A run system.role = both (Master+Worker) while others join as Workers; then A's system.worker.host must be its LAN IP, else it advertises 127.0.0.1 and other nodes can't fetch data.

What It Fits, What It Doesn't

Dojao's appeal isn't "another federated query engine" but explicit trade-offs on things others gloss over:

Memory-first, spill fallback: compute in memory, spill only when needed, and spill reduces data volume.

Window dedup prunes at spill time, not writing full intermediates.

Bounded output queue prevents result set piling in memory.

Parallel merge preserves Window partition order.

Unified node accounting keeps failure at query level, not whole machine kill.

UDF state stays in engine Arrow, sidecar stateless.

Connectors prefer fewer optimizations over silent wrong results.

Agent can query, but DDL requires human confirmation.

Boundaries are equally clear:

20+ nodes, pure-memory PB scale, absolute throughput — Trino and Spark remain more mature. 0.1.0 still has memory budget and engineering edges needing polish; not for production core replacement without stress testing.

Compare on same hardware, same data, same SQL; check correctness, peak memory, spill volume, disk usage, failure rate — not just latency.

Adoption suggestion: start with one real but non-critical cross-source query: single-node ( role=both, two JVMs), dedicated spill disk, open console to watch memory/spill, add a read-only Python UDF. Once stable, consider cluster expansion and more sources.

Project URLs Gitee: https://gitee.com/scottjia/Dojao GitHub: https://github.com/Jason1008Jia/Dojao

Requirements: JDK 21, Maven 3.9+, Python 3.11+; default system.role = both single-command launches Master and Worker (two JVMs). Code also has system.deploy.mode = standalone single-JVM mode, not yet in packaged config (still under development, may arrive next version).

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

Published

AI-assisted summary

Report an issue with this article
MPPfederated queryPython UDFunified memoryArrow Flightconnector SPIDFP protocolDojaoreduced spillspill-to-disk

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion