iceberg icon indicating copy to clipboard operation
iceberg copied to clipboard

Support version/timestamp range queries in Spark SQL syntax

Open ted-jenks opened this issue 8 months ago • 5 comments

Feature Request / Improvement

Spark SQL supports point-in-time queries via VERSION AS OF and TIMESTAMP AS OF, but there is no SQL syntax for querying a range of versions or timestamps. This is useful for incremental consumption patterns.

The underlying scan infrastructure fully supports this. IncrementalScan provides fromSnapshotInclusive, fromSnapshotExclusive, and toSnapshot.

There is:

  CALL spark_catalog.system.create_changelog_view(
    table => 'db.tbl',
    options => map('start-snapshot-id','1','end-snapshot-id', '2')
  );
  SELECT * FROM tbl_changes;

But this does not provide a direct SQL query syntax for version ranges.

Proposal

Add SQL syntax for version/timestamp range queries. Possible forms (open for discussion):

-- by snapshot ID
SELECT * FROM db.table VERSION BETWEEN 1 AND 5

-- by timestamp
SELECT * FROM db.table TIMESTAMP BETWEEN '2024-01-01' AND '2024-06-01'

-- by tag/branch ref
SELECT * FROM db.table VERSION BETWEEN 'tag-a' AND 'tag-b'

Query engine

Spark

Willingness to contribute

  • [ ] I can contribute this improvement/feature independently
  • [x] I would be willing to contribute this improvement/feature with guidance from the Iceberg community
  • [ ] I cannot contribute this improvement/feature at this time

ted-jenks avatar Mar 20 '26 14:03 ted-jenks

@manuzhang I see you have previously contributed to grammar and would be keen to hear your thoughts on syntax

ted-jenks avatar Mar 20 '26 14:03 ted-jenks

The current proposal doesn't specify the intended semantics of this range-based read, and it's not obvious. For example, if the snapshot is of type delete and removes some rows, what would SELECT * FROM db.table VERSION BETWEEN 1 AND 5 return?

IncrementalScan is an interface. The append scan would ignore deletes and return no rows in this case. A changelog scan would attempt to report the deletes (caveat is https://github.com/apache/iceberg/pull/14264). These semantics differ significantly

smaheshwar-pltr avatar Mar 20 '26 15:03 smaheshwar-pltr

My proposal would be that this should match the existing DataFrame incremental read semantics (start-snapshot-id / end-snapshot-id), which uses IncrementalAppendScan:

  • Start is exclusive, end is inclusive
  • Only returns newly added rows from APPEND snapshots. Deletes, overwrites, and replaces are not visible
  • This is deliberately limited in scope. Changelog semantics (reporting deletes, inserts, and updates with _change_type metadata) are a separate concern better served by the existing create_changelog_view procedure or the .changes metadata table, and could be considered as a follow-up.

ted-jenks avatar Mar 20 '26 15:03 ted-jenks

Before the syntax question, there is a structural obstacle that I think decides the shape of this: Iceberg cannot add VERSION BETWEEN ... AND ... to a SELECT on its own. Three points in the code, on Spark 4.1:

1. VERSION AS OF is Spark's syntax, not Iceberg's. Spark parses it and calls the catalog's time-travel overloads; Iceberg only receives the already-parsed value:

// SparkCatalog
public Table loadTable(Identifier ident, String version) { return load(ident, TimeTravel.version(version)); }
public Table loadTable(Identifier ident, long timestampMicros) { ... }

So the existing feature is not evidence that Iceberg can add sibling syntax — it is evidence that Spark owns this grammar and Iceberg implements a callback.

2. Iceberg's extension parser is whole-statement, all-or-nothing. It cannot hook a sub-rule of Spark's SELECT:

// IcebergSparkSqlExtensionsParser
private def parsePlanWithDelegate(sqlText: String)(delegateParse: String => LogicalPlan) = {
  if (isIcebergCommand(sqlTextAfterSubstitution)) {
    parse(...) { parser => astBuilder.visit(parser.singleStatement()) }
  } else {
    RewriteViewCommands(...).apply(delegateParse(sqlText))   // entire text to Spark
  }
}

3. And isIcebergCommand only ever matches ALTER TABLE:

normalized.startsWith("alter table") && (normalized.contains("add partition field") || ... )

A SELECT therefore goes wholesale to Spark's parser, which does not know VERSION BETWEEN. Correspondingly the statement rule in IcebergSqlExtensions.g4 contains only ALTER TABLE forms — no relation or FROM-clause syntax at all.

So implementing the proposal as written means an upstream Spark grammar change, not an Iceberg one. Worth knowing before the syntax is bikeshedded here, because the venue for that decision would be SPARK, not this repo.


On @smaheshwar-pltr's semantics question, @ted-jenks's answer checks out against the code. The DataFrame path builds an IncrementalAppendScan with start exclusive, end inclusive:

// SparkScanBuilder.buildIcebergIncrementalAppendScan
.fromSnapshotExclusive(startSnapshotId)
...
scan = scan.toSnapshot(endSnapshotId);

so "match the existing start-snapshot-id / end-snapshot-id semantics" is a well-defined answer: appended rows only, deletes and overwrites invisible. The ambiguity @smaheshwar-pltr raised is real, but it is resolved by picking IncrementalAppendScan, and that choice already has a precedent users rely on.

One further wrinkle in the proposal worth noting if it moves upstream: VERSION BETWEEN 'tag-a' AND 'tag-b' and VERSION BETWEEN 1 AND 5 are different types in one clause. TimeTravel.AsOfVersion already carries this tension and resolves it by probing (Longs.tryParse(version) != null decides snapshot-id versus ref name), so a range form would inherit the same ambiguity twice over — BETWEEN 1 AND 5 is a snapshot range, unless a branch happens to be named 1.


Given the above, the options that stay inside Iceberg are the ones that need no new FROM-clause syntax:

  • a table-valued function, e.g. SELECT * FROM iceberg_incremental('db.tbl', 1, 5)
  • read options on the existing metadata-table style access
  • keeping create_changelog_view and documenting the incremental-append equivalent

None is as pleasant as the proposed syntax, but all are implementable here rather than in Spark. Happy to prototype whichever direction the maintainers prefer — I have not written any code for this.

vbhanuchander-lang avatar Aug 11 '26 09:08 vbhanuchander-lang

Picking this back up since the thread stalled on direction. I went through the Spark 4.1/4.2 code and I think @vbhanuchander-lang's structural read is correct and decisive: the proposed VERSION BETWEEN … AND … SELECT syntax can't land in Iceberg alone.

Confirming the three blockers against current code:

  1. VERSION AS OF / TIMESTAMP AS OF are Spark's grammar; Iceberg only implements the catalog time-travel callbacks.
  2. The statement rule in IcebergSqlExtensions.g4 has only ALTER TABLE forms — no relation / FROM-clause syntax.
  3. IcebergSparkSqlExtensionsParser is whole-statement and isIcebergCommand only matches "alter table …", so any SELECT is delegated wholesale to Spark's parser, which doesn't know VERSION BETWEEN.

So the literal syntax is a Spark change, and that decision belongs upstream in Spark, not here.

Proposal: a table-valued function, fully inside Iceberg

The scan side already exists — SparkReadOptions.START_SNAPSHOT_ID / END_SNAPSHOT_ID, SparkReadConf.incrementalAppendScanBoundaries(), SparkScanBuilder.buildIcebergIncrementalAppendScan() — reachable today only via the DataFrame reader. The missing piece is a SQL entry point.

SparkSessionExtensions.injectTableFunction (Spark 3.4+) is a public hook that IcebergSparkSessionExtensions doesn't use yet (we currently inject a parser, resolution rules, an optimizer rule, and a planner strategy). It lets us add, with no Spark grammar change:

SELECT * FROM iceberg_incremental_changes('db.tbl', <startSnapshotId>, <endSnapshotId>)

I traced the resolution path against Spark 4.2.0 to confirm it actually reaches the incremental scan:

  • injectTableFunction takes a Seq[Expression] => LogicalPlan builder.
  • The builder returns UnresolvedRelation(Seq("db", "tbl"), new CaseInsensitiveStringMap({"start-snapshot-id": …, "end-snapshot-id": …}), false) — the public constructor carries the options map.
  • ResolveRelations resolves it via DataSourceV2Relation.create(table, catalog, ident, options, timeTravel) — the overload that carries options.
  • DataSourceV2Relation.options() flows into SparkTable.newScanBuilder(CaseInsensitiveStringMap), and SparkScanBuilder already branches on Spark3Util.containsIncrementalOptions(options) → incrementalAppendScanBoundaries() → buildIcebergIncrementalAppendScan().

So the function body is thin — it reuses the exact option plumbing the DataFrame incremental read already uses. (I verified the API at every hop; I haven't run it end-to-end — a small integration test closes the one remaining link, that ResolveRelations forwards the relation's options into create.)

Semantics

Match the established DataFrame incremental-append contract, as @ted-jenks proposed: start-exclusive, end-inclusive, appended rows only; deletes / overwrites / replaces are invisible. Changelog semantics (_change_type, reporting deletes) stay out of scope — create_changelog_view / the .changes metadata table already cover that. Choosing IncrementalAppendScan here is what resolves @smaheshwar-pltr's ambiguity: one well-defined answer rather than the append-vs-changelog fork.

On the id-vs-ref ambiguity: a TVF signature sidesteps the BETWEEN type collision. I'd start with snapshot-id arguments and add a timestamp-range overload as a follow-up, rather than probing both in one clause the way TimeTravel.AsOfVersion does.

Decision I'd like from a committer before writing code

  1. Is a table-valued function the direction you want, or do you prefer read-option / metadata-table-style access?
  2. Function naming — iceberg_incremental_changes, or something aligned with the existing *_changes / changelog vocabulary?
  3. Do you want the headline VERSION BETWEEN SELECT syntax pursued upstream in Spark in parallel, or dropped in favor of the TVF?

Happy to put up the TVF prototype as soon as there's a thumbs-up on direction; I can also take the Spark-grammar angle to dev@ if that's preferred.

hreddygayam avatar Oct 10 '26 07:10 hreddygayam