GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — [SQL] Emit the type for each expression in the IR JSON by mihaibudiu · Pull Request #7805 · feldera/feldera

[SQL] Emit the type for each expression in the IR JSON #7805

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Sign up for GitHub

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
mihaibudiu merged 1 commit into main from issue7803
Nov 4, 2026

Uh oh!

There was an error while loading. Please reload this page.

Merged

[SQL] Emit the type for each expression in the IR JSON #7805

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
1 commit
Select commit
f3bc9f8
[SQL] Emit the type for each expression in the IR JSON
mihaibudiu Nov 3, 2026
File filter
Filter by extension

Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

19 changes: 17 additions & 2 deletions 19 ...ompiler/SQL-compiler/src/main/java/org/dbsp/sqlCompiler/compiler/backend/JsonDecoder.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import org.dbsp.sqlCompiler.ir.IDBSPInnerNode;
import org.dbsp.sqlCompiler.ir.IDBSPNode;
import org.dbsp.sqlCompiler.ir.IDBSPOuterNode;
import org.dbsp.sqlCompiler.ir.expression.DBSPExpression;
import org.dbsp.sqlCompiler.ir.type.DBSPType;
import org.dbsp.sqlCompiler.ir.type.derived.DBSPTypeStruct;
import org.dbsp.util.Utilities;

Expand Down Expand Up @@ -39,6 +41,13 @@ public <S extends T> S lookup(Long id, Class<S> tClass) {
public void cache(Long originalId, IDBSPNode result) {
Utilities.putNew(this.decoded, originalId, result);
}

/** True if {@code json} is a reference, or a node already decoded. */
public boolean isDecoded(JsonNode json) {
if (json.has("node"))
return true;
return this.decoded.containsKey(Utilities.getLongProperty(json, "id"));
}
}

final Cache<IDBSPInnerNode> inner;
Expand Down Expand Up @@ -123,10 +132,16 @@ IDBSPNode decode(JsonNode node, boolean outer) {
JsonNode position = object.get("position");
if (position != null && result instanceof DBSPNode dbspNode && dbspNode.getNode().isEmpty())
dbspNode.setSourcePosition(SourcePositionRange.fromJson(position));
if (outer)
if (outer) {
this.outer.cache(originalId, result);
else
} else {
this.inner.cache(originalId, result);
// The fromJson of an expression whose type follows from its children does not read
// the "type" property; decode it, so that a later reference to the type resolves.
JsonNode type = object.get("type");
if (result instanceof DBSPExpression && type != null && !this.inner.isDecoded(type))
this.decodeInner(type, DBSPType.class);
}
return result;
} catch (InvocationTargetException e) {
throw new RuntimeException("Error decoding " + cls.asText() + " with id " + originalId, e.getCause());
Expand Down
35 changes: 25 additions & 10 deletions 35 .../SQL-compiler/src/main/java/org/dbsp/sqlCompiler/compiler/backend/ToJsonInnerVisitor.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPShortIntervalLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPLongIntervalLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPKeywordLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPRealLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPStrLiteral;
import org.dbsp.sqlCompiler.ir.expression.literal.DBSPStringLiteral;
Expand Down Expand Up @@ -55,24 +54,32 @@
import org.dbsp.sqlCompiler.ir.type.primitive.DBSPTypeString;
import org.dbsp.sqlCompiler.ir.type.user.DBSPTypeUser;
import org.dbsp.util.JsonStream;
import org.dbsp.util.Utilities;

import java.util.ArrayList;
import java.util.Base64;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/** Serializes an inner node as a JSON string.
* Since this visitor calls the visit methods for InnerVisitor, it should generally
* only handle fields which are not visited by InnerVisitor, i.e., the ones which are not DBSPNode objects. */
* only handle fields which are not visited by InnerVisitor, i.e., the ones which are not DBSPNode objects.
* Every expression gets a "type" property. */
public class ToJsonInnerVisitor extends InnerVisitor {
public final JsonStream stream;
final int verbosity;
final Set<Long> serialized;
/** One entry for each node in the visitor context: true when the JSON object of the node
* already has a "type" property. */
final List<Boolean> hasType;

public ToJsonInnerVisitor(DBSPCompiler compiler, JsonStream stream, int verbosity) {
super(compiler);
this.stream = stream;
this.verbosity = verbosity;
this.serialized = new HashSet<>();
this.hasType = new ArrayList<>();
}

boolean checkDone(IDBSPInnerNode node, boolean silent) {
Expand Down Expand Up @@ -100,12 +107,15 @@ public void endArrayProperty(String property) {

@Override
public void property(String name) {
if (name.equals("type") && !this.hasType.isEmpty())
this.hasType.set(this.hasType.size() - 1, true);
this.stream.label(name);
}

@Override
public void push(IDBSPInnerNode node) {
if (!this.checkDone(node, true)) {
boolean done = this.checkDone(node, true);
if (!done) {
this.stream.appendClass(node);
this.property("id");
this.stream.append(node.getId());
Expand All @@ -119,9 +129,21 @@ public void push(IDBSPInnerNode node) {
}
}
}
this.hasType.add(done);
super.push(node);
}

@Override
public void pop(IDBSPInnerNode node) {
// Some expressions do not visit their type, because it follows from their children
if (!Utilities.last(this.hasType) && node instanceof DBSPExpression expression) {
this.property("type");
expression.getType().accept(this);
}
Utilities.removeLast(this.hasType);
super.pop(node);
}

@Override
public VisitDecision preorder(IDBSPInnerNode node) {
if (this.checkDone(node, false))
Expand Down Expand Up @@ -699,13 +721,6 @@ public void postorder(DBSPUuidLiteral node) {
super.postorder(node);
}

@Override
public void postorder(DBSPLiteral node) {
this.property("type");
node.type.accept(this);
super.postorder(node);
}

@Override
public void postorder(DBSPBorrowExpression node) {
this.property("mut");
Expand Down
85 changes: 85 additions & 0 deletions 85 ...-compiler/SQL-compiler/src/test/java/org/dbsp/sqlCompiler/compiler/sql/Gen2JsonTests.java
Show comments
View file
Open in desktop
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package org.dbsp.sqlCompiler.compiler.sql;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.dbsp.sqlCompiler.circuit.DBSPCircuit;
import org.dbsp.sqlCompiler.circuit.annotation.OperatorHash;
import org.dbsp.sqlCompiler.circuit.operator.DBSPStreamAggregateOperator;
Expand All @@ -10,12 +12,16 @@
import org.dbsp.sqlCompiler.compiler.sql.tools.SqlIoTest;
import org.dbsp.sqlCompiler.compiler.visitors.outer.CircuitVisitor;
import org.dbsp.sqlCompiler.compiler.visitors.outer.RemoveTypedBox;
import org.dbsp.sqlCompiler.ir.expression.DBSPExpression;
import org.dbsp.util.Utilities;
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/** The circuit compiled for the Gen-2 engine ({@code --gen2}) carries no Rust-codegen
* artifacts: it has no {@code TYPEDBOX}, no {@code TypedBox<T, _>}, and no {@code clone()}, a
Expand Down Expand Up @@ -57,6 +63,22 @@ CREATE VIEW w AS SELECT region, SUM(score) OVER (
CREATE TABLE sales(region VARCHAR NOT NULL, price DECIMAL(10, 2));
CREATE VIEW labelled AS SELECT region || '-suffix', price * 1.25 FROM sales;""";

/** Views that compile to the expressions whose type follows from their children: IS NULL, a
* sort, a top-k with comparators, aggregates, a fallible cast, a common subexpression bound
* by a Let or a Lazy, an ASOF join with a custom order, and a string constant. */
static final String COVERAGE_PROGRAM = """
CREATE TABLE t(id INT NOT NULL, x INT, s VARCHAR, d DOUBLE, ts TIMESTAMP NOT NULL);
CREATE TABLE u(id INT NOT NULL, ts TIMESTAMP NOT NULL, y INT);
CREATE VIEW nulls AS SELECT id, x IS NULL AS xn FROM t;
CREATE VIEW sorted AS SELECT id, x FROM t ORDER BY x;
CREATE VIEW top AS SELECT id, x FROM t ORDER BY x DESC LIMIT 3;
CREATE VIEW agg AS SELECT id, SUM(x), MIN(s), ARRAY_AGG(d) FROM t GROUP BY id;
CREATE VIEW casts AS SELECT CAST(s AS INT) AS i FROM t;
CREATE VIEW cse AS SELECT CASE WHEN x > 0 THEN (x + 1) * (x + 1) ELSE 0 END AS c FROM t;
CREATE VIEW matched AS SELECT t.id, u.y FROM t
LEFT ASOF JOIN u MATCH_CONDITION (t.ts >= u.ts) ON t.id = u.id;
CREATE VIEW labelled AS SELECT s || '-suffix' FROM t;""";

DBSPCompiler compile(String program, boolean gen2, boolean checkSerialization) {
return this.compile(program, gen2, checkSerialization, false);
}
Expand Down Expand Up @@ -209,6 +231,69 @@ public void gen2CircuitRoundTripsThroughJson() {
Assert.assertNotNull(this.compile(program, true, true).getFinalCircuit(false));
}

/** True if {@code simpleName} names a subclass of {@link DBSPExpression}. */
static boolean isExpression(String simpleName) {
for (String pkg : List.of("org.dbsp.sqlCompiler.ir.expression.",
"org.dbsp.sqlCompiler.ir.expression.literal.", "org.dbsp.sqlCompiler.ir.aggregate.")) {
try {
return DBSPExpression.class.isAssignableFrom(Class.forName(pkg + simpleName));
} catch (ClassNotFoundException ignored) {
}
}
return false;
}

/** Add to {@code seen} the class of each expression in {@code node}, and to {@code untyped}
* the class of each expression that has no type. */
static void collectExpressions(JsonNode node, Set<String> seen, List<String> untyped) {
JsonNode cls = node.get("class");
if (cls != null && isExpression(cls.asText())) {
seen.add(cls.asText());
if (!node.has("type"))
untyped.add(cls.asText());
}
for (JsonNode child : node)
collectExpressions(child, seen, untyped);
}

/** Every expression in the JSON has a type, also an expression whose type follows from its
* children, such as a field projection. The Rust circuit keeps the clones and the statics
* that the Gen-2 circuit drops, and an incremental circuit keeps its aggregates. */
@Test
public void jsonGivesEveryExpressionAType() throws JsonProcessingException {
Set<String> seen = new HashSet<>();
for (String program : List.of(WINDOW_PROGRAM, FOLD_PROGRAM, INCREMENTAL_PROGRAM,
ROLLING_PROGRAM, WATERLINE_PROGRAM, CONSTANT_PROGRAM, COVERAGE_PROGRAM)) {
for (boolean gen2 : new boolean[] { false, true }) {
for (boolean incremental : new boolean[] { false, true }) {
CompilerOptions options = this.testOptions();
options.ioOptions.gen2 = gen2;
options.languageOptions.incrementalize = incremental;
// An ORDER BY that is kept compiles to a sort expression
options.languageOptions.ignoreOrderBy = false;
DBSPCompiler compiler = new DBSPCompiler(options);
compiler.submitStatementsForCompilation(program);
String text = this.circuitJson(compiler);
JsonNode json = Utilities.deterministicObjectMapper().readTree(text);
List<String> untyped = new ArrayList<>();
collectExpressions(json, seen, untyped);
Assert.assertEquals(List.of(), untyped);
}
}
}
// The expressions whose type follows from their children
List<String> derived = List.of("DBSPFieldExpression", "DBSPDerefExpression",
"DBSPBorrowExpression", "DBSPCloneExpression", "DBSPHandleErrorExpression",
"DBSPSomeExpression", "DBSPBlockExpression", "DBSPLetExpression", "DBSPLazyExpression",
"DBSPStaticExpression", "DBSPIsNullExpression", "DBSPSortExpression",
"DBSPUnwrapCustomOrdExpression", "DBSPFieldComparatorExpression",
"DBSPDirectComparatorExpression", "DBSPNoComparatorExpression", "DBSPZSetExpression",
"DBSPMinMax", "DBSPFold", "NonLinearAggregate");
List<String> missing = new ArrayList<>(derived);
missing.removeAll(seen);
Assert.assertEquals(List.of(), missing);
}

/** RemoveTypedBox refuses the waterline of an indexed input, whose boxed type it cannot rewrite. */
@Test
public void removeTypedBoxRejectsIndexedInputWaterline() {
Expand Down
Loading
Oops, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.