Skip to content

Commit 45005ee

Browse files
authored
feat(server): preview plans from the synced warehouse copy (#1437)
* feat(state): add the display-only observations state table * feat(state): record cursor observations after successful builds After a build, each successful incremental model's cursor MAX is read with the planner's own cursor SQL and appended to the observations table in its state schema. Failures only warn. * feat(state): record described source columns after builds A build keeps the columns planning described for each type-enforced expression source and appends them as source_columns observations in the state schema of every model reading the source. Plans record nothing. * feat(orchestration): mirror build observations into the control store Location sync reads _sqlbuild_observations as its own history kind and the server keeps the rows in sqb_warehouse_observations, keyed by the observation identity, with kind and node columns for latest-value reads. * test(policy): keep build observations out of planning and build decisions Add Fensu rule XSB078: Rust code may name observation state only in the files that write, prune, mirror or display it. An E2E build ignores a wrong cursor_max observation and appends from the live MAX. * fix(observations): record the described SQL hash with source columns A source_columns value is now {sql_hash, columns}, the SHA-256 of the exact expression SQL planning described, so a preview can tell when the expression changed since the observation and report it as unknown. * feat(server): serve the mirrored copy a plan preview plans from Add POST .../metadata/preview-copy for a location's fenced reader. It returns the target's catalog relations, each node's newest fingerprint with its definition, newest succeeded run and newest observation per kind, and synced_at: the oldest of the newest clean syncs of catalog, fingerprints and consumption, or null until all three synced cleanly. * feat(plan): plan location previews from the synced warehouse copy A location's requested plan now fetches the server's synced copy and runs sqb plan against an adapter that answers listings, columns and fingerprints from it, never connecting to the warehouse. Cursor targets use the newest successful build's cursor_max, inputs are read when the run starts, and expression sources use the columns described for the same SQL. The plan reports when the copy synced and what stays unknown until the run, and refuses --defer-to. Fensu XSB079 confines the synced copy to sqb plan. * refactor(state): share the fixed-column state table DDL between consumption and observations * refactor(plan): render the copy's optional database without a higher-layer helper * feat(ui): show what a plan preview planned from and each incremental window start A location plans a build from the server's synced copy of warehouse metadata. The plan page now says when that copy synced, lists what stays unknown until the run, and shows each incremental model's window start running to the latest data when the run starts. * docs(server): explain that plan previews read the synced warehouse copy * refactor(plan): read a synced-copy listing's scope in one place Record why the remaining per-table state bindings, the SQL Server keyed state DDL overrides, the observation ingest projection and the copy's Python object builders look alike. * test(plan): move the preview test's helpers beside the publication helpers Name the preview cases' outcomes expected_ and keep the Fensu rules module to its rule functions. * fix(plan): keep previews within the synced copy on every adapter and project shape Table types and retention stay unknown instead of reading the warehouse, and sources outside the mirrored schemas are not probed. The copy counts as synced only once every schema the snapshot builds into has synced each required table. A model whose lookback, backfill duration or microbatches move its start reports its window as unknown. * fix(plan): keep source freshness and moved cursor windows unknown in previews A preview observes no source freshness and warns about none, and reports a cursor window as unknown when lookback, replay on change, a start override, or a cursor_start floor past the last build moves the run's start. Cursor intrinsics bind to the bounds the run resolves, and typed source projections render through the facade. * fix(plan): bind preview cursor intrinsics only for models with watermark inputs Keep the preview's runtime-resolved bounds to models whose watermark inputs it cleared, so a model live planning cannot bound still fails the preview. XSB079 now also confines the synced copy's refusal error.
1 parent 71c36b3 commit 45005ee

102 files changed

Lines changed: 3801 additions & 265 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Makefile‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ E2E_DUCKDB_BUILD_INCREMENTAL_PATHS := \
147147
tests/e2e/src/sqlbuild/cli/commands/main/build/test_capped_microbatch_build.py \
148148
tests/e2e/src/sqlbuild/cli/commands/main/build/test_changed_builds.py \
149149
tests/e2e/src/sqlbuild/cli/commands/main/build/test_concurrent_microbatch_build.py \
150+
tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_observations.py \
150151
tests/e2e/src/sqlbuild/cli/commands/main/build/test_cursor_runtime_failures.py \
151152
tests/e2e/src/sqlbuild/cli/commands/main/build/test_dropped_relation_rebuild.py \
152153
tests/e2e/src/sqlbuild/cli/commands/main/build/test_empty_cursor_inputs.py \
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
{
2+
"record": {
3+
"state_database": null,
4+
"state_schema": "main",
5+
"observation_id": "observation-000",
6+
"kind": "cursor_max",
7+
"node": "orders_🧾",
8+
"cursor_type": "timestamp",
9+
"value": "2026-02-03 04:05:06.123456",
10+
"run_id": "external-run",
11+
"observed_at": "2026-02-03T04:05:06Z"
12+
},
13+
"source_rows": 104,
14+
"duplicate_rows": 3,
15+
"later_time": "2026-02-03T04:05:06.000001Z",
16+
"page_lengths": [
17+
100,
18+
7
19+
],
20+
"later_index": 106,
21+
"source_count": 107,
22+
"model": "MODEL (description 'Orders.', materialized table); SELECT 1 AS order_id",
23+
"retained_result": "observation-103",
24+
"kind": "observations",
25+
"source_key": "observation_id",
26+
"timestamp_key": "observed_at",
27+
"id_prefix": "observation",
28+
"later_record": {
29+
"observation_id": "observation-103",
30+
"kind": "source_columns",
31+
"node": "shop.orders_🧾",
32+
"cursor_type": null,
33+
"value": "{\"sql_hash\":\"928300f876a1cfe48302513f8c25ca06ec449c95f3480c06b84c694a39b6be0d\",\"columns\":[\"order_id\",\"amount_€\"]}",
34+
"observed_at": "2026-02-03T04:05:06.000001Z"
35+
},
36+
"last_record": {
37+
"observation_id": "observation-103",
38+
"kind": "source_columns",
39+
"node": "shop.orders_🧾",
40+
"cursor_type": null,
41+
"value": "{\"sql_hash\":\"928300f876a1cfe48302513f8c25ca06ec449c95f3480c06b84c694a39b6be0d\",\"columns\":[\"order_id\",\"amount_€\"]}",
42+
"observed_at": "2026-02-03T04:05:06.000001Z"
43+
},
44+
"record_overrides": {
45+
"observation-103": {
46+
"kind": "source_columns",
47+
"node": "shop.orders_🧾",
48+
"cursor_type": null,
49+
"value": "{\"sql_hash\":\"928300f876a1cfe48302513f8c25ca06ec449c95f3480c06b84c694a39b6be0d\",\"columns\":[\"order_id\",\"amount_€\"]}",
50+
"observed_at": "2026-02-03T04:05:06.000001Z"
51+
}
52+
}
53+
}

‎clients/typescript/src/schema.d.ts‎

Lines changed: 128 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1010,6 +1010,22 @@ export interface paths {
10101010
patch?: never;
10111011
trace?: never;
10121012
};
1013+
"/api/locations/{location_id}/targets/{target}/metadata/preview-copy": {
1014+
parameters: {
1015+
query?: never;
1016+
header?: never;
1017+
path?: never;
1018+
cookie?: never;
1019+
};
1020+
get?: never;
1021+
put?: never;
1022+
post: operations["preview_copy"];
1023+
delete?: never;
1024+
options?: never;
1025+
head?: never;
1026+
patch?: never;
1027+
trace?: never;
1028+
};
10131029
"/api/locations/{location_id}/targets/{target}/metadata/statistics-due": {
10141030
parameters: {
10151031
query?: never;
@@ -2308,6 +2324,30 @@ export interface components {
23082324
*/
23092325
scheduler_lease_expires_at?: string | null;
23102326
};
2327+
/** @description What the mirror knows as of `synced_at`; `None` when a required table never synced cleanly. */
2328+
PreviewCopy: {
2329+
fingerprints: components["schemas"]["WarehouseFingerprintRecord"][];
2330+
latest_runs: components["schemas"]["PreviewLatestRun"][];
2331+
observations: components["schemas"]["WarehouseObservationRecord"][];
2332+
relations: components["schemas"]["WarehouseCatalogRecord"][];
2333+
/** Format: date-time */
2334+
synced_at?: string | null;
2335+
};
2336+
/** @description A location asks for the mirrored copy a plan preview plans from, as its fenced reader. */
2337+
PreviewCopyRead: {
2338+
/** Format: int64 */
2339+
generation: number;
2340+
/** Format: uuid */
2341+
session_id: string;
2342+
};
2343+
/** @description The newest successful build of a node, which a `cursor_max` observation must come from. */
2344+
PreviewLatestRun: {
2345+
node_name: string;
2346+
node_type: string;
2347+
run_id: string;
2348+
state_database?: string | null;
2349+
state_schema: string;
2350+
};
23112351
/** @description A changed subject, such as `model:orders`, or `role:analyst` (`role:` for those who can't assign roles). */
23122352
PublishedChange: {
23132353
change_kind: string;
@@ -3078,11 +3118,30 @@ export interface components {
30783118
state_database?: string | null;
30793119
state_schema: string;
30803120
};
3121+
/** @description Fingerprints remain history here; latest-row selection belongs to the existing planner reader. */
3122+
WarehouseFingerprintRecord: {
3123+
definition: string;
3124+
definition_hash: string;
3125+
event_id?: string | null;
3126+
metadata_json: string;
3127+
node_name: string;
3128+
node_type: string;
3129+
run_id: string;
3130+
schema_fingerprint: string;
3131+
state_database?: string | null;
3132+
state_schema: string;
3133+
target_database?: string | null;
3134+
target_name?: string | null;
3135+
target_schema?: string | null;
3136+
/** Format: date-time */
3137+
ts: string;
3138+
version_hash: string;
3139+
};
30813140
/**
30823141
* @description Catalog observations require full scans; only immutable history supports a watermark.
30833142
* @enum {string}
30843143
*/
3085-
WarehouseHistoryKind: "fingerprints" | "source_freshness" | "audit_results" | "janitor_events" | "migrations" | "old_name_views" | "microbatches" | "column_migrations" | "node_results" | "consumption" | "catalog" | "statistics";
3144+
WarehouseHistoryKind: "fingerprints" | "source_freshness" | "audit_results" | "janitor_events" | "migrations" | "old_name_views" | "microbatches" | "column_migrations" | "node_results" | "consumption" | "observations" | "catalog" | "statistics";
30863145
/** @description Warehouse cleanup facts do not authorize control-plane deletion or worker recovery. */
30873146
WarehouseJanitorRecord: {
30883147
archive_name: string;
@@ -3131,6 +3190,19 @@ export interface components {
31313190
/** Format: date-time */
31323191
observed_at: string;
31333192
};
3193+
/** @description A display-only value a build observed, such as a cursor `MAX`; planning never reads it. */
3194+
WarehouseObservationRecord: {
3195+
cursor_type?: string | null;
3196+
kind: string;
3197+
node: string;
3198+
observation_id: string;
3199+
/** Format: date-time */
3200+
observed_at: string;
3201+
run_id: string;
3202+
state_database?: string | null;
3203+
state_schema: string;
3204+
value: string;
3205+
};
31343206
/** @description Physical namespace of SQLBuild's source-freshness state table, never a source query. */
31353207
WarehouseStateLocation: {
31363208
database?: string | null;
@@ -5889,6 +5961,61 @@ export interface operations {
58895961
};
58905962
};
58915963
};
5964+
preview_copy: {
5965+
parameters: {
5966+
query?: never;
5967+
header?: never;
5968+
path: {
5969+
location_id: string;
5970+
target: string;
5971+
};
5972+
cookie?: never;
5973+
};
5974+
requestBody: {
5975+
content: {
5976+
"application/json": components["schemas"]["PreviewCopyRead"];
5977+
};
5978+
};
5979+
responses: {
5980+
200: {
5981+
headers: {
5982+
[name: string]: unknown;
5983+
};
5984+
content: {
5985+
"application/json": components["schemas"]["PreviewCopy"];
5986+
};
5987+
};
5988+
400: {
5989+
headers: {
5990+
[name: string]: unknown;
5991+
};
5992+
content: {
5993+
"application/json": components["schemas"]["ApiErrorBody"];
5994+
};
5995+
};
5996+
/** @description Invalid credential */
5997+
401: {
5998+
headers: {
5999+
[name: string]: unknown;
6000+
};
6001+
content?: never;
6002+
};
6003+
/** @description Location not authorized */
6004+
403: {
6005+
headers: {
6006+
[name: string]: unknown;
6007+
};
6008+
content?: never;
6009+
};
6010+
/** @description Reader generation fenced */
6011+
409: {
6012+
headers: {
6013+
[name: string]: unknown;
6014+
};
6015+
content?: never;
6016+
};
6017+
};
6018+
};
58926019
statistics_due: {
58936020
parameters: {
58946021
query?: never;

‎crates/sqlbuild-analysis/src/janitor_planning/constants.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
use sqlbuild_core::constants::STATE_TABLE_NAMES;
44

55
/// SQLBuild state tables the janitor never acts on.
6-
pub const BUILT_IN_EXCLUDE_PATTERNS: [&str; 10] = STATE_TABLE_NAMES;
6+
pub const BUILT_IN_EXCLUDE_PATTERNS: [&str; 11] = STATE_TABLE_NAMES;
77
/// Prefix of every strict janitor archive name.
88
pub const ARCHIVE_NAME_PREFIX: &str = "_SQB_ARCHIVE__";
99
/// Separator between archive name segments.

‎crates/sqlbuild-cache/src/digest/constants.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,6 @@ pub(crate) const DIRECT_URL_FILE: &str = "direct_url.json";
5151

5252
/// Inputs at least this large are hashed across the rayon pool; the digest is the same either way.
5353
pub(crate) const PARALLEL_HASH_BYTES: usize = 1 << 20;
54+
/// The standard base64 alphabet.
55+
pub const BASE64_ALPHABET: &[u8; 64] =
56+
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//! Standard padded base64 text of bytes, as Python's `base64.b64encode(data).decode()` gives.
2+
3+
use crate::digest::constants::BASE64_ALPHABET;
4+
5+
/// Standard padded base64 of `data`.
6+
#[must_use]
7+
pub fn base64_text(data: &[u8]) -> String {
8+
let mut encoded = String::with_capacity(data.len().div_ceil(3) * 4);
9+
for chunk in data.chunks(3) {
10+
let bytes = [
11+
chunk[0],
12+
*chunk.get(1).unwrap_or(&0),
13+
*chunk.get(2).unwrap_or(&0),
14+
];
15+
let triple = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
16+
for index in 0..4 {
17+
if index <= chunk.len() {
18+
encoded.push(char::from(
19+
BASE64_ALPHABET[(triple >> (18 - 6 * index) & 63) as usize],
20+
));
21+
} else {
22+
encoded.push('=');
23+
}
24+
}
25+
}
26+
encoded
27+
}

‎crates/sqlbuild-cache/src/digest/main/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
pub mod base64_text;
12
pub mod bytes_digest;
23
pub mod compiled_code_identity;
34
pub mod content_digest;

‎crates/sqlbuild-cli/src/native_commands/main/_location_plan.rs‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,18 @@
1-
//! A requested plan runs as an ordinary `sqb plan --json` child on the server-frozen node keys.
1+
//! A requested plan runs as a `sqb plan --json` child on frozen node keys, from the synced copy.
22
33
use std::collections::{BTreeMap, BTreeSet};
44
use std::future::Future;
5-
use std::path::Path;
5+
use std::path::{Path, PathBuf};
66
use std::process::Stdio;
77

88
use serde_json::Value;
9+
use sqlbuild_core::plan_display::constants::PLAN_SYNCED_COPY_ENV;
10+
use sqlbuild_orchestration::platform::models::LocationWorkClient;
911
use sqlbuild_orchestration::store::errors::ControlError;
12+
use sqlbuild_orchestration::warehouse_metadata::models::PreviewCopyRead;
1013
use tokio::io::AsyncReadExt;
1114
use tokio::process::Child;
15+
use uuid::Uuid;
1216

1317
use crate::argv::main::accepted_settings_arguments::accepted_settings_arguments;
1418
use crate::native_commands::_helpers::execution::location_child;
@@ -21,9 +25,39 @@ use crate::native_commands::models::LocationServe;
2125
pub(super) async fn plan_location(
2226
(options, script): (&LocationServe, &Path),
2327
(selection, settings): (&BTreeSet<String>, &BTreeMap<String, Value>),
28+
(client, session_id, generation): (&LocationWorkClient, Uuid, i64),
2429
stopped: impl Future<Output = Result<(), ControlError>>,
2530
) -> Result<Option<Value>, ControlError> {
26-
let mut child = match plan_child((options, script), (selection, settings)) {
31+
let read = PreviewCopyRead {
32+
session_id,
33+
generation,
34+
};
35+
let copy = match client.preview_copy(&options.target, &read).await {
36+
Ok(copy) => copy,
37+
Err(error) => {
38+
return Ok(Some(plan_failure(&format!(
39+
"the synced warehouse copy is unavailable: {error}"
40+
))));
41+
}
42+
};
43+
let path: PathBuf =
44+
std::env::temp_dir().join(format!("sqlbuild-plan-copy-{}.json", Uuid::now_v7()));
45+
std::fs::write(
46+
&path,
47+
serde_json::to_vec(&copy).map_err(std::io::Error::other)?,
48+
)?;
49+
let planned = run_plan((options, script), (selection, settings), &path, stopped).await;
50+
drop(std::fs::remove_file(&path));
51+
planned
52+
}
53+
54+
async fn run_plan(
55+
(options, script): (&LocationServe, &Path),
56+
(selection, settings): (&BTreeSet<String>, &BTreeMap<String, Value>),
57+
copy: &Path,
58+
stopped: impl Future<Output = Result<(), ControlError>>,
59+
) -> Result<Option<Value>, ControlError> {
60+
let mut child = match plan_child((options, script), (selection, settings), copy) {
2761
Ok(child) => child?,
2862
Err(message) => return Ok(Some(plan_failure(&message))),
2963
};
@@ -57,6 +91,7 @@ pub(super) async fn plan_location(
5791
fn plan_child(
5892
(options, script): (&LocationServe, &Path),
5993
(selection, settings): (&BTreeSet<String>, &BTreeMap<String, Value>),
94+
copy: &Path,
6095
) -> Result<std::io::Result<Child>, String> {
6196
let flags = accepted_settings_arguments(PLAN_COMMAND, settings)?;
6297
let mut command = location_child(options, script);
@@ -78,6 +113,7 @@ fn plan_child(
78113
Ok(command
79114
.env_remove("SQLBUILD_LOCATION_TOKEN")
80115
.env_remove("SQLBUILD_RUN_TOKEN")
116+
.env(PLAN_SYNCED_COPY_ENV, copy)
81117
.stdout(Stdio::piped())
82118
.spawn())
83119
}

‎crates/sqlbuild-cli/src/native_commands/main/_location_work.rs‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use sqlbuild_orchestration::platform::models::{
1111
};
1212
use sqlbuild_orchestration::store::errors::ControlError;
1313
use tokio::time::Instant;
14+
use uuid::Uuid;
1415

1516
use crate::argv::models::Stream;
1617
use crate::native_commands::_helpers::execution::check_location_connection;
@@ -56,7 +57,8 @@ pub(super) async fn run_location_work(
5657
() = tokio::time::sleep_until(deadline) => Ok(()),
5758
}
5859
};
59-
let checked = perform_work((options, script), claim.request.work, expires).await?;
60+
let copy = (client, poll.session_id, claim.generation);
61+
let checked = perform_work((options, script), claim.request.work, copy, expires).await?;
6062
let Some((outcome, local_files)) = checked else {
6163
drop(write_output(&[(
6264
Stream::Stderr,
@@ -122,6 +124,7 @@ pub(super) async fn run_location_work(
122124
async fn perform_work(
123125
(options, script): (&LocationServe, &Path),
124126
work: LocationWork,
127+
copy: (&LocationWorkClient, Uuid, i64),
125128
expires: impl Future<Output = Result<(), ControlError>>,
126129
) -> Result<Option<(LocationWorkOutcome, Vec<PathBuf>)>, ControlError> {
127130
let message = match &work {
@@ -150,7 +153,7 @@ async fn perform_work(
150153
selection,
151154
settings,
152155
..
153-
} => plan_location((options, script), (&selection, &settings), expires)
156+
} => plan_location((options, script), (&selection, &settings), copy, expires)
154157
.await?
155158
.map(|document| (LocationWorkOutcome::Plan { document }, Vec::new())),
156159
})

0 commit comments

Comments
 (0)